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 |
|---|---|---|---|---|---|
17 April 2012 08:41 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
Output from the facility will be mainly sold to markets near Dazhou, the source said.
“We also built a 750cbm storage tank and bought 10 trucks for LNG delivery,” the source said, adding that “a phase two project with a capacity of 250,000cbm/day will be considered, depending on market demand”.
Construction work at the LNG plant was completed in late 2010 but its start-up was delayed because of the lack of feedstock gas supply, a source from a Chongqing-based LNG equipment design firm said.
“Feedstock gas is supplied by PetroChina’s southwest oil and gas fields in | http://www.icis.com/Articles/2012/04/17/9550926/chinas-sichuan-suoyu-gas-to-start-up-dazhou-lng-plant-in.html | CC-MAIN-2014-35 | refinedweb | 113 | 67.08 |
Hi All,
I have downlaoaded the WSDL for organization.svc and utilize this within a SSIS package (sql server integration services 2012) within a webservice task. At the second pane called input i am able to select a webservice method. When clicking the drop down
the following error occurs
Cannot find definition for .
Service description with namespace is missing. Parameter name : name
So I cannot see any webservice method. Could this be related to the use of AFDS?
Best regards,
Johan
I don't think you can use a webservice task to access Crm data in SSIS. There are 2 reasons for this: The authentication model, and the fact that Crm using relatively complex datatypes in the web services.
However, there are 2 alternate options to access the Crm data in SSIS:
Microsoft CRM MVP - | https://social.microsoft.com/Forums/en-US/242f2fe3-5511-4ab0-93ab-2eb8fe4f1559/using-webservices-while-using-crm-2013-online-with-afds?forum=crmdevelopment | CC-MAIN-2021-04 | refinedweb | 135 | 66.44 |
Table-Valued Function Support
One of the key features coming in the next release of Entity Framework is Table-Valued Function support. It is a very popular customer request and we have been working diligently to design a solution that we hope you find simple, yet useful. This design intends to make TVFs first-class citizens on Entity Framework, by allowing a user to map TVFs to both Entities and Complex types.
This article will explore the design of the feature in the framework, so we will focus on the metadata within the EDMX as opposed to the designer experience in Visual Studio. We will cover that experience in a later post. Other topics we will cover in the future include QueryViews and other complex Function Mapping scenarios.
With that said, here are the specific areas we will cover now:
· A basic overview of TVFs; pros and cons vs. Stored Procedures and Views
· How to call a TVF Directly
· Mapping a TVF to a Collection of Complex type
· Mapping a TVF to a Collection of Entity type and performing CRUD on the Entity
We’d love to hear your thoughts, so please feel free to comment and make suggestions about any part of this design.
What Are TVFs?
TVFs are User Defined Functions (UDFs) which live in the target database and whose return type is a table. UDFs are constructs made up of one or more T-SQL statements. In the context of a T-SQL query, TVFs can be used anywhere a View or a Table would be used. Although there is some overlap between TVFs, Views, and Stored Procedures, there are key advantages which make TVFs appealing in certain scenarios. Let’s look at how TVFs stack up against Views and Stored Procedures:
TVFs vs. Views
TVFs and Views are similar in that they are both composable. This means that you can use the function—or the view—anywhere within the body of a T-SQL query. Their major differences are, first, that SQL Views can only have one SELECT statement, whereas TVFs can have multiple statements as well as procedural code. This makes it possible to design more complex logic with TVFs than with Views. Additionally, TVFs can take parameters, whereas Views cannot.
TVFs vs. Stored Procedures
TVFs and stored procedures may both contain procedural code, but unlike stored procedures, TVFs can be used anywhere in a query. This allows us to both compose queries using TVFs and filter the result set of a TVF. One advantage of stored procedures over TVFs is that stored procedures are capable of returning multiple result sets.
Background: TVF declaration and usage in SQL
TVFs allow you to write complex statements and queries, all in the same place. In this post we will use relatively simple TVFs in order to keep complexity low. Please read this article to learn more about TVFs in SQL.
Throughout the post we will use these two TVFs to showcase functionality:
· GetCategories() returns all of the entries in the Categories table.
· GetDetailsForOrder(int) returns the Order Details for a given order for Id equal to Oid.
Typical usage of a TVF in T-SQL as follows:
This simple statement returns the category ID and Category Name from our TVF.
ProductID Quantity
----------- --------
11 12
42 10
72 5
Note that we were able to call the TVF in the FROM clause of our T-SQL query, as we would a table. Also note that we were able to pass in parameters, and that the result of the query was a table. This combination of factors, as well as the possibility to have procedural code within your function, is what makes TVFs appealing.
Why Should You Use TVFs in EF?
If you already use TVFs, the advantages of having EF support are obvious: You will now be able to use your TVFs as the source for materializing entity types and complex types via queries in EF – giving you the ability to use LINQ and Entity SQL against them. If you don’t already use TVFs, think about the potential we get from creating Entity or Complex type that is backed by a function instead of an entity. TVF support enables interesting scenarios such as Full-Text search since in SQL, it is implemented using TVFs.
Using TVFs in Entity Framework
Now that we’ve established what a TVF is, let’s see what artifacts we need in order to use one in an EF app:
· Metadata describing the store function and its return type.
· A function stub is required to call the function from a LINQ query. The stub is not required for Entity SQL queries.
These two items are all we need if we want to call the TVF directly in a LINQ or Entity SQL query. However, to truly take advantage TVFs in EF (reusability, change tracking, CUD), we also need to describe the mapping of the function to a Collection of Entity Type or Collection of Complex Type.
TVFs as Functions in SSDL returning RowType
Storage Layer
In order to make the TVF visible to Entity Framework, we must declare the store function in the storage layer (SSDL). We must specify the function name, whether or not it is composable, and the schema it belongs to. Up until version 4 of EF, the Function node was only capable of returning a scalar. Our new design required us to make two changes to this node: First, we can now set IsComposable to true, and therefore we are able to compose functions. Second, the return type is no longer a property of Function, but instead a child node in which we can describe the rich return types produced by TVFs.
Here is how we declare the store function called GetCategories in our SSDL:
Here we specify the ReturnType of the Function. In this case it will be a collection of RowTypes.
Object Layer
We need a function stub to refer to the store function from a LINQ query. The result of calling the function stub is a set of unstructured rows. See this design blog to learn more about function stubs. Here is what the stub will look like:
This stub will usually reside within your strongly typed ObjectContext class. Here are a few things to take note of:
· The stub returns a collection of DbDataRecord. These records aren’t richly typed and therefore only provide us with limited functionality.
· The EdmFunction attribute is the store’s namespace since we are calling a store function.
· Our function stub contains a meaningful body, as opposed to an exception (see here for an example). This ‘bootstrapping’ allows us to call the function in the FROM clause of our LINQ query. Here is exactly how we would call our TVF:
The stub is not required when using Entity SQL for our queries. Here is how to call the same TVF in Entity SQL:
The functionality above is useful, but only to a limited extent since unstructured data records are read only.
Mapping TVF to Complex Types and Entity Types
Function Mapping is a new feature which allows us to map the TVF’s results to a collection of Complex Type as well as a collection of Entity Type. By mapping to an Entity Type, we gain full CRUD functionality against our entities. The first step is to specify the function mapping in the mapping layer.
Result Type Mapping
Below we map a function in the conceptual layer to a function in the storage layer with an explicit return type mapping. Explicit mapping is supported for conceptual functions returning collection of Complex Type or a collection of Entity Type. Using explicit mapping, we describe how each property in the conceptual function will map to a property in the store function. We could use implicit mapping, but only for conceptual functions returning a scalar or a collection of Rowtype with primitive properties.
Collection of Complex Type
A TVF’s result set can map to a collection Complex Type. This is the default behavior when using Model First or EDMGen. Let’s explore this mapping using GetDetailsForOrder:
Storage Layer
Mapping Layer
To tie the function to a collection of Complex Types, we need to create a mapping between our store function and a conceptual function. We do that in the following way:
The explicit mapping above describes how to map the columns returned by the TVF to our Complex Type’s properties. It also describes the parameters. In this iteration we will only support parameters of Primitive type.
Conceptual Layer
Finally we need a conceptual function whose return type is a collection of Complex Types. The Complex type and the function look like the following:
In the code above we declared a complex type then we created a function which returns a collection of such type. EDMGen uses “<FunctionMame>_result” as the Complex Type’s name by default when generating metadata.
Object Layer
Once these are in place we can use call TVF using Entity SQL. However, we need a new function stub to use the TVF in a LINQ query:
The noteworthy differences from our first stub are that this one returns a collection of Complex Type, rather than a collection of unstructured records. Also, note that the first parameter in the EdmFunction attribute is the conceptual function, as opposed to the store function.
Usage
Let’s have a look at the basic usage of our function in LINQ and Entity SQL.
Both samples do the same. They call GetDetailsForOrder with an OrderId of 10248 and then iterate over the result.
Collection of Entity Type
We can also make our TVF return entities. We get all of the functionality we would expect from entities, such as reading, writing, and navigation provided by using NavigationProperties. EDMGen does not map to Entities by default, but we intend to provide tooling support to create such mapping without having to edit the EDMX.
Storage Layer
The store function definition remains the same as described above.
Mapping Layer
Now we need to describe the mapping between the store function and the conceptual function.
This mapping describes the TVF’s parameters and maps the function’s result to a collection of Entity types named OrderDetails. Each ScalarProperty node has two properties, Name and ColumnName. Name refers to the EntityType and ColumnName refers to the Store function. Function Mapping supports Table-Per-Hierarchy inheritance, much like in FunctionImportMapping. This topic will be covered in a later post.
Conceptual Layer
When you map a function to a collection of Entity types, you get the following in the CSDL:
This metadata is similar to our previous example. However, when mapping to Entity types, we must list two additional properties in our Function node: an EntityContainer and an EntitySet. These two values must refer to existing artifacts in the conceptual layer.
Object Layer
Here is our function stub for a TVF’s result set mapped to a collection of Entity Types:
Usage
With our mapping in place, we can begin using our Entities in the usual fashion. In the following example we will call our TVF and do some simple update to the resulting Entities:
In this example we get the products in Order #10248 with a quantity greater than 1. Then we change each quantity to 1. The important thing to note about this scenario is that we were able to query for a specific set of order details –those with a quantity greater than 1—using a TVF. Then we edited the resulting entities to which the TVFs result set was mapped.
Wrap-Up
In this article we have covered:
· Background on TVFs in SQL
· Calling a TVF directly from a LINQ or Entity SQL query
· Metadata for mapping a collection of Complex Type to a TVF, and subsequent usage
· Metadata for mapping a collection of Entity Type to a TVF, and subsequent usage including CUD
TVF support will be a key component of Entity Framework’s next release. Our goal is to provider first-class support for TVFs by allowing users to map the function’s result set to Entity types and Complex types. We look forward to getting your feedback, so feel free to make any comments or ask questions about this design.
Pedro Ardila
Program Manager
ADO.Net Entity Framework Team | https://docs.microsoft.com/en-us/archive/blogs/efdesign/table-valued-function-support | CC-MAIN-2021-49 | refinedweb | 2,054 | 60.04 |
.NET Structures: The Size
Description
To represent the size of something, the System.Drawing
namespace defines the Size structure that is equipped with two main properties.
There are four characteristics that define a Size value: its
location and its dimensions. A Size value must have a starting
point (X, Y) just as the Point object was illustrated earlier. The Width is the distance from the left to the right borders of a Size value. The
Height property represents the distance from the top to the bottom borders of
a Size value:
Based on this, to create a Size object, if you know only its
location (X and Y), you can use the following constructor:
Public Sub New (pt As Point)
After declaring a variable with this constructor, you
can access its Width and Height properties to complete the
definition of the Size object. If you already have the location of
a Size object by other means, you may not be interested in (re)defining
its location. In this case, you may only want to specify the dimensions of
the variable. To do this, you can use the following constructor:
Public Sub New(width As Integer, height As Integer)
Besides Size, the System.Drawing
namespace also provides the SizeF
structure. It uses the same properties as Size except that its members float
values. | http://functionx.com/vb/structures/size.htm | CC-MAIN-2018-51 | refinedweb | 222 | 59.84 |
.
I’m looking at that, and I think it is just a really bad example… It appears to add no value beyond clarifying just the naming convention. After all, why would you have multiple versions of ISessionChannel created for a specific type that supports ISession? I just don’t get it, and I’m sure that is the root of your anger. So I side with you, and agree that certain things just aren’t right in the world.
To note, if you have a struct that you are stringing the interface from, then there is a storage bonus by storing that structure in unboxed form on whatever class supports ISessionChannel. I don’t know if it is worth the extra constraints and adding generics… Damn you! Now I have to go find this stupid API and figure out what in the hell it does just to clarify in my own mind why in the hell they used it as an example 😉
Red flags were definitely raised when I first saw the type constraint "feature" of generics. I guess the use case is where you need to constrain a type and do operations on that type polymorphically within your class, but want to avoid casting of the specific type when implementing that class. However, I’m not convinced that this is a valid approach.
Polymorphism is the ability of an object to assume a more abstract form. Generics do not provide quite this capability. For instance:
LionPen can be cast to AnimalPen…
…but Pen<Lion> cannot be cast to Pen<Animal>.
In the latter case, if you wanted a *type-safe* way of referring to Pen<Lion>, Pen<Elephant>, or Pen<Penguin> using the same variable, you’d have to declare an abstract Pen type, and have Pen<Animal> derive from it:
public abstract class Pen
{
public abstract Animal Animal {get;}
}
public class Pen<Animal>: Pen
where Animal: Animal
{
…
}
In other words, you’d have to fall back to polymorphism, even if you limit the type parameter.
Generics solve a different set of problems than polymorphism does. It addresses the performance defects of using value types with collections, and it dramatically reduces the amount of code required to create classes that are on the *same level of abstraction*.
Polymorphism targets a different problem–that of facilitating the interaction of classes on different levels of abstraction.
They complement each other.
The parameter typing can be a big benefit because it gives you a lowest-common denominator when accessing objects of that type. You can then call methods/access properties on that generic parameter w/o casting.
I have a common base class used by several generic classes, and i’m able to assume that the parameters of type ‘T’ support this common denominator of methods/properties. | https://blogs.msdn.microsoft.com/scottdensmore/2004/11/05/generics/ | CC-MAIN-2017-39 | refinedweb | 465 | 57.4 |
TL;DR: if you use redis-namespace and you use
send,
Kernel#exec may get called. Please upgrade to 1.0.4, 1.1.1, 1.2.2, or 1.3.1 immediately.
Link to the fix:
Redis has an EXEC command. We handle commands through
method_missing.
This works great, normally:
r = Redis::Namespace.new("foo") r.exec # => error, not in a transaction, whatever
Here's the problem:
Kernel#exec. Since this is on every object, when
you use
#send, it skips the normal visibility, and calls the private
but defined
Kernel#exec rather than the
method_missing verison:
r = Redis::Namespace.new("foo") r.send(:exec, "ls") # => prints out your current directory
We fix this by not proxying
exec through
method_missing.
You are only vulnerable if you do the always-dangerous 'send random
input to an object through
send.' And you probably don't. A cursory
search through GitHub didn't find anything that looked vulnerable.
However, if you write code that wraps or proxies Redis in some way, you may do something like this.
The official Redis gem does not use
method_missing, so it should not
have any issues:
I plan on removing the
method_missing implementation in a further
patch, but since this is an immediate issue, I wanted to make minimal
changes.
Testing this is hard,
#exec replaces the current running process. I
have verified this fix by hand, but writing an automated test seems
difficult.
:heart::cry: | http://blog.steveklabnik.com/posts/2013-08-03-redis-namespace-1-3-1--security-release | CC-MAIN-2018-47 | refinedweb | 240 | 57.98 |
«
February 2005 |
»
Main
«
| April 2005
»
Thursday 31 March 2005
As I've mentioned, I've taken over responsibility for a body of C# code.
The layout code is filled with stuff like this:
this.Size = new Size(this.Size.Width, this.widgetsLabel.Location.Y + this.widgetsLabel.Size.Height);
To paraphrase Tevye, would it have spoiled some vast eternal plan to write this instead?:
this.Height = this.widgetsLabel.Bottom;
I spent quite some time today applying shrinking transformations:
x.Size.Height --> x.Heightx.Location.Y --> x.Topx.Top + x.Height --> x.Bottomx.Size = new Size(x.Width, y); --> x.Height = y;x.Location = new Point(x.Location.X, y); --> x.Top = y;
Believe me, it's much more readable afterwards!
Of course, I've a sneaking suspicion that a lot of this layout
code could just be chucked by setting proper constraints in the forms designer!
To quote another movie character, I can't think about that today, I'll think about that tomorrow.
I've slightly edited this post to remove asides about developers that
were distracting from my point. Reactions from readers about those comments have also been
removed.
Tuesday 29 March 2005
Emily Murphy has a pottery blog.
Actually, if you look at the domain name, she has the pottery blog.
Ian Bicking asked for help Googlebombing, so here it is.
Truth be told, I'm going to be asking for some Googlebomb help in the
not-too-distant future, so I'm trying to store up some karma points.
Cullen O'Neil wrote to tell me that he liked
Cog enough to re-implement it in
Ruby.
The result is Argent.
Now you can use Ruby for code generation:
// This is my C++ file..../*[[$argent ['DoSomething', 'DoAnotherThing', 'DoLastThing'].each do |fn| $argent.outl("void #{fn}();") end $]]*///[[$end$]]...
Reading the Argent code was an interesting experience: I don't really know Ruby,
but I'm familiar with how Cog is implemented, so I "knew" the code without knowing
the language. It helped me understand more about Ruby.
Also cool: Cullen uses Argent to manage its own Makefile. He generates test classes
and Makefile entries for them using Argent itself.
Monday 28 March 2005
Continuing my education in C#, I don't understand what happens to exceptions
in event handlers. For the most part, when I register an event handler for a UI event
(like button click), if the handler throws an exception, I get a detailed dialog box
showing what happened. But for some events, the exception is eaten silently.
One of my strongest passions when coding is to know what is going on under the covers,
and to be absolutely sure that error conditions are at the very least visible.
I'm starting to get the hang of events and delegates. It isn't yet another language
for me, still a foreign language. But I figured there ought to be a way to write
a delegate wrapper, so that I could take an event registration like this:
button1.Click += new EventHandler(button1_Click);
and using some yet-to-be-written class, make it look like this:
button1.Click += new WrappedHandler(new EventHandler(button1_Click));
where WrappedHandler would call the event handler passed into it, but inside a try-catch
block, so that exceptions could be displayed.
I had to take a few stabs at it, and I ended up with three "new"s rather than the two
I thought I would need, but here's something that works:
public class WrappedHandler{ private EventHandler handler; public WrappedHandler(EventHandler handler) { this.handler += handler; } public void Handler(object sender, EventArgs e) { try { handler(sender, e); } catch (Exception ex) { // Our handler threw an exception. // Show it. MessageBox.Show("Exception: " + ex.ToString()); // Then re-throw it. throw; } }}
Now the event handler can be registered like this:
button1.Click += new EventHandler( new WrappedHandler( new EventHandler( button1_Click ) ).Handler );
Is this the simplest it could be? Did I miss a left turn a half mile back?
BTW: as I was making a new tiny project to experiment with this, I noticed that all
of the event handlers were nicely reporting exceptions. My real project still has
exceptions which aren't being reported. I'll have to track down whether it's because
they are different handlers, or because of the third-party controls we're using,
or even because my predecessor is eating exceptions somewhere. Fun fun.
Friday 25 March 2005
The coolest thing to happen as a result of our Myst cake is that
Robyn Miller
sent me an email about it. Robyn (along with his brother Rand) created the
Myst world (including the games) which inspired the cake. In his email,
he pronounced the cake "entirely cool".
My son and I were thrilled and flabbergasted. It was as if I'd mentioned
Star Wars in a blog posting and got an email out of the blue from George Lucas about it.
I wrote back to Robyn about my son's interest in his work, and in video games,
movies and their intersection in general, and asked Robyn if he had any
advice for a budding auteur. Robyn wrote back:DP.S. You can visit me at me at my new, online-university (I've accredited myself, by the way):D
P.S. You can visit me at me at my new, online-university (I've accredited myself, by the way):
Entirely cool.
Thursday 24 March 2005
A thread on comp.lang.python asking about text-to-speech libraries turned into a
call for Python limericks.
The discussion meandered on for a while (let's just say there's a reason most of these people
are engineers rather than poets), until Michael Spencer posted this piece of brilliance:P.S. I know 'three' doesn't rhyme.
P.S. I know 'three' doesn't rhyme.
Not only is the Python code itself in the form of a limerick, but if you run it,
it prints this:
DA-DA-DUM DA-DA-DUM DA-DA-DUMDA-DA-DUM DA-DA-DUM DA-DA-DUMDA-DA-DUM DA-DA-DUMDA-DA-DUM DA-DA-DUMDA-DA-DUM DA-DA-DUM DA-DA-DUM
Genius!
Monday night it occurred to me that my Myst birthday cake would appeal to
readers of Boing Boing,
so I filled in their handy "suggest a site" form. Three hours later, it appeared on the site:
Myst island birthday cake.
Something interesting always happens when Boing Boing links to me.
The last time was in 2003
(Bizcard origami),
and that resulted in my page becoming a
top Google hit,
which lead to ad revenue, which lead
to a New York Times mention, and so on.
So I was interested to see what would happen this time.
It's only been two days, but already, stuff has happened.
For one thing, my visitor traffic doubled (to about 6000 visits per day).
The first day, as expected, it all came from Boing Boing.
But the second day, I was surprised to get even more hits from a site I'd never heard of:
Blues News, a compendium of video game news.
In fact, there were so many hits (3000 compared to Boing Boing's 2000),
I assumed they had linked directly to an image
(so that my hits were a reflection of their page views).
But no, they had a simple text link to me, buried in a long page of text and links.
They must have a huge readership.
The Boing Boing entry is now in the top ten results in a Google search for
birthday cake,
and of course, the first for
Myst birthday cake.
That last search reveals a
previous Myst-themed cake,
along with other geeky cake goodies.
Tuesday 22 March 2005
I was fiddling at work with a velcro cable tie, and I ended up making a snail:
It reminded me of something I saw years ago:
Sculptures in my Geekosphere,
a collection of animals made from the type of junk found lying around any office.
The blog it came from was a favorite of mine, Jimwich,
but Jim Leftwich stopped writing it over two years ago.
My velcro snail inspired me to go look up Jimwich again, and hurray!,
Jim is writing again! His blog is eclectic, with unusual finds in architecture,
vehicles, and art. Welcome Jim back, and let's hope he doesn't take another long break.
Sunday 20 March 2005
Ain't It Cool News describes a tour of Pixar.
The workspaces are amazing! I wonder if the novelty wears off and becomes cloying after a while,
or if you're in the business of making kids movies you're OK with it.
Saturday 19 March 2005
March madness in our house involves two birthdays, each with a themed cake.
The first, for our now-13-year-old, was based on the
Myst island:
»
read more of: Myst island birthday cake... (4 paragraphs)
A Cog email correspondent asked a question about using Cog with
SCons, so I read up on it.
It's very interesting: A "make" replacement for building software,
but uses full Python scripts instead of declarative Makefiles.
But don't worry: most build tasks are handled in declarative style.
For example, building hello.exe from hello.c is simply:
Program('hello.c')
Another interesting feature is that SCons determines the need for
building using an MD5 checksum of the file, so the need to build is
determined more accurately. For example, a C file may change, but
if the .o file it produces hasn't (because the C file only changed a comment),
then there's no need to execute the link step.
BTW: the Cog question had to do with using Cog in an SCons environment,
where the same file is both the input and output for Cog, and how to get
SCons to do the right thing. Anyone know?
Friday 18 March 2005
I.
»
read more of: Opening a file with an unknown extension... (9 paragraphs)
Thursday 17 March 2005
Here's a story about six new faces that Microsoft will be shipping in 2006:
The Next Big Thing in Online Type.
I'm way disappointed. I've got a pretty discerning type eye, and these don't look that
different than the faces Microsoft already ships, Trebuchet, Georgia, and Lucida Console.
They don't even look different from each other. And the names of these "new" faces merely
underscore their carbon-copy nature:
Calibri, Cambria, Candara, Consolas, Constantia, and Corbel.
Couldn't they at least have given us something to replace the awful
Comic Sans?
In any case, get used to them. If Microsoft ships them, we'll be seeing a lot of them.
OK,.
This.
Wednesday 16 March 2005
I haven't tried it, but SQLFairy
looks useful. It's a set.
What is it about Mario? He keeps cropping up as pixelated low-tech crafts
projects. So far I've seen a
quilt,
and two different renditions in Post-Its: a single sprite,
and a four-floor extravaganza.
As I have mentioned here in the past, my youngest son is a drawing fiend.
We wonder sometimes how best to encourage his developing skill.
We figure one way is to expose him to visual excellence where we can find it.
That's why I was pleased to find Drawn!,
"a collaborative weblog for illustrators, artists, cartoonists, and anyone who likes to draw."
The rest of my family (me included) have an appreciation for graphic works
as well, so I expect we'll all find things of interest there.
The original pointer to Drawn! was to Spamusement
("Poorly-drawn cartoons inspired by actual spam subject lines!"), but in keeping
with the kid-art theme, I also enjoyed
Lizette Greco, who make physical artifacts
(toys, bags, and so on) from drawings by her young children.
Another interest my kids share is how movies are made, and a recent favorite movie is
The Iron Giant,
so we all enjoyed the post about
Whatever happened to.. Mark Whiting,
the art director for the movie, complete with links to concept art for the animation. Cool!
Monday 14 March 2005
RoboType is an online doo-dad for making pictures out of
type. You choose typeface and character, then drag and stretch it where you want, then get
some more until you have a picture. Here are two good ones I found in the gallery:
Most of the pictures are along these lines, though there are quite a few R- or X-rated attempts
as well!
Today!
Sund.
The NYPL Digital Gallery
is the New York Public Library's large searchable collection of scanned images available
for free use:.
If you want historic or old-fashioned images, this is the place to look.
I found this forgotten piece of western civilization:
Saturday 12 March 2005
The.
Friday 11 March 2005
The Ultimate Boot CD
is a single CD crammed full of an astonishing array of tools for diagnosing, testing,
installing, managing, and otherwise administering all aspects of your computer.
I haven't tried it (and hope to never have to), but it sure looks impressive.!
Thursday 10 March 2005
Chris Gavalier's
Who's On First?
is a video store dialogue in the style of Abbot and Costello:
CUSTOMER: When is this one due back?CASHIER: The day after tomorrow.CUSTOMER: Yeah, when's it due back?CASHIER: The day after tomorrow.CUSTOMER: Yes. The Day After Tomorrow.CASHIER: Right.CUSTOMER: Right. When's it due back?CASHIER: The day after tomorrow.
CUSTOMER: When is this one due back?
CASHIER: The day after tomorrow.
CUSTOMER: Yeah, when's it due back?
CUSTOMER: Yes. The Day After Tomorrow.
CASHIER: Right.
CUSTOMER: Right. When's it due back?
Wednesday 9 March 2005
The Lord of The Rings, translated into l33t5p34k:
F3ll0wsh1p of teh R1ng (scroll down a bit)
and
Teh Tw0 T0werz.
Not mentioned by most other linkers: The first link starts with a hilarious list of "survival tips"
for watching the movies in theaters:
7. Finish off every one of Elrond's lines with "Mr. Anderson."16. Every time someone kills an Orc, yell: "That's what I'm Tolkien about!"
See how long it takes before you get kicked out of the theatre.
7. Finish off every one of Elrond's lines with "Mr. Anderson."
16. Every time someone kills an Orc, yell: "That's what I'm Tolkien about!"
See how long it takes before you get kicked out of the theatre.
LOL!
When I link to Amazon (for example, when writing about
books), I do it with an
Amazon Associates link.
Amazon Associates is an affiliate program: when you follow my link, I get a small percentage
of the money you spend at Amazon. Your price remains the same, so it's a win-win situation
for both of us.
I'm not going to get rich off of it (I've earned a grand total of $25.31 in the two years
I've been a member), but money is money, am I right?
I've added an Amazon link to the sidebar on the left.
If you want to toss a few pennies my way, the next time you
are heading to Amazon, use
my Amazon link.
Thanks!.
T.
»
read more of: Properties vs. public members... (11 paragraphs)
Monday 7 March 2005
Today brings us two video clips of animals getting around in ways they shouldn't.
This skiing ostrich
has to be fake, though extremely well done (thanks, Bob).
But the dog walking on his two front legs
seems genuine, if not inexplicable. Maybe the Japanese captions provide a clue?
Today is this blog's three-year birthday. It all started way back in 2002 with a post about
my first job ever.
I've had many cool interactions because of this blog, of a greater number and a wider diversity
than I would have guessed when I started it. Thanks everyone!
Sund!
I should have known it would come to this:
Charles Smith conducts a serious discussion about
Who owns blog comments.
As in, when you post a comment on my blog, do I own the copyright to it, or do you?
Is anyone really worried about this kind of thing? Other than IP lawyers that is?
What's next? Who owns the copyright to cocktail party chatter?
I'm not belittling the value of a blog comment, but please: is there no simple good
will left in the world?
To complicate things further, a comment on the posting claims that while the
individual comments are owned by their authors, the compilation
of comments onto the posting are owned by the blogger. Oy!
Charles actually suggests that bloggers use a
them a license to display people's comments:.
I'm starting to wonder about the irony of the name of Charles' blog:
Reasonable Man.
Saturday 5 March 2005
Yesterday, driving to work, my car's odometer read 111111. It seemed like some kind of milestone.
That's all.
Wired magazine has a good piece about wikipedia:
The Book Stops Here.
It covers a lot of familiar ground: the history of encyclopedias, old media vs. wikis,
is it reliable, what can be done about vandals and so on.
Here's something revealing:
"You can create life in there," says Wikiped. ...
Today, the Lawrie entry has grown from two sentences to several thorough paragraphs,
a dozen photos, and a list of references.
I never would have thought of that: find out about a topic by creating a stub
Wikipedia article about it, and let the fanatic Wikipedians fill it in.
Very cool.
Portrait Illustration Maker
is an another online gizmo to create a picture of yourself. You pick from dozens of pieces to put
together the perfect 96×96 pixel icon of you.
The choices are manga-influenced, and lean heavily toward youthful Japanese tastes (naturally).
Here's me (or as close as I could get in 20 minutes of trying):
Actually, this looks more like Steven Spielberg than it does like me.ursday 3 March 2005
I've taken over responsibility at work for a UI written in C#.
This is challenging on a number of levels: I haven't done a lot of UI,
I haven't done a lot of C#, and the previous owner was (shall we say)
not the most disciplined developer.
Debugging UI code is a pain because if your debugger obscures the
UI, then exposing the UI causes window messages, which change the
behavior of the code, or trip more breakpoints, and so on.
So I'm using printf-style debugging: printed messages in key points
to understand what's going on. Here's some tips on how to do it.
»
read more of: C# and OutputDebugString... (14 paragraphs)
While in New York City a few weeks back, we walked past the
Guggenheim Museum.
Outside on the sidewalk, a young man had set up a table with scupltures on it.
Looking closer, they had all been fashioned out of forks! In fact, the man
had before him a stack of forks, and in his hand, a needle-nose pliers, and
was busy making more fork scupltures.
His gallery at fork-art.com doesn't
do the sculptures justice: they struck just the right balance between abstract
and figurative, and each had real flair.
I've done SQL work for a number of years, but it's usually been pretty plain vanilla
relational data: I haven't had to venture too far into the truly wild and wooly SQL
hacks. For example, I'd never heard of a
numbers table.
It's a table with one integer column, and a row for each integer in a range
(for example, 1 through 10,000). The table gets used for
all kinds of unusual queries.
But is it a good idea? A quick look at some of these queries gives me the impression
that they'd be inefficient:
DECLARE @csv VARCHAR(255)SET @csv = '1,3,5,7,9,14,36,395'SELECT n FROM numbers WHERE CHARINDEX ( ','+CONVERT(VARCHAR(12),n)+',', ','+@csv+',' ) > 0 ORDER BY n
This will examine each row in the numbers table, and check if the number is in the
string. This is bone-headed.
In fact, if that exact algorithm were coded in a procedural language, it would
qualify as a Daily WTF.
Sometimes the pure relational model nudges you into odd hacks like this, and sometimes
it is hard to know the best way to slice a problem. For example, if the alternative
to a numbers table is to write a loop in the client, then shuttling all the data to the
client may be a bottleneck, and the numbers query may be better in any case.
As with all performance issues, you can take a guess, but the only way to really
know is to measure a real system.
BTW: XSLT is another programming model that leads to these sorts of tricks.
Both XSLT and SQL give you a fundamentally declarative style of programming.
But developers think procedurally. The conceptual mismatch leads to difficulties
expressing yourself, and then off-the-wall ideas like a numbers table to make more
things possible.
T:
»
read more of: Doodle-O drawings... (4 paragraphs)
2005,
Ned Batchelder | http://nedbatchelder.com/blog/200503.html | crawl-002 | refinedweb | 3,550 | 72.97 |
<ac:macro ac:<ac:plain-text-body><![CDATA[
Framework: Zend_Form Component Proposal
Table of Contents
1. Overview
2. References
3. Component Requirements, Constraints, and Acceptance Criteria
_Form is a component to simplify the process of form validation, data filtering, and data storage. It will also allow forms to consist of multiple pages and maintain the data across those pages.
- This component will validate form input.
- This component will filter form input.
- This component will support Zend_Filter filters.
- This component will support Zend_Validate validations.
- This component will support custom filters and validations.
- This component will allow forms to span multiple pages.
- This component will manage temporary data storage of multiple pages through storage containers (Zend_Session).
- This component will allow instances of forms, fields, and pages to be reused within other forms.
- This component will not provide helpers for modifying the view.
4. Dependencies on Other Framework Components
- Zend_Exception
- Zend_Session
- Zend_Validate_*
- Zend_Filter_*
5. Theory of Operation
- The programmer creates an instance of Zend_Form.
- Pages are added to the instance of Zend_Form (optional). If no pages are added, a default page is used for a single-page form.
- Fields are added to the Zend_Form_Page instance returned from adding a new page, or directly to Zend_Form if it is a single-page form.
- Validators and Filters are added to the Zend_Form_Field instance returned from adding a field.
- The data source and other configuration data is set on the Zend_Form instance.
- Validation and data filtering occurs in the order they are added. Methods are available to modify the ordering of these actions. Data validation occurs only for the fields of the submitted page, if part of a multi-page form.
- If valid and is a single-page form, the programmer saves the filtered data. If it is a multi-page form, the form moves on to the next page, otherwise the programmer saves the data.
- If invalid, the user is directed back to the form page and is shown the errors he or she must correct to move on.
The added pages, fields, and validator/filters are added to their own contextual flows. A flow is just a chain of items which occur in a particular order. Pages are seen in order, fields are validating in a particular order, and the validators/filters are run in a particular order. The reason a flow needs to be identified is for branching and reusability. Flows can contain conditionals so that forms may branch to different pages under the circumstance a certain option is set, for example. Additionally, field validation can contain conditionals also, such as certain validations only being run if a condition is met, such as another field being valid. Visual examples of this are available in the use cases.: Proposal
- Milestone 2: Implementing single-page form with fields, validators, and filters.
- Milestone 3: Implementing conditionals to validators/filters.
- Milestone 4: Implementing multi-page form with Zend_Session temporary storage.
- Milestone 5: Implementing page conditionals
- Milestone 6: Unit Tests
- Milestone 7: Done
7. Class Index
- Zend_Form
- Zend_Form_Element (abstract)
- Zend_Form_Element_Field
- Zend_Form_Element_Page
- Zend_Form_Element_Branch
- Zend_Form_Element_Exception
- Zend_Form_Flow
- Zend_Form_Flow_Conditional (abstract)
- Zend_Form_Flow_Conditional_Valid
- Zend_Form_Flow_Conditional_Value
- Zend_Form_Flow_Conditional_Exception
- Zend_Form_Storage (abstract)
- Zend_Form_Storage_Session
- Zend_Form_Storage_Exception
- Zend_Form_Exception
8. Use Cases
A basic single-page form consisting of two fields with validations and filters for each. Because the filters and validators for the password field would be the same as the username field, I use the getFlow() method call on the field instance to copy the flow over to the password, saving lines. This is just one example of the usefulness of a "flow." Also, added fields can be accessed like properties of the Zend_Form object, as username is done in this example.
Assuming we are continuing on to UC-01, this use case shows the addition of a new field password_confirmation. The change here is that I only want to validate that this field matches the password field if the password field itself is valid, so I use a conditional flow. Remember that validators/filters are run in the order they are added, so the flow we copy from password will run as normal, but the matches validator will not run unless password is valid.
Assuming we are continuing on to UC-01, this use case adds a new field last_name and its various validators and filters using dynamic methods. Dynamic methods are an easy way to control the order of your pages, fields, validators, and filters.
This use case shows how to create a multi-page form, and how to handle view rendering for it. It also shows that pages may be accessed like properties of a Zend_Form object, just like fields.
This use case showcases the use of page branching with conditionals with a multi-page form. Some forms' pages only need to be shown under certain conditions, and using conditionals and branching, this is possible.
This use case shows how easy it is to assign error messages to your view, and also how easy it is to create custom error messages for your validations. This example is based on a multi-page form, but it would be the same for a single page. The '%s' when adding custom error messages is a placeholder for the field name.
9. Class Skeletons
These are just the skeletons of the main classes. For complete class information, download the package or browse the subversion repository at:
14 Commentscomments.show.hide
Aug 30, 2007
Micha? Taszycki
<p>I like this proposal much better than other ones. Flows and branches are great ideas. <br />
It will give more flexibility than other two proposals since it focuses only on validation of received data and transitions between form components. Someone who wants to pass options to select field for example (or any other information to any other field type) could easily derive new class from Zend_Form_Element_Field.<br />
Keep up good work, I can't wait to see it working.</p>
Aug 31, 2007
Mitchell Hashimoto
<p>I've created a SourceForge project for this component until it moves up the proposal chain (if it does). I've also finished coding a basic version 0.1 of this component. All the features mentioned above are present and working, and it has a complete test suite done also. There is also a user guide up for instructions on using the component.</p>
<p>Zend_Form Homepage: <a class="external-link" href=""></a><br />
SF.net Project Page: <a class="external-link" href=""></a><br />
Browse Subversion: <a class="external-link" href=""></a></p>
<p>I hope this will get more people interested in this component! I truly believe this is a useful component for most web applications and therefore should be included in the Zend Framework.</p>
Sep 04, 2007
Laurent Melmoux
<p>What about adding some method like Zend_Form::setValidators($validators)and Zend_Form::getValidators()</p>
<p>Where $validators is an array</p>
<ac:macro ac:<ac:parameter ac:php</ac:parameter><ac:plain-text-body><![CDATA[
$validators = arrays ('username' => 'Alnum',
'username' => array('StringLength', 5, 12),
'password' => 'Alnum'
);
]]></ac:plain-text-body></ac:macro>
<p>So with Zend_Form::getValidators() you could pass validations rules to a wiew helper responsible for the client side validation.</p>
<p>And with Zend_Form::setValidators($validators) validations rules could be defined in a config file.</p>
<p>Best the configuration file could contain validation rules and information about how to layout the form (name, field type, label,... ) which could be handle by a form wiew helper. </p>
Sep 04, 2007
Mitchell Hashimoto
<p>This is a good idea. A global set validators via array on a page can be very useful, like you said, with config files. I don't quite follow you on the form view helpers since Zend_Form will not provide any view helpers (as is planned).</p>
<p>Furthermore, it was suggested to me that I add support for filter and validator "namespaces" so that filters and validators other than those in the Zend framework can be used. An example would be:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
$form = new Zend_Form();
$form->addValidatorNamespace('Zend_Validate');
$form->addValidatorNamespace('My_Validate');
]]></ac:plain-text-body></ac:macro>
<p>Although Zend_Validate would be used by default, it just shows how you could add your own namespaces.</p>
Sep 05, 2007
Laurent Melmoux
<blockquote>
<p>I don't quite follow you on the form view helpers since Zend_Form will not provide any view helpers (as is planned).</p></blockquote>
<p>I just meant it could be implement.</p>
Sep 05, 2007
Laurent Melmoux
<p>Your solution could be simplified by delegation all the validation and filtering stuff to a Zend_Input_Filter instance. </p>
<p 07, 2007
Mitchell Hashimoto
<p>I admit I haven't looked at ZFI in quite awhile, slightly forgetting what features it was composed of. Now that I have reacquainted myself with the ZFI component, I believe that this would probably be the least redundant way of implementing the validation and filter chains. It even has the namespace idea (which I thought was unique). </p>
<p>The only problem is conditionals with a fields validation and filtering. However, I have an idea which could overcome this, by grouping filters and validators up to a conditional, then having the conditional object, then another ZFI instance below that holding the validators and filters.</p>
<p>I will look further into this, thank you for the thought.</p>
Sep 09, 2007
Mitchell Hashimoto
<p>The problem, after looking through ZFI, is that it doesn't support on-the-fly adding of filters or validators. Comments? I'd really like to implement it but one of the key features of Zend_Form is the fact that a flow is run in order, and it seems that with ZFI I can't control this.</p>
Oct 21, 2007
Micha? Taszycki
<p>I see couple of possibilities:<br />
1. Creating ZFIs on the fly during validation. Each one for one conditional as you mentioned before. Not the most efficient way I presume.<br />
2. Open ticket for adding filters and validators to ZFI on the fly. This will require implementing some kind of functionality you implemented in the Flow. In this case ZFI would become too similar to your proposal. Also some people might not need this functionality and think that will unnecessarily complicate ZFI.<br />
3. Create a proposal for a class that will be only able to create filters and validators in the same way as ZFI does. This would simply require some refactoring of ZFI. This way both ZFI and your Zend_Form could proxy to this class methods responsible for creation of filters and validators.</p>
<p>3rd way in my opinion would be the best solution. I would submit proposal myself if only I had time and signed CLA. </p>
Sep 09, 2007
Mitchell Hashimoto
<p>I've released a "0.2" packaged release that fixes quite a few problems with 0.1. The biggest issue being the fact that with 0.1, the storage implementation was in place in such a way that with multi-page forms, opening them in multiple tabs (multiple instances of a form), could not be differentiated. Therefore progressing the form in one tab would corrupt the data of the other, and vice versa. I've added a new feature which forces multi-page forms to have a "__uniqueid" hidden field.</p>
<p>I've also added working demos to the release. As always you can view the latest release notes, API docs, browse SVN, etc. from the main website:</p>
<p><a class="external-link" href=""></a></p>
<p>I'm also working on refactoring the nextPage/climbPage methods because they are quite messy. And the test suite needs to be polished (there are currently 108 tests, but its not enough). I've improved the API reference quite a bit but that also still needs some work.</p>
<p>Any feedback and comments are greatly appreciated.</p>
Oct 21, 2007
Micha? Taszycki
<p>I was playing around with version 0.2 and found one annoying thing.<br />
Here is what I wanted to do:<br />
Here is an example of how we can retrieve the data in normal way.</p>
<ac:macro ac:<ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form = new Zend_form();
$form->addField('some_field')->setValue('some_value');
if ($response->isPost()) {
$form->setDataSource($response->getParams());
if ($form->isValid())
}
]]></ac:plain-text-body></ac:macro>
<p>This works fine. But let's say we want to do something with default data set for each field after adding them to a form.</p>
<ac:macro ac:<ac:default-parameter>php</ac:default-parameter><ac:plain-text-body><![CDATA[
$form = new Zend_form();
$form->addField('some_field')->setValue('some_default_value');
if ($response->isPost()) {
do some stuff
} else {
$data = $form->getData();
//do some stuff with default $data
}
]]></ac:plain-text-body></ac:macro>
<p>This time $form->getData() throws an exception due to not validated data. When we call $form->isValid() before that line we will get an exception because data source is not set. Ok but in this scenario we don't want to set any other data than this which already sits in each field. Passing empty array as data source won't work because no data will be put into $form->_data and code that tells if form was validated is checking only if $form->_data is null.</p>
<p>Here are some of my proposition how it could be resolved:<br />
A parameter could be added to any of methods $form->getData(), $form->isValid(), $form->setDataSource() telling whether or not we want to include default data from fields.<br />
In my opinion it would be best to tell $form->setDataSource() to use internal data source. Then retrieving data using $form->getData() would still require validation.</p>
Oct 22, 2007
Micha? Taszycki
<p>Another thought. I think it would be useful to allow instances of Zend_Form_Element_Field validate themselves using isValid() method just as Zend_Form allows it. Possibly Zend_Form_Element_Page would benefit from ability of validation as well.<br />
This way if you would add a 'dirty' flag to each class able to validate you would be able to validate all data only once and not validate everything again when only one field has changed. <br />
For fields this flag would be true when new value is set or flow has changed and false after validation.<br />
In pages you would need to listen for changes of the flag in child elements and update its own flag accordingly. It would also need to notify it's parent page about change.</p>
<p>This way the problem I've mentioned one comment above would be solved as well.</p>
Oct 29, 2007
Laurent Melmoux
<p>A couple more comment </p>
<p><strong>Validator and Filters</strong></p>
<p>As Micha? said the validation and filtering could be extract from Zend_Form then it could proxy to this / those class. About validation and filtering Bryce Lohr has done some interesting thing too <a class="external-link" href=""></a></p>
<p>Having filters and validators class coming from a config + an addFields() method would allow some quick form setup, but may be purist won't like it <ac:emoticon ac:</p>
<ac:macro ac:<ac:plain-text-body><![CDATA[
$form = new Zend_Form();
$form->addFields(array('username', 'password', 'firstname', 'lastname')
$form->addValidators($validators);
$form->addFilters($validators);
$form->setDataSource($_POST);
if ($form->isValid()) {
$this->_redirect('/success', array('exit' => true));
}
]]></ac:plain-text-body></ac:macro>
<p><strong>Errors messages and i18n</strong></p>
<p>It'is a bit of topic, but correct i18n support should be implement in Zend_Validate_* </p>
<p>1) the '%s' placeholder for the field name in custom error messages is useless for me : the fields name would be 'firstname' but the user will have 'prénom' in front of the form field.<br />
Bryce has a good solution for custom messages and i18n support.</p>
<p>2) Most of the time I would be happy with default message but has Zend_Validate_* is not Locale aware, I always have to use custom message which is a pain. </p>
<p>Well, I guess now we have to wait Matthew's mash up Zend_Form proposal ... Maaattheeeeeeeewwwwwwwwwww !!!!</p>
Dec 04, 2007
John Holden
<p>I'm just starting to work with the Zend Framework, and this proposal seems like a valuable, well-designed addition. However, I'm not sure what is the ideal way to display a pre-populated form displaying, for instance, values from a database. </p>
<p>I'm thinking of situations where a user might need to edit, for example, a calendar event, where the same form would be appropriate for creating new records as well as editing existing ones. Using the Zend_Controller class, I've been creating a single "edit" action, but the logic involved for populating blank/existing/submitted values is rather tedious. Does anyone have a recommendation?</p>
<p>Thanks much!<br />
John</p> | http://framework.zend.com/wiki/display/ZFPROP/Zend_Form+-+Mitchell+Hashimoto | CC-MAIN-2014-10 | refinedweb | 2,813 | 54.93 |
How to detect and avoid memory and resources leaks in .NET applications
Introduction
Recently, I've been working on a big .NET project (let's name
it project X) for which one of my duties was to track memory and resources
leaks. I was mostly looking after leaks related to the GUI, more precisely in a
Windows Forms application based on the Composite UI
Application Block (CAB).
While some of the information that I'll expose here applies directly to Windows Forms, most of the points will equally apply to any kind of .NET applications (WPF, Silverlight, ASP.NET, Windows service, console application, etc.)
I wasn't an expert in leak hunting before I had to delve into
the depths of the application to do some cleaning. The goal of the present
article is to share with you what I learned in the process. Hopefully, it will
be useful to anyone who needs to detect and fix memory and resources leaks.
We'll start by giving an overview of what leaks are, then we'll see how to detect leaks and find the leaking resources, how to solve and avoid leaks, and we'll finish with a list of helpful tools and...resources.
Leaks? Resources? What do you mean?
Memory leaks
Before going further, let's defined what I call a "memory leak". Let's simply reuse the definition found in Wikipedia. It perfectly matches what I intend to help you solve with this article:
In computer science,.
Still in Wikipedia: "Languages that provide automatic memory management, like Java, C#, VB.NET or LISP, are not immune to memory leaks."
The garbage collector recovers only memory that has become unreachable. It does not free memory that is still reachable. In .NET, this means that objects reachable by at least one reference won't be released by the garbage collector.
Handles and resources
Memory is not the only resource to keep an eye on. When your .NET application runs on Windows, it consumes a whole set of system resources. Microsoft defines three categories of system objects: user, graphics device interface (GDI), and kernel. I won't give here the complete list of objects. Let's just name important ones:
-.
You can find all the details about system objects on MSDN.
In addition to system objects, you'll encounter handles.
As stated on MSDN, applications cannot directly access object data or the
system resource that an object represents. Instead, an application must obtain
an object handle, which it can use to examine or modify the system resource.
In .NET however, this will be transparent most of the time because system objects and handles are represented directly or indirectly by .NET classes.
Unmanaged resources
Resources such as system objects are not a problem in themselves, however I cover them in this article because operating systems such as Windows have limits on the number of sockets, files, etc. that can be open simultaneously. That's why it's important that you pay attention to the quantity of system objects you application uses.
Windows has quotas for the number of User and GDI objects that a process can use at a given time. The default values are 10,000 for GDI objects and 10,000 for User objects. If you need to read the values set on your machine, you can use the following registry keys, found in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows: GDIProcessHandleQuota and USERProcessHandleQuota.
Guess what? It's not even that simple. There are other limits you can reach quickly. See my blog post about the Desktop Heap, for example.
Given that these values can be customized, you may think that a solution to break the default limits is to raise the quotas. I think that this is a bad idea for several reasons:
- Quotas exist for a reason: your application is not alone on the system and it should share the system resources with the other processes running on the machine.
- If you change them , they may be different on another one. You have to make sure that the change is done on all the machines your application will run on, which doesn't come without issues from a system administration point of view.
- The default quotas are most of the time. If you find the quotas are not enough for your application, then you probably have some cleaning to do.
How to detect leaks and find the leaking resources
The real problem with leaks is well stated in an article about leaks with GDI code:
Even a little leak can bring down the system if it occurs many times.
This is similar to what happens with leaking water. A drop of water is not a big issue. But drop by drop, a leak can become a major problem.
As I'll explain later, a single insignificant object can maintain a whole graph of heavy objects in memory.
Still in the same article, you can learn that:
There are usually three steps in leak eradication:
- Detect a leak
- Find the leaking resource
- Decide where and when the resource should be released in the source code
The most direct way to "detect" leaks is to suffer from them
You won't likely see your computer run out of memory. "Out of memory" messages are quite rare. This is because when operating systems run out of RAM, they use hard disk space to extend the memory workspace (this is called virtual memory).
What you're more likely to see happen are "out of handles" exceptions in your Windows graphical applications. The exact exception is either a System.ComponentModel.Win32Exception or a System.OutOfMemoryException with the following message: "Error creating window handle". This happens when two many resources are consumed at the same time, most likely because of objects not being released while they should.
Another thing you may see even more often is your application or the whole computer getting slower and slower. This can happen because your machine is simply getting out of resources.
Let me make a blunt assertion: most applications leaks. Most of the time it's not a problem because the issues resulting from leaks show up only if you use applications intensively and for a long period of time.
If you suspect that objects are lingering in memory while they should have been released, the first thing you need to do is to find what these objects are.
This may seem obvious, but what's not so obvious is how to find these objects.
What I suggest is that you look for unexpected and lingering high level objects or root containers with your favorite memory profiler. In project X, this can be objects such as LayoutView instances (we use the MVP pattern with CAB/SCSF). In your case, it all depends on what the root objects are.
The next step is to find why these objects are being kept in
memory while they shouldn't be. This is where debuggers and profilers really
help. They can show you how objects are linked together.
It's by looking at the incoming references to the zombie object you have identified that you'll be able to find the root cause of the problem.
You can choose to follow the the
ninja way (See SOS.dll and WinDbg in the section
about tools below).
I used the JetBrains dotTrace tool for project X and that's what I'll use in this article too. I'll tell you more about this tool later in the same Tools section.
Your goal should be to find the root reference. Don't stop at the first object you'll find, but ask yourself why this object is kept in memory.
Common memory leak causes
I wrote above that leaks are common in .NET. The good news is that there is only a small set of causes. That means that you won't have to look for a lot of cases when you'll try to solve a leak.
Let's review the usual culprits I've identified:
- Static references
- Event with missing unsubscription
- Static event with missing unsubscription
- Dispose method not invoked
- Incomplete Dispose method
In addition to these classical traps, here are other more specific problem sources:
- Windows Forms: BindingSource misused
- CAB: missing Remove call on WorkItem
The culprits I've just listed concern your applications, but you should understand that leaks can happen in other pieces of .NET code that your applications rely on. There can actually be bugs in libraries you use.
Let's take an example. In project X, a third-party visual
controls suite is used to build the GUI. One of these controls is used to
display toolbars. The way it is used is via a component that manages a list of
toolbars. This works fine, except that even though the toolbar class implements
IDisposable, the manager class never calls the Dispose method on the toolbars
it manages. This is a bug. Fortunately, a workaround is easy to find: just call
Dispose by ourselves on each toolbar. Unfortunately, this is not enough because
the toolbar class itself is buggy: it does not dispose the controls (buttons,
labels, etc.) it contains. Again, the solution is to dispose each control the
toolbar contain, but that's not so easy this time because each sub-control is
different.
Anyway, this is just a specific example. My point is that any libraries and components you use may cause leaks in your applications.
Finally, I'd like to add that saying "It's the .NET
framework that leaks!" is adopting a very bad stance that consists in
washing your hands of it. Even if it can of course happen that
.NET creates leaks by itself, it's something that remains exceptional and
that you'll encounter very rarely.
It is easy to blame .NET, but you should instead start by questioning your own code before offloading issues onto someone else...
Common memory leaks causes demonstrated
I've listed the main sources of leaks, but I don't want to stop here. I think that this article will be much more useful if I can illustrate each point with a quick example. So, let's take Visual Studio and dotTrace and walk through some sample code. I'll show at the same time how to solve or avoid each leak.
Project X is built with CAB and the MVP (Model-View-Presenter) pattern, that means that the GUI consists of workspaces, views and presenters. To keep things simple, I've decided to use a basic Windows Forms application with a set of forms. This is the same approach as the one used by Jossef Goldberg in his post about memory leaks in WPF-based applications. I'll even reuse the same examples for event handlers.
When a form is closed and disposed, we expect it to be released from memory, right? What I'll show below is how the causes I listed above prevent the forms to be released.
Here is the main form of the sample application I've created:
This main form can open different child forms; each can cause a separate memory leak.
You'll find the source code of this sample application at the end of this article, in the Resources section.
Static references
Let's get rid of the obvious first. If an object is referenced
by a static field, then it will never be released.
This is also true with such things as singletons. Singletons are often static objects, and if it's not the case, they are usually long-lived objects anyway.
This may be obvious, but keep in mind that not only direct references are dangerous. The real danger comes from indirect references. In fact, you must pay attention to the chains of references. What counts is the root of each chain. If the root is static, then all the objects down the chain will stay alive forever.
If Object1 on the above diagram is static, and most likely long-lived, then all the other objects down the reference chain will be kept in memory for a long time. The danger is that the chain can be too long to realize that the root of the chain is static. If you care about only one level of depth, you will consider that Object3 and Object4 will go away when Object2 goes away. That's correct, for sure, but you need to take into account the fact that they may never go away because Object1 keeps the whole object graph alive.
Be very careful with all kinds of statics. Avoid them if possible. If not, pay careful attention to the objects your static objects and singletons keep in memory.
A specific kind of risky statics are static events. I'll cover them just after I cover events in general.
Events, or the "lapsed listener" issue
A child form is subscribing to an event of the main form to get notified when the opacity changes (EventForm.cs):
The problem is that the subscription to the OpacityChanged event creates a reference from the main form to the child form.
Here is how objects are connected after the subscription:
See this post of mine to learn more about events and references. Here is a figure from this post that shows the "back" reference from a subject to its observers:
Here is what you'll see in dotTrace if you search for EventForm and click on "Shortest" in "Root Paths":
As you can see, MainForm keeps a reference to EventForm. This is the case for each instance of EventForm that you'll open in the application. This means that all the child forms that you'll open will stay in memory while the application is alive, even if you don't use them anymore.
Not only does this maintain the child forms in memory, but it also causes exceptions if you change the opacity after a child form has been closed because the main form tries to notify a disposed form.
The most simple solution is to remove the reference by having the child forms unsubscribe from the main form's event when they get disposed:
Nota Bene: We have a problem here because the MainForm object remains alive until the application is shut down. Interconnected objects with shorter lifetimes may not cause issues with memory. Any isolated graph of objects gets unloaded automatically from memory by the garbage collector. An isolated graph of objects is formed by two objects that only reference one another, or by a group of connected objects without any external reference.
Another solution would be to use weak delegates, which are based on weak references. I touch this subject in my post about events and references. Several articles on the Web demonstrate how to put this into action. Here is a good one, for example. Most of the solutions you'll find are based on the WeakReference class. You can learn more about weak references in .NET on MSDN.
Note that a solution for this exists in WPF, in the form of the WeakEvent pattern.
There are other solutions if you work with frameworks such as in CAB (Composite UI Application Block) or Prism (Composite Application Library), respectively EventBroker and EventAggregator. If you want, you can also use your own implementation of the event broker/aggregator/mediator pattern.
Event handlers with missing unsubscriptions from events on static or long-lived objects are a problem. Another one is static events.
Static events
Let's see an example directly (StaticEventForm.cs):
This is similar to the previous case, except that this time we subscribe to a static event. Since the event is static, the listener form object will never get released.
Again, the solution is to unsubscribe when we're done:
Dispose method not invoked
You've paid attention to events, static or not? Great, but that's not enough. You can still get lingering references even with correct cleanup code. This happens sometimes simply because this cleanup code doesn't get invoked...
Using the Dispose method or the Disposed event to unsubscribe from event and to release resources is a best practice, but it's useless if Dispose doesn't get called.
Let's take an interesting example. Here is sample code that creates a context-menu for a form (ContextMenuStripNotOKForm.cs):
Here is what you'll see with dotTrace after the form has been closed and disposed:
The ContextMenuStrip is still alive in memory! Note: To see the problem happen, show the context-menu with a right-click before closing the form.
Again this is a problem with static events. The solution is the same as usual:
I guess you start to understand how events can be dangerous in
.NET if you don't pay careful attention to them and the references they imply.
What I want to stress here is that it's easy to introduce a leak with just a line of code. Would you have thought about potential memory leaks when creating a context-menu?
It's even worst than what you imagine. Not only the
ContextMenuStrip is maintained alive, but it maintains the complete form alive
with it!
In the following screenshot, you can see that the ContextMenuStrip references the form:
The result is that the form will be alive as long as the ContextMenuStrip is. Oh, of course you should not forget that while the form is alive, it maintains itself a whole set of objects alive - the controls and components it contains, to start with:
This is something that I find important enough to warrant a big warning. A small object can potentially maintain big graphs of other objects in memory. I've seen this happen all the time in project X. This is the same with water: a small leak can cause big damages.
Because a single control points to its parent or to events of its parent, it has the potential to keep a whole chain of container controls alive if it hasn't been disposed. And of course, all the other controls contained in these containers are also kept in memory. This can for example lead to a complete form and all its content that remain in memory for ever (at least until the application stops).
At this point, you may be wondering if this problem always exists with ContextMenuStrip. It doens't. Most of the time, you create ContextMenuStrips with the designer directly on their form, and in this case Visual Studio generates code that ensures the ContextMenuStrip components get disposed correctly.
If you're interested in knowing how this is handled, you can take a look at the ContextMenuStripOKForm class and its components field in the ContextMenuStripOKForm.Designer.cs file.
I'd like to point out another situation I've seen in project X. For some reason there was no .Designer.cs files associated with the source files of some controls. The designer code was directly in the .cs files. Don't ask me why. Besides the unusual (and not recommended) code structure, the problem was that the designer code had not been completely copied: either the Dispose method was missing or the call to components.Dispose was missing. I guess you understand the bad things that can happen in these cases.
Incomplete Dispose method
I guess that you've now understood the importance of calling Dispose on all objects that have this method. However, the is one thing I'd like to stress about Dispose. It's great to have your classes implement the IDisposable interface and to include calls to Dispose and using blocks all over your code, but that's really useful only if the Dispose methods are implemented correctly.
This remark may seem a bit stupid, but if I make it it's because I've seen many cases where the code of Dispose methods was not complete.
You know how it happens. You create your classes; you have them implement IDisposable; you unsubscribe from events and release resources in Dispose; and you call Dispose everywhere. That's fine, until later on you have one of your classes subscribe to a new event or consume a new resource. It's easy to code, you're eager to finish coding and to test your code. It runs fine and you're happy with it. You checkin. Great! But... oops, you've forgotten to update Dispose to release everything. It happens all the time.
I won't provide an example for this. It should be pretty obvious.
Windows Forms: BindingSource misused
Let's address an issue specific to Windows Forms. If you use the BindingSource component, be sure you use it the way it has been designed to be.
I've seen code that exposed BindingSource via static references. This leads to memory leaks because of the way a BindingSource behaves. A BindingSource keeps a reference to controls that use it as their DataSource, even after these controls have been disposed.
Here is what you'll see with dotTrace after a ComboBox has been disposed if its DataSource is a static (or long-lived) BindingSource (BindingSourceForm.cs):
A solution to this issue is to expose a BindingList instead of a BindingSource. You can, for example, drop a BindingSource on your form, assign the BindingList as the DataSource for the BindingSource, and assign the BindingSource as the DataSource for the ComboBox. This way, you still use a BindingSource.
See BindingListForm.cs in the sample source code to see this in action.
This doesn't prevent you from using a BindingSource, but it should be created in the view (the form here) that uses it. That makes sense anyway: BindingSource is a presentation component defined in the System.Windows.Forms namespace. BindingList, in comparison, is a collection that's not attached to visual components.
Note: If you don't really need a BindingSource, you can simply use just a BindingList all the way.
CAB: Removal from WorkItem missing
Here is now an advice for CAB applications, but that you can apply to other kinds of applications.
WorkItems are central when building CAB applications. A WorkItem is a container that keeps track of alive objects in a context, and performs dependency injection. Usually, a view gets added to a WorkItem after it's created. When the view is closed and should be released, it should be removed from its WorkItem, otherwise the WorkItem will keep the view alive because it maintains a reference to it.
Leaks can happen if you forget to remove views from their WorkItem.
In project X, we use the MVP design pattern (Model-View-Presenter). Here is how the various elements are connected when a view is displayed:
Note that the presenter is also added to the WorkItem, so it can benefit from dependency injection too. Most of the time, the presenter is injected to the view by the WorkItem, by the way. To ensure that everything gets released properly in project X, we use a chain-of-responsibility as follows:
When a view is disposed (most likely because it has been closed), its Dispose method is invoked. This method in turn invokes the Dispose method of the presenter. The presenter, which knows the WorkItem, removes the view and itself from the WorkItem. This way, everything is disposed and released properly.
We have base classes that implement this chain-of-responsibility in our application framework, so that views developers don't have to re-implement this and worry about it every time. I encourage you to implement this kind of pattern in your applications, even if they are not CAB applications. Automating release patterns right into your objects will help you avoid leaks by omission. It will also ensure that this processing is implemented only in one way, and not differently by each developer because she/he may not know a proper way of doing it - which could lead to leaks by lack of know-how..
Tools
Several tools are available to help you track object instances, as well as system objects and handles. Let's name a few.
Bear
Bear is a free program that displays for all processes running under Windows:
-
GDIUsage
Another useful tool is GDIUsage. This tool is free too and comes with source code.
GDIUsage focuses on GDI Objects. With it, you can take a snapshot of the current GDI consumption, perform an action that might cause leaks, and make a comparison between the previous resources usage and the current one. This helps a lot because it allows you to see what GDI objects have been added (or released) during the action.
In addition, GDIUsage doesn't only give you numbers, but can also provide a graphical display of the GDI Objects. Visualizing what bitmap is leaked makes it easier to find why it has been leaked.
dotTrace
JetBrains dotTrace is a memory and performance profiler for .NET.
The screenshots I used in this article have been taken with dotTrace. This is also the tool I used the most for project X. I don't know the other .NET profilers well, but dotTrace provided me with the information I needed to solve the leaks detected in project X - more than 20 leaks so far... did I tell you that it's a big project?
dotTrace allows you to identify which objects are in memory at a given moment in time, how they are kept alive (incoming references), and which objects each object keeps alive (outgoing references). You also get advanced debugging with allocations stack traces, the list of dead objects, etc.
Here is a view that allows you to see the differences between two memory states:
dotTrace is also a performance profiler:
The way you use dotTrace, is by launching it first, then you ask it to profile your application by providing the path to the .EXE file.
If you want to inspect the memory used by your application, you can take snapshots while it's running and ask dotTrace to show you information. The first things you'll do are probably ask dotTrace to show you how many instances of a given class exist in memory, and how they are kept alive.
In addition to searching for managed instances, you can also search for unmanaged resources. dotTrace doesn't offer direct support for unmanaged resources tracking, but you can search for .NET wrapper objects. For example, you can see if you find instances of the Bitmap, Font or Brush classes. If you find an instance of such a class that hasn't been disposed, then the underlying system resource is still allocated to your application.
The next tool I'll present now offers built-in support for tracking unmanaged resources. This means that with it you'll be able to search directly for HBITMAP, HFONT or HBRUSH handles.
.NET Memory Profiler
.NET Memory Profiler is another interesting tool. Useful features it offers that you don't get with dotTrace include:
- View objects that have been disposed but are still alive
- View objects that have been released without having been disposed
- Unmanaged resources tracking
- Attach to a running process
- Attach to a process at the same time as Visual Studio's debugger
- Automatic memory analysis (tips and warnings regarding common memory usage issues)
Many .NET profilers are available
The above tools are just examples of what is available to help you. dotTrace and .NET Memory Profiler are two of the several memory (and performance) profilers available for .NET. Other big names include ANTS Profiler, YourKit Profiler, PurifyPlus, AQtime and CLR Profiler. Most of these tools offer the same kind of services as dotTrace. You'll find a whole set of tools dedicated to .NET profiling on SharpToolbox.com.
SOS.dll and WinDbg
Another tool you can use is SOS.dll. SOS.dll is a debugging extension that helps you debug managed programs in the WinDbg.exe debugger and in Visual Studio by providing information about the internal CLR (common language runtime) environment. SOS can be used to get information about the garbage collector, objects in memory, threads and locks, call stacks and more.
WinDbg is the tool you'll use most often when attaching to a process in production. You can learn more about SOS.dll and WinDBg on Rico Mariani's blog, on Mike Taulty's blog (SOS.dll with WinDbg and SOS.dll with Visual Studio), and on Wikipedia.
SOS.dll and WinDbg are provided free-of-charge by Microsoft as parts of the Debugging Tools for Windows package. One advantage of SOS.dll and WinDbg compared to the other tools I listed is their low resources consumption, while remaining powerful.
Sample output with sos.dll and the gcroot command:
WinDbg screenshot:
Custom tooling
In addition to tools available on the market, don't forget that you can create your own tools. Those can be standalone tools that you'd reuse for several of your applications, but they can be a bit difficult to develop.
What we did for project X is develop integrated tools that help us keep track in real-time of resource usage and potential leaks.
One of these tools displays a list of alive and dead objects,
right from the main application. It consists of a CAB service and a CAB view
that can be used to check whether objects we expect to be released have indeed
been released.
Here is a screenshot of this tooling:
Keeping track of each object of the application would be too expensive and anti-productive given the number of objects involved in a large application. In fact, we don't keep an eye on all objects, but only on the high level objects and root containers of the application. Those are the objects I advised to track when I explained how to detect leaks.
The technique we used for creating this tool is quite simple. It uses weak references. The WeakReference class allows you to reference an object while still allowing that object to be reclaimed by garbage collection. In addition, it allows you to test whether the referenced object is dead or alive, via the IsAlive property.
In project X, we also have a widget that provides an overview of the GDI and User objects usage:
When resources are nearing exhaustion, the widget reports it with a warning sign:
In addition, the application may ask the user to close some of the currently opened windows/tabs/documents, and prevent her/him from opening new ones, until the resources usage gets back below the critical level.
In order to read the current UI resources usage, we use the GetGuiResources function from User32.dll. Here is how we import it in C#:
// uiFlags: 0 - Count of GDI objects // uiFlags: 1 - Count of USER objects // GDI objects: pens, brushes, fonts, palettes, regions, device contexts, bitmaps, etc. // USER objects: accelerator tables, cursors, icons, menus, windows, etc. [DllImport("User32")] extern public static int GetGuiResources(IntPtr hProcess, int uiFlags); public static int GetGuiResourcesGDICount(Process process) { return GetGuiResources(process.Handle, 0); } public static int GetGuiResourcesUserCount(Process process) { return GetGuiResources(process.Handle, 1); }
We retrieve the memory usage via the Process.GetCurrentProcess().WorkingSet64 property.
Conclusion
I hope that this article has provided you with a good base for improving your applications and for helping you solve leaks. Tracking leaks can be fun... if you don't have anything better to do with your time :-) Sometimes, however, you have no choice because solving leaks is vital for your application.
Once you have solved leaks, you still have work to do. I strongly advise you to improve your application so that it consumes as less resources as possible. Without losing functionality, of course. I invite you to read my recommendations at the end of this blog post.
Resources
The source code for the demonstration application is available for download.
Here are some interesting additional resources if you want to dig further:
- Jossef Goldberg: Finding memory leaks in WPF applications
- Tess Ferrandez has a series of posts about memory issues (ASP.NET, WinDbg, and more)
- MSDN article by Christophe Nasarre: Resource Leaks: Detecting, Locating, and Repairing Your Leaky GDI Code
- Article in French by Sami Jaber: Audit et analyse de fuites mémoire
- My blog post about the Desktop Heap
- My blog post about lapsed listeners
- My blog post that shows how to force unsubscription from an event
Version française de cet article
About the author
Fabrice Marguerie
September 2009 | http://msdn.microsoft.com/en-us/library/ee658248.aspx | CC-MAIN-2014-52 | refinedweb | 5,405 | 63.09 |
Hi, Vincent Bernat wrote: > OoO En cette nuit striée d'éclairs du dimanche 27 avril 2008, vers > 02:06, Ansgar Burchardt <ansgar@2008.43-1.org> disait: > > > Lintian v1.23.46 complains about files generated by configure in the > > upstream tarball (config.log, config.status). I added an override, because > > they will be regenerated (and later removed by the clean target). > > There is also a precompiled version of gnurobbo executable. I don't know > if such a tarball should be repacked or not. For such a small binary > (117K), I think that repacking is not needed. I was not sure about repacking as well, but I too think it isn't necessary. The package was already repackaged once, because it did contain a non-free font (that's also the reason that the current version is not available upstream). > You may want to add a debian/watch file, even if upstream seems to be > dead. Done. > You can drop this snippet from debian/rules: > ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS))) > CFLAGS += -O0 > else > CFLAGS += -O2 > endif > > This is already done by dpkg-buildpackage. Done, and uploaded the new version to mentors. It's still available with dget > Otherwise, you did a great job at cleaning up this package. Has someone > From Debian Games team already proposed to sponsor this upload? No, not yet. | https://lists.debian.org/debian-devel-games/2008/05/msg00001.html | CC-MAIN-2014-10 | refinedweb | 221 | 74.69 |
Powierzchnia 3D: Obszar powierzchni
Description
Surface Sections is used to create a surface from edges that represent transversal sections of a surface.
Left: control edges (transversal sections). Right: surface produced from these edges.
Usage
- Make sure you have at lease two edges or curves in space. For example, these can be created with tools of the
Draft Workbench or the
Sketcher.
- Press the
Surface sections button.
- Press Add edge.
- Use the pointer to pick the desired edges in the 3D view; a preview of the final shape will be shown after selecting two valid edges.
- Press OK to complete the operation.
Options
- Add edge: press once to start picking edges in the 3D view. Individual lines such as
Draft BSplines and
Sketcher BSplines can be chosen, as well as any edge from solid objects, like those of
PartDesign Bodies and
Part Primitives.
- Remove edge: press once to start picking edges in the 3D view; these must be edges that were previously picked with Add edge.
- Right mouse button: open the context menu and select Remove, or press Del in the keyboard, to remove the currently selected edge in the list.
- Drag: drag the currently selected element in the list in order to change the order in which it will be processed; the list is processed from top to bottom.
- Press Cancel or Esc to abort the current operation.
Properties
A Surface Sections (
Surface::Sections class) is derived from the basic Part Feature (
Part::Feature class, through the
Part::Spline subclass), therefore it shares all the latter's properties.
In addition to the properties described in Part Feature, the Surface Sections has the following properties in the property editor.
Data
Sections
- DANENSections (
LinkSubList): a list of edges that will be used to build the surface.
View
Base
- WIDOK. See the information in
GeomFillSurface for a more complete explanation.
Scripting
See also: FreeCAD Scripting Basics.
The Surface Sections tool can be used in macros and from the Python console by adding the
Surface::Sections object.
- The edges to be used to define the surface must be assigned as a LinkSubList to the
NSectionsproperty of the object.
- All objects with edges need to be computed before they can be used as input for the properties of the Sections object.
import FreeCAD as App import Draft doc = App.newDocument() pl1 = App.Placement() obj1 = Draft.make_circle(50, placement=pl1, face=False, startangle=0, endangle=180) pl2 = App.Placement(App.Vector(0, 0, 25), App.Rotation()) obj2 = Draft.make_circle(30, placement=pl2, face=False, startangle=0, endangle=180) points3 = [App.Vector(18, -10, 50), App.Vector(12, 10, 50), App.Vector(-12, 10, 50), App.Vector(-18, -10, 50)] obj3 = Draft.make_bspline(points3) points4 = [App.Vector(15, -20, 100), App.Vector(0, 6, 100), App.Vector(-15, -20, 100)] obj4 = Draft.make_bspline(points4) doc.recompute() surf = doc.addObject("Surface::Sections", "Surface") surf.NSections = [(obj1, "Edge1"), (obj2, "Edge1"), (obj3, "Edge1"), (obj4, "Edge1")] doc.recompute()
- Jak zacząć
- Instalacja: Pobieranie programu, Windows, Linux, Mac, Dodatkowych komponentów, Docker, AppImage, Ubuntu Snap
- Podstawy: Informacje na temat FreeCAD, Interfejs użytkownika, Profil nawigacji myszką, Metody wyboru, Nazwa obiektu, Edytor ustawień, Środowiska pracy, Struktura dokumentu, Właściwości, Pomóż w rozwoju FreeCAD, Dotacje
- Pomoc: Poradniki, Wideo poradniki
- Środowiska pracy: Strona Startowa, Architektura, Rysunek Roboczy, MES, Obraz, Inspekcja, Siatka, OpenSCAD, Część, Projekt Części, Path, Punkty, Raytracing, Inżynieria Wsteczna, Szkicownik, Arkusz Kalkulacyjny, Start, Powierzchnia 3D, Rysunek Techniczny, Test Framework, Web
- Przestarzałe środowiska pracy: Complete, Kreślenie, Robot | https://wiki.freecadweb.org/Surface_Sections/pl | CC-MAIN-2021-49 | refinedweb | 568 | 59.19 |
Storing settings in the memory of the Core
Storing settings in the memory of the Core
Hello! If you are fortunate enough to hold the ESP32 microcontroller in your hands (I was more fortunate and have M5Stack in my hands) from the Chinese company ESPRESSIF, then this post may be useful.
There is a situation when it is necessary to save some parameters in non-volatile memory (for example: count the number of times the device is turned on for the entire time or save the Wi-Fi settings). This can be done with ease using the Preferences library.
We declare an instance of the Preferences class, and there we will see ...
The first thing we need to do is create a keychain by calling the begin method with a pair of arguments (but only with the first one): the name of the keychain and the read-only flag.
To save a string value in memory, you need to pass the key and the value itself to a method whose name consists of two parts: the first is put and the second is the type name, for example: String. Everything is clear and understandable. True, there are still "raw" bytes
without roasting, to which no one wants to assign a type. In this case, the method also takes the third argument with the number of these bytes. With this procedure, everything seems to be.
After the value has been written, you can read using the method (whose name is similar to the previous one), where the first part will be get. This method returns the value for the key of the corresponding type. Remember the byte case? If you don’t know (or don’t remember) how many bytes are on the key, then pull the getBytesLength method with a single argument - the key, it will calculate everything and return the amount to size_t.
If you want to remove a certain key from the keychain, then give it the only argument to the remove method.
Do you want to bring a real marafet and clear the whole bunch? Call the clear method without any arguments!
When you wish to complete the work with the bundle, call the end method without any arguments.
In general, the following types are supported: Char, UChar, Short, UShort, Int, UInt, Long, ULong, Long64, ULong64, Float, Double, Bool, String and Bytes.
I understand that I want
somethingcode, so here is a sketch. A sketch counts the number of turns on the device and displays it on the display:
#include <M5Stack.h> #include <Preferences.h> Preferences preferences; const char* key = "OnOff"; uint32_t count; void setup() { m5.begin(); preferences.begin("MyKeyChain"); count = preferences.getUInt(key); preferences.putUInt(key, count + 1); M5.Lcd.setTextSize(3); M5.Lcd.setTextColor(TFT_WHITE); M5.Lcd.println("Hello, Habr!"); M5.Lcd.setTextSize(2); M5.Lcd.println("M5Stack Turned On:"); M5.Lcd.setTextSize(3); M5.Lcd.setTextColor(TFT_RED); M5.Lcd.println(count); M5.Lcd.setTextColor(TFT_WHITE); M5.Lcd.setTextSize(2); M5.Lcd.println("times"); } void loop() { } | https://forum.m5stack.com/topic/1496/storing-settings-in-the-memory-of-the-core/1 | CC-MAIN-2022-40 | refinedweb | 501 | 63.49 |
- Title
SJ No 57 - 25 September 1901
- Database
Senate Journals
- Parl No.
1
- Number
57
- Page
- Status
Final
- System Id
chamber/journalshistorical/1901-09-25
153
153
COMMONWEALTH OF AUSTRALIA,
No. 57.
JOURNALS OF THE SENATE.
WEDNESDAY, 25th SEPTEMBER, 1901.
1. M eeting of S enate.—The Senate met pursuant to adjournment.
2. PRAYERS.
3. T ransferred Officers : Salaries.—Senator Keating, pursuant to notice, asked the Vice-President of the Executive Council have any officers in the transferred Departments received increases in their salaries since entering the service of the Commonwealth ; and, if so, will he place upon the Table of this Senate a return showing the names and offices of such officers, and the amounts of their respective increases. The Vice-President of the Executive Council replied—The information is being compiled, and will
be laid upon the Table of the House in the form of a Return.
4. M essage from the H ouse of R epresentatives.—The following Message from the House of Repre sentatives was received and read :— M r. P resident, Message No. 20.
The House of Representatives returns to the Senate the Bill intituled “ An Act relating to the Customs,” and acquaints the Senate that the House of Representatives has agreed to Nos. 1 to 26, 29 to 45, 47, 48, 50 to 64, 66, 68, 70 to 78, 80 to 87, 90 to 100, 102 to 109, 111, 112, 115, and 117 to 121 of the amendments made by the Senate, has agreed to amendments Nos. 27,
28, 65, 79, 88, 89, 1 14, 116, and 122 with the amendments indicated by the annexed Schedule, and has disagreed to amendments Nos. 46, 49, 67, 69, 101, 110, and 113 for the reasons assigned herewith. The House of Representatives desires the concurrence of the Senate in the amendments to the amendments of the Senate, and desires its reconsideration of the Bill in respect of the amend ments disagreed to.
E. W. HOLDER,
House of Representatives, Speaker.
Melbourne, 25th September, 1901.
SCHEDULE OF THE AMENDMENTS MADE BY THE HOUSE OF REPRESENTATIVES TO CERTAIN AMENDMENTS MADE BY THE SENATE IN THE CUSTOMS BILL.
In amendment No. 2 7 , viz :— No. 2 7 .—Page 8, after clause 50, insert the following new clause :— “ 5 0 a . A s to all tea imported:— Tea t0
(а) Samples shall be taken without payment and examined by the on importa-Collector. tlon'
(б) Unless the Collector is as a result of the examination satisfied that the tea is not a prohibited import he shall submit the samples for analysis to an official analyst appointed by the Governor-General for the purposes of this Act. (c) If as the result of the analysis it appears that the tea is a prohibited
import it shall after compliance with the next succeeding paragraph be dealt with accordingly. (d) Notice shall be given to the owner of the report of the analyst if the tea is thereby shown to be a prohibited import, · and the owner shall be
allowed fourteen days after the receipt of the notice to satisfy the Collector that the tea is not a prohibited import. (e) Any tea not complying with the prescribed standard of strength and purity shall be deemed unfit for human use.” At end of paragraph (d) add—
“ and if the Collector is not so satisfied the tea shall be a prohibited import.”
154
In amendment No. 28, viz :—
No. 28.·—Page 9, after clause 52, insert the following new clause : —
“ 5 2 a . There shall be publicly exposed at the principal ports of Aus- List of tralia printed lists of all books wherein the copyright shall be subsisting, and booitstobe as to which the proprietor of such copyright or his agent shall have given exposed at notice in writing that such copyright exists stating in such notice when such ports!1 ⢠1 copyright expires.” .
In line 1 omit “ publicly exposed ” and insert “ open to public inspection at the Customs House.” In line 4 after “ writing ” insert “ pursuant to section forty-nine.”
In amendment No. 65, viz :—
No. 65.—Page 22, after clause 154, insert the following new clause:—
“ 1 5 4 a . ( 1 ) For the protection of the revenue against the undervaluation customs may of goods subject to ad valorem duties any goods entered as of a specified value may at any time before sale to a person having no knowledge of the declared value entry and subject as may be prescribed be purchased by the Customs at their cent. ten per
declared value with an addition of Ten pounds per centum on the amount of such value. “ (2) The purchase shall be effected by the seizure of the goods by an officer and written notice of the seizure given to the owner. “ (3) The officer shall remove the goods to a warehouse or some place of security, and the owner shall thereupon be entitled to the purchase money.
“ (4) The goods shall become the property of the King immediately on seizure, and shall afterwards be disposed of as may be prescribed or as the Collector may direct. “ (5) A refund in whole or in part of any duty paid on the goods may be made by the Collector.
“ (6) This section shall not limit or restrict any other power possessed by the Customs relating to the goods.” In line 3 omit “ to a person having no ” and insert “ and delivery to a person who shall prove to the satisfaction of the Collector that he purchased and took delivery in good faith and
without any.”
In amendment No. 79, viz :—
No. 79.—Page 28, clause 192, line 14, omit “ the same and,” insert “ and search.” Omit the words “ omit ‘the same and’ ” (and consequentially omit the further word “ and ”).
In amendment No. 88, viz :—
No. 88.—Page 31, clause 213, line 8, at end of clause add “ unless a Justice of the High Court of Australia or the Supreme Court of a State has granted leave to the plaintiff to proceed without notice, which leave such Justice or Judge may grant on such terms as he may think just.”
After “ Australia o r” insert “ of.” Omit “ or Judge.”
In amendment No. 89, viz :—
No. 89.—Page 31, after clause 213 insert the following new clause :—· “ 2 1 3 a . No notice under the last preceding section shall be deemed De(ect in notice invalid by reason of any defect or inaccuracy therein unless the Court is of n°t_ to invaii· opinion that the defect or inaccuracy would prejudice the defendant in his ' defence.”
After “ defence ” add “ and the Court may give leave to amend such notice as it thinks just.”
In amendment No. 114, viz.:—
No. 114.—Page 39, clause 256, line 21, after “ order ” insert “ published in the Gazette.” Before “ published ” insert “ which shall forthwith be.”
In amendment No. 116, viz.:—
No. 116.—Page 40, after clause 259, insert the following new clause :—
“ 2 5 9 a . Any matter of difference arising under this Act, or in relation ^ eterm ine^ to the Customs, and not involving a contravention of this Act, may, at the differences, request of the parties interested, be referred to the Minister for decision, and thereupon the Minister shall in such manner as he shall think fit, inform his mind of the circum
stances, and finally decide the difference.”
In line 4, after “ Minister ” omit “ shall ” and insert “ may.”
155
In amendment No. 122, viz.:— No. 122.—Page 42, after Schedule II. insert the following new Schedule:—
SCHEDULE I I a. Commonwealth of Australia.
Writ of Assistance.
His Majesty the King {or Queen, as the case may be). To all Peace Officers, and to all whom it may concern : Greeting. We command you to permit A.B. of an Officer of the Customs of
the Commonwealth of Australia, and his assistants, and each and every of them at any time in the day or night to enter in and search any house premises or place and to break open and search the same and any chests trunks or packages in which goods may be or are supposed to be, and to seize any goods forfeited to Us and any goods that he the said A.B. has reason
able cause to believe are forfeited to Us, and to take such goods to the nearest King’s warehouse or to such other place of security as Our Collector of Customs for Our State of in Our said Commonwealth shall direct. And We grant to the said A.B. all powers which are capable of being granted by a W rit of Assistance.
And We command all Peace Officers and all Our loving subjects in Our said Common wealth of Australia upon sight of this Our Writ, and upon being so required by the said A.B. to be aiding and assisting the said A.B. in the matters aforesaid : Herein fail not at your peril :
And We declare that this Our W rit of Assistance shall remain in force so long as the said A.B. remains an Officer of Customs in Our Commonwealth of Australia whether in his present capacity or not.
Witness {name and description of the Judge testing the Writ) at the day of One thousand nine hundred and .
(Seal) By the Court.
In line 4, omit “ {or Queen as the case may be).”
Schedule of the A mendments made by the Senate in the Customs B ill to which the H ouse of R epresentatives has D isagreed.
No. 46·—Page 17, clause 112, lino 9, after “ export ” omit the remainder of the clause. No. 49·—Page 18, clause 121, line 14, after “ Customs ” omit the remainder of the clause. No. 67-—Page 24, clause 166, line 24, after “ n o t ” {first occurring) insert “ to his knowledge.” No. 69.—Page 24, clause 168, line 41, after “ place” insert “ beyond Australia.” No. 101.—Page 33, clause 220, line 5, after “ o r ” (second occurring) insert “ wilfully.” No. 110.—Page 34, clause 224, line 35, after “ goods” insert “ subject to the control of the
Customs.” No. 113.—Page 37, clause 245, omit sub-clause (2).
Reasons of the House of Representatives fo r Disagreeing to certain Amendments of the Senate.
As to Amendment No. 46 :— Because the provision proposed to be omitted is usual and necessary for the proper protection of the revenue; further, it is permissive and to be exercised only when the Collector sees reason to require it, instead of as in many existing Acts, in all cases.
As to Amendment No. 49 :— Because when a person declines to comply with the law in his relations with the Customs it is reasonable that the Department should have the power to postpone, until compliance, the transaction of further business with the person in default.
As to Amendment No. 67 :— Because the State has a right to ask for a positive assurance that the necessary conditions have been performed before paying away money which is only payable when those conditions have been performed.
As to Amendment No. 69 :— Because the amendment is unnecessary and not altogether consistent with the context.
As to Amendment No. 101 :— Because so long as the statement is misleading the injury to the revenue and to more careful traders is the same whatever the intention ; further, where necessary any forfeiture can be waived, but to make the right of forfeiture for misleading entries depend on proof of
intention would in many cases defeat the course of justice.
As to Amendment No. 110:— Because the result of the amendment would be to unnecessarily limit the effect of the clause.
As to Amendment No. 113 :— Because the amendment would prevent the truth from being elicited.
C. GAY AN DUFFY,
20th September, 1901. Clerk of the House of Representatives.
Ordered—That the Message and amendments be printed and taken into consideration in Committee of the Whole to-morrow.
5. D istillation B ill.—The Senate, according to Order, resolved itself into a Committee for the further consideration of the Distillation Bill.
In the Committee,
Title agreed to. Clause 3 reconsidered, amended, and agreed to. Clause 4 reconsidered and agreed to. Clause f> reconsidered and agreed to.
Clause 8 reconsidered, amended, and agreed to. Clause 10 reconsidered and agreed to. Clause 12 reconsidered and agreed to. Clause 13 reconsidered and agreed to. Clause 14 reconsidered. Senator McGregor moved an amendment, viz., in line 2, to leave out “ two gallons,” with a view to
insert “ one gallon ” in lieu thereof. Question—That the words proposed to be left out stand part of the clause—put. Committee divided. Ayes, 18.
Senator Best Clemons Dobson Sir J. W. Downer Drake Ferguson
Glassey Major Gould Macfarlane Millen Lieut.-Col. Neild
O’Connor O’Keefe Pulsford Lieut.-Col. Sir F. T. Sargood
Walker Sir W. A. Zeal.
Noes, 9.
Senator Charleston Dawson Do Largie Higgs McGregor Playford Smith Stewart.
Teller.
Senator Pearce.
Teller.
Senator Barrett.
Clause ]4 agreed to. Clause 25 reconsidered and agreed to. Clause 28 reconsidered and agreed to. Clause 31 reconsidered and agreed to. Clause 34 reconsidered. Senator Sir J. H. Symon moved an amendment, viz., after “ shall,” inline 1, to insert “ except
by authority.” Question—That the words proposed to be inserted be inserted—put. Committee divided.
Ayes, 10.
Senator Charleston Clemons Major Gould Macfarlane Lieut.-Col, Neild
Playford Pulsford Lieut.-Col. Sir F. T. Sargood Sir J. H. Symon.
Teller.
Senator Millen.
Noes, 20.
Senator Barrett Best Dawson Dobson Sir J. W. Downer Drake Ewing Ferguson Glassey Higgs Keating McGregor O’Connor O’Keefe Pearce
Smith Stewart Walker Sir W. A. Zeal.
Teller.
Senator Do Largie.
Clause 34 agreed to. Clause 51 reconsidered, amended, and agreed to. Clause 52 reconsidered and agreed to. Clause 53 reconsidered and agreed to. Clause 54 reconsidered and agreed to.
157 1.17
Clause 55 reconsidered and agreed to. Clause 57 reconsidered. Senator Sir F. T. Sargood moved an amendment, viz., to leave out “ thirty,” in line 3.
(i. Suspension of Committee.—At half-past six p.ra. the sitting of the Committee was suspended till half-past seven p.m.
7. R esumption of Committee.—A t half-past seven p.m. the sitting of the Committee was resumed.
8. D istillation B ill.—Clause 57 further considered.
Question—That the word “ thirty ” proposed to be left out stand part of the clause—put. Committee divided.
Ayes, 17.
Senator Charleston Clemons Dobson Sir J. W. Downer Drake Glassey
Major Gould Keating Macfarlane McGregor Millen Lieut.-Col. Neild O’Connor Playford Pulsford
Sir J. II. Symon.
Teller.
Senator O’Keefe.
Senator McGregor moved an amendment, viz., after “ Proof,” in line 3, to insert “ in the case of wine spirit and of at least sixty degrees above proof in the case of any other spirit.” Question—That the words proposed to be inserted be inserted—put. Committee divided.
Ayes, 19.
Senator Sir R. C. Baker Barrett Best Charleston Clemons De Largie Dobson Glassey Higgs Macfarlane McGregor
O’Keefe Pearce Playford Lieut.-Col. Sir F. T. Sargood Stewart Sir J. H. Symon Walker. "
Teller.
Senator Keating.
Clause 57, as amended, agreed to. Clause 58 reconsidered, amended, and agreed to. Clause G4 reconsidered, amended, and agreed to. Clause 75 reconsidered and agreed to. Clause 82 reconsidered, amended, and agreed to. Clause 83 reconsidered, amended, and agreed to. Clause 84 reconsidered and struck out. Schedule I. reconsidered and agreed to. Schedule II. reconsidered and agreed to. Schedule 111. reconsidered and amended. Senator Lieut.-Col. Neild moved a further amendment, viz., in Regulation 93 to leave out “ three
days,” with a view to insert “ forty-eight hours ” in lieu thereof. Question—That the words proposed to be left out stand part of the Regulation—put.
Noes, 8.
Senator Sir J. W. Downer Drake Ewing Major Gould Lieut.-Col. Neild O’Connor Pulsford.
Teller.
Senator Millen.
Noes, 9.
Senator Barrett Best De Largie Higgs Pearce Lieut.-Col. Sir F. T. Sargood Smith Walker.
Teller.
Senator Stewart.
158
Committee divided. Ayes, 18.
Senator Sir R. C. Baker Barrett Best De Largic
Dobson Sir J. W. Downer Drake Glassey Higgs Keating O’Connor O’Keefe Pearce Playford
Lieut.-Col. Sir F. T. Sargood Smith Stewart,
Teller.
Senator Charleston.
Schedule III. further amended and agreed to. New clause 10λ inserted, to follow clause 10. Bill to be reported with amendments. The President resumed the Chair; and Senator Best, from the Committee, reported that the Com
mittee had considered the Bill, and had agreed to the same with amendments. Ordered—That the Bill as reported be considered to-morrow.
9. M essage from H ouse of R epresentatives.—The following Message from the House of Repre sentatives was received and read :— Mr. P resident, Message No. 21.
The House of Representatives transmits to the Senate a Bill intituled “ An Act relating to Excise,” with which it desires the concurrence of the Senate. F. W. HOLDER, House of Representatives, Speaker.
Melbourne, 25th September, 1901.
10. E xcise B ill.—The Vice-President of the Executive Council moved, That the Excise Bill be now read a first time. Question—put and passed. Bill read a first time, and ordered to be read a second time to-morrow.
11. P ostponement of B usiness.—Ordered, That Orders of the Day Nos. 2 and 3 be postponed till after the consideration of Order of the Day No. 4.
12. B eer E xcise B ill.—On the Order of the Day being read for the consideration of the Beer Excise Bill as reported a second time, Ordered—That the Bill be recommitted for the reconsideration of Clauses 5, 7, 14, 19, 2 7 a, 67, Schedule III., and new clauses. The Senate, according to Order, resolved itself into a Committee for the reconsideration of the
Bill.
In the Committee,
Clause 5 reconsidered and agreed to. Clause 7 reconsidered, amended, and agreed to. Clause 14 reconsidered, amended, and agreed to Clause 19 reconsidered, amended, and agreed to. Clause 2 7 a reconsidered, amended, and agreed to. Clause 67 reconsidered and struck out. Schedule III. reconsidered, amended, and agreed to.
New Clause 18a inserted to follow Clause 18. Bill to be reported with further amendments. The President resumed the Chair; and Senator Best, from the Committee, reported that the Com mittee had reconsidered the Bill, and had agreed to the same with further amendments.
Ordered—That the Bill as reported a third time be considered to-morrow.
13. A djournment.—The Senate adjourned at fifty-six minutes past nine p.m. till to-morrow, at half-past two p.m.
14. A ttendance.—Present, all the Members except Senators Lieut.-Col. Cameron, Fraser (on leave), Harney, Matheson (on leave), and Styles (on leave).
Noes, 6.
Senator Major Gould Millen Lieut.-Col. Neild Pulsford
Walker.
Teller.
Senator Macfarlane.
E. G. BLACKMORE, Clerk of the Parliaments.
Printed and Published for the Government of the Commonwealth of A ustralia by R oet. S. B rain, Government Printer for the State of Victoria. | https://parlinfo.aph.gov.au/parlInfo/search/display/display.w3p;query=Id:%22chamber/journalshistorical/1901-09-25%22 | CC-MAIN-2019-39 | refinedweb | 3,170 | 66.94 |
This file contains information about GCC releases up to GCC 2.8.1, and a tiny bit of information on EGCS. For details of changes in EGCS releases and GCC 2.95 and later releases, see the release notes on the GCC web site or the file NEWS which contains the most relevant parts of those release notes in text form. Changes in GCC for EGCS (that are not listed in the web release notes) --------------------------------------------------------------------- The compiler now supports the "ADDRESSOF" optimization which can significantly reduce the overhead for certain inline calls (and inline calls in general). Compile time for certain programs using large constant initializers has been improved (affects glibc significantly). Various improvements have been made to better support cross compilations. They are still not easy, but they are improving. Target-specific changes: M32r: Major improvements to this port. Arm: Includes Thumb and super interworking support. Noteworthy changes in GCC version 2.8.1 --------------------------------------- Numerous bugs have been fixed and some minor performance improvements (compilation speed) have been made. Noteworthy changes in GCC version 2.8.0 --------------------------------------- A major change in this release is the addition of a framework for exception handling, currently used by C++. Many internal changes and optimization improvements have been made. These increase the maintainability and portability of GCC. GCC now uses autoconf to compute many host parameters. The following lists changes that add new features or targets. See cp/NEWS for new features of C++ in this release. New tools and features: The Dwarf 2 debugging information format is supported on ELF systems, and is the default for -ggdb where available. It can also be used for C++. The Dwarf version 1 debugging format is also permitted for C++, but does not work well. gcov.c is provided for test coverage analysis and branch profiling analysis is also supported; see -fprofile-arcs, -ftest-coverage, and -fbranch-probabilities. Support for the Checker memory checking tool. New switch, -fstack-check, to check for stack overflow on systems that don't have such built into their ABI. New switches, -Wundef and -Wno-undef to warn if an undefined identifier is evaluated in an #if directive. Options -Wall and -Wimplicit now cause GCC to warn about implicit int in declarations (e.g. `register i;'), since the C Standard committee has decided to disallow this in the next revision of the standard; -Wimplicit-function-declarations and -Wimplicit-int are subsets of this. Option -Wsign-compare causes GCC to warn about comparison of signed and unsigned values. Add -dI option of cccp for cxref. New features in configuration, installation and specs file handling: New option --enable-c-cpplib to configure script. You can use --with-cpu on the configure command to specify the default CPU that GCC should generate code for. The -specs=file switch allows you to override default specs used in invoking programs like cc1, as, etc. Allow including one specs file from another and renaming a specs variable. You can now relocate all GCC files with a single environment variable or a registry entry under Windows 95 and Windows NT. Changes in Objective-C: The Objective-C Runtime Library has been made thread-safe. The Objective-C Runtime Library contains an interface for creating mutexes, condition mutexes, and threads; it requires a back-end implementation for the specific platform and/or thread package. Currently supported are DEC/OSF1, IRIX, Mach, OS/2, POSIX, PCThreads, Solaris, and Windows32. The --enable-threads parameter can be used when configuring GCC to enable and select a thread back-end. Objective-C is now configured as separate front-end language to GCC, making it more convenient to conditionally build it. The internal structures of the Objective-C Runtime Library have changed sufficiently to warrant a new version number; now version 8. Programs compiled with an older version must be recompiled. The Objective-C Runtime Library can be built as a DLL on Windows 95 and Windows NT systems. The Objective-C Runtime Library implements +load. The following new targets are supported (see also list under each individual CPU below): Embedded target m32r-elf. Embedded Hitachi Super-H using ELF. RTEMS real-time system on various CPU targets. ARC processor. NEC V850 processor. Matsushita MN10200 processor. Matsushita MN10300 processor. Sparc and PowerPC running on VxWorks. Support both glibc versions 1 and 2 on Linux-based GNU systems. New features for DEC Alpha systems: Allow detailed specification of IEEE fp support: -mieee, -mieee-with-inexact, and -mieee-conformant -mfp-trap-mode=xxx, -mfp-round-mode=xxx, -mtrap-precision=xxx -mcpu=xxx for CPU selection Support scheduling parameters for EV5. Add support for BWX, CIX, and MAX instruction set extensions. Support Linux-based GNU systems. Support VMS. Additional supported processors and systems for MIPS targets: MIPS4 instruction set. R4100, R4300 and R5000 processors. N32 and N64 ABI. IRIX 6.2. SNI SINIX. New features for Intel x86 family: Add scheduling parameters for Pentium and Pentium Pro. Support stabs on Solaris-x86. Intel x86 processors running the SCO OpenServer 5 family. Intel x86 processors running DG/UX. Intel x86 using Cygwin32 or Mingw32 on Windows 95 and Windows NT. New features for Motorola 68k family: Support for 68060 processor. More consistent switches to specify processor. Motorola 68k family running AUX. 68040 running pSOS, ELF object files, DBX debugging. Coldfire variant of Motorola m68k family. New features for the HP PA RISC: -mspace and -mno-space -mlong-load-store and -mno-long-load-store -mbig-switch -mno-big-switch GCC on the PA requires either gas-2.7 or the HP assembler; for best results using GAS is highly recommended. GAS is required for -g and exception handling support. New features for SPARC-based systems: The ultrasparc cpu. The sparclet cpu, supporting only a.out file format. Sparc running SunOS 4 with the GNU assembler. Sparc running the Linux-based GNU system. Embedded Sparc processors running the ELF object file format. -mcpu=xxx -mtune=xxx -malign-loops=xxx -malign-jumps=xxx -malign-functions=xxx -mimpure-text and -mno-impure-text Options -mno-v8 and -mno-sparclite are no longer supported on SPARC targets. Options -mcypress, -mv8, -msupersparc, -msparclite, -mf930, and -mf934 are deprecated and will be deleted in GCC 2.9. Use -mcpu=xxx instead. New features for rs6000 and PowerPC systems: Solaris 2.51 running on PowerPC's. The Linux-based GNU system running on PowerPC's. -mcpu=604e,602,603e,620,801,823,mpc505,821,860,power2 -mtune=xxx -mrelocatable-lib, -mno-relocatable-lib -msim, -mmve, -memb -mupdate, -mno-update -mfused-madd, -mno-fused-madd -mregnames -meabi -mcall-linux, -mcall-solaris, -mcall-sysv-eabi, -mcall-sysv-noeabi -msdata, -msdata=none, -msdata=default, -msdata=sysv, -msdata=eabi -memb, -msim, -mmvme -myellowknife, -mads wchar_t is now of type long as per the ABI, not unsigned short. -p/-pg support -mcpu=403 now implies -mstrict-align. Implement System V profiling. Aix 4.1 GCC targets now default to -mcpu=common so that programs compiled can be moved between rs6000 and powerpc based systems. A consequence of this is that -static won't work, and that some programs may be slightly slower. You can select the default value to use for -mcpu=xxx on rs6000 and powerpc targets by using the --with-cpu=xxx option when configuring the compiler. In addition, a new options, -mtune=xxx was added that selects the machine to schedule for but does not select the architecture level. Directory names used for storing the multilib libraries on System V and embedded PowerPC systems have been shortened to work with commands like tar that have fixed limits on pathname size. New features for the Hitachi H8/300(H): -malign-300 -ms (for the Hitachi H8/S processor) -mint32 New features for the ARM: -march=xxx, -mtune=xxx, -mcpu=xxx Support interworking with Thumb code. ARM processor with a.out object format, COFF, or AOF assembler. ARM on "semi-hosted" platform. ARM running NetBSD. ARM running the Linux-based GNU system. New feature for Solaris systems: GCC installation no longer makes a copy of system include files, thus insulating GCC better from updates to the operating system. Noteworthy changes in GCC version 2.7.2 --------------------------------------- A few bugs have been fixed (most notably the generation of an invalid assembler opcode on some RS/6000 systems). Noteworthy changes in GCC version 2.7.1 --------------------------------------- This release fixes numerous bugs (mostly minor) in GCC 2.7.0, but also contains a few new features, mostly related to specific targets. Major changes have been made in code to support Windows NT. The following new targets are supported: 2.9 BSD on PDP-11 Linux on m68k HP/UX version 10 on HP PA RISC (treated like version 9) DEC Alpha running Windows NT When parsing C, GCC now recognizes C++ style `//' comments unless you specify `-ansi' or `-traditional'. The PowerPC System V targets (powerpc-*-sysv, powerpc-*-eabi) now use the calling sequence specified in the System V Application Binary Interface Processor Supplement (PowerPC Processor ABI Supplement) rather than the calling sequence used in GCC version 2.7.0. That calling sequence was based on the AIX calling sequence without function descriptors. To compile code for that older calling sequence, either configure the compiler for powerpc-*-eabiaix or use the -mcall-aix switch when compiling and linking. Noteworthy changes in GCC version 2.7.0 --------------------------------------- GCC now works better on systems that use ".obj" and ".exe" instead of ".o" and no extension. This involved changes to the driver program, gcc.c, to convert ".o" names to ".obj" and to GCC's Makefile to use ".obj" and ".exe" in filenames that are not targets. In order to build GCC on such systems, you may need versions of GNU make and/or compatible shells. At this point, this support is preliminary. Object file extensions of ".obj" and executable file extensions of ".exe" are allowed when using appropriate version of GNU Make. Numerous enhancements were made to the __attribute__ facility including more attributes and more places that support it. We now support the "packed", "nocommon", "noreturn", "volatile", "const", "unused", "transparent_union", "constructor", "destructor", "mode", "section", "align", "format", "weak", and "alias" attributes. Each of these names may also be specified with added underscores, e.g., "__packed__". __attribute__ may now be applied to parameter definitions, function definitions, and structure, enum, and union definitions. GCC now supports returning more structures in registers, as specified by many calling sequences (ABIs), such as on the HP PA RISC. A new option '-fpack-struct' was added to automatically pack all structure members together without holes. There is a new library (cpplib) and program (cppmain) that at some point will replace cpp (aka cccp). To use cppmain as cpp now, pass the option CCCP=cppmain to make. The library is already used by the fix-header program, which should speed up the fixproto script. New options for supported targets: GNU on many targets. NetBSD on MIPS, m68k, VAX, and x86. LynxOS on x86, m68k, Sparc, and RS/6000. VxWorks on many targets. Windows/NT on x86 architecture. Initial support for Windows/NT on Alpha (not fully working). Many embedded targets, specifically UDI on a29k, aout, coff, elf, and vsta "operating systems" on m68k, m88k, mips, sparc, and x86.. Additions for RS/6000: Instruction scheduling information for PowerPC 403. AIX 4.1 on PowerPC. -mstring and -mno-string. -msoft-float and floating-point emulation included. Preliminary support for PowerPC System V.4 with or without the GNU as. Preliminary support for EABI. Preliminary support for 64-bit systems. Both big and little endian systems. New features for MIPS-based systems: r4650. mips4 and R8000. Irix 6.0. 64-bit ABI. Allow dollar signs in labels on SGI/Irix 5.x. New support for HP PA RISC: Generation of PIC (requires binutils-2.5.2.u6 or later). HP-UX version 9 on HP PA RISC (dynamically links even with -g). Processor variants for HP PA RISC: 700, 7100, and 7100LC. Automatic generation of long calls when needed. -mfast-indirect-calls for kernels and static binaries. The called routine now copies arguments passed by invisible reference, as required by the calling standard. Other new miscellaneous target-specific support: -mno-multm on a29k. -mold-align for i960. Configuration for "semi-hosted" ARM. -momit-leaf-frame-pointer for M88k. SH3 variant of Hitachi Super-H and support both big and little endian. Changes to Objective-C: Bare-bones implementation of NXConstantString has been added, which is invoked by the @"string" directive. Class * has been changed to Class to conform to the NextSTEP and OpenStep runtime. Enhancements to make dynamic loading easier. The module version number has been updated to Version 7, thus existing code will need to be recompiled to use the current run-time library. GCC now supports the ISO Normative Addendum 1 to the C Standard. As a result: The header <iso646.h> defines macros for C programs written in national variants of ISO 646. The following digraph tokens are supported: <: :> <% %> %: %:%: These behave like the following, respectively: [ ] { } # ## Digraph tokens are supported unless you specify the `-traditional' option; you do not need to specify `-ansi' or `-trigraphs'. Except for contrived and unlikely examples involving preprocessor stringizing, digraph interpretation doesn't change the meaning of programs; this is unlike trigraph interpretation, which changes the meanings of relatively common strings. The macro __STDC_VERSION__ has the value 199409L. As usual, for full conformance to the standard, you also need a C library that conforms. The following lists changes that have been made to g++. If some features mentioned below sound unfamiliar, you will probably want to look at the recently-released public review copy of the C++ Working Paper. For PostScript and PDF (Adobe Acrobat) versions, see the archive at. For HTML and ASCII versions, see. On the web, see. The scope of variables declared in the for-init-statement has been changed to conform to; as a result, packages such as groff 1.09 will not compile unless you specify the -fno-for-scope flag. PLEASE DO NOT REPORT THIS AS A BUG; this is a change mandated by the C++ standardization committee. Binary incompatibilities: The builtin 'bool' type is now the size of a machine word on RISC targets, for code efficiency; it remains one byte long on CISC targets. Code that does not use #pragma interface/implementation will most likely shrink dramatically, as g++ now only emits the vtable for a class in the translation unit where its first non-inline, non-abstract virtual function is defined. Classes that do not define the copy constructor will sometimes be passed and returned in registers. This may illuminate latent bugs in your code. Support for automatic template instantiation has *NOT* been added, due to a disagreement over design philosophies. Support for exception handling has been improved; more targets are now supported, and throws will use the RTTI mechanism to match against the catch parameter type. Optimization is NOT SUPPORTED with -fhandle-exceptions; no need to report this as a bug. Support for Run-Time Type Identification has been added with -frtti. This support is still in alpha; one major restriction is that any file compiled with -frtti must include <typeinfo.h>. Preliminary support for namespaces has been added. This support is far from complete, and probably not useful. Synthesis of compiler-generated constructors, destructors and assignment operators is now deferred until the functions are used. The parsing of expressions such as `a ? b : c = 1' has changed from `(a ? b : c) = 1' to `a : b ? (c = 1)'. The code generated for testing conditions, especially those using || and &&, is now more efficient.. g++ now accepts the typename keyword, though it currently has no semantics; it can be a no-op in the current template implementation. You may want to start using it in your code, however, since the pending rewrite of the template implementation to compile STL properly (perhaps for 2.8.0, perhaps not) will require you to use it as indicated by the current draft. Handling of user-defined type conversion has been overhauled so that type conversion operators are now found and used properly in expressions and function calls. -fno-strict-prototype now only applies to function declarations with "C" linkage. g++ now warns about 'if (x=0)' with -Wparentheses or -Wall. #pragma weak and #pragma pack are supported on System V R4 targets, as are various other target-specific #pragmas supported by gcc. new and delete of const types is now allowed (with no additional semantics).. The template instantiation code now handles more conversions when passing to a parameter that does not depend on template arguments. This means that code like 'string s; cout << s;' now works. Invalid jumps in a switch statement past declarations that require initializations are now caught. Functions declared 'extern inline' now have the same linkage semantics as inline member functions. On supported targets, where previously these functions (and vtables, and template instantiations) would have been defined statically, they will now be defined as weak symbols so that only one out-of-line definition is used. collect2 now demangles linker output, and c++filt has become part of the gcc distribution. Noteworthy changes in GCC version 2.6.3: A few more bugs have been fixed. Noteworthy changes in GCC version 2.6.2: A few bugs have been fixed. Names of attributes can now be preceded and followed by double underscores. Noteworthy changes in GCC version 2.6.1: Numerous (mostly minor) bugs have been fixed. The following new configurations are supported: GNU on x86 (instead of treating it like MACH) NetBSD on Sparc and Motorola 68k AIX 4.1 on RS/6000 and PowerPC systems Sequent DYNIX/ptx 1.x and 2.x. Both COFF and ELF configurations on AViiON without using /bin/gcc Windows/NT on x86 architecture; preliminary AT&T DSP1610 digital signal processor chips i960 systems on bare boards using COFF PDP11; target only and not extensively tested The -pg option is now supported for Alpha under OSF/1 V3.0 or later. Files with an extension of ".c++" are treated as C++ code. The -Xlinker and -Wl arguments are now passed to the linker in the position they were specified on the command line. This makes it possible, for example, to pass flags to the linker about specific object files. The use of positional arguments to the configure script is no longer recommended. Use --target= to specify the target; see the GCC manual. The 386 now supports two new switches: -mreg-alloc=<string> changes the default register allocation order used by the compiler, and -mno-wide-multiply disables the use of the mul/imul instructions that produce 64 bit results in EAX:EDX from 32 bit operands to do long long multiplies and 32-bit division by constants. Noteworthy changes in GCC version 2.6.0: Numerous bugs have been fixed, in the C and C++ front-ends, as well as in the common compiler code. This release includes the C, Objective-C, and C++ compilers. However, we have moved the files for the C++ compiler (G++) files to a subdirectory, cp. Subsequent releases of GCC will split these files to a separate TAR file. The G++ team has been tracking the development of the ANSI standard for C++. Here are some new features added from the latest working paper: * built-in boolean type 'bool', with constants 'true' and 'false'. * array new and delete (operator new [] and delete []). * WP-conforming lifetime of temporaries. * explicit instantiation of templates (template class A<int>;), along with an option (-fno-implicit-templates) to disable emission of implicitly instantiated templates, obsoletes -fexternal-templates. * static member constants (static const int foo = 4; within the class declaration). Many error messages have been improved to tell the user more about the problem. Conformance checking with -pedantic-errors has been improved. G++ now compiles Fresco. There is now an experimental implementation of virtual functions using thunks instead of Cfront-style vtables, enabled with -fvtable-thunks. This option also enables a heuristic which causes the compiler to only emit the vtable in the translation unit where its first non-inline virtual function is defined; using this option and -fno-implicit-templates, users should be able to avoid #pragma interface/implementation altogether. Signatures have been added as a GNU C++ extension. Using the option -fhandle-signatures, users are able to turn on recognition of signatures. A short introduction on signatures is in the section `Extension to the C++ Language' in the manual. The `g++' program is now a C program, rather than a shell script. Lots and lots and lots of bugs fixes, in nested types, access control, pointers to member functions, the parser, templates, overload resolution, etc, etc. There have been two major enhancements to the Objective-C compiler: 1) Added portability. It now runs on Alpha, and some problems with message forwarding have been addressed on other platforms. 2) Selectors have been redefined to be pointers to structs like: { void *sel_id, char *sel_types }, where the sel_id is the unique identifier, the selector itself is no longer unique. Programmers should use the new function sel_eq to test selector equivalence. The following major changes have been made to the base compiler and machine-specific files. - The MIL-STD-1750A is a new port, but still preliminary. - The h8/300h is now supported; both the h8/300 and h8/300h ports come with 32 bit IEEE 754 software floating point support. - The 64-bit Sparc (v9) and 64-bit MIPS chips are supported. - NetBSD is supported on m68k, Intel x86, and pc523 systems and FreeBSD on x86. - COFF is supported on x86, m68k, and Sparc systems running LynxOS. - 68K systems from Bull and Concurrent are supported and System V Release 4 is supported on the Atari. - GCC supports GAS on the Motorola 3300 (sysV68) and debugging (assuming GAS) on the Plexus 68K system. (However, GAS does not yet work on those systems). - System V Release 4 is supported on MIPS (Tandem). - For DG/UX, an ELF configuration is now supported, and both the ELF and BCS configurations support ELF and COFF object file formats. - OSF/1 V2.0 is supported on Alpha. - Function profiling is also supported on Alpha. - GAS and GDB is supported for Irix 5 (MIPS). - "common mode" (code that will run on both POWER and PowerPC architectures) is now supported for the RS/6000 family; the compiler knows about more PPC chips. - Both NeXTStep 2.1 and 3 are supported on 68k-based architectures. - On the AMD 29k, the -msoft-float is now supported, as well as -mno-sum-in-toc for RS/6000, -mapp-regs and -mflat for Sparc, and -membedded-pic for MIPS. - GCC can now convert division by integer constants into the equivalent multiplication and shift operations when that is faster than the division. - Two new warning options, -Wbad-function-cast and -Wmissing-declarations have been added. - Configurations may now add machine-specific __attribute__ options on type; many machines support the `section' attribute. - The -ffast-math flag permits some optimization that violate strict IEEE rules, such as converting X * 0.0 to 0.0. Noteworthy changes in GCC version 2.5.8: This release only fixes a few serious bugs. These include fixes for a bug that prevented most programs from working on the RS/6000, a bug that caused invalid assembler code for programs with a `switch' statement on the NS32K, a G++ problem that caused undefined names in some configurations, and several less serious problems, some of which can affect most configuration. Noteworthy change in GCC version 2.5.7: This release only fixes a few bugs, one of which was causing bootstrap compare errors on some systems. Noteworthy change in GCC version 2.5.6: A few backend bugs have been fixed, some of which only occur on one machine. The C++ compiler in 2.5.6 includes: * fixes for some common crashes * correct handling of nested types that are referenced as `foo::bar' * spurious warnings about friends being declared static and never defined should no longer appear * enums that are local to a method in a class, or a class that's local to a function, are now handled correctly. For example: class foo { void bar () { enum { x, y } E; x; } }; void bar () { class foo { enum { x, y } E; E baz; }; } Noteworthy change in GCC version 2.5.5: A large number of C++ bugs have been fixed. The fixproto script adds prototypes conditionally on __cplusplus. Noteworthy change in GCC version 2.5.4: A bug fix in passing of structure arguments for the HP-PA architecture makes code compiled with GCC 2.5.4 incompatible with code compiled with earlier versions (if it passes struct arguments of 33 to 64 bits, interspersed with other types of arguments). Noteworthy change in gcc version 2.5.3: The method of "mangling" C++ function names has been changed. So you must recompile all C++ programs completely when you start using GCC 2.5. Also, GCC 2.5 requires libg++ version 2.5. Earlier libg++ versions won't work with GCC 2.5. (This is generally true--GCC version M.N requires libg++ version M.N.) Noteworthy GCC changes in version 2.5: * There is now support for the IBM 370 architecture as a target. Currently the only operating system supported is MVS; GCC does not run on MVS, so you must produce .s files using GCC as a cross compiler, then transfer them to MVS to assemble them. This port is not reliable yet. * The Power PC is now supported. * The i860-based Paragon machine is now supported. * The Hitachi 3050 (an HP-PA machine) is now supported. * The variable __GNUC_MINOR__ holds the minor version number of GCC, as an integer. For version 2.5.X, the value is 5. * In C, initializers for static and global variables are now processed an element at a time, so that they don't need a lot of storage. * The C syntax for specifying which structure field comes next in an initializer is now `.FIELDNAME='. The corresponding syntax for array initializers is now `[INDEX]='. For example, char whitespace[256] = { [' '] = 1, ['\t'] = 1, ['\n'] = 1 }; This was changed to accord with the syntax proposed by the Numerical C Extensions Group (NCEG). * Complex numbers are now supported in C. Use the keyword __complex__ to declare complex data types. See the manual for details. * GCC now supports `long double' meaningfully on the Sparc (128-bit floating point) and on the 386 (96-bit floating point). The Sparc support is enabled on Solaris 2.x because earlier system versions (SunOS 4) have bugs in the emulation. * All targets now have assertions for cpu, machine and system. So you can now use assertions to distinguish among all supported targets. * Nested functions in C may now be inline. Just declare them inline in the usual way. * Packed structure members are now supported fully; it should be possible to access them on any supported target, no matter how little alignment they have. * To declare that a function does not return, you must now write something like this (works only in 2.5): void fatal () __attribute__ ((noreturn)); or like this (works in older versions too): typedef void voidfn (); volatile voidfn fatal; It used to be possible to do so by writing this: volatile void fatal (); but it turns out that ANSI C requires that to mean something else (which is useless). Likewise, to declare that a function is side-effect-free so that calls may be deleted or combined, write something like this (works only in 2.5): int computation () __attribute__ ((const)); or like this (works in older versions too): typedef int intfn (); const intfn computation; * The new option -iwithprefixbefore specifies a directory to add to the search path for include files in the same position where -I would put it, but uses the specified prefix just like -iwithprefix. * Basic block profiling has been enhanced to record the function the basic block comes from, and if the module was compiled for debugging, the line number and filename. A default version of the basic block support module has been added to libgcc2 that appends the basic block information to a text file 'bb.out'. Machine descriptions can now override the basic block support module in the target macro file. New features in g++: * The new flag `-fansi-overloading' for C++. Use a newly implemented scheme of argument matching for C++. It makes g++ more accurately obey the rules set down in Chapter 13 of the Annotated C++ Reference Manual (the ARM). This option will be turned on by default in a future release. * The -finline-debug flag is now gone (it was never really used by the compiler). * Recognizing the syntax for pointers to members, e.g., "foo::*bar", has been dramatically improved. You should not get any syntax errors or incorrect runtime results while using pointers to members correctly; if you do, it's a definite bug. * Forward declaration of an enum is now flagged as an error. * Class-local typedefs are now working properly. * Nested class support has been significantly improved. The compiler will now (in theory) support up to 240 nested classes before hitting other system limits (like memory size). * There is a new C version of the `g++' driver, to replace the old shell script. This should significantly improve the performance of executing g++ on a system where a user's PATH environment variable references many NFS-mounted filesystems. This driver also works under MS-DOS and OS/2. * The ANSI committee working on the C++ standard has adopted a new keyword `mutable'. This will allow you to make a specific member be modifiable in an otherwise const class. Noteworthy GCC changes in version 2.4.4: A crash building g++ on various hosts (including m68k) has been fixed. Also the g++ compiler no longer reports incorrect ambiguities in some situations where they do not exist, and const template member functions are now being found properly. Noteworthy GCC changes in version 2.4: * On each target, the default is now to return short structures compatibly with the "usual" compiler on that target. For most targets, this means the default is to return all structures in memory, like long structures, in whatever way is used on that target. Use -freg-struct-return to enable returning short structures (and unions) in registers. This change means that newly compiled binaries are incompatible with binaries compiled with previous versions of GCC. On some targets, GCC is itself the usual compiler. On these targets, the default way to return short structures is still in registers. Use -fpcc-struct-return to tell GCC to return them in memory. * There is now a floating point emulator which can imitate the way all supported target machines do floating point arithmetic. This makes it possible to have cross compilation to and from the VAX, and between machines of different endianness. However, this works only when the target machine description is updated to use the new facilities, and not all have been updated. This also makes possible support for longer floating point types. GCC 2.4 supports extended format on the 68K if you use `long double', for targets that have a 68881. (When we have run time library routines for extended floating point, then `long double' will use extended format on all 68K targets.) We expect to support extended floating point on the i386 and Sparc in future versions. * Building GCC now automatically fixes the system's header files. This should require no attention. * GCC now installs an unsigned data type as size_t when it fixes the header files (on all but a handful of old target machines). Therefore, the bug that size_t failed to be unsigned is fixed. * Building and installation are now completely separate. All new files are constructed during the build process; installation just copies them. * New targets supported: Clipper, Hitachi SH, Hitachi 8300, and Sparc Lite. * A totally new and much better Objective C run time system is included. * Objective C supports many new features. Alas, I can't describe them since I don't use that language; however, they are the same ones supported in recent versions of the NeXT operating system. * The builtin functions __builtin_apply_args, __builtin_apply and __builtin_return let you record the arguments and returned value of a function without knowing their number or type. * The builtin string variables __FUNCTION__ and __PRETTY_FUNCTION__ give the name of the function in the source, and a pretty-printed version of the name. The two are the same in C, but differ in C++. * Casts to union types do not yield lvalues. * ## before an empty rest argument discards the preceding sequence of non-whitespace characters from the macro definition. (This feature is subject to change.) New features specific to C++: * The manual contains a new section ``Common Misunderstandings with GNU C++'' that C++ users should read. * #pragma interface and #pragma implementation let you use the same C++ source file for both interface and implementation. However, this mechanism is still in transition. * Named returned values let you avoid an extra constructor call when a function result has a class type. * The C++ operators <? and >? yield min and max, respectively. * C++ gotos can exit a block safely even if the block has aggregates that require destructors. * gcc defines the macro __GNUG__ when compiling C++ programs. * GNU C++ now correctly distinguishes between the prefix and postfix forms of overloaded operator ++ and --. To avoid breaking old code, if a class defines only the prefix form, the compiler accepts either ++obj or obj++, unless -pedantic is used. * If you are using version 2.3 of libg++, you need to rebuild it with `make CC=gcc' to avoid mismatches in the definition of `size_t'. Newly documented compiler options: -fnostartfiles Omit the standard system startup files when linking. -fvolatile-global Consider memory references to extern and global data items to be volatile. -idirafter DIR Add DIR to the second include path. -iprefix PREFIX Specify PREFIX for later -iwithprefix options. -iwithprefix DIR Add PREFIX/DIR to the second include path. -mv8 Emit Sparc v8 code (with integer multiply and divide). -msparclite Emit Sparclite code (roughly v7.5). -print-libgcc-file-name Search for the libgcc.a file, print its absolute file name, and exit. -Woverloaded-virtual Warn when a derived class function declaration may be an error in defining a C++ virtual function. -Wtemplate-debugging When using templates in a C++ program, warn if debugging is not yet fully available. +eN Control how C++ virtual function definitions are used (like cfront 1.x). | http://opensource.apple.com/source/libstdcxx/libstdcxx-39/libstdcxx/gcc/ONEWS | CC-MAIN-2016-26 | refinedweb | 5,752 | 58.18 |
October 2006 [Revision number: V1-0]
The Java Platform, Enterprise Edition 5 (Java EE 5) Tools Bundle includes NetBeans IDE 5.5, NetBeans Enterprise Pack 5.5, and Java Platform, Enterprise Edition 5 SDK Update 1 or Update 2 (Java EE 5 SDK Update 1 or Update 2). The NetBeans Enterprise Pack 5.5 includes XML schema tools modules, BPEL modules, Secure Web Services modules, Project Open ESB Starter Kit, Sun Java System Access Manager 7.1, and Sun Java System Policy Agent 2.2 for Sun Java System Application Server 9.0 Update 1/ Web Services.
These release notes apply to the Java EE 5 Tools Bundle.
Note: The UML functionality is no longer available in the final (FCS) release of the NetBeans Enterprise Pack 5.5 download. Instead, the UML functionality is offered separately on the Auto Update Center.
Note: If you are looking for information about installing the software included in Java EE 5 Tools Bundle, see the Java EE 5 Tools Bundle Installation Instructions.
Supported Operating Systems
The NetBeans IDE 5.5 runs on operating systems that support the Java VM. Below is a list of platforms that the Java EE 5 Tools Bundle has been tested on.
NetBeans Enterprise Pack also runs on the following platforms:
Minimum Hardware Configuration
Note: The NetBeans IDE's minimum screen resolution is 1024x768 pixels.
Recommended Hardware Configuration
Required Software
NetBeans IDE 5.5 runs on the Java SE Development Kit 5.0 Update 9 or higher (JDK 5.0, version 1.5.0_09 or higher), which consists of the Java Runtime Environment plus developer tools for compiling, debugging, and running applications written in the Java language. Sun Java System Application Server Platform Edition 9 Update 1 has been tested with JDK 5.0 update 6.
Sun Java System Application Server Requirements
In order to use the J2EE development features of the Java EE 5 Tools Bundle, you must have Sun Java System Application Server Platform Edition 9 Update 1. This Application Server is bundled with the Java EE 5 Tools Bundle download.
This topic provides configuration information that you may need in order to configure the software.
Sun Java System Application Server
The default username and password values for the default Application Server domain,
domain1, are as follows:
username:
admin
adminadmin
Sun Java System Access Manager
If you need to access the administration console for the Access Manager server, use the following values:
username:
amadmin
admin123
Limitations in this NetBeans Enterprise Pack 5.5 release are as follows:
This Java EE 5 Tools Bundle lets you explore and evaluate new functionality in the IDE. We encourage you to send us feedback by logging any issues you encounter in the Issue Tracking system at.
Note: Refer to NetBeans IDE 5.5 Release Notes for the list of issues specific to the IDE.
The unresolved issues for this release are as follows:
Installation
tempdirectory.
Description: On Microsoft Windows, if your system is set up to use a temporary directory on your
Cdrive, and that temporary directory does not have enough space for the temporary files needed by the installer, the installer will report that there is not enough disk space on the
Cdrive. This is the case even if you chose to install to a different drive. The installer is in fact reporting that it needs additional temporary space.
The issue exists in the InstallShield framework.
Workaround: Start the installer with the
-is:tempdir custom-temp-dircommand line parameter. The
custom-temp-dirshould contain at least 130 MB of free disk space.
NoClassDefFoundError: cannot access amserveroccurs during installation.
Description: If you try to install the software a second time without cleaning up the Access Manager directory, the configuration of Access Manager may fail during installation.
Workaround:
- On Microsoft Windows:
Delete the directory specified in:
%SystemDrive%\Documents and Settings\ user-name\AMConfig_server_amserver_and then remove the file
%SystemDrive%\Documents and Settings\ user-name\AMConfig_server_amserver_.
- On UNIX/Mac OS X:
Delete the directory specified in:
$HOME\AMConfig_server_amserver_and then remove the file
$HOME\AMConfig_server_amserver_.
-consoleand
-silentoptions.
Description: On UNIX platforms, if the installer cannot run the installation process without the graphics mode, the installer suggests that you run it using the
-consoleand
-silentoptions. If you try this, the installer fails.
Workaround: Ignore the message from the installer and set up the GUI environment as described below to proceed with the installation.
The most common cause for this issue is that you are connecting to the target system via telnet/ssh/rlogin, which means you must redirect the GUI to the originating system. To do this successfully, the following two requirements must be met:
- An X server should be set up and running on the system from which you are connecting.
- The DISPLAY environment variable should be set to the correct value on the target system. Assuming a bash shell, the correct value and command for the variable are:
export DISPLAY= machine-name: display-number
Where
machine-nameis the IP address of the system from where you are connecting, and
display-numberis the number of the display, usually
0.0.
Description: If you try to install the product after performing a manual uninstallation by deleting files, the installation will fail because the data in InstallShield's VPD registry is not cleaned up.
Workaround: Before starting a new installation, remove the InstallShield VPD registry. This registry resides on Microsoft Windows in
%SystemDrive%\Program Files\Common Files\InstallShield\Universalor on Linux/Solaris/Mac OS X in
~/InstallShield.
Note that other applications (for example, NetBeans IDE) can use the InstallShield VPD registry to store their uninstallation data. The InstallShield VPD registry removal prevents such applications from correct uninstallation. It is strongly advised to uninstall applications that use the InstallShield Universal installer engine prior to removing the VPD registry.
Description: On Mac OS, if the default java version on your system is 1.4, you will not be able to double-click the
.jarfile to start the installation.
Workaround: Run the
.jarfile manually from the command line using java 1.5.
Description: On Microsoft Windows, if there is no preinstalled compatible JDK on the target machine, the InstallShield Windows launcher allows you to select a custom
java.exe. After you select a custom
java.exe, the installer does not perform a validation for compatibility. This means that if you select a
java.exefrom a 1.4 JRE which is not compatible with the installer, you will encounter a number of exceptions. The issue exists in the InstallShield framework.
Workaround: Select a
java.exefrom a 1.5 JRE. See Required Software for information about downloading and installing a compatible JDK.
Description: The installer fails to start correctly on UNIX when is there is little or no disk space in the root directory of the file system. The problem exists in the InstallShield framework. This issue was observed on machines with less than 2.5 MB free in the root of the file system.
Workaround: Free up enough disk space in the root of the file system and restart the installer.
Description: When dragging a tab, a black square area is being dragged. After you drop the tab problems with the Welcome screen repainting appear.
Workaround: Set -J-Dapple.awt.graphics.UseQuartz=true or use Java 1.5 for running the IDE (or _select_ Java 1.5 during the NetBeans Enterprise Pack installation).
BPEL
Description: The WSDL model cannot resolve portType when the main and imported WSDL have the same targetNamespace.
Workaround: Assign a namespace for the imported WSDL file, distinct from the namespace of the importing WSDL file.
Description: The BPEL Mapper is not refreshed after adding a new element in an XSD file.
Workaround: Close and reopen the Mapper window.
Description: Import of a WSDL file into another WSDL file is not validated. Corresponding error message displays.
Workaround: Go to the Source view of the WSDL Editor, remove the import and namespace that have just been added. Go to the tree mode of the WSDL view, and add the same import again.
Description: Today all xpath expressions created in the BPEL tool have a namespace prefix. In all prior versions of the tool xpath expressions were not prefixed with namespace. If you edit an older BPEL (created with an older version of the tool) and add new assigns to it, you will get a mix of prefixed and non-prefixed expressions since the engine cannot handle this mix. The following combination of problems may occur:
- You may not get the expected result because the non-prefixed expressions may not return a result.
- You may get an exception because the code expects a result to be returned and due to the missing prefix no results are returned.
Workaround: Manually edit non-prefixed expressions to add a prefix.
Description: The Unexpected Reply Activity Encountered. Possible Cause: Potential multiple reply activities for given receive activity. server-side error occurs when running the benchmark project in a multi-thread environment, that is:
- The BPEL-SE is configured with more than 1 thread (default is 10 threads)
- The BPEL-SE is running on a multi-processor machine (might occur on a very powerful single CPU machine too)
This problem can occur in any business process which receives a fault from another business process or an external web service and is running in a multi-threaded environment.
Since the benchmark project has a business process which receives a fault from another business process, this error displays while running the longetivity test.
The issue reproduces on Solaris and Windows.
Workaround: Change the benchmark project so that the business processes do not communincate using faults, but rather using normal replies.
Description: Currently runtime does not support time-outs for a process execution. This makes a business process wait for a certain event for unlimited time.
Workaround: Consider using Pick activities with onAlarm branches where applicable.
Description: After deploying the BluePrint4Application project to the application server, the sample tests will fail if not run in a specific order. This is caused by the use of correlation in the BluePrint 4 BPEL processes.
Workaround: Run the BluePrint4Application tests in any order specified below:
- poServiceRequest -> poRequestCancel
- poServiceRequest -> poRequestConfirm
Description: If you cancel the PartnerLink dialog that appears when you drag a WSDL file or a Web Service node from a NetBeans project onto a diagram, the IDE does not roll back the retrieval of the WSDL files(s).
Workaround: If these files are not needed by the project, simply delete them manually from the Projects window, as you would delete any other project resource.
Description: If you delete a property from a correlation set using pop-up menu commands in the Navigator, the property is incorrectly deleted from the WSDL file.
Workaround: Use the correlation set property editor to delete a property from a correlation set correctly.
Description: If the interface of your partner service changes, for example, when the signature of a web service operation changes, and you have not imported the modified WSDL file, then the BPEL process hangs.
Workaround: Import the new WSDL file and redeploy the application. The BPEL service engine restart may require.
Description: The Unable to Show Diagram message displays although the BPEL file is well-formed.
Workaround: Restart the IDE.
Description: Invoking actions from the Navigator for a broken BPEL may lead to exceptions thrown or the IDE hang.
Workaround: All actions should be disabled from the Navigator when BPEL is broken. Do not invoke actions for a broken BPEL from the Navigator. Correct the BPEL first.
Description: On UNIX, after double-clicking the text field in the string literal box changes to the edit mode for a second and then goes back to the non-edit mode.
Workaround: Double-click the text field in the string literal box, then click a white place inside the BPEL Mapper editor field quickly (before it turns back to the non-edit mode). The string literal box will stay in the edit mode.
Description: NetBeans Visual Web Pack 5.5 breaks the drag and drop functionality in NetBeans Enterprise Pack 5.5 BPEL/SOA projects.
Workaround: Choose Tools > Update Center from the main NetBeans IDE menu to launch the Update Center Wizard. Install Update 1 for NetBeans Visual Web Pack 5.5 final release via the Update Center.
Note that though Update 1 is visible for the NetBeans Visual Web Pack 5.5 Technology Preview users, you need to uninstall the Technology Preview release and download and install the final release of the NetBeans Visual Web Pack 5.5 from the NetBeans Visual Web Pack 5.5 Download page for the Update 1 to take effect.
Secure Web Services
Description: Execution of secure web services enabled application with liberty profile fails if the URL is "localhost"-based. When the Run project is invoked from the IDE, the default URL generated by the IDE includes localhost.
Workaround: Access the stockclient from the browser with the hostname that does not include the localhost name.
Description: If you add Liberty Token Profile secured J2EE modules to the Enterprise Application project, the roles added to the J2EE modules need to be manually added in the Enterprise Application for end-to-end security to work.
Workaround: Manually add the lines below to the EnterpriseApplication->Configuration Files->sun-application.xml file using the xml text editor.<security-role-mapping> <role-name>AUTHENTICATED_USERS</role-name> <principal-name>AUTHENTICATED_USERS</principal-name> </security-role-mapping>
Description: On Windows, the NetBeans Enterprise Pack 5.5 uses the proxy settings for the Internet Explorer as the system proxy settings. This may cause the connection failure and makes editing of Access Manager profiles unavailable if the IE's proxy settings are incorrect.
Workaround: Set up your own proxy settings in the IDE. Open Tools > Options dialog, switch to HTTP Proxy and enter the correct proxy settings.
Description: This is an Access Manager feature. There is a setting in AMConfig.properties for a timeout limit on response from discovery service. The registration request is rejected as an "old message" due to the time difference between the system clocks.
Workaround: Put the system clocks in synch.
Description: Access Manager is not supported for Java version 1.6.
Workaround: Use Java 1.5.x to run the Access Manager.
Description: If the Access Manager server configuration is changed after an installation, the AMConfig.properties file does not get modified to reflect the changes. This can cause discrepancies between the configured Access Manager server and the AMConfig.properties file resulting in the IDE not being able to talk to the Access Manager server via the client SDK.
Workaround: Manually sync up the client's AMConfig.properties file to reflect the proper Access Manager server information.
XML Schema Tools
Description: When using the column view, sometimes only one of the multi selected nodes is removed after the Delete command from the pop-up menu is invoked on them .
Workaround: Multi select and use the Delete key, or sequentially single select and choose Delete from the context menu, or use the Tree Editor.
XML Schema Tools, BPEL, and Secure Web Services Modules
The issues described below occur with IDE when using the NetBeans Enterprise Pack 5.5 modules.
Description: On Mac OS X, Solaris, and Linux, the IDE does not recognize projects created under root directory
"/".
Workaround: Create projects in a folder.
Description: When running the IDE on Red Hat Fedora Core 3 in the zh_CN locale and possibly some other Asian locales, the text may be unreadable because of rendering problems. This problem is a result of font support issues with the JDK on the Fedora Core distribution, so this problem also might apply to other Java applications running on Fedora Core.
Workaround: There is no safe workaround for the rendering problem on Red Hat Fedora Core 3, so it is best to use a different Linux distribution or operating system in these locales. We have verified that this problem does not occur on Red Hat Enterprise Linux 3.
See Also: | http://www.oracle.com/technetwork/java/javaee/sdkentpack-relnotes-jsp-135373.html | CC-MAIN-2015-40 | refinedweb | 2,657 | 55.95 |
One way to address the difficulties and better support the design of multithreaded applications is to transfer the creation and management of threading from application developers to compilers and run-time libraries. This, termed implicit threading, is a popular trend today.
Implicit threading is mainly the use of libraries or other language support to hide the management of threads. The most common implicit threading library is OpenMP, in context of C.
Open:
#include <omp.h> #include <stdio.h> int main(int argc, char *argv[]){ /* sequential code */ #pragma omp parallel{ printf("I am a parallel region."); } /* sequential code */ return 0; }
I am a parallel region.. Eg, they can set the number of threads manually. It also allows developers to identify whether data are shared between threads or are private to a thread. OpenMP is available on several open-source and commercial compilers for Linux, Windows, and Mac OS X systems.
Grand Central Dispatch (GCD)—a technology for Apple’s Mac OS X and iOS operating systems—is a combination of extensions to the C language, an API, and a run-time library that allows application developers to spot sections of code to run in parallel. Like OpenMP, GCD also manages most of the details of threading. It identifies extensions to the C and C++ languages known as blocks. A block is simply a self-contained unit of work. It is specified by a caret ˆ inserted in front of a pair of braces { }. A simple example of a block is shown below −
{ ˆprintf("This is a block"); }
It schedules blocks for run-time execution by placing them on a dispatch queue. When GCD removes a block from a queue, it assigns the block to an available thread from the thread pool it manages. It identifies two types of dispatch queues: serial and concurrent. Blocks placed on a serial queue are removed in FIFO order. Once a block has been removed from the queue, it must complete execution before another block is removed. Each process has its own serial queue (known as main queue). Developer can create additional serial queues that are local to particular processes. Serial queues are useful for ensuring the sequential execution of several tasks. Blocks placed on a concurrent queue are also removed in FIFO order, but several blocks may be removed at a time, thus allowing multiple blocks to execute in parallel. There are three system-wide concurrent dispatch queues, and they are distinguished according to priority: low, default, and high. Priorities represent an estimation of the relative importance of blocks. Quite simply, blocks with a higher priority should be placed on the high priority dispatch queue. The following code segment illustrates obtaining the default-priority concurrent queue and submitting a block to the queue using the dispatch async() function:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch async(queue, ˆ{ printf("This is a block."); });
Internally, GCD’s thread pool is composed of POSIX threads. GCD actively manages the pool, allowing the number of threads to grow and shrink according to application demand and system capacity.
In alternative languages, ancient object-oriented languages give explicit multithreading support with threads as objects. In these forms of languages, classes area written to either extend a thread class or implement a corresponding interface. This style resembles the Pthread approach, because the code is written with explicit thread management. However, the encapsulation of information inside the classes and extra synchronization options modify the task.
Java provides a Thread category and a Runnable interface that can be used. Each need to implement a public void run() technique that defines the entry purpose of the thread. Once an instance of the object is allotted, the thread is started by invoking the start() technique on that. Like with Pthreads, beginning the thread is asynchronous, that the temporal arrangement of the execution is non-deterministic.
Python additionally provides two mechanisms for multithreading. One approach is comparable to the Pthread style, wherever a function name is passed to a library method thread.start_new_thread(). This approach is very much and lacks the flexibility to join or terminate the thread once it starts. A additional flexible technique is to use the threading module to outline a class that extends threading. Thread. almost like the Java approach, the category should have a run() method that gives the thread's entry purpose. Once an object is instantiated from this category, it can be explicitly started and joined later.
Newer programming languages have avoided race condition by building assumptions of concurrent execution directly into the language style itself. As an example, Go combines a trivial implicit threading technique (goroutines) with channels, a well-defined style of message-passing communication. Rust adopts a definite threading approach the same as Pthreads. However, Rust has terribly strong memory protections that need no extra work by the software engineer.
The Go language includes a trivial mechanism for implicit threading: place the keyword go before a call. The new thread is passed an association to a message-passing channel. Then, the most thread calls success := <-messages, that performs a interference scan on the channel. Once the user has entered the right guess of seven, the keyboard auditor thread writes to the channel, permitting the most thread to progress.
Channels and goroutines are core components of the Go language, that was designed beneath the belief that almost all programs would be multithreaded. This style alternative streamlines the event model, permitting the language itself up-to-date the responsibility for managing the threads and programing.
Another language is Rust that has been created in recent years, with concurrency as a central design feature. The following example illustrates the use of thread::spawn() to create a new thread, which can later be joined by invoking join() on it. The argument to thread::spawn() beginning at the || is known as a closure, which can be thought of as an anonymous function. That is, the child thread here will print the value of a.
use std::thread; fn main() { /* Initialize a mutable variable a to 7 */ let mut a = 7; /* Spawn a new thread */ let child_thread = thread::spawn(move || { /* Make the thread sleep for one second, then print a */ a -= 1; println!("a = {}", a) }); /* Change a in the main thread and print it */ a += 1; println!("a = {}", a); /* Join the thread and print a again */ child_thread.join(); }
However, there is a subtle point in this code that is central to Rust's design. Within the new thread (executing the code in the closure), the a variable is distinct from the a in other parts of this code. It enforces a very strict memory model (known as "ownership") which prevents multiple threads from accessing the same memory. In this example, the move keyword indicates that the spawned thread will receive a separate copy of a for its own use. Regardless of the scheduling of the two threads, the main and child threads cannot interfere with each other's modifications of a, because they are distinct copies. It is not possible for the two threads to share access to the same memory. | https://www.tutorialspoint.com/implicit-threading-and-language-based-threads | CC-MAIN-2021-17 | refinedweb | 1,178 | 54.42 |
In a previous posting, I began a fast and furious mini-tutorial on building a hyper-video player. In this segment, I’ll demonstrate how to:
- Use Encoder to add markers to a video
- Use Encoder to create a player
- Modify the player Encoder creates using templates
- Have the player respond to each marker as it is encountered
To begin, you’ll need a bit of video. I downloaded the 4th segment of the video on Building a Skinnable Custom Control and then cut out the middle to create a very abridged version that runs just over a minute.
I then imported that video into Encoder, and added markers as shown in the earlier blog entry.
Use Encoder to create a player
With the markers in place I turned to creating my player. Again, this is reviewed in the previous blog entry so I won’t repeat that here, but now we’re ready to actually make the changes. For today’s exercise, this is a process of eliminating those controls that we don’t need. We’ll start by opening the player in Expression Blend and as with any custom control you may now ask to edit a copy of the template,
You are prompted, as usual to pick a name and to choose whether to put the template into the file or into App.xaml (for the entire application). We’ll choose the latter. Once these choices are made you are dropped into the template editor, the view states are revealed as are the parts of the media player.
This allows you to drill down into the player and simply delete those controls we won’t need, including the entire set of “miscControls,”
which are conveniently highlighted on the player to indicate which controls you are about to assassinate,
In the same way, I proceeded to eliminate the buttons used for rapid navigation
Once these were deleted the player was simplified and ready for use.
Responding to the Markers
I’d like to tell you that responding to the markers that we added to the video involves a bit of tricky programming, and you’re lucky you found my blog because I can show you how to do it right….
Opening the project in Visual Studio reveals otherwise. You’ll remember that what we’ve created is a template for the ExpressionPlayer class that was emitted by Encoder and that is found in ExpressionPlayerClass.cs:
namespace ExpressionMediaPlayer
{
public class ExpressionPlayer : MediaPlayer
Stripping out the using statements and comments reveals that the class created by Encoder is just a specialization of Media Player. MediaPlayer’s source is provided as well. Opening MediaPlayer.cs and scrolling down to the Events region reveals this:
public event TimelineMarkerRoutedEventHandler MarkerReached;
That is the event we want to respond to; it is fired every time the player encounters a marker in the video.
The EventArgs type that we are passed is well documented in the standard Silverlight documentation, which includes among other things sample code that makes our work embarrassingly easy,
public void OnMarkerReached(object sender, TimelineMarkerRoutedEventArgs e)
{
timeTextBlock.Text = e.Marker.Time.Seconds.ToString();
typeTextBlock.Text = e.Marker.Type.ToString();
valueTextBlock.Text = e.Marker.Text.ToString();
}
All we need is a TextBlock to display the values we’ll receive when we hit the marker. Open Page.xaml and add two rows to the grid, and a TextBlock in the second row,
<Grid x:
<Grid.RowDefinitions>
<RowDefinition
Height="9*" />
<RowDefinition
Height="0.5*" />
</Grid.RowDefinitions>
<ExpressionPlayer:ExpressionPlayer
Margin="0,0,0,0"
x:Name="myPlayer"
Style='{StaticResource ExpressionPlayerBlogVersion }'
Grid.
<TextBlock
x:Name='Message'
Grid.
</Grid>
You can now implement the event handler in Page.xaml.cs,
public partial class Page : UserControl
{
public Page( object sender, StartupEventArgs e )
{
InitializeComponent();
myPlayer.OnStartup( sender, e );
myPlayer.MarkerReached +=
new TimelineMarkerRoutedEventHandler( myPlayer_MarkerReached );
}
void myPlayer_MarkerReached( object sender,
TimelineMarkerRoutedEventArgs e )
{
Message.Text = e.Marker.Text + " at " + e.Marker.Time.Seconds.ToString() +
" seconds."
}
}
The result, as we hoped, is that the player shows the video and when it encounters a marker, it shows the name of the marker and the time the marker was hit. The easiest way to test this is to navigate to the output directory you designated in encoder,
and pick up a copy of the the Default.html and the .wmv file output by encoder. Drop these in the debug directory of the encoder folder
Double click on Default.html and “let ‘er rip!”
Note the marker indicated at just below the (cropped) player. Be careful when you recompile, the default.html in the Encoder project will be over-written.
Previous: HyperVideo: Getting Started Next: HyperVideo Put To Work | http://jesseliberty.com/2009/01/05/building-a-hypervideo-player-%E2%80%93-1/ | CC-MAIN-2021-31 | refinedweb | 771 | 53.1 |
In this blog, I will walk you through the basics of NumPy. If you want to do machine learning then knowledge of NumPy is necessary. It one of the most widely used python library Numeric Python. It is the most useful library if you are dealing with numbers in python. NumPy guarantees great execution speed comparing it with python standard libraries. It comes with a great number of built-in function.
Advantages of using NumPy with Python:
- array-oriented computing
- efficiently implemented multi-dimensional arrays
- designed for scientific computation
First, let’s talk about its installation. NumPy is not part of a basic Python installation. We need to install it after the installation of python in our system. We can do it by pip using command pip install NumPy or it comes with conda as well.
We are done with the installation and now let’s jump right into NumPy. First, let start with the most important object in NumPy that is the ndarray or multi-dimensional array. Multi-dimensional array in similar words in an array of arrays which means array for example [1,2,3] is a one-dimensional array because it contains only one row where two-dimensional array as given below contain multiple rows as well as multiple columns.
[[1 2 3]
[4 5 6]
[7 8 9]]
Let’s do some coding now. Here I am using Jupyter Notebook to run my code you can use any IDE available and best suited to you.
We start with import NumPy into our project first and in order to do so just write import NumPy.
In the following code, I am renaming the package as np just for my convince.
import numpy as np
Now in order to create an array in NumPy, we are call use it’s array function as mentioned below
array = np.array([1,2,3]) print(array) Output: [1 2 3]
This an example of a one-dimensional array.
Another way to create an array in NumPy is by using zeros function.
zeros = np.zeros(3) print(zeros) Output: [0. 0. 0.]
If you look closely at the output the generated array contains three zeros but the type of the value is a float and by default, NumPy creates the array of float values.
type(zeros[0]) Output: numpy.float64
Going back to the first example inside NumPy’s array function we pass a list so we can also pass the list variable inside array function and the output will be the same.
my_list = [1,2,3] array = np.array(my_list) print(array) Output: [1 2 3]
Now let’s look into how to create a two-dimensional array using NumPy. Instead of passing the list now we have to pass a list of tuples or list of lists as mentioned below.
two_dim_array = np.array([(1,2,3), (4,5,6), (7,8,9)]) print(two_dim_array) Output: [[1 2 3] [4 5 6] [7 8 9]]
Note that the number of columns should be equal otherwise NumPy will create an array of a list.
arr = np.array([[1,2,3], [4,6], [7,8,9]]) print(arr) Output: [list([1, 2, 3]) list([4, 6]) list([7, 8, 9])]
Now to create an array of a range which very good for making plot we use the linspace function.
range_array = np.linspace(0, 10, 4) print(range_array) Output: [ 0. 3.33333333 6.66666667 10. ]
Here the first argument is the starting point and next is the endpoint and the last argument defines how many elements you want in your array.
Now to create random arrays we can use random function. Here I created an array of random integers, therefore, used randint where first I specified the maximum value and then the size of my array.
random_array = np.random.randint(15, size=10) print(random_array) Output: [ 7 11 8 2 6 4 9 6 10 9]
Now we know the basic of how to create arrays in NumPy. Now let’s look into some of its basic operations. First, we will start by finding the size and shape of an array. Size will give the number of elements in an array where shape will give us the shape of an array.
For a one dimensional array, the shape would be (n,) where n is the number of elements in your array.
For a two dimensional array, the shape would be (n,m) where n is the number of rows and m is the number of columns in your array.
print(array.size) Output: 3 print(array.shape) Output: (3,) print(multi_dim_array.size) Output: 9 print(multi_dim_array.shape) Output: (3, 3)
If we want to change the shape of an array we can easily do it with reshape function. It will look like something
two_dim_array = np.array([(1,2,3,4), (5,6,7,8)]) two_dim_array = two_dim_array.reshape(4,2) print(two_dim_array) Output: [[1 2] [3 4] [5 6] [7 8]]
We need to make sure that the rows and columns can be interchangeable for example here we can change rows and columns from (2,4) to (4,2) but can not to (4,3) because for that we need 12 elements and here we have only 8. Doing so will give an error as mentioned below.
ValueError: cannot reshape array of size 8 into shape (4,3)
To check the dimension of our array we can use the ndim function.
print(two_dim_array.ndim) Output: 2
Now to get values from array also known as slicing can be done in various ways. For example array[1] will fetch the second element of my array but if I want a range we can use array[0:1] which will bring me the first two elements. For the last value of the array, we can use array[-1] similar to the standard method of getting elements from the list in python.
Now to find the sum all we have to use is sum() function but if we want to find the sum of axis we can pass an argument for the axis.
print(two_dim_array.sum(axis=0)) Output: [ 6 8 10 12] print(two_dim_array.sum(axis=1)) Output: [10 26]
Now to add two array all we have to use if + operator for example:
print(two_dim_array + two_dim_array) Output: [[ 2 4 6 8] [10 12 14 16]]
Similarly, we can use other operands as well like multiple, subtract and divide.
We have many other operations present in NumPy like sqrt which will give us the square root of every element and std to find the standard deviation. To explore more about these operations visit the NumPy’s documentation.
And that’s it for the introduction of NumPy.
Resources: | https://blog.knoldus.com/introduction-to-numpy/ | CC-MAIN-2021-04 | refinedweb | 1,120 | 70.33 |
This namespace is a collection of algorithms working on triangulations, such as shifting or rotating triangulations, but also finding a cell that contains a given point. See the descriptions of the individual functions for more information.
The enum type given to the Cache class to select what information to update.
You can select more than one flag by concatenation using the bitwise or
operator|(CacheUpdateFlags,CacheUpdateFlags).
Definition at line 35 of file grid_tools_cache_update_flags.h.
Return the diameter of a triangulation. The diameter is computed using only the vertices, i.e. if the diameter should be larger than the maximal distance between boundary vertices due to a higher order mapping, then this function will not catch this.
Definition at line 76 of file grid_tools.cc.
Compute the volume (i.e. the dim-dimensional measure) of the triangulation. We compute the measure using the integral \(\sum_K \int_K 1 \; dx\) where \(K\) are the cells of the given triangulation. The integral is approximated via quadrature for which we need the mapping argument.
If the triangulation is a dim-dimensional one embedded in a higher dimensional space of dimension spacedim, then the value returned is the dim-dimensional measure. For example, for a two-dimensional triangulation in three-dimensional space, the value returned is the area of the surface so described. (This obviously makes sense since the spacedim-dimensional measure of a dim-dimensional triangulation would always be zero if dim < spacedim.
This function also works for objects of type parallel::distributed::Triangulation, in which case the function is a collective operation.
Definition at line 133 of file grid_tools.cc.
Return an approximation of the diameter of the smallest active cell of a triangulation. See step-24 for an example of use of this function.
Notice that, even if you pass a non-trivial mapping, 3280 of file grid_tools.cc.
Return an approximation of the diameter of the largest active cell of a triangulation.
Notice that, even if you pass a non-trivial mapping to this function, 3308 of file grid_tools.cc.
Given a list of vertices (typically obtained using Triangulation::get_vertices) as the first, and a list of vertex indices that characterize a single cell as the second argument, return the measure (area, volume) of this cell. If this is a real cell, then you can get the same result using
cell->measure(), but this function also works for cells that do not exist except that you make it up by naming its vertices from the list.
A version of the last function that can accept input for nonzero codimension cases. This function only exists to aid generic programming and calling it will just raise an exception.
Computes an aspect ratio measure for all locally-owned active cells and fills a vector with one entry per cell, given a
triangulation and
mapping. The size of the vector that is returned equals the number of active cells. The vector contains zero for non locally-owned cells. The aspect ratio of a cell is defined as the ratio of the maximum to minimum singular value of the Jacobian, taking the maximum over all quadrature points of a quadrature rule specified via
quadrature. For example, for the special case of rectangular elements in 2d with dimensions \(a\) and \(b\) ( \(a \geq b\)), this function returns the usual aspect ratio definition \(a/b\). The above definition using singular values is a generalization to arbitrarily deformed elements. This function is intended to be used for \(d=2,3\) space dimensions, but it can also be used for \(d=1\) returning a value of 1.
Definition at line 419 of file grid_tools.cc.
Computes the maximum aspect ratio by taking the maximum over all cells.
Definition at line 485 of file grid_tools.cc.
Compute the smallest box containing the entire triangulation.
If the input triangulation is a
parallel::distributed::Triangulation, then each processor will compute a bounding box enclosing all locally owned, ghost, and artificial cells. In the case of a domain without curved boundaries, these bounding boxes will all agree between processors because the union of the areas occupied by artificial and ghost cells equals the union of the areas occupied by the cells that other processors own. However, if the domain has curved boundaries, this is no longer the case. The bounding box returned may be appropriate for the current processor, but different from the bounding boxes computed on other processors.
Definition at line 501 of file grid_tools.cc.
Return the point on the geometrical object
object closest to the given point
trial_point. For example, if
object is a one-dimensional line or edge, then the returned point will be a point on the geodesic that connects the vertices as the manifold associated with the object sees it (i.e., the geometric line may be curved if it lives in a higher dimensional space). If the iterator points to a quadrilateral in a higher dimensional space, then the returned point lies within the convex hull of the vertices of the quad as seen by the associated manifold.
object) but may only provide a few correct digits if the object has high curvature. If your manifold supports it then the specialized function Manifold::project_to_manifold() may perform better.
Return the arrays that define the coarse mesh of a Triangulation. This function is the inverse of Triangulation::create_triangulation().
The return value is a tuple with the vector of vertices, the vector of cells, and a SubCellData structure. The latter contains additional information about faces and lines.
This function is useful in cases where one needs to deconstruct a Triangulation or manipulate the numbering of the vertices in some way: an example is GridGenerator::merge_triangulations().
Definition at line 643 of file grid_tools.cc.
Remove vertices that are not referenced by any of the cells. This function is called by all
GridIn::read_* functions to eliminate vertices that are listed in the input files but are not used by the cells in the input file. While these vertices should not be in the input from the beginning, they sometimes are, most often when some cells have been removed by hand without wanting to update the vertex lists, as they might be lengthy.
This function is called by all
GridIn::read_* functions as the triangulation class requires them to be called with used vertices only. This is so, since the vertices are copied verbatim by that class, so we have to eliminate unused vertices beforehand.
Not implemented for the codimension one case.
Definition at line 740 of file grid_tools.cc.
Remove vertices that are duplicated, due to the input of a structured grid, for example. If these vertices are not removed, the faces bounded by these vertices become part of the boundary, even if they are in the interior of the mesh.
This function is called by some
GridIn::read_* functions. Only the vertices with indices in
considered_vertices are tested for equality. This speeds up the algorithm, which is, for worst-case hyper cube geometries \(O(N^{3/2})\) in 2D and \(O(N^{5/3})\) in 3D: quite slow. However, if you wish to consider all vertices, simply pass an empty vector. In that case, the function fills
considered_vertices with all vertices.
Two vertices are considered equal if their difference in each coordinate direction is less than
tol.
Definition at line 841 of file grid_tools.cc.
Transform the vertices of the given triangulation by applying the function object provided as first argument to all its vertices.
The transformation given as argument is used to transform each vertex. Its respective type has to offer a function-like syntax, i.e. the predicate is either an object of a type that has an
operator(), or it is a pointer to the function. In either case, argument and return value have to be of type
Point<spacedim>.
This function is used in the "Possibilities for extensions" section of step-38. It is also used in step-49 and step-53.
Shift each vertex of the triangulation by the given shift vector. This function uses the transform() function above, so the requirements on the triangulation stated there hold for this function as well.
Definition at line 1064 of file grid_tools.cc.
Rotate all vertices of the given two-dimensional triangulation in counter-clockwise sense around the origin of the coordinate system by the given angle (given in radians, rather than degrees). This function uses the transform() function above, so the requirements on the triangulation stated there hold for this function as well.
Definition at line 1073 of file grid_tools.cc.
Rotate all vertices of the given
triangulation in counter-clockwise direction around the axis with the given index. Otherwise like the function above.
Definition at line 1080 of file grid_tools.cc.
Transform the given triangulation smoothly to a different domain where, typically, each of the vertices at the boundary of the triangulation is mapped to the corresponding points in the
new_points map.
The unknown displacement field \(u_d(\mathbf x)\) in direction \(d\) is obtained from the minimization problem
\[ \min\, \int \frac{1}{2} c(\mathbf x) \mathbf \nabla u_d(\mathbf x) \cdot \mathbf \nabla u_d(\mathbf x) \,\rm d x \]
subject to prescribed constraints. The minimizer is obtained by solving the Laplace equation of the dim components of a displacement field that maps the current domain into one described by
new_points . Linear finite elements with four Gaussian quadrature points in each direction are used. The difference between the vertex positions specified in
new_points and their current value in
tria therefore represents the prescribed values of this displacement field at the boundary of the domain, or more precisely at all of those locations for which
new_points provides values (which may be at part of the boundary, or even in the interior of the domain). The function then evaluates this displacement field at each unconstrained vertex and uses it to place the mapped vertex where the displacement field locates it. Because the solution of the Laplace equation is smooth, this guarantees a smooth mapping from the old domain to the new one.
Return a std::map with all vertices of faces located in the boundary
Definition at line 1235 of file grid_tools.cc.
Scale the entire triangulation by the given factor. To preserve the orientation of the triangulation, the factor must be positive.
This function uses the transform() function above, so the requirements on the triangulation stated there hold for this function as well.
Definition at line 1091 of file grid_tools.cc.
Distort the given triangulation by randomly moving around all the vertices of the grid. The direction of movement of each vertex is random, while the length of the shift vector has a value of
factor times the minimal length of the active edges adjacent to this vertex. Note that
factor should obviously be well below
0.5.
If
keep_boundary is set to
true (which is the default), then boundary vertices are not moved.
Distort a triangulation in some random way.
Definition at line 1268 of file grid_tools.cc.
Remove hanging nodes from a grid. If the
isotropic parameter is set to
false (default) this function detects cells with hanging nodes and refines the neighbours in the direction that removes hanging nodes. If the
isotropic parameter is set to
true, the neighbours refinement is made in each directions. In order to remove all hanging nodes this procedure has to be repeated: this could require a large number of iterations. To avoid this a max number (
max_iterations) of iteration is provided.
Consider the following grid:
isotropic ==
false would return:
isotropic ==
true would return:
Definition at line 4068 of file grid_tools.cc.
Refine a mesh anisotropically such that the resulting mesh is composed by cells with maximum ratio between dimensions less than
max_ratio. This procedure requires an algorithm that may not terminate. Consequently, it is possible to set a maximum number of iterations through the
max_iterations parameter.
Starting from a cell like this:
This function would return:
Definition at line 4101 of file grid_tools.cc.
Analyze the boundary cells of a mesh, and if one cell is found at a corner position (with dim adjacent faces on the boundary), and its dim-dimensional angle fraction exceeds
limit_angle_fraction, refine globally once, and replace the children of such cell with children where the corner is no longer offending the given angle fraction.
If no boundary cells exist with two adjacent faces on the boundary, then the triangulation is left untouched. If instead we do have cells with dim adjacent faces on the boundary, then the fraction between the dim-dimensional solid angle and dim*pi/2 is checked against the parameter
limit_angle_fraction. If it is higher, the grid is refined once, and the children of the offending cell are replaced with some cells that instead respect the limit. After this process the triangulation is flattened, and all Manifold objects are restored as they were in the original triangulation.
An example is given by the following mesh, obtained by attaching a SphericalManifold to a mesh generated using GridGenerator::hyper_cube:
The four cells that were originally the corners of a square will give you some troubles during computations, as the jacobian of the transformation from the reference cell to those cells will go to zero, affecting the error constants of the finite element estimates.
Those cells have a corner with an angle that is very close to 180 degrees, i.e., an angle fraction very close to one.
The same code, adding a call to regularize_corner_cells:
generates a mesh that has a much better behaviour w.r.t. the jacobian of the Mapping:
This mesh is very similar to the one obtained by GridGenerator::hyper_ball. However, using GridTools::regularize_corner_cells one has the freedom to choose when to apply the regularization, i.e., one could in principle first refine a few times, and then call the regularize_corner_cells function:
This generates the following mesh:
The function is currently implemented only for dim = 2 and will throw an exception if called with dim = 3.
Definition at line 4130 of file grid_tools.cc.
Given a Triangulation's
cache and a list of
points create the quadrature rules.
cells: A vector of all the cells containing at least one of the
points.
qpoints: A vector of vectors of points.
qpoints[i] contains the reference positions of all points that fall within the cell
cells[i] .
indices: A vector of vectors of integers, containing the mapping between local numbering in
qpoints, and global index in
points.
If
points[a] and
points[b] are the only two points that fall in
cells[c], then
qpoints[c][0] and
qpoints[c][1] are the reference positions of
points[a] and
points[b] in
cells[c], and
indices[c][0] = a,
indices[c][1] = b. The function Mapping::transform_unit_to_real(qpoints[c][0]) returns
points[a].
The algorithm assumes it's easier to look for a point in the cell that was used previously. For this reason random points are, computationally speaking, the worst case scenario while points grouped by the cell to which they belong are the best case. Pre-sorting points, trying to minimize distances between them, might make the function extremely faster.
return_type, is
Definition at line 4445 of file grid_tools.cc.
This function is similar to GridTools::compute_point_locations(), but it tries to find and transform every point of
points.
return_typecontains the indices of points which are neither found inside the mesh nor lie in artificial cells. The
return_typeequals the following tuple type:
For a more detailed documentation see GridTools::compute_point_locations().
Definition at line 4481 of file grid_tools.cc.
Given a
cache and a list of
local_points for each process, find the points lying on the locally owned part of the mesh and compute the quadrature rules for them. Distributed compute point locations is a function similar to GridTools::compute_point_locations but working for parallel::TriangulationBase objects and, unlike its serial version, also for a distributed triangulation (see parallel::distributed::Triangulation).
The elements of the output tuple are:
qpoints[i] the reference positions of all points that fall within the cell
cells[i] .
points[i][j] is the point in the real space corresponding. to
qpoints[i][j] . Notice
pointsare the points lying on the locally owned part of the mesh; thus these can be either copies of
local_pointsor points received from other processes i.e. local_points for other processes
owners[i][j] contains the rank of the process owning the point[i][j] (previous element of the tuple).
The function uses the triangulation's mpi communicator: for this reason it throws an assert error if the Triangulation is not derived from parallel::TriangulationBase .
In a serial execution the first three elements of the tuple are the same as in GridTools::compute_point_locations .
Note: this function is a collective operation.
return_type, is
Definition at line 5192 of file grid_tools.cc.
Return a map
vertex index -> Point<spacedim> containing the used vertices of the given
container. The key of the returned map (i.e., the first element of the pair above) is the global index in the triangulation, whereas the value of each pair is the physical location of the corresponding vertex. The used vertices are obtained by looping over all cells, and querying for each cell where its vertices are through the (optional)
mapping argument.
In serial Triangulation objects and parallel::shared::Triangulation objects, the size of the returned map equals Triangulation::n_used_vertices() (not Triangulation::n_vertices()). Note that in parallel::distributed::Triangulation objects, only vertices in locally owned cells and ghost cells are returned, as for all other vertices their real location might not be known (e.g. for distributed computations using MappingQEulerian).
If you use the default
mapping, the returned map satisfies the following equality:
Notice that the above is not satisfied for mappings that change the location of vertices, like MappingQEulerian.
Definition at line 5426 of file grid_tools.cc.
Find and return the index of the closest vertex to a given point in the map of vertices passed as the first argument.
p.
Definition at line 5445 of file grid_tools.cc.
Find and return the index of the used vertex (or marked vertex) in a given mesh that is located closest to a given point.
This function uses the locations of vertices as stored in the triangulation. This is usually sufficient, unless you are using a Mapping that moves the vertices around (for example, MappingQEulerian). In this case, you should call the function with the same name and with an additional Mapping argument.
Definition at line 1505 of file grid_tools.cc.
Find and return the index of the used vertex (or marked vertex) in a given mesh that is located closest to a given point. Use the given mapping to compute the actual location of the vertices.
If the Mapping does not modify the position of the mesh vertices (like, for example, MappingQEulerian does), then this function is equivalent to the one with the same name, and without the
mapping argument.
Definition at line 1571 of file grid_tools.cc.
Find and return a vector of iterators to active cells that surround a given vertex with index
vertex_index.
For locally refined grids, the vertex itself might not be a vertex of all adjacent cells that are returned. However, it will always be either a vertex of a cell or be a hanging node located on a face or an edge of it.
Definition at line 1633 of file grid_tools.cc.
Find and return an iterator to the active cell that surrounds a given point. This function simply calls the following one with a MappingQ1 for the mapping argument. See the following function for a more thorough discussion.
Definition at line 549 of file grid_tools_dof_handlers.cc.
Find and return an iterator to the active cell that surrounds a given point
p.
The algorithm used in this function proceeds by first looking for the vertex located closest to the given point, see GridTools::find_closest_vertex(). Secondly, all adjacent cells to this vertex are found in the mesh, see GridTools::find_cells_adjacent_to_vertex(). Lastly, for each of these cells, the function tests whether the point is inside. This check is performed using the given
mapping argument to determine whether cells have straight or curved boundaries, and if the latter then how exactly they are curved.
If a point lies on the boundary of two or more cells, then the algorithm tries to identify the cell that is of highest refinement level.
marked_verticesis specified the function should always be called inside a try block to catch the exception that the function might throw in the case it couldn't find an active cell surrounding the point. The motivation of using
marked_verticesis to cut down the search space of vertices if one has a priori knowledge of a collection of vertices that the point of interest may be close to. For instance, in the case when a parallel::shared::Triangulation is employed and we are looking for a point that we know is inside the locally owned part of the mesh, then it would make sense to pass an array for
marked_verticesthat flags only the vertices of all locally owned active cells. If, however, the function throws an exception, then that would imply that the point lies outside locally owned active cells.
Definition at line 568 of file grid_tools_dof_handlers.cc.
A version of the previous function that exploits an already existing map between vertices and cells, constructed using the function GridTools::vertex_to_cell_map, a map of vertex_to_cell_centers, obtained through GridTools::vertex_to_cell_centers_directions, a guess
cell_hint, and optionally an RTree constructed from the used vertices of the Triangulation. All of these structures can be queried from a GridTools::Cache object.
Definition at line 1828 of file grid_tools.cc.
A version of the previous function where we use that mapping on a given cell that corresponds to the active finite element index of that cell. This is obviously only useful for hp problems, since the active finite element index for all other DoF handlers is always zero.
Definition at line 1260 of file grid_tools_dof_handlers.cc.
A version of the previous function that exploits an already existing GridTools::Cache<dim,spacedim> object.
Definition at line 5462 of file grid_tools.cc.
A variant of the previous find_active_cell_around_point() function that, instead of returning only the first matching cell, identifies all cells around a point for a given tolerance level
tolerance in terms of unit coordinates. More precisely, whenever the point returned by find_active_cell_around_point() is within the given tolerance from the surface of the unit cell, all corresponding neighbors are also identified, including the location of the point in unit coordinates on any of these cells.
This function is useful e.g. for discontinuous function spaces where, for the case the given point
p coincides with a vertex or an edge, several cells might hold independent values of the solution that get combined in some way in a user code.
Definition at line 589 of file grid_tools_dof_handlers.cc.
Return a list of all descendants of the given cell that are active. For example, if the current cell is once refined but none of its children are any further refined, then the returned list will contain all its children.
If the current cell is already active, then the returned list is empty (because the cell has no children that may be active).
Extract the active cells around a given cell
cell and return them in the vector
active_neighbors. These neighbors are specifically the face neighbors of a cell or, if that neighbor is further refined, its active children that border on that face. On the other hand, the neighbors returned do not include cells that lie, for example, diagonally opposite to a vertex but are not face neighbors themselves. (In 3d, it also does not include cells that are adjacent to one of the edges of the current cell, but are not face neighbors.)
Extract and return the active cell layer around a subdomain (set of active cells) in the
mesh (i.e. those that share a common set of vertices with the subdomain but are not a part of it). Here, the "subdomain" consists of exactly all of those cells for which the
predicate returns
true.
An example of a custom predicate is one that checks for a given material id
and we can then extract the layer of cells around this material with the following call:
Predicates that are frequently useful can be found in namespace IteratorFilters. For example, it is possible to extract a layer of cells around all of those cells with a given material id,
or around all cells with one of a set of active FE indices for an hp::DoFHandler
Note that in the last two examples we ensure that the predicate returns true only for locally owned cells. This means that the halo layer will not contain any artificial cells.
Definition at line 737 of file grid_tools_dof_handlers.cc.
Extract and return the cell layer around a subdomain (set of cells) on a specified level of the
mesh (i.e. those cells on that level that share a common set of vertices with the subdomain but are not a part of it). Here, the "subdomain" consists of exactly all of those cells for which the
predicate returns
true.
Definition at line 776 of file grid_tools_dof_handlers.cc.
Extract and return ghost cells which are the active cell layer around all locally owned cells. This is most relevant for parallel::shared::Triangulation where it will return a subset of all ghost cells on a processor, but for parallel::distributed::Triangulation this will return all the ghost cells.
Definition at line 859 of file grid_tools_dof_handlers.cc.
Extract and return the set of active cells within a geometric distance of
layer_thickness around a subdomain (set of active cells) in the
mesh. Here, the "subdomain" consists of exactly all of those cells for which the
predicate returns
true.
The function first computes the cells that form the 'surface' of the subdomain that consists of all of the active cells for which the predicate is true. Using compute_bounding_box(), a bounding box is computed for this subdomain and extended by
layer_thickness. These cells are called interior subdomain boundary cells. The active cells with all of their vertices outside the extended bounding box are ignored. The cells that are inside the extended bounding box are then checked for their proximity to the interior subdomain boundary cells. This implies checking the distance between a pair of arbitrarily oriented cells, which is not trivial in general. To simplify this, the algorithm checks the distance between the two enclosing spheres of the cells. This will definitely result in slightly more cells being marked but also greatly simplifies the arithmetic complexity of the algorithm.
The image shows a mesh generated by subdivided_hyper_rectangle(). The cells are marked using three different colors. If the grey colored cells in the image are the cells for which the predicate is true, then the function compute_active_cell_layer_within_distance() will return a set of cell iterators corresponding to the cells colored in red. The red colored cells are the active cells that are within a given distance to the grey colored cells.
layer_thicknessfrom the set of active cells for which the
predicatereturns
true.
See compute_active_cell_halo_layer().
Definition at line 881 of file grid_tools_dof_handlers.cc.
Extract and return a set of ghost cells which are within a
layer_thickness around all locally owned cells. This is most relevant for parallel::shared::Triangulation where it will return a subset of all ghost cells on a process, but for parallel::distributed::Triangulation this will return all the ghost cells. All the cells for the parallel::shared::Triangulation class that are not owned by the current processor can be considered as ghost cells; in particular, they do not only form a single layer of cells around the locally owned ones.
layer_thicknessfrom the locally owned cells of a current process.
Also see compute_ghost_cell_halo_layer() and compute_active_cell_layer_within_distance().
Definition at line 1027 of file grid_tools_dof_handlers.cc.
Compute and return a bounding box, defined through a pair of points bottom left and top right, that surrounds a subdomain of the
mesh. Here, the "subdomain" consists of exactly all of those active cells for which the
predicate returns
true.
For a description of how
predicate works, see compute_active_cell_halo_layer().
Definition at line 1063 of file grid_tools_dof_handlers.cc.
Compute a collection of bounding boxes so that all active cells for which the given predicate is true, are completely enclosed in at least one of the bounding boxes. Notice the cover is only guaranteed to contain all these active cells but it's not necessarily exact i.e. it can include a bigger area than their union.
For each cell at a given refinement level containing active cells for which
predicate is true, the function creates a bounding box of its children for which
predicate is true.
This results in a cover of all active cells for which
predicate is true; the parameters
allow_merge and
max_boxes are used to reduce the number of cells at a computational cost and covering a bigger n-dimensional volume.
The parameters to control the algorithm are:
predicate: the property of the cells to enclose e.g. IteratorFilters::LocallyOwnedCell . The predicate is tested only on active cells.
refinement_level: it defines the level at which the initial bounding box are created. The refinement should be set to a coarse refinement level. A bounding box is created for each active cell at coarser level than
refinement_level; if
refinement_levelis higher than the number of levels of the triangulation an exception is thrown.
allow_merge: This flag allows for box merging and, by default, is false. The algorithm has a cost of O(N^2) where N is the number of the bounding boxes created from the refinement level; for this reason, if the flag is set to true, make sure to choose wisely a coarse enough
refinement_level.
max_boxes: the maximum number of bounding boxes to compute. If more are created the smaller ones are merged with neighbors. By default after merging the boxes which can be expressed as a single one no more boxes are merged. See the BoundingBox::get_neighbor_type () function for details. Notice only neighboring cells are merged (see the
get_neighbor_typefunction in bounding box class): if the target number of bounding boxes max_boxes can't be reached by merging neighbors an exception is thrown
The following image describes an example of the algorithm with
refinement_level = 2,
allow_merge = true and
max_boxes = 1. The cells with the property predicate are in red, the area of a bounding box is slightly orange.
allow_merge= true the number of bounding boxes is reduced while not changing the cover. If
max_boxeswas left as default or bigger than 1 these two boxes would be returned.
max_boxes= 1 the smallest bounding box is merged to the bigger one. Notice it is important to choose the parameters wisely. For instance,
allow_merge= false and
refinement_level= 1 returns the very same bounding box but with a fraction of the computational cost.
This function does not take into account the curvature of cells and thus it is not suited for handling curved geometry: the mapping is assumed to be linear.
Definition at line 2074 of file grid_tools.cc.
Given an array of points, use the global bounding box description obtained using GridTools::compute_mesh_predicate_bounding_box to guess, for each of them, which process might own it.
unsigned intof the point in
pointsto the rank of the owner.
unsigned intof the point in
pointsto the ranks of the guessed owners.
return_type, is
Definition at line 2221 of file grid_tools.cc.
Given a covering rtree (see GridTools::Cache::get_covering_rtree()), and an array of points, find a superset of processes which, individually, may own the cell containing the points.
For further details see GridTools::guess_point_owner; here only different input/output types are reported:
unsigned intof the point in
pointsto the rank of the owner; these are points for which a single possible owner was found.
unsigned intof the point in
pointsto the ranks of the guessed owners; these are points for which multiple possible owners were found.
return_type, is
Definition at line 2269 of file grid_tools.cc.
Return the adjacent cells of all the vertices. If a vertex is also a hanging node, the associated coarse cell is also returned. The vertices are ordered by the vertex index. This is the number returned by the function
cell->vertex_index(). Notice that only the indices marked in the array returned by Triangulation<dim,spacedim>::get_used_vertices() are used.
Definition at line 2319 of file grid_tools.cc.
Return a vector of normalized tensors for each vertex-cell combination of the output of GridTools::vertex_to_cell_map() (which is expected as input parameter for this function). Each tensor represents a geometric vector from the vertex to the respective cell center.
An assertion will be thrown if the size of the input vector is not equal to the number of vertices of the triangulation.
result[v][c] is a unit Tensor for vertex index v, indicating the direction of the center of the c-th cell with respect to the vertex v.
Definition at line 1765 of file grid_tools.cc.
Return the local vertex index of cell
cell that is closest to the given location
position.
Definition at line 1992 of file grid_tools.cc.
Compute a globally unique index for each vertex and hanging node associated with a locally owned active cell. The vertices of a ghost cell that are hanging nodes of a locally owned cells have a global index. However, the other vertices of the cells that do not touch an active cell do not have a global index on this processor.
The key of the map is the local index of the vertex and the value is the global index. The indices need to be recomputed after refinement or coarsening and may be different.
Definition at line 2370 of file grid_tools.cc.
Return the highest value among ratios between extents in each of the coordinate directions of a
cell. Moreover, return the dimension relative to the highest elongation.
firstvalue is the dimension of the highest elongation and the
secondvalue is the ratio among the dimensions of the
cell.
Definition at line 4036 of file grid_tools.cc.
Produce a sparsity pattern in which nonzero entries indicate that two cells are connected via a common face. The diagonal entries of the sparsity pattern are also set.
The rows and columns refer to the cells as they are traversed in their natural order using cell iterators.
Definition at line 2723 of file grid_tools.cc.
Produce a sparsity pattern 2771 of file grid_tools.cc.
Produce a sparsity pattern for a given level mesh 2800 of file grid_tools.cc.
Use graph partitioner to partition the active cells making up the entire domain. After calling this function, the subdomain ids of all active cells will have values between zero and
n_partitions-1. You can access the subdomain id of a cell by using
cell->subdomain_id().
Use the third argument to select between partitioning algorithms provided by METIS or ZOLTAN. METIS is the default partitioner.
If deal.II was not installed with ZOLTAN or METIS, this function will generate an error when corresponding partition method is chosen, unless
n_partitions is one. I.e., you can write a program so that it runs in the single-processor single-partition case without packages installed, and only requires them installed when multiple partitions are required.
cell_weightsignal has been attached to the
triangulation, then this will be used and passed to the partitioner.
Definition at line 2836 2887 of file grid_tools.cc.
This function does the same as the previous one, i.e. it partitions a triangulation using a partitioning algorithm into a number of subdomains identified by the
cell->subdomain_id() flag.
The difference to the previous function is the second argument, a sparsity pattern that represents the connectivity pattern between cells.
While the function above builds it directly from the triangulation by considering which cells neighbor each other, this function can take a more refined connectivity graph. The sparsity pattern needs to be of size \(N\times N\), where \(N\) is the number of active cells in the triangulation. If the sparsity pattern contains an entry at position \((i,j)\), then this means that cells \(i\) and \(j\) (in the order in which they are traversed by active cell iterators) are to be considered connected; partitioning algorithm will then try to partition the domain in such a way that (i) the subdomains are of roughly equal size, and (ii) a minimal number of connections are broken.
This function is mainly useful in cases where connections between cells exist that are not present in the triangulation alone (otherwise the previous function would be the simpler one to use). Such connections may include that certain parts of the boundary of a domain are coupled through symmetric boundary conditions or integrals (e.g. friction contact between the two sides of a crack in the domain), or if a numerical scheme is used that not only connects immediate neighbors but a larger neighborhood of cells (e.g. when solving integral equations).
In addition, this function may be useful in cases where the default sparsity pattern is not entirely sufficient. This can happen because the default is to just consider face neighbors, not neighboring cells that are connected by edges or vertices. While the latter couple when using continuous finite elements, they are typically still closely connected in the neighborship graph, and partitioning algorithm will not usually cut important connections in this case. However, if there are vertices in the mesh where many cells (many more than the common 4 or 6 in 2d and 3d, respectively) come together, then there will be a significant number of cells that are connected across a vertex, but several degrees removed in the connectivity graph built only using face neighbors. In a case like this, partitioning algorithm may sometimes make bad decisions and you may want to build your own connectivity graph.
cell_weightsignal has been attached to the
triangulation, then this will be used and passed to the partitioner.
Definition at line 2929 2982 of file grid_tools.cc.
Generates a partitioning of the active cells making up the entire domain using the same partitioning scheme as in the p4est library if the flag
group_siblings is set to true (default behavior of this function). After calling this function, the subdomain ids of all active cells will have values between zero and
n_partitions-1. You can access the subdomain id of a cell by using
cell->subdomain_id().
group_siblingsis set to false, children of a cell might be placed on different processors even though they are all active, which is an assumption made by p4est. By relaxing this, we can can create partitions owning a single cell (also for refined meshes).
Definition at line 3063 of file grid_tools.cc.
Partitions the cells of a multigrid hierarchy by assigning level subdomain ids using the "youngest child" rule, that is, each cell in the hierarchy is owned by the processor who owns its left most child in the forest, and active cells have the same subdomain id and level subdomain id. You can access the level subdomain id of a cell by using
cell->level_subdomain_id().
Note: This function assumes that the active cells have already been partitioned.
Definition at line 3168 of file grid_tools.cc.
For each active cell, return in the output array to which subdomain (as given by the
cell->subdomain_id() function) it belongs. The output array is supposed to have the right size already when calling this function.
This function returns the association of each cell with one subdomain. If you are looking for the association of each DoF with a subdomain, use the
DoFTools::get_subdomain_association function.
Definition at line 3195 of file grid_tools.cc.
Count how many cells are uniquely associated with the given
subdomain index.
This function may return zero if there are no cells with the given
subdomain index. This can happen, for example, if you try to partition a coarse mesh into more partitions (one for each processor) than there are cells in the mesh.
This function returns the number of cells associated with one subdomain. If you are looking for the association of DoFs with this subdomain, use the
DoFTools::count_dofs_with_subdomain_association function.
Definition at line 3209 of file grid_tools.cc.
For a triangulation, return a mask that represents which of its vertices are "owned" by the current process in the same way as we talk about locally owned cells or degrees of freedom (see GlossLocallyOwnedCell and GlossLocallyOwnedDof). For the purpose of this function, we define a locally owned vertex as follows: a vertex is owned by that processor with the smallest subdomain id (which equals the MPI rank of that processor) among all owners of cells adjacent to this vertex. In other words, vertices that are in the interior of a partition of the triangulation are owned by the owner of this partition; for vertices that lie on the boundary between two or more partitions, the owner is the processor with the least subdomain_id among all adjacent subdomains.
For sequential triangulations (as opposed to, for example, parallel::distributed::Triangulation), every user vertex is of course owned by the current processor, i.e., the function returns Triangulation::get_used_vertices(). For parallel triangulations, the returned mask is a subset of what Triangulation::get_used_vertices() returns.
Definition at line 3225 of file grid_tools.cc.
Given two meshes (i.e. objects of type Triangulation, DoFHandler, or hp::DoFHandler) that are based on the same coarse mesh, this function figures out a set of cells that are matched between the two meshes and where at most one of the meshes is more refined on this cell. In other words, it finds the smallest cells that are common to both meshes, and that together completely cover the domain.
This function is useful, for example, in time-dependent or nonlinear application, where one has to integrate a solution defined on one mesh (e.g., the one from the previous time step or nonlinear iteration) against the shape functions of another mesh (the next time step, the next nonlinear iteration). If, for example, the new mesh is finer, then one has to obtain the solution on the coarse mesh (mesh_1) and interpolate it to the children of the corresponding cell of mesh_2. Conversely, if the new mesh is coarser, one has to express the coarse cell shape function by a linear combination of fine cell shape functions. In either case, one needs to loop over the finest cells that are common to both triangulations. This function returns a list of pairs of matching iterators to cells in the two meshes that can be used to this end.
Note that the list of these iterators is not necessarily ordered, and does also not necessarily coincide with the order in which cells are traversed in one, or both, of the meshes given as arguments.
Definition at line 1112 of file grid_tools_dof_handlers.cc.
Return true if the two triangulations are based on the same coarse mesh. This is determined by checking whether they have the same number of cells on the coarsest level, and then checking that they have the same vertices.
The two meshes may have different refinement histories beyond the coarse mesh.
Definition at line 1217 of file grid_tools_dof_handlers.cc.
The same function as above, but working on arguments of type DoFHandler, or hp::DoFHandler. This function is provided to allow calling have_same_coarse_mesh for all types of containers representing triangulations or the classes built on triangulations.
Definition at line 1249 of file grid_tools_dof_handlers.cc.
Given a triangulation and a list of cells whose children have become distorted as a result of mesh refinement, try to fix these cells up by moving the center node around.
The function returns a list of cells with distorted children that couldn't be fixed up for whatever reason. The returned list is therefore a subset of the input argument.
For a definition of the concept of distorted cells, see the glossary entry. The first argument passed to the current function is typically the exception thrown by the Triangulation::execute_coarsening_and_refinement function.
Definition at line 3788 of file grid_tools.cc.
This function returns a list of all the active neighbor cells of the given, active cell. Here, a neighbor is defined as one having at least part of a face in common with the given cell, but not edge (in 3d) or vertex neighbors (in 2d and 3d).
The first element of the returned list is the cell provided as argument. The remaining ones are neighbors: The function loops over all faces of that given cell and checks if that face is not on the boundary of the domain. Then, if the neighbor cell does not have any children (i.e., it is either at the same refinement level as the current cell, or coarser) then this neighbor cell is added to the list of cells. Otherwise, if the neighbor cell is refined and therefore has children, then this function loops over all subfaces of current face adds the neighbors behind these sub-faces to the list to be returned.
Definition at line 1390 of file grid_tools_dof_handlers.cc.
This function takes a vector of active cells (hereafter named
patch_cells) as input argument, and returns a vector of their parent cells with the coarsest common level of refinement. In other words, find that set of cells living at the same refinement level so that all cells in the input vector are children of the cells in the set, or are in the set itself.
Definition at line 1438 of file grid_tools_dof_handlers.cc.
This function constructs a Triangulation (named
local_triangulation) from a given vector of active cells. This vector (which we think of the cells corresponding to a "patch") contains active cells that are part of an existing global Triangulation. The goal of this function is to build a local Triangulation that contains only the active cells given in
patch (and potentially a minimum number of additional cells required to form a valid Triangulation). The function also returns a map that allows to identify the cells in the output Triangulation and corresponding cells in the input list.
The function copies the location of vertices of cells from the cells of the source triangulation to the triangulation that is built from the list of patch cells. This adds support for triangulations which have been perturbed or smoothed in some manner which makes the triangulation deviate from the standard deal.II refinement strategy of placing new vertices at midpoints of faces or edges.
The operation implemented by this function is frequently used in the definition of error estimators that need to solve "local" problems on each cell and its neighbors. A similar construction is necessary in the definition of the Clement interpolation operator in which one needs to solve a local problem on all cells within the support of a shape function. This function then builds a complete Triangulation from a list of cells that make up such a patch; one can then later attach a DoFHandler to such a Triangulation.
If the list of input cells contains only cells at the same refinement level, then the output Triangulation simply consists of a Triangulation containing only exactly these patch cells. On the other hand, if the input cells live on different refinement levels, i.e., the Triangulation of which they are part is adaptively refined, then the construction of the output Triangulation is not so simple because the coarsest level of a Triangulation can not contain hanging nodes. Rather, we first have to find the common refinement level of all input cells, along with their common parents (see GridTools::get_cells_at_coarsest_common_level()), build a Triangulation from those, and then adaptively refine it so that the input cells all also exist in the output Triangulation.
A consequence of this procedure is that the output Triangulation may contain more active cells than the ones that exist in the input vector. On the other hand, one typically wants to solve the local problem not on the entire output Triangulation, but only on those cells of it that correspond to cells in the input list. In this case, a user typically wants to assign degrees of freedom only on cells that are part of the "patch", and somehow ignore those excessive cells. The current function supports this common requirement by setting the user flag for the cells in the output Triangulation that match with cells in the input list. Cells which are not part of the original patch will not have their
user_flag set; we can then avoid assigning degrees of freedom using the FE_Nothing<dim> element.
Definition at line 1484 of file grid_tools_dof_handlers.cc.
This function runs through the degrees of freedom defined by the DoFHandlerType and for each dof constructs a vector of active_cell_iterators representing the cells of support of the associated basis element at that degree of freedom. This function was originally designed for the implementation of local projections, for instance the Clement interpolant, in conjunction with other local patch functions like GridTools::build_triangulation_from_patch.
DoFHandlerType's built on top of Triangulation or parallel:distributed::Triangulation are supported and handled appropriately.
The result is the patch of cells representing the support of the basis element associated to the degree of freedom. For instance using an FE_Q finite element, we obtain the standard patch of cells touching the degree of freedom and then add other cells that take care of possible hanging node constraints. Using a FE_DGQ finite element, the degrees of freedom are logically considered to be "interior" to the cells so the patch would consist exclusively of the single cell on which the degree of freedom is located.
Definition at line 1701 of file grid_tools_dof_handlers.cc.
An orthogonal equality test for faces.
face1 and
face2 are considered equal, if a one to one matching between its vertices can be achieved via an orthogonal equality relation.
Here, two vertices
v_1 and
v_2 are considered equal, if \(M\cdot v_1 + offset - v_2\) is parallel to the unit vector in unit direction
direction. If the parameter
matrix is a reference to a spacedim x spacedim matrix, \(M\) is set to
matrix, otherwise \(M\) is the identity matrix.
If the matching was successful, the relative orientation of
face1 with respect to
face2 is returned in the bitset
orientation, where
In 2D
face_orientation is always
true,
face_rotation is always
false, and face_flip has the meaning of
line_flip. More precisely in 3d:
face_orientation:
true if
face1 and
face2 have the same orientation. Otherwise, the vertex indices of
face1 match the vertex indices of
face2 in the following manner:
face_flip:
true if the matched vertices are rotated by 180 degrees:
face_rotation:
true if the matched vertices are rotated by 90 degrees counterclockwise:
and any combination of that... More information on the topic can be found in the glossary article.
Definition at line 2420 of file grid_tools_dof_handlers.cc.
Same function as above, but doesn't return the actual orientation
Definition at line 2471 of file grid_tools_dof_handlers.cc.
This function will collect periodic face pairs on the coarsest mesh level of the given
mesh (a Triangulation or DoFHandler) and add them to the vector
matched_pairs leaving the original contents intact.
Define a 'first' boundary as all boundary faces having boundary_id
b_id1 and a 'second' boundary consisting of all faces belonging to
b_id2.
This function tries to match all faces belonging to the first boundary with faces belonging to the second boundary with the help of orthogonal_equality().
The bitset that is returned inside of PeriodicFacePair encodes the relative orientation of the first face with respect to the second face, see the documentation of orthogonal_equality() for further details.
The
direction refers to the space direction in which periodicity is enforced. When matching periodic faces this vector component is ignored.
The
offset is a vector tangential to the faces that is added to the location of vertices of the 'first' boundary when attempting to match them to the corresponding vertices of the 'second' boundary. This can be used to implement conditions such as \(u(0,y)=u(1,y+1)\).
Optionally, a \(dim\times dim\) rotation
matrix can be specified that describes how vector valued DoFs of the first face should be modified prior to constraining to the DoFs of the second face. The
matrix is used in two places. First,
matrix will be supplied to orthogonal_equality() and used for matching faces: Two vertices \(v_1\) and \(v_2\) match if \(\text{matrix}\cdot v_1 + \text{offset} - v_2\) is parallel to the unit vector in unit direction
direction. (For more details see DoFTools::make_periodicity_constraints(), the glossary glossary entry on periodic conditions and step-45). Second,
matrix will be stored in the PeriodicFacePair collection
matched_pairs for further use.
matched_pairs(and existing entries will be preserved), it is possible to call this function several times with different boundary ids to generate a vector with all periodic pairs.
Definition at line 2196 of file grid_tools_dof_handlers.cc.
This compatibility version of collect_periodic_faces() only works on grids with cells in standard orientation.
Instead of defining a 'first' and 'second' boundary with the help of two boundary_ids this function defines a 'left' boundary as all faces with local face index
2*dimension and boundary indicator
b_id and, similarly, a 'right' boundary consisting of all face with local face index
2*dimension+1 and boundary indicator
b_id. Faces with coordinates only differing in the
direction component are identified.
This function will collect periodic face pairs on the coarsest mesh level and add them to
matched_pairs leaving the original contents intact.
See above function for further details.
Exchange arbitrary data of type
DataType provided by the function objects from locally owned cells to ghost cells on other processors.
After this call, you typically will have received data from
unpack on every ghost cell as it was given by
pack on the owning processor. Whether you do or do not receive information to
unpack on a given ghost cell depends on whether the
pack function decided that something needs to be sent. It does so using the std_cxx17::optional mechanism: if the std_cxx17::optional return object of the
pack function is empty, then this implies that no data has to be sent for the locally owned cell it was called on. In that case,
unpack will also not be called on the ghost cell that corresponds to it on the receiving side. On the other hand, if the std_cxx17::optional object is not empty, then the data stored within it will be sent to the received and the
unpack function called with it.
Here is an example that shows how this function is to be used in a concrete context. It is taken from the code that makes sure that the
active_fe_index (a single unsigned integer) is transported from locally owned cells where one can set it in hp::DoFHandler objects, to the corresponding ghost cells on other processors to ensure that one can query the right value also on those processors:
You will notice that the
pack lambda function returns an
unsigned int, not a
std_cxx17::optional<unsigned int>. The former converts automatically to the latter, implying that data will always be transported to the other processor.
(In reality, the
unpack function needs to be a bit more complicated because it is not allowed to call DoFAccessor::set_active_fe_index() on ghost cells. Rather, the
unpack function directly accesses internal data structures. But you get the idea – the code could, just as well, have exchanged material ids, user indices, boundary indicators, or any kind of other data with similar calls as the ones above.)
In this collective operation each process provides a vector of bounding boxes and a communicator. All these vectors are gathered on each of the processes, organized in a search tree which, and then returned.
The idea is that the vector of bounding boxes describes a relevant property of the computations on each process individually, which could also be of use to other processes. An example would be if the input vector of bounding boxes corresponded to a covering of the locally owned partition of a mesh (see GlossLocallyOwnedCell) of a parallel::distributed::Triangulation object. While these may overlap the bounding boxes of other processes, finding which process owns the cell that encloses a given point is vastly easier if the process trying to figure this out has a list of bounding boxes for each of the other processes at hand.
The returned search tree object is an r-tree with packing algorithm, which is provided by boost library. See for more information.
In the returned tree, each node contains a pair of elements: the first being a bounding box, the second being the rank of the process whose local description contains the bounding box.
Definition at line 5584 of file grid_tools.cc.
Collect for a given triangulation all locally relevant vertices that coincide due to periodicity.
Coinciding vertices are put into a group, e.g.: [1, 25, 51], which is labeled by an arbitrary element from it, e.g.: "1". All coinciding vertices store the label to its group, so that they can quickly access all the coinciding vertices in that group: e.g.: 51 -> "1" -> [1, 25, 51]
Definition at line 5647 of file grid_tools.cc.
Output operator which outputs assemble flags as a set of or'd text values.
Definition at line 100 of file grid_tools_cache_update CacheUpdateFlags.
Definition at line 127 of file grid_tools_cache_update_flags.h.
Global operator which returns an object in which all bits are set which are not set in the argument. This operator exists since if it did not then the result of the bit-negation
operator ~ would be an integer which would in turn trigger a compiler warning when we tried to assign it to an object of type CacheUpdateFlags.
Definition at line 143 of file grid_tools_cache_update_flags.h.
Global operator which sets the bits from the second argument also in the first one.
Definition at line 158 of file grid_tools_cache_update CacheUpdateFlags.
Definition at line 174 of file grid_tools_cache_update_flags.h.
Global operator which clears all the bits in the first argument if they are not also set in the second argument.
Definition at line 189 of file grid_tools_cache_update_flags.h. | https://dealii.org/developer/doxygen/deal.II/namespaceGridTools.html | CC-MAIN-2020-16 | refinedweb | 9,679 | 52.39 |
I have concentrated on the Node.js backend for Azure Mobile Apps thus far. However, Azure Mobile Apps also supports an ASP.NET 4.6 (not ASP.NET core) backend. I’m going to start exploring the ASP.NET backend in this article, looking at a lot of the same functionality as I did for the Node.js backend.
Why use the ASP.NET backend?
Given the functionality of the Node.js backend, you may be wondering why you would even consider the ASP.NET backend. Well, there are a few reasons:
- You are more familiar with C# and ASP.NET in general.
- You want to utilize the large package library available via NuGet.
- You are doing cross-platform development in Xamarin and want to share code between backend and client apps.
- You want to use more complex types than a string, number, date or boolean.
Similarly, there are good reasons to use the Node.js backend:
- You are more familiar with Javascript and/or node programming.
- You want to utilize the large package library available via npm.
- You are primarily a frontend developer, don’t care about the schema and want to use the dynamic schema feature.
I find Node.js to be simpler to write – it requires less code to write functionally identical backends. I find ASP.NET to be easier to debug a lot of the time, with many errors being found at compile time (something that doesn’t exist in Node) rather than run time.
Starting with an ASP.NET MVC application
When kicking off a new project, I’d normally tell you to start with an example or template that is close to the pattern you want to deploy. Azure Mobile Apps has templates for the ASP.NET backend in the Azure SDK. Why not start with one of those?
Great question and you can certainly start with a specific Azure Mobile Apps project template. However, I want to show off how you can add Azure Mobile Apps to any ASP.NET application. Azure Mobile Apps is a good platform for exposing SQL data to a web or mobile application. There is nothing magical about the Azure Mobile Apps templates – they are really just ASP.NET templates with some in-built code. So I’ve started my code with the standard ASP.NET 4.6 MVC template. I’ve done some changes to it – most notably removing the built-in identity manager (which creates a database table for handling sign-ins) and removing Application Insights.
You might be wondering how I get two backends in the same solution and choose which one to deploy. The
.deploymentfile has a project property that tells Azure App Service which project to deploy.
You can find my initial code at my GitHub Repository, tagged as pre-day-17.
Introducing the Azure Mobile Apps .NET Server SDK
Did you know the Azure Mobile Apps team develops all their SDKs as open source on GitHub? Here is a complete list of the SDKs, together with their links:
- HTML / JavaScript Client SDK (there is an Apache Cordova plugin as well – it’s just a wrapper)
- .NET Client SDK (for Xamarin as well as Universal Windows)
- iOS Client SDK
- Android Client SDK
- Node.js Server SDK
- .NET Server SDK
In addition, the Azure Mobile Apps team publishes the SDKs in “the normal places” – that depends on the client language – npm for JavaScript, for example, or NuGet for the .NET Server SDKs. That means you can generally just work with the SDKs as you normally would.
There are several parts to installing the Server SDK into an ASP.NET application:
- Configure Entity Framework for your database
- Configure Azure Mobile Apps Server SDK
- Create your model
- Create a table controller
I’m going to do the basic one today – starting where I did with the Node.js backend – at the beginning, configuring the server to handle the TodoItem model and table.
Configuring Entity Framework
My first stop is to the
web.config file. In the standard template, the connection string is called
DefaultConnection – I need to change it to match the connection string that is used by Azure Mobile Apps:
<connectionStrings> <add name="MS_TableConnectionString" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-backend.dotnet-20160417041539.mdf;Initial Catalog=aspnet-backend.dotnet-20160417041539;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>
Just the name needs to change here. I don’t need to do any other changes because the Azure Mobile Apps Server SDK takes care of it for me.
Configuring Azure Mobile Apps
First stop – I need to add some NuGet packages. Here is the list:
- Microsoft.Azure.Mobile.Server
- Microsoft.Azure.Mobile.Server.Entity
- Microsoft.WindowsAzure.ConfigurationManager
- Microsoft.AspNet.WebApi.Owin
To install the NuGet packages, right-click on the References node and select Manage NuGet Packages… Click on Browse and then search for the packages. Once you’ve found one, click on the Install button:
This list is a minimal list – I haven’t included items that are in the dependencies.
Pretty much any plugin of this magnitude has a startup process. I am placing mine in
App_Start/AzureMobile.cs:
using Owin; using System.Data.Entity; using System.Web.Http;()); // Link the Web API into the configuration app.UseWebApi(config); } } public class AzureMobileInitializer : CreateDatabaseIfNotExists<MyDbContext> { protected override void Seed(MyDbContext context) { // You can seed your database here base.Seed(context); } } }
The major work here is done after the
MobileAppConfiguration(). I add any table controllers that are defined and hook them up to the data source defined via the DbContext. Once that is done, I call the database initializer, which will create the database and tables that I need. For that, I need a database context, which is defined in
Models/MyDbContext.cs:
using backend.dotnet.DataObjects; using Microsoft.Azure.Mobile.Server.Tables; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; namespace backend.dotnet.Models { public class MyDbContext : DbContext { private const string connectionStringName = "Name=MS_TableConnectionString"; public MyDbContext() : base(connectionStringName) { } public DbSet<TodoItem> TodoItems { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>( "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString() ) ); } } }
This is fairly standard stuff. I set the connection string name to the MS_TableConnectionString – which I am using because that’s the connection string that Azure App Service creates when adding a data connection. The
OnModelCreating() method is boilerplate for Azure Mobile Apps – just go with it.
Finally, don’t forget to link the configuration into the
Startup.cs file:
using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(backend.dotnet.Startup))] namespace backend.dotnet { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureMobileApp(app); } } }
If you find yourself not able to query anything at all and are getting 404 responses to everything, then it’s likely you missed this step.
Create a Model (or DTO)
Normally, I would be talking about models here. Azure Mobile Apps uses things called “Data Transfer Objects” or DTOs for short. They inherit from EntityData – this adds the five system columns to my table. Here is my
DataObjects/TodoItem.cs file:
using Microsoft.Azure.Mobile.Server; namespace backend.dotnet.DataObjects { public class TodoItem : EntityData { public string Text { get; set; } public bool Complete { get; set; } } }
Want a different field name on the remote end? Just use a JsonProperty transform – like this:
using Microsoft.Azure.Mobile.Server; using Newtonsoft.Json; namespace backend.dotnet.DataObjects { public class TodoItem : EntityData { public string Text { get; set; } [JsonProperty(PropertyName = "complete")] public bool IsComplete { get; set; } } }
I’m not doing this since I’m reusing the database I used for the Node.js backend. At this point, everything should compile, so you can do some sanity checks on your code – are you missing the NuGet packages, for example?
Create a Table Controller
A Table Controller looks just like a regular controller. In fact, there is some scaffolding help you get from the Azure SDK. Just right-click on the Controllers folder in the Solution Explorer and select Add -> Controller… – the Azure Mobile Apps Table Controller will be listed:
On the next screen, you will be asked for the model class and the DbContext – I’ve conveniently just completed those:
Click on OK and that’s it – you don’t need to do anything else.
Running locally
You can just press F5 to run this now (or right-click on the project, use Set As Startup Project… and then run it). Test it with Postman:
Next Steps
I’m not ready to deploy this to Azure yet. I’ve got just a basic ASP.NET backend running. My Node.js backend handled authentication and provided a unique view of the data based on the users email address. I want to implement that capability before I deploy to Azure. That will be the topic next time.
Until then, you can get my code from my GitHub Repository.
Pingback: Dew Drop – May 9, 2016 (#2247) | Morning Dew | https://shellmonger.com/2016/05/06/30-days-of-zumo-v2-azure-mobile-apps-day-17-asp-net-backend-introduction/ | CC-MAIN-2017-51 | refinedweb | 1,489 | 58.99 |
Please read instructions at the end of article on how to run the application after downloading the source.
ASP.NET Atlas is a rich set of client side and server side libraries to develop AJAX-style applications using ASP.NET. This tutorial (and probably more in this series) attempts to provide a general view of the features available in Atlas. Since, Atlas is a very vast library this very first tutorial concentrates on two most important features of Atlas:
MFC Scribble application was one of the first application that I used to learn MFC. Therefore, I decided to base this tutorial on Scribble. Scribble application allows users to draw freehand sketches using the mouse. I first saw a similar application on the web, utilizing AJAX technologies, at the JavaScript Draw website. The JavaScript draw website works only on Mozilla Firefox. This article describes how to build a cross-browser version of the application. We will build on the application in each article in this series to demonstrates more features of Atlas.
At the time of writing of this article, December CTP of Atlas can be downloaded by clicking this link. If this link does not work you can always go to the Atlas website to get the correct link. The Atlas library is available as a Visual Studio 2005 template (VSI). The download site has instructions on how to install the template.
Once the Atlas template is installed you can create a blank Atlas project by clicking selecting the menu option: File -> New -> Web Site. This brings up the New Web Site dialog box as shown.
Under location you can either select File System or HTTP. Selecting HTTP will allow you to create a web site on an IIS server and selecting File System will allow you to create a web site on your local file system (which you can debug and test using the ASP.NET development web server). You can select either option but I have found the application to work better with Internet Explorer on IIS.
The newly created Atlas web site has the following directory structure.
The December release of Atlas has the following client scripts.
Atlas adds the following files to the root directory of the web site.
The Scribble application allows users to draw freehand sketches by clicking on the left mouse button and moving mouse around. A sketch stroke ends when the user releases the mouse button or moves outside the drawing area. There are ways to draw using JavaScript by utilizing VML, but we are not going to use VML in this sample.
The default web page in Scribble will have an image (a regular HTML image - the IMG tag). The user mouse events over the image are captured using JavaScript event handlers. The JavaScript functions send the series of points in a sketch stroke to a web service. The web service updates and image object saved in a session variable by drawing lines through all the points sent by the client. Finally, the client requests an updated image from the server. The image source is an HTTP handler which streams the image stored in the session variable to the client. Here are the main components of the application.
Session_Startand the
Session_Endevents are handled in Global.asax. The
Session_Startcreates the session variable and
Session_Enddisposes the image stored in the session variable.
We begin our coding process from Global.asax.
System.Drawingnamespace. Insert the following line of code just after the first line.
<%@ Import Namespace="System.Drawing" %>
Session_Startfunction.
void Session_Start(object sender, EventArgs e) { Bitmap bmp = new Bitmap(200, 200); using (Graphics g = Graphics.FromImage(bmp)) { g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, bmp.Width, bmp.Height)); g.Flush(); } Session["Image"] = bmp; }The code creates a simple bitmap 200 pixels by 200 pixels white, paints the entire background white and assigns it to the session variable named
Image.
Session_Endfunction should dispose the image stored in the session variable.
Bitmap bmp = (Bitmap)Session["Image"]; bmp.Dispose();
System.Drawingin the Add Reference dialog box and click OK
This web handler is supposed to stream the image stored in the session variable back to the client.
IRequiresSessionState. This is only marker interface and has no methods to override. Edit the class declaration to look like the following.
public class ScribbleImage : IHttpHandler, System.Web.SessionState.IRequiresSessionState
ProcessRequestmethod.
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "image/png"; context.Response.Cache.SetNoStore(); context.Response.Cache.SetCacheability(HttpCacheability.NoCache); context.Response.Cache.SetExpires(DateTime.Now); context.Response.Cache.SetValidUntilExpires(false); System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)context.Session["Image"]; lock(bmp) { using (MemoryStream ms = new MemoryStream()) { bmp.Save(ms, ImageFormat.Png); ms.Flush(); context.Response.BinaryWrite(ms.GetBuffer()); } } } }
ContentTypeheader in the response to image/png. This make sure that the browser identifies the response to be a png image instead of HTML.
BinaryWritefunction is used, as the image is binary data.
We have means of initializing the session image and to stream the image contents as response. Now we need some method to add content to the image itself. We expect the clients to call on ScribbleService.asmx web service to add lines to the image.
using System.Drawing;
System.Drawing.Pointclass as it is not XML serializable. In a later tutorial we will see how we can use
System.Drawing.Pointinstead of the custom class. Add the following code just before the
ScribbleServiceclass declaration
public class Point { public int X; public int Y; };
Drawto our web service.
[WebMethod(EnableSession = true)] public void Draw(Point[] points) { Image scribbleImage = (Image)Session["Image"]; lock(scribbleImage) { using (Graphics g = Graphics.FromImage(scribbleImage)) using(Pen p = new Pen(Color.Black, 2)) { if (points.Length > 1) { int startX = points[0].X; int startY = points[0].Y; for (long i = 1; i < points.Length; i++) { g.DrawLine(p, startX, startY, points[i].X, points[i].Y); startX = points[i].X; startY = points[i].Y; } } } } }
WebMethod(EnableSession = true)ensures that the session variables are accessible from the web service.
pointsarray.
We have the server side image handler and the server side web service to update the image. Now we need the client side script in scribble application that will send the points from mouse events to the server web service.
//The HTML image element that is to be drawn var image; //The source of the image var originalSrc; //The number of iteration var iter = 0; //The array of points var points = null;The comments above the variable declaration describe the purpose behind each variable. The
itervariable is used to modify the source of the image after a draw request is sent to the server. In case of Internet Explorer setting
image.src = image.srcdoes refresh the image but the same code does not work for Firefox. To work around this problem we maintain the variables
iterwhich is incremented every time we send a
Drawrequest to the Webservice. We add the iteration number to the
originalSrcvariable so that the browser thinks that the it needs to request the server to get fresh data as opposed to using the cached image.
startStrokewhich starts a stroke in response to the
mousedownevent.
function startStroke() { points = new Array(); window.event.returnValue = false; }When a new stroke starts we create a fresh set of points as indicated by the first line. The second line cancels the default behavior of the event. This is necessary as the default behavior of the mousedown event for an image is to start a drag operation which prevents any further events from being fired.
mouseupevent or
mouseoutevent, we need to make the actual call to the webservice. This is done in the
endStrokefunction.
function endStroke() { if (!points || points.length < 2) return true; //Send the points to the webservice ScribbleService.Draw(points, onWebMethodComplete, onWebMethodTimeout, onWebMethodError); points = null; window.event.returnValue = false; }The only interesting line in the function is
ScribbleService.Draw(points, onWebMethodComplete, onWebMethodTimeout, onWebMethodError);, which invokes the web service method
Drawin ScribbleService.asmx asynchronously. The function is automatically made available to us by the Atlas framework.
onWebMethodErroris a function which gets invoked by Atlas framework when an error occurs in the web service method and
onWebMethodTimeoutgets invoked when the web method call exceeds a configurable timeout defined in the Atlas framework. In this version we just show the user a message box with the error text.
function onWebMethodError(fault) { alert("Error occured:\n" + fault.get_message()); } function onWebMethodTimeout() { alert("Timeout occured"); }
onWebMethodCompletefunction is called when the web method call is successful. The image needs to be reloaded when this happens.
function onWebMethodComplete(result, response, context) { //We need to refresh the image var shimImage = new Image(200, 200); shimImage.src = originalSrc + "?" + iter++; shimImage.onload = function() { image.src = shimImage.src; } }
Imageobject
shimImageand set its source to the original source of the image we are drawing on. When the image object loads we set the source of the actual HTML image element on the page to the source of the temporary image object. This is done to avoid flicker when replacing the image.
pointsarray during the
mousemoveevent. This is done in the
addPointsfunction.
function addPoints() { if (points) { var point = { X : window.event.offsetX, Y : window.event.offsetY}; points.push(point); if (points.length == 3) { endStroke(); points = new Array(); points.push(point); } window.event.returnValue = false; } }
offsetXand
offsetYproperties of the event object and then it is appended to the
pointsarray. The
offsetXand
offsetYproperties give the relative mouse position with respect to the HTML element causing the event.
pointsarray. This is done so that the user can see the drawing before he releases the mouse button.
pageLoadfunction.
function pageLoad() { var surface = document.getElementById("drawingSurface"); image = surface.getElementsByTagName("IMG")[0]; originalSrc = image.src; surface.attachEvent("onmousedown", startStroke); surface.attachEvent("onmouseup", endStroke); surface.attachEvent("onmouseout", endStroke); surface.attachEvent("onmousemove", addPoints); }
pageLoadfunction is a special function which gets invoked when the Atlas framework has finished loading. We use this instead of the regular window or body load events so that we can be sure that Atlas has finished loading.
divtag with an id of
drawingSurface. The size of the element is same as the size of the image so we can safely attach to the events to the
drawingSurfacediv.
The individual components of the application need to be assembled in the Default.aspx page. Here is the code of this page.
<%@ Page <html xmlns=""> <head runat="server"> <title>Atlas Scribble Sample</title> </head> <body> <form id="form1" runat="server"> <Atlas:ScriptManager <Services> <Atlas:ServiceReference </Services> <Scripts> <Atlas:ScriptReference </Scripts> </Atlas:ScriptManager> <div id="drawingSurface" style="border:solid 1px black;height:200px;width:200px"> <img alt="Scribble" src="ScribbleImage.ashx" style="height:200px;width:200px" galleryimg="false" /> </div> </form> </body> </html>
The most important aspect of this page is the
atlas:ScriptManager server control. The
ScriptManager server control is responsible for generating client side script blocks for Atlas and for any web service proxy scripts. Lets examine the usage of the
ScriptManager control in the Default.aspx page.
EnableScriptComponentsproperty is set to false. This generates a client side script block referring to AtlasRuntime.js instead of Atlas.js. We prefer the lightweight version of Atlas Framework in this version of scribble as we are not using any Atlas components or controls.
This brings all the pieces together and now you can compile and run the project. I encourage you to see the actual client html generated by the Atlas Script Manager.
Here is what Atlas framework did for us.
attachEventand
event.offsetXand
event.offsetYare made available to Firefox. You can look at AtlasCompat.js file to see how this is done.
We have seen how to call web services and how to write cross browser applications with ease using Atlas. In an upcoming tutorial we see more of Atlas client side controls and declarative programming (depending on user feedback!). If you liked the tutorial please free to write a comment. If you did not like it please write a comment on how to improve it.
As Atlas is not yet redistributable, I have not included the Atlas files in the source download. Here are the steps you need to get the downloaded source to work.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/ajax/ajax_scribble.aspx | crawl-002 | refinedweb | 2,019 | 50.12 |
The UDRP: Is It Un-Fair.com? 119."
Domain brackets trick not working in sigs? (Score:1)
I was already beginning to appreciate and trust the cool new
Devil's Advocat (Score:2, Interesting)
Ben Spigel
Sic Transit Gloria
Re:Devil's Advocat (Score:2, Insightful)
Re:Devil's Advocat (Score:1)
Countries that do not respect IP laws will be simply denied access to the Internet.
And I woudn't have a problem with that.
Re:Devil's Advocat (Score:1)
who's idea of IP do they have to respect?
consider Russia's take on Sklyarov's eBook processor vs the US's take. one country thinks it protects the consumers rights to IP they paid for. another thinks it violates the producers rights over the same IP.
and now for something completely different:
forget IP laws! what about countries that don't respect IP headers? or TCP headers? I for one am sick and tired of the tcp urgent flag being ignored by rogue nation states!
Re:Devil's Advocat (Score:1)
I guess most powerful and influential state will win here.
Not like it has not happened before
Re:Devil's Advocat (Score:1)
Re:Devil's Advocat (Score:2)
Or even the same set of numbers under every country code (including +800 and +87x).
The whole point of having different domain names is so that joe blow's auto parts could have joesauto.com, but joe smith's automatic internet provider can have joesauto.net. I know the given example is kind of lame, but the point is simple.
Or even joesauto.la.ca.us and joesauto.ny.ny.us but that's just too simple...
Re:Devil's Advocat (Score:1)
I think the main issue is not that there is an international organization deciding this stuff. I think it is more that they have no oversite (oversight?). What they say goes, and screw you if you don't like it. That is a sucky attitude to begin with, and in obviously non-cybersquatting rulings in favor of a trademark holder, it just seems like a big bully taking the candy away from a baby.
Re:Devil's Advocat (Score:2)
Actually the fault here is having too many
You're missing letters at the end (Score:2)
cnn.co --> cnn.coM
Thank you.
Shared Jurisdiction or other alternatives (Score:2)
The problem isn't weather or not there's an international organization for settling trademark disputes, it who defines the venue for the dispute settlement, and who is actually arbitrating. The argument is that the arbitration that is being done isn't fair, but this is only because the person doing the research doesn't feel that it's fair, since 'fair' is an entirely subjective thing in this case.
--CTH
Re:Devil's Advocat (Score:2)
Whilst the Internet may be the vast majority of companies doing business on the internet (especially if they are shipping physical products) do not trade globally.
some sort of Internatinal orginization with binding arbatration powers is needed to make sure that some one in Brazil or Burni can't get a copywrited name, or some one using the Colombia suffix
What is done with
As for the CNN example they are quite happy to broadcast an Atlanta telephone number on screen, even well outside the USA, so maybe they should have something like cnn.atl.ge.us
Re:Devil's Advocat (Score:2)
Another real-world example - a trademarked software product I once worked on turned out to be type of adult diaper in Italy and a line of modular shelving in the UK - we didn't own the name any more than they did
You might find it usefull to check out the USPTO where they say. [uspto.gov]:1)
Of course, an outlandish sum should not be the result, but something. It's free market, just like any other.
Re:Logic bombs away! (Score:2)
Next thing you know he'll be advocating the rule of law......
Re:Logic bombs away! (Score:1)
-Freed
Re:Logic bombs away! (Score:1)
Re:Logic bombs away! (Score:2)
The basic problem here is misuse of domain names into.
We saw EXACTLY this same thing happen when they added new toll-free prefixes in the US -- American Express tried suing to guarantee that they got 888-the-card, to match their 800-the-card.
The difference is that telephone numbers cannot generally be "extended" (except in Germany).
DNS names are more like postal addresses. In that you can always add more "buildings", "offices", "departments", etc on to the beginning.
Re:Logic bombs away! (Score:1)
"Cybersquatters" should not be sued and forced to relinquish the trademarked domain name. I would think that making an offer to the squatter would be infinitely more cost-effective than actual litigation.
Re:Logic bombs away! (Score:1)
Perhaps, but what if the guy who happens to own "ford.com" says "yeah, I'd like a $200 million for it"? There is a lot of invalid litigation out there by corporations trying to stop people using anything with their copyrighted name in it, but there are also a number of valid suits. If I'm looking for an intro to linux products, I'll type in "". If it takes me to a cybersquatter's website, it wastes that much more of my time. Cybersquatting makes web traversal more difficult.
Re:Logic bombs away! (Score:2)
You don't go to amazon.com to get info on amazons. You don't go to imdb.com because you like those four letters. DNS is a mnemonic system, not a frickin' search engine.
--G
Re:Logic bombs away! (Score:1)
Of course not, because if it were, then a group of three wouldn't decide differently than a group of one,
as was clearly explained in the article.
Re:Logic bombs away! (Score:1)
If you think McDonalds is going to want to build a McDonalds on the corner of 7th and Main, and you buy the land for cheap before they come and buy it from you for twice what you paied for it, it is legal.
If you think some company might want to use company.place.domain and you buy it cheap before they come suddenly you have to give it up and loose your investment.
It looks the same to me.
==>lazn
Re:Logic bombs away! (Score:1)
This land has nothing to do with McDonalds while domain McDonalds.com clearly does.
Does that still look the same to you ?
Re:Logic bombs away! (Score:2)
But the real-estate question is more akin to something along the lines of this: Say you buy the name "bigturkey.com", and squat it. Sometime later, McDonald's introduces the Big Turkey sandwich into their menu, and because they want to get web site traffic, they try to register 'bigturkey.com', and find it taken.
Presuming that you had no inside knowledge of the direction that McDonald's was taking, who's got the right to the name? By real-estate standards, it's you, but WIPO would most likely rule in McD's favor. This leads to retroactive trademarks, which IMO can open up a whole host of new lawsuits.
To the best of my knowlegde, there's yet to be a case as this: nearly all the domain name squabbles involve the fact that there was pre-existing trademarks before the domain was registered. But this case would be the type that would definitely tell us how imbalanced that the WIPO is (Beyond what we know already, of course.)
Re:Logic bombs away! (Score:1)
Re:Logic bombs away! (Score:1)
Re:Logic bombs away! (Score:1)
Yep, your logic bombs all right (Score:2)
What does that have to do with this guy's study, which is not about the absolute percentage of these cases resolved in favor of the complainants, but about some mighty suspicious looking differences in those percentages depending on which arbitrator is hearing the case and which of the alternate procedures are followed?
His argument is basically that, out of all the arbitrators legitimately accredited by this process, some seem much more likely to rule in favor of complainants than others, and oddly enough it looks as though somebody is using the process to steer cases to those arbitrators. That's procedural bias even if these "hangin' arbitrators" are in the right. Not that I think they probably are..
Mod this up (Score:3, Funny)
A very apt analogy.
Re:Cybersquatters are scum... (Score:1)
Yeah, sometimes people do get screwed to some degree when someone buys a domain name. But to compare it to the people who extort money after a hurricane blows through is a bit excessive.
Re:Cybersquatters are scum... (Score:2)
Yes, I do. I respect people who take something and make it valuable, not people that try to get rich without contributing anything to society or the economy.
Yeah, sometimes people do get screwed to some degree when someone buys a domain name. But to compare it to the people who extort money after a hurricane blows through is a bit excessive.
How? What's your neighbor's house worth? Now how much damage is done to a business that can't have a recognizable domain? How much would it cost Compaq if some cybersquatter had, for example?
Re:Cybersquatters are scum... (Score:1)
How much damage is done to J. Crew because some cybersquatter has crew.com?
Re:Cybersquatters are scum... (Score:1)
Re:Cybersquatters are scum... (Score:1)
Domain name squatting isn't truly speculation because the value of the name already exists. True speculation would involve making up a name and hoping it becomes used and valuable.
Re:Cybersquatters are scum... (Score:1)
Thats a good idea, wish i lived on a coast, alas there aren't many hurricanes on the great lakes.
Either way, I tend to agree with all but a small portion of one comment, you forget guilty till proven innocent. Cyber squatters are shit, but that shouldn't mean my company has to give up our name if another company decides they want it, and had payed out their ass for a trademark just to take it from me. This should all be subjective, and up the courts...
Re:Cybersquatters are scum... (Score:2)
But, unlike cybersquatting, it's illegal.
Re:Cybersquatters are scum... (Score:1)
Re:Cybersquatters are scum... (Score:2)
So, in my hypothetical example, the buying public types, find's a "this domain for sale" sign, and then types or. Compaq would lose far more money than Bob's vacation home in Florida was ever worth. If it's a dot-com rather than Compaq, being stuck with a crappy domain name could cost them their business, their investors would lose their investments, and their employees would lose their jobs.
By the way, plywood protects windows, not people's lives. People who board up their houses normally have enough sense to evacuate them before the storm hits.
Re:Cybersquatters are scum... (Score:1)
Not that it is on-topic or anything, but it realy pisses me off that the domain for my first name: zachery.com [zachery.com], is being developed by a retarded 6 year old's retarded family.
Jesus! Did you use enough Javascript on that page, junior?
Re:Cybersquatters are scum... (Score:1)
I don't see much Javascript, but I do take offense at the loud Flash intro. "ZERRROOOOM. ZERRROOOOOOM."
Re:Cybersquatters are scum... (Score:2)
So you are saying that this justifies cybersquatting -- that because some firms behave unthically, that we should hold no one accountable for their actions?
New rule: No individual or company can own more than 10 domains. It's absurd that some cybersquatters have each grabbed thousands of domains that they neither want nor plan to develop.
Re:Cybersquatters are scum... (Score:1)
Every desirable name (and even most typos) have been gobbled up by a bunch of greedy, talentless parasites who are hoping to strike it rich by cyberextorting from companies.
I don't find this to be as bad as it seems. I think up domains all the time and see if they're registered and most of the time they aren't (much to my surprize). And these aren't wierdly spelled or obfiscated names either. Maybe it's just that most people are too lazy to actually think something up anymore?
-- kruhft --
Demo set, original music and reccomended tracks [kruhftwerk.com]
51st state? (Score:5, Funny)
OTTAWA, ONTARIO, CANADA, U.S.A.,
20 Aug 2001, 8:12 AM CST
When did Canada become the 51st state? News to me!
Re:51st state? (Score:2)
Re:51st state? (Score:2)
Re:51st state? (Score:1)
I too have been Canadian my whole life. I know Canada often feels like the 51st State, I was merely commenting on how it has now become "official."
Arbitrator should be randomly assigned (Score:2)
That way, Joe Corporation can't nuke JoeCoSucks.com as easily by going to one of the "Trademark Friendly" arbitrators.
No! (Score:1)
When the one doing the suing decides the arena it is heard in. it is inevitable that "trademark friendly" arenas will predominate the process.
The system does protect he moneyed interests at the expense of free speech and legitimate alternative trademark holder. Who should get sun.com? It is a computer company, a dishwasher detergent, and a newspaper. Shold Sun microsystems get the domain just becuase they have a "more valuable" trademark?
Squatting... (Score:2)
Re:Squatting... (Score:1)
The whole internet is unfair! (Score:1)
Re:The whole internet is unfair! (Score:2)
If you were in Scotland you probably could. Lord McDonald has been known to take a dim view of that company.
Why do we have multiple, limited TLDs... (Score:1)
Correct! Give that author 10 000 Quatloos (Score:1)
To the people who think multiple TLDs are going to end an 'artificial scarcity' of names: Guess what? It only makes trademark holders pay five, six, ten (?) times the amount for a domain name, stress the hell out of the namespace, confuse the hell out of visitors, and by confusing the hell out of visitors discourage them from buying anything online.
"Would you like a dot-biz with that dot:
Re:Demonstration and explanation of the bug (Score:1)
Link is guaranteed goatse.cx free.
Re:Demonstration and explanation of the bug (Score:1)
Re:Pre-Trademark domains? (Score)
tobacco.com: you overreacted (Score:2)
You overreacted, spending the $3500.
Should have handled this UDRP defense yourself. Even the most out-to-lunch single-person panel would never let this one get through. If the unthinkable happens, you can still go ahead and stick a lawyer up their ass and keep your domain, but it won't come to that.
Scandalous about NAF keeping your money, though.
PS, Canadian corporate info is available online [ic.gc.ca] , but I was unable to find a Tobacco.com, Inc. Is it possible they filed a trademark application on behalf of a non-existent entity? By the way, 401 Queen's Quay West is Harbour Terrace [torontocondo.com] (luxury condominiums), so they may have assets worth going after. Canada has an advanced legal system, after all.
PPS, Your domain tobacco.com may not be worth as much as you think... e-commerce or even advertising is a complete non-starter in today's climate. Suggestion: put up tobacco lawsuit resource info (class action lawsuits, ambulance-chaser lawyer ads, etc), and the tobacco companies might find it cost-effective to pay you a million to take the domain off your hands (after all, literally hundreds of billions of dollars are at stake).. | https://slashdot.org/story/01/08/20/1852227/the-udrp-is-it-un-faircom | CC-MAIN-2017-47 | refinedweb | 2,644 | 66.23 |
I try to hash a string using SHA256, I'm using the following code:
using System;
using System.Security.Cryptography;
using System.Text;
public class Hash
{
public static string getHashSha256(string text)
{
byte[] bytes = Encoding.Unicode.GetBytes(text);
SHA256Managed hashstring = new SHA256Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString;
}
}
Encoding.Unicode is Microsoft's misleading name for UTF-16 (a double-wide encoding, used in the Windows world for historical reasons but not used by anyone else).
If you inspect your
bytes array, you'll see that every second byte is
0x00 (because of the double-wide encoding).
You should be using
Encoding.UTF8.GetBytes instead.
But also, you will see different results depending on whether or not you consider the terminating
'\0' byte to be part of the data you're hashing. Hashing the two bytes
"Hi" will give a different result from hashing the three bytes
"Hi". You'll have to decide which you want to do. (Presumably you want to do whichever one your friend's PHP code is doing.)
For ASCII text,
Encoding.UTF8 will definitely be suitable. If you're aiming for perfect compatibility with your friend's code, even on non-ASCII inputs, you'd better try a few test cases with non-ASCII characters such as
é and
家 and see whether your results still match up. If not, you'll have to figure out what encoding your friend is really using; it might be one of the 8-bit "code pages" that used to be popular before the invention of Unicode. (Again, I think Windows is the main reason that anyone still needs to worry about "code pages".) | https://codedump.io/share/7o2VItzF69R7/1/hashing-a-string-with-sha256 | CC-MAIN-2018-26 | refinedweb | 291 | 66.13 |
Library for optimally representing data with neural networks with respect to statistical inference in a particle physics context.
Project description
neos
nice end-to-end optimized statistics ;)
Install
pip install neos
How to use (and reproduce the results from the cool animation)
import jax import neos.makers as makers import neos.cls as cls import numpy as np import jax.experimental.stax as stax import jax.experimental.optimizers as optimizers import jax.random import time
Initialise network using
jax.experimental.stax
init_random_params, predict = stax.serial( stax.Dense(1024), stax.Relu, stax.Dense(1024), stax.Relu, stax.Dense(2), stax.Softmax, )
Initialse tools from
neos:
The way we initialise in
neos is to define functions that make a statistical model from histograms, which in turn are themselves made from a predictive model, such as a neural network. Here's some detail on the unctions used below:
hists_from_nn_three_blobs(predict)uses the nn decision function
predictdefined in the cell above to form histograms from signal and background data, all drawn from multivariate normal distributions with different means. Two background distributions are sampled from, which is meant to mimic the situation in particle physics where one has a 'nominal' prediction for a nuisance parameter and then an alternate value (e.g. from varying up/down by one standard deviation), which then modifies the background pdf. Here, we take that effect to be a shift of the mean of the distribution. The value for the background histogram is then the mean of the resulting counts of the two modes, and the uncertainty can be quantified through the count standard deviation.
nn_hepdata_like(hmaker)uses
hmakerto construct histograms, then feeds them into the
neos.models.hepdata_likefunction that constructs a pyhf-like model. This can then be used to call things like
logpdfand
expected_datadownstream.
cls_makertakes a model-making function as it's primary argument, which is fed into functions from
neos.fitthat minimise the
logpdfof the model in both a constrained (fixed parameter of interest) and a global way. Moreover, these fits are wrapped in a function that allows us to calculate gradients through the fits using fixed-point differentiation. This allows for the calculation of both the profile likelihood and its gradient, and then the same for cls :)
All three of these methods return functions. in particular,
cls_maker returns a function that differentiably calculates cls values, which is our desired objective to minimise.
hmaker = makers.hists_from_nn_three_blobs(predict) nnm = makers.nn_hepdata_like(hmaker) loss = cls.cls_maker(nnm, solver_kwargs=dict(pdf_transform=True))
_, network = init_random_params(jax.random.PRNGKey(2), (-1, 2))
/home/phinate/envs/neos/lib/python3.7/site-packages/jax-0.1.59-py3.7.egg/jax/lib/xla_bridge.py:122: UserWarning: No GPU/TPU found, falling back to CPU.
Define training loop!
opt_init, opt_update, opt_params = optimizers.adam(1e-3) def update_and_value(i, opt_state, mu): net = opt_params(opt_state) value, grad = jax.value_and_grad(loss)(net, mu) return opt_update(i, grad, opt_state), value, net def train_network(N): cls_vals = [] _, network = init_random_params(jax.random.PRNGKey(1), (-1, 2)) state = opt_init(network) losses = [] for i in range(N): start_time = time.time() state, value, network = update_and_value(i,state,1.0) epoch_time = time.time() - start_time losses.append(value) metrics = {"loss": losses} yield network, metrics, epoch_time
Let's run it!!
maxN = 20 # make me bigger for better results! # Training for i, (network, metrics, epoch_time) in enumerate(train_network(maxN)): print(f"epoch {i}:", f'CLs = {metrics["loss"][-1]}, took {epoch_time}s')
epoch 0: CLs = 0.06680655092981347, took 5.355436325073242s epoch 1: CLs = 0.4853891149072429, took 1.5733795166015625s epoch 2: CLs = 0.3379355596004474, took 1.5171947479248047s epoch 3: CLs = 0.1821927415636535, took 1.5081253051757812s epoch 4: CLs = 0.09119136931683047, took 1.5193650722503662s epoch 5: CLs = 0.04530559823843272, took 1.5008423328399658s epoch 6: CLs = 0.022572851867672883, took 1.499192476272583s epoch 7: CLs = 0.013835564056077887, took 1.5843737125396729s epoch 8: CLs = 0.01322058601444187, took 1.520324468612671s epoch 9: CLs = 0.013407422454837725, took 1.5050244331359863s epoch 10: CLs = 0.011836452218993765, took 1.509469985961914s epoch 11: CLs = 0.00948507486266359, took 1.5089364051818848s epoch 12: CLs = 0.007350505632595539, took 1.5106918811798096s epoch 13: CLs = 0.005755974539907838, took 1.5267891883850098s epoch 14: CLs = 0.0046464301411786035, took 1.5851080417633057s epoch 15: CLs = 0.0038756402968267434, took 1.8452086448669434s epoch 16: CLs = 0.003323640670405803, took 1.9116990566253662s epoch 17: CLs = 0.0029133909840759475, took 1.7648999691009521s epoch 18: CLs = 0.002596946123608612, took 1.6314191818237305s epoch 19: CLs = 0.0023454051342963744, took 1.5911424160003662s
And there we go!! We discovered a new signal (depending on your arbitrary thershold) ;)
If you want to reproduce the full animation, a version of this code with plotting helpers can be found in
demo_training.ipynb! :D
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/neos/ | CC-MAIN-2020-16 | refinedweb | 788 | 54.9 |
MooseX::CompileTime::Traits - Allow compile time traits for classes/roles
version 1.102570
role Bar(Int :$bar) { method bar { $bar + 2 } } role Baz(Int :$baz) { method baz { $baz + 4 } } class Foo with MooseX::CompileTime::Traits { } class Flarg with MooseX::CompileTime::Traits { } ... use Foo traits => [ Bar => { bar => 2 } ]; use Flarg traits => [ Bar => { bar => 1 }, Baz => { baz => 1} ]; Foo->new()->bar(); # 4 my $flarg = Flarg->new(); $flarg->bar(); # 3 $flarg->baz(); # 5
Mo
(ClassName $class: ArrayRef :$traits?)
import is provided such that when your class or role is use'd it can take additional arguments that will be validatated and interpreted as roles or traits that need to be applied.
Nicholas Perez <nperez@cpan.org>
This software is copyright (c) 2010 by Infinity Interactive.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. | http://search.cpan.org/~nperez/MooseX-CompileTime-Traits-1.102570/lib/MooseX/CompileTime/Traits.pm | CC-MAIN-2016-40 | refinedweb | 146 | 61.56 |
Tools for doing hyperparameter search with Scikit-Learn and Dask
Project description
Tools for performing hyperparameter search with Scikit-Learn and Dask.
Highlights
- Drop-in replacement for Scikit-Learn’s GridSearchCV and RandomizedSearchCV.
- Hyperparameter optimization can be done in parallel using threads, processes, or distributed across a cluster.
- Works well with Dask collections. Dask arrays, dataframes, and delayed can be passed to fit.
- Candidate estimators with identical parameters and inputs will only be fit once. For composite-estimators such as Pipeline this can be significantly more efficient as it can avoid expensive repeated computations.
For more information, check out the documentation.
Install
Dask-searchcv is available via conda or pip:
# Install with conda $ conda install dask-searchcv -c conda-forge # Install with pip $ pip install dask-searchcv
Example
from sklearn.datasets import load_digits from sklearn.svm import SVC import dask_searchcv as dcv import numpy as np digits = load_digits() param_space = {'C': np.logspace(-4, 4, 9), 'gamma': np.logspace(-4, 4, 9), 'class_weight': [None, 'balanced']} model = SVC(kernel='rbf') search = dcv.GridSearchCV(model, param_space, cv=3) search.fit(digits.data, digits.target)
Project details
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/dask-searchcv/ | CC-MAIN-2021-39 | refinedweb | 204 | 51.75 |
Particle transferring between 3d softwares has always been an issue for me.
During the last couple of years I used some workarounds. Using realflow, krakatoa and partio plugins to pass the information back and forth were some of them
Recently, I had to transfer some particles from Houdini to Maya. Using Krakatoa or Realflow plugins are nice workarounds but since these solutions are heavily dependent on the plugins, this time I did not prefer to use these.
On the other hand, partio author(s) seems stopped compiling the code since 2014.
To bypass the issue, I have used compiled standalone version of partio and written a python script to convert the bhclassic particles. bhclassic is the former bgeo particles. Starting from Houdini 12, bgeo extension replaced with bgeo.sc and it is not compatible with partio converter.
You need to export the particles from houdini as bhclassic with enough padding. Rest is easy. Run the script, select one of the exported particles and script converts each particle using the partio converter, names it using the “ancient naming convention” of .pdc cache files.
Since the script deals with legacy Houdini formats and legacy Maya particles, it seems there may be no other use for this tool in the future, but who knows.
Installation is easy,
Unrar the rar file into the \Users\<user>\Documents\maya\scripts folder
Run these lines in python shell from maya:
from particleConverter import PConvertHouToMaya as converter converter.ParticleImporter().&amp;lt;wbr /&amp;gt;run()
Since I have used it for a specific project, script is not fully fool proofed and missing many possible features. Yet again, I do not see any point working on it since this solution depends deprecated functions of each software.
However, having that as an option is a good thing.
You can also find it in this GitHub Repository
There is a good reason why pdc cache dying. To be honest, I am surprised that it still exists even as a legacy system. 3ds Max users may remember they did not show the same courtesy to havoc powered Reactor tool.
Let me explain;
I was ready to use partio plugin with Maya 2014, convert particles into cache and open it again with Maya 2018 but fortunately realized the truth before attempting
Pdc caches are not only very limited, extremely picky (you cannot put them wherever you want), hard to use, and impractical as it can be, but also are not backward compatible anymore. That’s right. If you cache a particle system with Maya 2014, you cannot open it in Maya 2018. It needs to be cached again for Maya 2018 (and 2017, possibly 2016 too) This is not because the inner structure of pdc file changed. What becomes incompatible is the naming convention. This is probably because of the different ‘smallest unit of time’.
Assuming the project is set to 25fps, in Maya 2014 pdc files are created with this naming convention like tihs:
nameOfTheParticleShape.240.pdc
nameOfTheParticleShape.480.pdc
nameOfTheParticleShape.720.pdc
…
Notice that the digits increment with a value of 240. Maya 2014’s smallest unit of time is 1/6000th of a second. 6000/25fps = 240. Easy? Yes. Why? I don’t know.
In Maya 2018 this value is 5,644,800… The real problem begins with limitations of integer values. The maximum value of an integer variable can hold is 2,147,483,647. With a step size of 240, this is fairly acceptable. It is possible to cache 8,947,848 frames. I think no one exceeded that (I truly wish that no one exceeded that)
However, with a step size of 5,644,800, it only takes 380 frame to reach the limit. Once it reaches the limit, it flips the value negative and continues from there. It was already not making any sense before…
One more thing. If you create a particle system, cache it lets say between 1-200, delete the emitter and as soon as you pass 200, Maya crashes instantly. Every time, everywhere. | http://www.ardakutlu.com/houdini-to-maya-particle-converter/ | CC-MAIN-2021-49 | refinedweb | 674 | 63.29 |
At 11:59 +0200 2001/04/24, Torbjorn Granlund wrote: >I don't recognize any of your problems with using a C++ compiler in >connection with GMP. What C++ environment are you using? I use Metrowerks CodeWarrior Pro 5 C/C++ compiler, which is one of the more compliant (even though it may be old by now, as it is from summer 1999). The problem is that, by your definition, I got names such as "free" and "std::free" side-by-side, plus the fact that the confusion happened in the Flex/Bison output files, meaning that there is no simple way to fix it from within those (unless one wants to edit the skeleton files). Also, as I compile these files under C++, the C names "free" etc. end up in the C++ namespace "std". I think that it is legal, in order to give C++ compiler writers a chance, to define std:: to be the global namespace ::, in which case you would not experience any problem on any such compiler. Also, it may be less common to use "free", "malloc", etc., in C++ code. This happened only because there is no version for Flex or Bison using operator new() in the output parser files. So the safest thing is to change it. Hans Aberg | https://lists.gnu.org/archive/html/bug-gmp/2001-04/msg00027.html | CC-MAIN-2015-32 | refinedweb | 216 | 77.77 |
Proposed coding convention for closures
May 15 2009By now, many of us have gotten used to using closures in JavaScript to define a scope that holds private variables and utility functions so that we don't have to put these in the global namespace. The idiomatic code... read more
New version of Jude, plus Java 1.5 server JVM bug
April 27 2009I've just released Jude version 1.07. This is a relatively minor bug-fix release. Thanks to B.L. for reporting the bugs and helping to isolate them. Interestingly, one of the bugs reported against the previous version was an ArrayIndexOutOfBoundsException at a... read more
New ECMAScript version numbering scheme
March 30 2009Per a post today on the es-discuss mailing list, the next version of the JavaScript standard will be ECMAScript 5. This version was previously called ECMAScript 3.1, and is a relatively small and long-overdue update to the language. Version 4... read more
November 14 2008While researching Ruby's new-in-1.9 Object methods untrusted?, untrust, and trust, I discovered something I did not know about the $SAFE variable: in addition to being Thread-local, it is also Proc-local. Proc objects (both procs and lambdas) have their own... read more
Bending the Arc of History
November 06 2008President-elect Obama sure writes and delivers a great speech! My favorite line from his victory speech last night: put their hands on the arc of history and bend it once more toward the hope of a better day. I... read more
October 28 2008I've migrated my site to a new webhost, and am now trying to upgrade my blogging software... Comments are broken, and other stuff is too!... read more
October 28 2008The comments on my last post about method chaining in JavaScript were spectacular, and I want to publicly thank all who took the time to read my code and think about it. The final version of the code (which you... read more
Method chaining in JavaScript inheritance hierarchies
October 28 2008In the 5th edition of my JavaScript book I made the embarrassing mistake of recommending a constructor and method chaining technique that only works for shallow class hierarchies--it works when class B extends A, for example, but not when... read more
October 28 2008The Ruby Programming Language has been gratifyingly well received by readers and reviewers. In addition to glowing reviews at rubyinside.com and slashdot.org, it has been reviewed ten times at amazon.com and I proud to say that all ten reviews... read more
October 28 2008I've put together a list of 81 errors and updates to my Ruby book. These are fixed in the next printing. If you already own a copy of the book, however, you can go through and enter the changes... read more
Help fix up my book, please
October 28 2008The Ruby Programming Language is going to be reprinted next week, and O'Reilly has given me SVN write access to the docbook files to fix typos, errors, etc. I've got a list of about 25 relatively minor erros that... read more
Will C++ get Closures before Java does?
October 28 2008I just read that closures are being added to C++ [PDF link]. A note to Sun: you know your language is falling embarrassingly behind if the C++ standards committee can move more nimbly than you can! (For those who... read more
October 28 2008Tomorrow marks the 5th anniversary of Bush's war with Iraq. The costs: 3990 US soldiers dead That is more than 2 per day. 20,416 US soldiers wounded (badly enough to require air transport). That's more than 11 per day.... read more
October 28 2008If you arrived here after reading slashdot's review of The Ruby Programming Language, you've come to the right place. Thanks, Brian, for the kind words! The post below includes links to the book's table of contents and to an... read more | http://www.oreillynet.com/pub/au/156 | crawl-002 | refinedweb | 665 | 73.37 |
Windows 8 Roundup 474
There has been no shortage of Windows 8 news today. MrSeb writes: ." netbuzz pointed out that even the famous Blue Screen of Death will get a new look. Lastly mikejuk writes: "While everyone else is looking at the surface detail of Windows 8 there are some deep changes going on. Perhaps the biggest is that Metro now provides an alternative environment that doesn't use the age old Win32 API. This means no more overlapping windows — yes Metro really does take the windows out of Windows."
The cloud... (Score:3)
Re:The cloud... (Score:5, Insightful)
and I thought Microsoft was irrelevant before.
Ah, the internet, where 90% market share means you just don't matter.
Re: (Score:3)
I thought the same thing but more from a company perspective, where they limit and restrict just about everything one does on the internet. This doesn't seem like a sound business move, or it will severely limit the need to upgrade from a business perspective at least. IS Security groups are already frowning on cloud services where I work.
Re: (Score:3)
Outsourcing staff for cheaper support isn't the same thing as putting your data out in the cloud. Outsourcing comes with it's own security risks, but to my mind and to most security professionals, the cloud doesn't exactly give me a warm fuzzy. It contains inherent risks when data is no longer under your control. Embedding cloud services in the OS to such a degree will require a lot of work to restrict, lock down, and disable such features.
Then again this might give MS yet another reason to split off yet an
Re: (Score:3)
On the other hand, "moving to the cloud" is basically a software-and-IT-support way of saying "outsourcing,"
And here's me thinking it was just a way for Microsoft to move their lockin from Office to Sharepoint, now the idea of open formats has started to gain traction...
Re: (Score:2)
Re: (Score:2)
Re: (Score:3)
Interesting, where I live, it's the republicans who make the religious view of others very much a part of my life.
Oh my (Score:2)
Re: (Score:2)
Re: (Score:2)
Re: (Score:3, Insightful)
I think it's a project by Microsoft to see if they can hype things out (like they did with Windows 7) and get massive results (like Windows 7)... sort of like emulating the Apple rumor mill, but instead of leaving the world to speculate, MSFT is trying to fuel the fire itself.
OTOH, I think it will backfire, mostly because I think they mis-read the reason Windows 7 was moderately successful: Windows 7 didn't become popular by the hype machine; it became moderately successful because the last decent version o
Re: (Score:3)
One tactic I have noticed firsthand from early evaluations of pre-release Microsoft products is that they hype you up on lots of stuff, then tell you "it's just a preview release." So you get all excited, then you start to notice flaws... things seem a little half-baked... you have questions. Criticisms, even. But you kind of convince yourself "it's only a preview." Maybe you mention your reservations on some online forum, but someone immediately shouts you down: "Look you asshole, it's just a preview, ever
Re:Oh my (Score:5, Interesting)
> Windows 7 works just fine. It's the new XP - didn't you know?
It's sad, but you're probably right. Microsoft today is kind of like a rock star who's made so much cash, he's just going to be weird and do whatever the fsck he feels like doing from now on. If Microsoft is hyping "Metro" in an effort to generate developer excitement, they're having the exact opposite effect. Everyone *I* know is like, "WTF, has Microsoft gone completely batshit insane?"
It's almost like Microsoft's entire developer elite just hit their mid-40s, had a midlife crisis, realized they have enough cash to spend the rest of their lives coding for fun, retired en masse, and handed over the company to a marketing department that thinks making Windows look like a tablet UI so it can run phone apps better is somehow a good idea.
Re: (Score:2)
Re: (Score:2, Interesting)
Re: (Score:3)
Re: (Score:3)
We're really spamming the Windows 8 articles recently. Yeah no thanks, Windows 7 works just fine.
Oh, admit it. You're desperately wanting to upgrade just for the new, revamped BSOD!
In other news, Win8 still BSODs.
What's a vamp again?
So we're back to Windows 1.0? (Score:3, Funny)
So we're back to Windows 1.0 with no overlapping windows? How am I suppose to quickly look at two open applications? or drag and drop items?
Re: (Score:2)
no overlapping windows? How am I suppose to quickly look at two open applications? or drag and drop items?
This is no problem. Just hit Mod4-space [naquadah.org] to cycle through tiling layouts until you see one you like.
Re:So we're back to Windows 1.0? (Score:5, Interesting)
The windows 8 tiles system supports true multitasking, and has a few window arrangements that let you have 1/2/3 (or 4?) applications on screen at once.
Its actually pretty well though out, and should work pretty well for tablet users and netbooks.
For those of us power users with big desktops and multiple screens with 10+ windows open... guess what... that's not going away. You just launch Explorer, and have a full desktop window manager.
Seriously... what's with all the idiotic hate on this?
Microsoft is only changing the DEFAULT window manager to be more consumer / tablet friendly. Good for them.
The prosumer/business/productivity group will still have the more pro oriented traditional window manager for doing what we do.
Nobody even half expects people working on an excel spreedsheet business projection drawing data from pdfs, web pages, and their email to do so using the new interface. Some things make sense to do in multiple overlapping windows. That's not going away.
So stop flipping out about it.
I can answer that! (Score:4, Insightful)
Because Microsoft is changing the default behaviour in the new product. And the new default behaviour will be LESS effective for the users of the traditional Windows systems (desktops and laptops).
Here's an idea. Why not leave the DEFAULT behaviour as it is already and add a new OPTION to change it to the tablet-friendly format for those who want it that way?
Re: (Score:2)
That's pretty simple, the majority of computer users don't benefit from the traditional environment. For typical sales guys which live in Outlook they'll actually be more effective as the things they use readily will be easily accessible.
Usability is what Microsoft is after, they will make the easiest interface the default as they always have. More advanced features which we'll use on the regular will still be accessible and not really all that different from Windows 7, so what's with the complaining?
I just answered that. (Score:2)
Again. Because Microsoft is changing the default behaviour in the new product. And the new default behaviour will be LESS effective for the users of the traditional Windows systems (desktops and laptops).
So you say
Re:I just answered that. (Score:5, Insightful)
Resisting change, did you even test it or try to see the good and bad points? You know, get a balanced view
...
I've got a high UID, so I'm not crusty in my ways: I know what works for me, I've been working on my computer for 25 years, so I damn well know how I work. I know that EVERY single other PC OS or DE has window overlap as a default behavior for a damn good reason. I'm not sure what was broken about it. I'm not even convinced its easier for "normal" users, both my Mom and Dad have no problem with windows overlapping, and neither of them are at all close to being expert.
Earlier today, using my computer for fun, I had over 6 windows open. I had a torrent client open, and squeezed down so I could just see the progress bar, I had iTunes open, I had Steam open, I had both a Firefox and two Chrome windows open, I had three explorer windows open as well. This is normal use. I'm sure Microsoft knows what best though, obviously I meant to buy a tablet and not a desktop. Yes, I have the option of not using a gimped interface, but why should I jump through hoops? When I'm actually working this will be infuriating, I don't need extra steps, I don't need Microsoft telling me how to do things, I just want to forget all about my OS and focus on the task at hand. Sometimes that task requires tons of extra windows arranged in such a way that suits my work flow, which might not be a way that MS approves of. I'm imagining this in a corporate environment, where using multiple windows is the norm, as is users of all abilities and experience levels.
Hell, I don't understand why I can't have a start menu. Whats wrong with being able to quickly access another program without losing focus on whatever task your doing? I don't understand why a tablet interface makes any sense on a desktop, either. I have a large monitor, plenty of real estate, so I don't need to focus on one thing at a time. A tablet is a toy, I use a real computer. If I wanted the tablet experience, I'd be using a damn tablet. I have nothing against tablets, or OSs on tablets, but they don't work for me.
I've noticed that the trend in OS design of late is to try to kill the idea of multi-tasking, and try to force the user to focus at single tasks. This is all well and fine, but it doesn't match many peoples actual work flows. Sure, I'm doing one task, but this generally leads to needing to have multiple other things working at the same time. I'm editing a file, thats my single task. For this I need an email program open to see what the customer/boss wants, I might need a chat window or Skype to actually communicate, I need a PDF viewer or browser to see documentation, I need some music to keep me sane, I need a text editor to scribble notes and documentation, I need multiple file browsers to keep track of other files and documents, etc... Rarely can I do my job with a single, or a few, windows.
But marketing departments decided that ALL computers should now be toys made for mere media consumption, and not tools.
I don't need to test it, just watching the videos and reading the reviews tell me that I get to skip a version of Windows.
If it isn't broke, don't fix it.
Re: (Score:3)
Because Microsoft is changing the default behaviour in the new product. And the new default behaviour will be LESS effective for the users of the traditional Windows systems (desktops and laptops).
First, the classic desktop is an application tile in the new interface. They've added an abstraction layer. The old system is not "gone", its just one step away. Its not even an "either or" really... because you launch the classic desktop from Metro... and then switch to and from that and other metro tiles. Hell.
Re: (Score:2, Insightful)
1) Because the people who would most benefit from the "new" Window manager are the ones that would be least likely to find the option to turn it on.
2) Because the full classic desktop manager is simply a "full screen" application. In other words, its a tile in the new system.
The user does not need to "switch" to classic, they just launch it, because its an application.
Which is stupid. The moment Win8 detects a touchscreen it could immediately opt to make Metro the standard; the moment it detects no touch ca
Re: (Score:3)
Re: (Score:2)
And the new default behaviour will be LESS effective for the users of the traditional Windows systems (desktops and laptops).
Will it? I haven't used that specific UI, but tilling WMs are more effective than floating (i.e. "traditional"), in my opinion and of many other power users.
Of course, it requires multiple workspaces to work well, which I don't know if this will have.
Re: (Score:2)
An even better idea--why not develop two distinctly different OSes like Apple...one for tablets/phones, and one for computers?
I might be as wrong as "No wireless, less space than a Nomad, lame" on this one, but I just don't see the allure of mixing the two paradigms into one OS.
Re:I can answer that! (Score:5, Insightful)
According to Google, more than 90% of users do not know that they can use search functionality in Windows. The majority of Windows (computer) users are barely able to distinguish between a document, a website, an email and an application, it is all a blur to them. The typical computer user thinks that if he drags the small icon from the URL bar in IE/Firefox/Chrome to his desktop he has "saved" the webpage to his computer, he doesn't know the difference between a link, a shortcut and a document.
Microsoft should attempt to make computers easier to use for these people, they are the vast majority of computer users. They need help. The fact that you get to click once more time than you would when starting Windows should not factor into that issue at all. As a power user you are able to make it work. It is optional after all.
Re: (Score:2)
Hard to say what is more or less difficult on an OS that ain't released yet... izn't?
Not really, the new metro stuff is a lot like windows phone 7, and will clearly feel very ipad-esque on a tablet / netbook.
And the classic windows explorer is a pretty well known quantity.
Its not that hard to see that Apple got a lot of things right with the ipad user interface. (It got a lot of things wrong too... and quite bluntly I think windows 8 shows a lot of promise in terms of addressing those short comings.
Re: (Score:2)
Re: (Score:2)
"For those of us power users with big desktops and multiple screens with 10+ windows open... guess what... that's not going away. You just launch Explorer, and have a full desktop window manager."
except if you dl the actual dev preview you will see that no, you can not just dismiss metro like the xp/vista/7 theme. explorer IS metro now. your 'desktop' app is just a task bar and wallpaper. the start menu is not the normal metro ui start screen. also you will have a metro ui panel docked on the right hand sid
Re: (Score:2)
Seriously... what's with all the idiotic hate (Score:2)
Re:So we're back to Windows 1.0? (Score:4, Funny)
That stupid desktop metro app. without a start menu isn't a window manager since you can't simply start programs with it, not even Linux manages to create something that stupid.
I believe that's a planned upgrade in Gnome 4.
Re: (Score:3)
Isn't that a tad obvious? The fact that MS takes away a perfect good Window manager (Aero) and replaces it with this crap.
They haven't taken away the window manager, it's still there, it's just that it's decoupled from the core system now (which is good because you can have a desktop GUI on desktop/laptops, a touch-oriented GUI on touch devices and no GUI at all on servers) and you launch it if you need it or applications that need it launch it automatically (like VS does in the preview).
without a start menu isn't a window manager since you can't simply start programs with it
Since when does a window manager require a start menu?
I agree with you that the start menu should remain, and i really hope that it does in
Re: (Score:2)
Ballmer thinks you'll buy two screens.
Cause that's what billionaires like him do.
Two computers, surely? Otherwise the single application will spread across both screens.
Two Computers? (Score:2)
Re: (Score:2)
Re: (Score:2)
This is cool (Score:3, Insightful)
It looks increasingly like Windows 7 will be the last version of Windows I ever have to use.
Re:This is cool (Score:5, Insightful)
Re: (Score:3)
That's what most people said about XP when Vista was on the horizon.
True, I might have to look at it again around Windows 9 or 10.
Re:This is cool (Score:4, Funny)
True, I might have to look at it again around Windows 9 or 10.
Windows X with Magic Mouse. Think Differentlier.
Re: (Score:2)
I'm still running XP and loving it (just as long as it stays nicely locked away in it's VM running on my Ubuntu box) - so as far as I am concerned, XP IS the last version of windows I have to use.
Re: (Score:3, Interesting)
Re: (Score:2)
Had Vista stuck around and Win 7 not come to the rescue, people would still be saying that about Vista.
Re: (Score:2, Informative)
Indeed. Tried Win8 out yesterday. Extremely disappointed with the forced nature of the Metro UI and how it takes over
.. everything. Must admit I'm a fan of the ribbon changes to Explorer, et al. It's just a shame it's all hidden behind this horrible Metro UI that I never want to see. It's a shame that it's so difficult to switch apps if you want to "search" or actually use Explorer.
"What's that? You want to look up something on Wikipedia in Internet Explorer, then go bac
Re: (Score:2)
Metro will be good on tablets which is what its aiming for. And I already like it more than iOS on the ipad.
Nobody should seriously be using the metro interface while writing an artical in word while referencing websites, email, pdfs, etc... that's just asinine.
Use explorer where it makes more sense. Its not going away anytime soon, and if it does go away it will be replaced with something just as powerful... its absurd to think we are going to be forced into metro.
Re:This is cool (Score:4, Insightful)
Vux - I completely agree. It's more the point that it forces you to. If you hit F3 to search, you're taken to the Metro search interface. You're now forced to pick one of their search "targets" and to use their interface. You can't even see your application as you're now in a full-screen Metro interface, so it's going to take at least three clicks to get back to your program (one in the lower left corner to bring up the Start screen, then one on Desktop to open the desktop "gadget", then one on your application).
If, heaven forbid, you use Internet Explorer (which sadly, many users still do as the default browser on their PCs), it's also now a full-screen metro "app". If in the above example, you followed search to a Wikipedia link, you're now in a full-screen IE session with your original application several clicks away (and several clicks to get back to your IE to make sure you read something correctly, etc).
I understand it's for tablets. That's great. But forcing it on desktop users as at present is asinine. I hope to be shown in beta that we have the option to not use Metro at all. That hasn't been mentioned yet. What we've been told is that we're going to have to "change the way you do a lot of things" and that we need to "interact with the screen" more. That suggests they are going to force this Metro crapware on top of everything.
Re: (Score:3)
If you hit F3 to search, you're taken to the Metro search interface.
And its these little quirks that i think need to be cleaned up between now and release or its going to be another Vista.
If you are in the explorer windows interface, you should be able to search withotu leaving it. You should be able to open a web browser window without leaving it etc.
I'm REALLY skeptical that they would force you to keep ending up on a metro tile if you start within the explorer desktop.
Yes IE will run in Metro as
Re: (Score:2)
Definitely. I'm looking forward to beta so I can eat my words.
:)
Re: (Score:2)
The Metro IE has a button (second or third one from the right in the lower bar) which allows to move the IE as it is into the desktop. You then end up with your website in the same IE window that you already know from Windows 7. And if you launch it from the desktop I believe it starts in that mode immediately, not in the Metro UI.
Re: (Score:3)
Err.. who launches Internet Explorer from an explorer window? You don't navigate to C:\Program Files\Internet Explorer and launch it. At the very least, you launch it from your Start menu except - oh, didn't you know - there's no Start menu in Win8. You click the Start button and you're taken to the full-screen MetroUI Start Screen.
Re: (Score:2)
It's not hard to get to the desktop. It's just hard to stay there. Any number of common operations take you back out to the Metro UI, and from there it's multiple clicks to get back where you were. The desktop is quite usable, just as long as you're not trying to mix common applicatons and Metro Apps. User-interfacing between the two is ridiculously clunky and awkward.
Basically they're trying to replace Win32 with Metro, which is fine if that's what basic users want. For advanced users, it's like a straight
Re: (Score:2)
Why do you still have to use it now? What's holding you back?
Re: (Score:2)
Why do you still have to use it now? What's holding you back?
At home, games and video editing, though I don't do either much anymore so I boot into Windows about once a month.
At work, Word for documents incompatible with Open Office. But I normally put it off until I have to reboot for a kernel upgrade anyway.
BSOD (Score:2)
>> Your PC ran into a problem that it couldn't handle, and now it needs to restart.
Your software caused a giant fuck-up; don't try to blame the hardware.
BSODs are very often hardware related (Score:3, Informative)
Not always the hardware itself, sometimes the driver, but I'd say 90% or more of the BSODs I see at work are related to hardware. Very rare that it is purely a software issue.
Re: (Score:2)
Re: (Score:2)
This happened to me, but it was an hardware issue (with the DMA chip, IIRC) - Linux simply was able to detect and disable it.
Re: (Score:2)
Re: (Score:2)
So when things go screwy with the driver it is a kernel level fault and often knocks the whole OS down. It was a poor design
And how would you have designed it at the time to get adequate performance? Why do you think pretty much all major OSes do the same thing?
Actually more performance reasons (Score:3)
That and the ability to support arbitrary functions of arbitrary hardware is where it first came from. Back in the NT days, nearly the entire graphics layer got put in the kernel to speed things up. These days they've managed to move more things in to user space, there are a number of kinds of drivers that are mostly either mostly user mode with a bit of a shim in the kernel, or entirely user mode and they talk to the hardware via something like a class driver in the kernel. It's helped a lot, but you can s
Re: (Score:2)
To be fair, it could be either.
always-on? (Score:2)
Re:always-on? it's Cloud-y in Seattle (Score:2)
If only these 'clouds' or 'cloud services' actually had effective redundancy like they claim to and we didn't have so many 'clear sky' moments where they go down.
Oh, come on, it's not like all the big Clouds got hacked this past weekend
... like Google and Amazon ... .... oh ... wait ...
From the article... (Score:2)
"Are we really ready for a world where the devices we use for most of our waking hours can communicate behind our backs?"
We're in that world now thanks to Windows. Our devices ALREADY communicate behind our backs. Trouble is, they are communicating with the criminals in Russia...
Horrible marketing at work. (Score:5, Insightful)
So here's what everyone is hearing in the Windows world about Win8: "We're changing Windows. A lot. It's gonna look completely different. It's gonna act completely different. A lot of the things you do today probably need to be thought about differently".
Here's how IT management is interpreting that: "We might completely break Windows again. A lot. It's gonna confuse users. It's gonna make them less productive. Don't even think about using this product in a business environment without considering all of the extra support they're going to need."
Guess what? Based on what I've already seen, there's no way I'm even bringing this product into our environment for even a test basis until it's been out for over a year. If we're gonna have to completely retrain users how to do something, we're going to consider other things. That new Motorola Bionic with it's full screen dock and keyboard is looking more and more like something I want to own.
Retraining (Score:2, Insightful)
Funny how companies keep eating the retraining costs, while claiming those same training costs are the reason they don't deploy Linux desktops.
Re: (Score:3)
What retraining costs? I recently upgraded a whole slew of users from XP to Windows 7, those that noticed any difference were happier for the changes and were used to them inside of a day. The bigger retraining came with Office, not the OS and OpenOffice or LibreOffice are quite different from modern MS Office. They work in a pinch for a lot of people but not everybody.
Of course if you're talking about admin training that's different and I haven't met too many admins lately that are Windows only, most depl
Re: (Score:3)
If I'm being honest, I don't think it is the training costs that are the issue. I think it's dependencies.
Let me explain.
Every company I've ever worked in, yes they depend on Office (but could probably get by with Libre/OpenOffice). But dig beneath the surface and you find:
Re: (Score:2)
Win8, 25 years too late (Score:5, Funny) [imgur.com]
Re: (Score:2)
I remember Vista(?) was supposed to have different colors of screens of death.
Brilliant (Score:2, Interesting)
Cloud computing is the wave of the future. The idea of using a desktop PC as a primary computing device is increasingly becoming an anachronism. The wave of the future is ubiquitous computing capability not tied to one specific device.
Re:Brilliant (Score:5, Insightful)
The problem is that cloud computing tantamount to slavery computing, turning users into slaves. It takes away all control and concentrates it in the hands of large corporations.
I'm all for ubiqutous computing, but unless I own and control all of the devices I use, and the software running on them, what's the point?
I'm tired of being a slave. A slave to the dollar, a slave to the government, a slave to the company I need to work at to survive in this pitiful existence. I don't want some big corporation to take away my personal computing experience.
I don't see how people are so blind as to think cloud computing is an improvement.
Re: (Score:3)
^^^ Exactly. People have forgotten that PCs were revolutionary BECAUSE they devolved control and power away from centralized IT departments, and put it directly in the hands of end users who could skirt bureaucracy and do cool, new useful things without having to wade through months of committee meetings first. Those who don't remember the past are doomed to repea...NO CARRIER
Re: (Score:2)
Why couldn't you have your own cloud? (Ok, one answer is that you still wouldn't control the conduit.)
Re: (Score:2)
Its becoming an anachronism primarily because software developers (yes I am one) would much rather have their code running protected on hardware they control (but preferably don't own e.g. EC2 Azure) and acting as a service than letting you have control of it on your own cheap commodity hardware. Really this is plugging the 'digital hole'. Damn now I'm sounding like Stallman, see what they've done to me?
Re: (Score:2)
Fine. Let my desktop PC use UPnP to configure my router, let my router update my DDNS hostname, and let my Android phone & tablet sync directly with my desktop PC. Maybe add a server appliance running Samba into the equation. No need to screw with proprietary online services that either cost lots of money or can vanish tomorrow without warning. I guess we're the geezers now, but anyone old enough to remember dotcom services we depended upon disappearing overnight (or mid-afternoon), never to return, is
Re: (Score:2)
> beat.
> Obviously this won't happen with Windows 8 but at least it's step in the right direction.
I wouldn't expect it to happen with any version of Windows. I don't see windows ever having that degree of integration. At least i
Sanity Check? (Score:2, Insightful)
Is anyone actually stopping to say - "hang on a minute, what do people actually use?"
The hype of "the valley" would have us believe that everyone was sitting with a tablet with everything in the cloud.
The reality I see around me everyday is that everyone is sitting with a desktop/monitor/keyboard and is using a wide variety of local software. Not only are they doing that because it is "what has been", but also they are doing it because it is "what is required".
Is all this hype added to everything just to s
Re: (Score:2)
The reality I see around me everyday is that everyone is sitting with a desktop/monitor/keyboard and is using a wide variety of local software.
In the future everyone will plug in their phone when they get to work, and edit Excel spreadsheets in The Cloud using the touchscreen.
I read it on
/. so it must be true.
Re: (Score:2)
That is a rather incomplete inquiry. The better questions to ask are why do people use the things they use? What goals are they trying to accomplish? How can we make their lives better?
Security (Score:2)
Re: (Score:3)
Not a lot of details yet, only one short (but tantalizing) talk at the general keynote today. Active Directory will now be paired up with some kind of security rules engine that can inspect claims (user attributes) and the contents of files and implement enterprise-wide access policies based on the values it finds. The example shown was someone putting a file with sensitive data in a public share. When an unauthorized user inspected that share, the sensitive file wasn't even shown.
Re: (Score:3)
It depends on what exactly you mean by "security". One fairly big thing of note that is directly relevant is that new-style ("Metro") apps run in a sandbox, quite similar to what you see on iOS and Android. By default, they don't get access to your entire FS - even for read - only to their own little corner ("isolated storage"). No network, either, nor cameras and most other hardware. App developer has to explicitly list features he needs in the app manifest when packaging it, and user needs to confirm that
Two things (Score:3, Insightful)
I have two things:
1 - Given Microsoft's track record for abject failure in the innovation department, does anyone really believe any of this hype?
2 - Does anyone else think trying to be two things at once will just be one hot mess? Unlike Apple who does iOS very well, and OS X very well, this seems to be doomed to trying to be two things at once, while simply sucking at both. I think Apple dabbled with the concept with Lion but quickly realized that when I'm using a desktop, I want a desktop OS, not a 27" iPad.
Re: (Score:2)
Actually, this hits the nail on the head. The current state of the system is exactly the hybrid that you fear.
The overall behaviour of the new UI is a trainwreck in its current form, although some some aspects are quite OK. The problem is that is the frequent switching between Metro and the normal desktop that gets forced on the user. Sometimes you get thrown out of Metro onto the desktop because the system wants to ask you a trivial question and brings up a regular window for that. Other times you are forc
What is Metro? (Score:2)
what innovation (Score:4, Funny)
Regarding the new improved BSOD: "After expressing emoticon-style sadness"
Windows catches up with 1980's mac.
Well, I guess it's a start.
Win8 will be competitive (Score:4, Interesting)
I'm at the BUILD conference, and my impression is that Windows 8 will be very competitive. The re-imagining effort is sweeping, and touches everything from the back end to Consumer devices. The big news is that HTML 5 is now a "native" programming platform for the client UI. There are two JS libraries, a pure JS library that implements the new Metro look-and-feel (WinJS), and a Windows/JS bridge library that exposes the Windows API (and hence the Windows-controlled hardware such as the camera) in Javascript (WinRT). Tooling improvements include terrific new debugging scenarios and a major upgrade to Expression Blend to be able to edit HTML/CSS as well as XAML.
Basically, MS has taken the best ideas of the web development world, and leveraged them to massively improve the development experience for their next OS. If I wanted to write Windows-specific apps, Win8 is a huge improvement. It's an open question, however, whether people want to write Windows-specific apps as opposed to web-centric apps. Even then, Win8 will definitely shorten and simplify the transition from a web app to a Windows app.
Congratulations! We have a winner! (Score:3)
WinRT corrections (Score:5, Informative)
The article linked from TFA has got quite a few things regarding WinRT wrong. Point by point:
Windows Run Time, WinRT- a C++ object-oriented API.
It's not a C++ API. It's a COM-based API/ABI that can be accessed from any language that knows what a raw function pointer is. It's relatively easier to do that from C++, because COM vtables map nicely to C++ vtables. But WinRT ABI itself is intentionally designed to be projected to different languages, adapting along the way. C++ has its own projection, but so do
.NET and JS.
Applications can choose to use either the old Win32 API or the new WinRT but not both.
Wrong. You can use Win32 APIs in Metro apps - some of them are not available (largely because they are pointless in the sandbox, or deal with the old UI concepts), but some are. If you open windows header files - "windows.h" and friends - they now have blocks of code that look like this:
Desktop partition is what's available to non-Metro apps running on the classic desktop. App partition is what's available to Metro apps.
Furthermore, classic apps can actually use WinRT (while retaining full access to Win32 APIs). Not all of WinRT will work - specifically, most of UI stuff won't - but huge chunks of WinRT are not UI-related and are accessible. Examples include I/O and networking libraries, XML parser, XSLT engine, new device and multimedia APIs etc.
Of course WinRT is delivered to the programmer via XAML (or HTML)
WinRT is not "delivered via XAML", and most definitely not "via HTML". WinRT includes a UI library (Windows.UI.* namespaces), which allow you to use XAML as a declarative markup language for your UI (but you don't have to, strictly speaking). This is what is normally used by Metro C++ and
.NET apps. JS apps don't use WinRT for UI at all - they use HTML5/CSS3, rendered by chromeless IE. They do get access to non-UI parts of WinRT, but they don't have to use it, and in any case it's completely orthogonal to their (HTML5) UI..
You absolutely can P/Invoke from a
.NET Metro app. For one thing, you can P/Invoke to call any of Win32 API functions that are available to Metro apps, as described earlier. Furthermore, you can write a C++ DLL (e.g. for perf), bundle it with your app, and call it from C# as usual via P/Invoke.
Now, in practice, you probably won't, for the simple reason that pretty much everything that a Metro app can do is covered by WinRT APIs. So why would you mess around with P/Invoke declarations when you already have an object-oriented API that can be used directly? Mixed C#/C++ scenarios are also better supported that way - you can make a private WinRT component DLL in C++, and reference it from C#. Your WinRT C++ classes automagically become visible as
.NET classes, no P/Invoke declarations needed.
In fact, you could even go the other way around - write a WinRT component DLL in C#, and reference it from C++. And then both of those can be used in JS, so you can really mix all three if you want.
When you create a Page object with WinRT and run it then it expands to fill the entire screen real estate
By default, yes, but you can have two Metro apps run side by side.
If you want overlapping windows and dialog
Re: (Score:2)
The world squeals at the deliverance of Metro. [cue banjo]
Re: (Score:3)
Not that I use Windows for anything than gaming, and even there it sucks.
Windows sucks for gaming?
Re: (Score:3) | https://tech.slashdot.org/story/11/09/14/2219226/windows-8-roundup | CC-MAIN-2016-36 | refinedweb | 6,635 | 71.44 |
Hi,
I suspect this is a CE bug but here goes - I got a really weird behavior while importing DXF data,
The DXF is all georeferenced - when imported, some of the objects in the DXF come nicely in place. However, others, from the very same DSF, come totally in the wrong place and in close inspection they are located in a mirrored location to the original on the DXF - essentially seems like their X value got a negative value.
I tried several things such as:
- saving other DXF file versions
- saving from Autocad / Civil
- changing the objects' layer
- isolating the objects in a separate file
- exploding into standalone lines
But they keep on coming mirrored in the wrong place
File attached,
I'm using CE 2017.0 (should really upgrade to 2018 soon)
Cheers
Tal
p.s. I've uploaded the DWG as, for some onscure reason, the page tells me that the 3.2mb DXF file is 'too big' ?!?!? - just save as DXF
Does anyone from ESRI / CE has any feedback on this ?
Thanks
Tal
Thank you for reporting this issue. The CE team will look into it.
As a workaround please use this Python script to mirror the imported shape coordinates:
from scripting import * # get a CityEngine instance ce = CE() # axisIndex: [0,1,2] = [x,y,z] def mirrorShape(shapes,axisIndex): for i in xrange(0,len(shapes)): vertices = ce.getVertices(shapes[i]) for j in xrange(axisIndex,len(vertices),3): vertices[j] *= -1 ce.setVertices(shapes[i], vertices) if (i%100==0) | (i==len(shapes)-1): status = r"progress %3.1f%%" % ((i+1) * 100. / len(shapes)) print(status) if __name__ == '__main__': shapes = ce.getObjectsFrom(ce.selection(),ce.isShape) mirrorShape(shapes,0) pass | https://community.esri.com/t5/arcgis-cityengine-questions/potential-dxf-import-bug/m-p/17261 | CC-MAIN-2022-33 | refinedweb | 285 | 63.49 |
Unix Socket - Network Byte Orders
Unfortunately, not all computers store the bytes that comprise a multibyte value in the same order. Consider a 16-bit internet that is made up of 2 bytes. There are two ways to store this value.
Little Endian − In this scheme, low-order byte is stored on the starting address (A) and high-order byte is stored on the next address (A + 1).
Big Endian − In this scheme, high-order byte is stored on the starting address (A) and low-order byte is stored on the next address (A + 1).
To allow machines with different byte order conventions communicate with each other, the Internet protocols specify a canonical byte order convention for data transmitted over the network. This is known as Network Byte Order.
While establishing an Internet socket connection, you must make sure that the data in the sin_port and sin_addr members of the sockaddr_in structure are represented in Network Byte Order.
Byte Ordering Functions
Routines for converting data between a host's internal representation and Network Byte Order are as follows −
Listed below are some more detail about these functions −
unsigned short htons(unsigned short hostshort) − This function converts 16-bit (2-byte) quantities from host byte order to network byte order.
unsigned long htonl(unsigned long hostlong) − This function converts 32-bit (4-byte) quantities from host byte order to network byte order.
unsigned short ntohs(unsigned short netshort) − This function converts 16-bit (2-byte) quantities from network byte order to host byte order.
unsigned long ntohl(unsigned long netlong) − This function converts 32-bit quantities from network byte order to host byte order.
These functions are macros and result in the insertion of conversion source code into the calling program. On little-endian machines, the code will change the values around to network byte order. On big-endian machines, no code is inserted since none is needed; the functions are defined as null.
Program to Determine Host Byte Order
Keep the following code in a file byteorder.c and then compile it and run it over your machine.
In this example, we store the two-byte value 0x0102 in the short integer and then look at the two consecutive bytes, c[0] (the address A) and c[1] (the address A + 1) to determine the byte order.
#include <stdio.h> int main(int argc, char **argv) { union { short s; char c[sizeof(short)]; }un; un.s = 0x0102; if (sizeof(short) == 2) { if (un.c[0] == 1 && un.c[1] == 2) printf("big-endian\n"); else if (un.c[0] == 2 && un.c[1] == 1) printf("little-endian\n"); else printf("unknown\n"); } else { printf("sizeof(short) = %d\n", sizeof(short)); } exit(0); }
An output generated by this program on a Pentium machine is as follows −
$> gcc byteorder.c $> ./a.out little-endian $> | http://www.tutorialspoint.com/unix_sockets/network_byte_orders.htm | CC-MAIN-2019-22 | refinedweb | 472 | 62.17 |
The new guidance feature in the VS2010 profiler will look familiar to people who have used the static code analysis tools in previous versions. However, instead of statically analyzing your code, the profiler runs it and analyzes the results to provide guidance to fix some common performance issues.
Probably the best way to introduce this feature is via an example. Let’s assume you have written a simple application as follows:
1: using System;
2: namespace TestApplication
3: {
4: class Program
5: {
6: static void Main(string[] args)
7: {
8: BadStringConcat();
9: }
10:
11: private static void BadStringConcat()
12: {
13: string s = "Base ";
14: for (int i = 0; i < 10000; ++i)
15: {
16: s += i.ToString();
17: }
18: }
19: }
20: }
If you profile this application in Sampling Mode you’ll see an Action Link called ‘View Guidance’ on the Summary Page:
Clicking on this link brings up the Error List, which is where you would also see things like compiler errors and static code analysis warnings:
DA0001: System.String.Concat(.*) = 96.00; Consider using StringBuilder for string concatenations.
As you can see there is a 1 warning, which is DA0001, warning about excessive usage of String.Concat. The number 96.00 is the percentage of inclusive samples in this function.
Double-clicking on the warning in the Error List switches to the Function Details View. Navigating up one level of callers, we see that BadStringConcat is calling Concat (96% of Inclusive Samples) and doing some work itself (4%). The String.Concat call is not a direct call, but looking at the Function Code View you can see a ‘+=’ call on a string triggers the call.
The DA0001 rule suggests fixing the problem by changing the string concatenation to use a StringBuilder but I’ll leave that up to the reader. Instead, I’ll cover some of the other aspects of rules.
One of the more important questions is what to do if you wish to turn off a given rule (or even all rules)? The answer is to open up the ‘Tools/Options’ dialog and in the Performance section, navigate to the new ‘Rules’ subsection:
Here you can see that I’ve started searching by typing ‘st’ in the search box at the top. This dialog can be used to turn off rules (by clicking on the checkboxes on the left), or to change rule categories to ‘Warning’, ‘Information’ or ‘Error’. The only affect is to change how the rule is displayed in the Error List.
If you have a situation where you are sharing a profiler report (VSP file) with team members, sometimes it might be useful to let them know that a warning is not important or has already been considered. In this case you can right-click on the Error List and choose ‘Suppress Message’.
The rule warning is crossed out and you can choose to save the VSP file so that the next time it is opened, the suppression is shown:
That’s it for now. I plan on covering a little more about rules in a future post, including more details about the rules themselves, how you can tweak thresholds and even write your own rules.
[Colin Thomsen] | http://blogs.msdn.com/b/profiler/archive/2010/02/25/vs2010-profiler-guidance-rules-part-1.aspx | CC-MAIN-2015-18 | refinedweb | 533 | 64.54 |
Generating the .defs files.
The .defs files are text files, in a lisp format, that describe the API of a C library, including its
- objects (GObjects, widgets, interfaces, boxed-types and plain structs)
- functions
- enums
- signals
- properties
- vfuncs
At the moment, we have separate tools for generating different parts of these .defs, so we split them up into separate files. For instance, in the gtk/src directory of the gtkmm sources, you will find these files:
- gtk.defs
Includes the other files.
- gtk_methods.defs
Objects and functions.
- gtk_enums.defs
Enumerations.
- gtk_signals.defs
Signals and properties.
- gtk_vfuncs.defs
vfuncs (function pointer member fields in structs), written by hand.
- G.2.1. Generating the methods .defs
- G.2.2. Generating the enums .defs
- G.2.3. Generating the signals and properties .defs
- G.2.4. Writing the vfuncs .defs
G.2.1. Generating the methods .defs
This .defs file describes objects and their functions. It is generated by the h2def.py script which you can find in glibmm's tools/defs_gen directory. For instance,
$ ./h2def.py /usr/include/gtk-3.0/gtk/*.h > gtk_methods.defs
G.2.2. Generating the enums .defs
This .defs file describes enum types and their possible values. It is generated by the enum.pl script which you can find in glibmm's tools directory. For instance,
$ ./enum.pl /usr/include/gtk-3.0/gtk/*.h > gtk_enums.defs
G.2.3. Generating the signals and properties .defs
This .defs file describes signals and properties. It is generated by the special extra_defs utility that is in every wrapping project, such as gtkmm/tools/extra_defs_gen/. For instance
$ cd tools/extra_defs_gen $ ./generate_extra_defs > gtk_signals.defs
You must edit the source code of your own generate_extra_defs tool in order to generate the .defs for the GObject C types that you wish to wrap. In the skeleton source tree, the source file is named codegen/extradefs/generate_extra_defs_skeleton.cc. If not done so already, the file should be renamed, with the basename of your new binding substituted for the skeleton placeholder. The codegen/Makefile.am file should also mention the new source filename.
Then edit the .cc file to specify the correct types. For instance, your main() function might look like this:
#include <libsomething.h> int main(int, char**) { something_init(); std::cout << get_defs(EXAMPLE_TYPE_SOMETHING) << get_defs(EXAMPLE_TYPE_THING); return 0; } | http://developer.gnome.org/gtkmm-tutorial/unstable/sec-wrapping-defs-files.html | crawl-003 | refinedweb | 383 | 61.12 |
Agenda
See also: IRC log
<RalphS> Previous: 2006-12-12
<TomB> Scribenick: JonP
RESOLUTION: Accept minutes
<aliman> I will be on holiday 2 Jan
Telecon times
<TomB> RESOLVED: Next telecon 9 January 1600 UTC
RESOLUTION: Next teleconference 9 January 1600 UTC
<scribe> ACTION: TomB and Guus to look at proposal for assigning scribe duties [recorded in] [CONTINUES]
--continuing
<TomB>
<aliman> looks good Tom
TomB: Requesting that each editor check the deliverables page before telecon to make sure the links are updated and correct on that page
... Editors should raise any issues with that page during the telecon
<RalphS> Please register by 10 Jan for the January Face-to-face
RalphS: Reminding everyone that we should build time into our agenda for linches, breaks
<guus> [sorry. i'm sick]
<RalphS> f2f registration form
<scribe> ACTION: Everyone should be registered for the F2F by 10 Jan [recorded in]
<RalphS> scribenick: tomb
Jon: Saw links to OWL issues list, etc - would be a good idea to consolidate a format - will try to wikify the OWL and former SW issues lists.
... Three old formats. Will try to consolidate those.
<JonP>
<aliman> SKOS issues
Alistair: Assumed we are migrating to completely new issues list. That list was mine. Action on me to prepare this old list as input for January meeting. Action on someone else to prepare new issues list.
<JonP>
<RalphS> RDFa issues list (now moved to wiki)
Alistair: Not sure what needs to be done to old list - just print it off?
RalphS: Alistair use judgement in categorizing issues, handing them over to this WG.
Alistair: only seven open issues, all important.
... important to understand those issues in context of use cases.
Antoine: Existing SKOS issues list - there were some closed issues. Re-open?
JonP, can you please scribe again?
<JonP> scribenick: JonP
aliman: we have to deal with issue of translations we receive and might be worth raising a new issue around that
<scribe> ACTION: Jon to create an issues page on the wiki [recorded in] [CONTINUES]
<scribe> ACTION: Alistair to prepare issues list for January meeting [recorded in] [CONTINUES]
<scribe> ACTION: Alistair will send the outstanding issues to the list and Jon will paste into the formatted page [recorded in]
<scribe> ACTION: sean to submit SKOS and rules issue using agreed issue format, directly into issues wiki page (waiting for Jon) [recorded in] [CONTINUES]
- SKOS and ISO 11179
<scribe> ACTION: Elisa to keep us posted as SKOS/iso 11179 [recorded in] [DONE]
<RalphS> brief update on 11179 from Elisa
<RalphS> [[
<RalphS> I'll be meeting with some of the contributors from Lawrence Berkeley
<RalphS> Laboratories next week to talk about this, and have invited Dan Rubin to
<RalphS> join me, so we should have more to share after that.
<RalphS> ]]
<RalphS> -- Elisa, in msg 0053
aliman: Looking at the old issues list, it's actually "SKOS-core" and it's good to move that to a more general issues list
... also makes sense to rebrabd SKOS-core as SKOS with a single unified specification
RalphS: endorses that suggestion
benadidia: report on RDFa telecon...
<RalphS> RDFa use case wiki
benadidia: collecting more use cases over the next few days, for example science bloggers
... should have use cases reviewed in time for January F2F
... continuing work on XHTML1.1 integration with Mark
... XHTML1.1 Module needs to be updated on the deliverables page
TomB: it would be helpful to make it possible for anyone to get a full picture of the complete project from the deliverables page
... suggesting that the deliverables page might point to the RDFa overview page
<scribe> ACTION: guus to review RDFa documents [recorded in] [CONTINUES]
<scribe> ACTION: guus/tomb to put item on f2f agenda to make publication decision for RDFa documents (use cases and primer) [recorded in] [CONTINUES]
<TomB>
<scribe> ACTION: DanBri to send a report on the configuration he used to the list [recorded in] [DONE]
aliman: just a quick glance indicates that DanB's configuration doesn't conform to the recipes
TomB: would Alistair please bring these issues out on the list
berrueta: posted a link to his unit test code to the list, but no one has tried it yet
TomB: suggest we take one of these issues pages as an exemplar
<RalphS> Jon: it would be hard to replicate the OWL issues list format in a wiki
<scribe> ACTION: Jon will choose one of the three issues pages, create a proposed format, and then post to the list for discussion [recorded in]
- Deliverable 3: Principles for Managing RDF Vocabularies (namespaces, change management, versioning)
TomB: still no editor(s). Still no volunteers
<RalphS> RIF issues tracker
RalphS: points out that a number of groups are using a database-driven issues tracking tool
TomB: feels that it's a bit too much, but is worth considering if a lot of issues show up
This is scribe.perl Revision: 1.127 of Date: 2005/08/16 15:12:03 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Found ScribeNick: JonP Found ScribeNick: tomb Found ScribeNick: JonP Inferring Scribes: JonP, tomb Scribes: JonP, tomb ScribeNicks: JonP, tomb WARNING: No "Topic:" lines found. Default Present: TomB, Ralph, Antoine, SeanB, Alistair, JonP, Diego, benadida Present: TomB Ralph Antoine SeanB Alistair JonP Diego benadida WARNING: Replacing previous Regrets list. (Old list: Bernard, Danbri, Daniel) Use 'Regrets+ ... ' if you meant to add people without replacing the list, such as: <dbooth> Regrets+ Guus Regrets: Guus Agenda: Got date from IRC log name: 19 Dec 2006 Guessing minutes URL: People with action items: alistair everyone g | http://www.w3.org/2006/12/19-swd-minutes.html | CC-MAIN-2014-41 | refinedweb | 926 | 50.5 |
PROLOGThis manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
NAMEffs — find first set bit
SYNOPSIS
#include <strings.h>
int ffs(int i);
DESCRIPTIONThe ffs() function shall find the first bit set (beginning with the least significant bit) in i, and return the index of that bit. Bits are numbered starting at one (the least significant bit).
RETURN VALUEThe ffs() function shall return the index of the first bit set. If i is 0, then ffs() shall return 0.
ERRORSNo errors are defined.
The following sections are informative.
EXAMPLESNone.
APPLICATION USAGENone.
RATIONALENone.
FUTURE DIRECTIONSNone.
SEE ALSOThe Base Definitions volume of POSIX.1‐2017, <strings . | https://man.archlinux.org/man/ffs.3p.en | CC-MAIN-2021-04 | refinedweb | 133 | 50.02 |
README
Elastic ECS Typescript DefinitionsElastic ECS Typescript Definitions
This wraps up the Elastic Common Schema into strict Typescript types by parsing the official ECS schema document. Since this library is pure types and a strict reflection of ECS, the version is pinned to the ECS version itself, starting from version 1.7. You can also clone this repo to build against a given ECS version yourself.
FeaturesFeatures
- Get all ECS fields as a flat associative array (EcsFields) or as a full object hierarchy (EcsTree).
- Breakout by ECS core and/or extended fields
- Convience Schema type util to guarantee type-safe events and schema
- Generic enough parsing to run yourself against any ECS version
InstallInstall
Run:
npm install elastic-ecs
VersioningVersioning
This NPM package's version is pinned to the associated ECS version, so version 1.7.0 of this lib would represent ECS version 1.7.0, for example.
Any patch or minor updates will be reflected with appending -[a-z]* to the ECS semver version.
Example UsageExample Usage
Basic Usage: Reference field names/valuesBasic Usage: Reference field names/values
import { EcsFields, EcsTree } from 'elastic-ecs'; interface MyBasicEcsEvent extends EcsFields { [EcsFields["event.created"]]: new Date(), [EcsFields["event.action"]]: 'page-viewed', [EcsFields["event.kind"]]: 'event', [EcsFields["event.category"]]: ['myCat'], // Causes Compile error, myCat is not a valid value! }
Advanced Usage: Define Events through a type-safe custom schemaAdvanced Usage: Define Events through a type-safe custom schema
By defining your own Schema, you can get lots of free type safety when both defining your custom fields on top of ECS fields and when defining individual events:
import { NewEventType, NewSchema, EcsFields } from 'elaastic-ecs' // All the custom fields you ever put in events should go here interface MyCustomFields { // Optional fields on some events 'attempts.count'?: number, // Required fields on ALL events 'customer.id': string, } // Make all ECS fields available, another good option could be EcsCoreFields if you don't need extended fields type MyEcsFieldNames = EcsFields & { // Required ECS fields '@timestamp': Date, 'event.action': string, } // Define my schema based on my custom fields and the ECS fields I have available type MySchema = NewSchema<MyCustomFields, MyEcsFieldNames> // My Event Types // Verbose schema, spell out the field names AND types type MyLogoutEvent = NewEventSchema<MySchema, { '@timestamp': Date, 'event.action': 'User Logout', 'customer.id': string // Optional fields 'event.category'?: 'authentication'[], }> // Shorthand schema, don't need to include fields' types type MyLoginEvent = NewEventType<MySchema, '@timestamp' | 'event.action' | 'customer.id', // Required Event Fields 'event.category' | 'attempts.count', // Optional Event Fields {'event.action': 'User Login'} // Per-Event schema type narrowing > const loginEvent: MyLoginEvent = { 'event.action': 'User Login', '@timestamp': new Date(), 'attempts.count': 1, 'customer.id': '123', }; const logoutEvent: MyLogoutEvent = { '@timestamp': new Date(), 'event.action': 'User Logout', 'customer.id': '123', };
Keeping up-to-dateKeeping up-to-date
I may be too lazy to keep up-to-date with the latest ECS version on a weekly or monthly basis. If you require the latest and greatest now, please run the automated build process below and send me a pull request! This'll probably be motivating enough to get me off my rear.
Building against an ECS versionBuilding against an ECS version
- Clone this repository and ensure you have Node.js version 10 or above installed.
- Use a terminal to cd into the rot of this repo.
- Change the version in
package.jsonto match the ECS version you want to build against, plus an extra zero such as
1.7.0.
- Change the ECS branch version number in
package.jsonunder the
build-typesscript and make sure it matches the version from step 3, but without the last number, ex.
1.7.
- Run
npm installto install dependencies.
- Run
npm run buildto build the type definitions.
- Open a Pull Request for me if it's the latest ECS version or copy index.ts to your project. | https://www.skypack.dev/view/elastic-ecs | CC-MAIN-2022-05 | refinedweb | 629 | 57.47 |
I need to read all the HTML text from a url like into a string in C.
I know that if i put on
telnet -> telnet 80 Get webpage.... it returns all the html.
How do I do this in a linux environment with C?
How to profile my C++ application on linux
1:Running commands though PHP/Perl scripts as a priviledged user on Linux
I would suggest using a couple of libraries, which are commonly available on most Linux distrialthough ions:. Generating a reasonable ctags database for Boost libcurl and libxml2. Where are my ruby gems? libcurl provides a comprehensive suite of http features, and libxml2 provides a module for parsing html, called HTMLParser. Creating a new window that stays on top even when in full screen mode (Qt on Linux) Hope this points you in the right direction. How can I figure out why cURL is hanging and unresponsive?Linux - Want To Check For Possible Duplicate Directories (Probably RegEx Needed)How to track the memory usage in C++
2:
Below is a rough outline of code (i.e. not enough error checking and I haven't tried to compile it) to receive your started, although use to learn socket programming. Lookup receive hostbyname if you need to translate a hostname (like google.com) into an IP address. Also you may need to did any job to parse out the content length from the HTTP response and then make sure you keep calling recv until you've gotten all the bytes..
#include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> #include <string.h> #include <stdlib.h> void receive Webpage(char *buffer, int bufsize, char *ipaddress) { int sockfd; struct sockaddr_in destAddr; if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){ fprintf(stderr, "Error opening client socket\n"); close(sockfd); return; } destAddr.sin_family = PF_INET; destAddr.sin_port = htons(80); // HTTP port is 80 destAddr.sin_addr.s_addr = inet_addr(ipaddress); // Get int representation of IP memset(&(destAddr.sin_zero), 0, 8); if(connect(sockfd, (struct sockaddr *)&destAddr, sizeof(struct sockaddr)) == -1){ fprintf(stderr, "Error with client connecting to server\n"); close(sockfd); return; } // Send http request char *httprequest = "GET / HTTP/1.0"; send(sockfd, httprequest, strlen(httprequest), 0); recv(sockfd, buffer, bufsize, 0); // Now buffer has the HTTP response which includes the webpage. You must either // trim off the HTTP header, or just leave it in depending on what you are doing // with the page }
3:
You use sockets, interrogate the web server with HTTP (where you have "") and then parse the data which you have received.. Helpful if you are a beginner in socket programming:.
4:
if you really don't feel like messing around with sockets, you could always create a named temp file, fork off a process and execvp() it to run wreceive -0 , and then read the input from this temp file. . although this would be a pretty lame and inefficient way to did things, it would mean you wouldn't have to mess with TCP and sending HTTP requests. .
5:
Assuming you know how to read a file into a string, I'd try.
You fork a process, although it's a lot easier to letYou fork a process, although it's a lot easier to let
const char *url_contents(const char *url) { // create w3m command and pass it to popen() int bufsize = strlen(url) + 100; char *buf = malloc(bufsize); snprintf(buf, bufsize, "w3m -dump_source '%s'"); // receive a file handle, read all the html from it, close, and return FILE *html = popen(buf, "r"); const char *s = read_file_into_string(html); // you write this function fclose(html); return s; }
w3mdid the heavy lifting.. | http://media4u.ir/?t=1344&e=1584071632&ref=back40news&z=Invoke+web+page+from+Linux+C | CC-MAIN-2017-13 | refinedweb | 603 | 61.97 |
elm package install etaque/elm-dialog
A modal component for Elm. Not named
elm-modal because it would be type-error-prone with the
model we have everywhere in our apps!
It assumes that you can only have one instance at a time of an open modal, so the state can be global in the Elm way: declared once, usable from anywhere.
To avoid boilerplate in update delegation, an
Address is exposed so this global state (ie dialog content, visibility) can be updated from anywhere in you views and updates.
A minor drawback is that the dialog content is stored as
Html in the state, so can't be automaticaly rerendered from you app model if you need so: you have to send a task to update the dialog content.
Don't forged to
import Dialog in every impacted module. See example/ for a fully working usage example.
Add the dialog instance to your model:
type alias Model = WithDialog { ... } -- or without record extension: type alias Model = { dialog : Dialog , ... }
See
getContent,
getOptions,
getTransition,
isOpen and
isVisible for model querying. Initialize it with
dialog = Dialog.initial.
Add a type case for the dialog actions:
type Action = NoOp | ... | DialogAction Dialog.Action
wrappedUpdate, otherwise you should use the regular
updatefunction.
update : Action -> Model -> (Model, Effects Action) update action model = case action of DialogAction dialogAction -> Dialog.wrappedUpdate DialogAction dialogAction model
StartApp.Start { ... , inputs = [ Signal.map DialogAction Dialog.actions ] }
This package provides a simple theme under
Dialog.Simple, here
is a default stylesheet (you can roll out your own theme if you need it).
Simple.viewat the bottom of your top-level view. It's only a shell, hidden by default. It will be in charge of showing up the dialog content and backdrop according to state.
view : Address Action -> Model -> Html view addr model = div [ ] [ ... -- your app view , Dialog.Simple.view model.dialog ]
openOnClick(or
openWithOptionsOnClickif you need more control):
-- Somewhere in your views, where you need to open a dialog somePartOfYourView addr = button [ Dialog.openOnClick (dialog addr) ] [ text "..." ] dialog : Address Action -> Dialog.Options -> List Html dialog addr options = [ Dialog.header options "Are you sure?" , Dialog.body [ p [] [ text "Please give it a second thought." ] ] , Dialog.footer [ a [ class "btn btn-default" , Dialog.onClickHide ] [ text "You make me doubt" ] , a [ class "btn btn-primary" , Dialog.onClickHideThenSend addr SomeAction ] [ text "FFS, go on!" ] ] ]
Here we're using:
headeras the title decorator, taking
optionsas parameter: if
options.onCloseis non empty, it will display a close button
bodyfor the message of the modal
footerfor the actions.
Options are:
durationfor the fade animation, in ms
onClosefor the task to run when closing the modal. Set to
Nothingto prevent closing.
The package provide two levels to control dialog:
The basis is
address : Address Dialog.Action in combination with those action builders:
open,
openWithOptionsto open the modal with the provided content,
updateContentto update content without touching opened state
closeThenSend,
closeThenDoto close the modal and send a message/run a task.
That makes it controllable from everywhere in your app, not only views.
Some
onClick shortcuts are available for the views, they produce an HTML attribute:
openOnClickand
openWithOptionsOnClick
closeOnClickand
closeThenSendOnClick | https://package.frelm.org/repo/427/1.1.0 | CC-MAIN-2018-51 | refinedweb | 518 | 50.73 |
Introduction
About a year ago there was a reddit post on the Ising Model in Haskell. The discussion seems to have fizzled out but Ising models looked like a perfect fit for Haskell using repa. In the end it turns out that they are not a good fit for repa, at least not using the original formulation. It may turn out that we can do better with Swendson-Yang or Wolff. But that belongs to another blog post.
We can get some parallelism at a gross level using the Haskell parallel package via a one line change to the sequential code. However, this does not really show off Haskell’s strengths in this area. In any event, it makes a good example for “embarassingly simple” parallelism in Haskell, the vector package and random number generation using the random-fu package.
The Ising model was (by Stigler’s law) proposed by Lenz in 1920 as a model for ferromagnetism, that is, the magnetism exhibited by bar magnets. The phenomenon ferromagnetism is so named because it was first observed in iron (Latin ferrum and chemical symbol Fe). It is also exhibited, for example, by rare earths such as gadolinium. Ferromagnetic materials lose their magnetism at a critical temperature: the Curie temperature (named after Pierre not his more famous wife). This is an example of a phase transition (ice melting into water is a more familiar example).
The Ising model (at least in 2 dimensions) predicts this phase transition and can also be used to describe phase transitions in alloys.
Abstracting the Ising model from its physical origins, one can think of it rather like Conway’s Game of Life: there is a grid and each cell on the grid is updated depending on the state of its neighbours. The difference with the Game of Life is that the updates are not deterministic but are random with the randomness selecting which cell gets updated as well as whether it gets updated. Thus we cannot update all the cells in parallel as would happen if we used repa. The reader only interested in this abstraction can go straight to the implementation (after finishing this introduction).
The diagram below shows a 2 dimensional grid of cells. Each cell can either be in an (spin) up state or (spin) down state as indicated by the arrows and corresponding colours. The Ising model then applies a parameterized set of rules by which the grid is updated. For certain parameters the cells remain in a random configuration, that is the net spin (taking up = 1 and down = -1) remains near zero; for other parameters, the spins in the cells line up (not entirely as there is always some randomness). It is this lining up that gives rise to ferromagnetism.
On the other hand, the physics and the Monte Carlo method used to simulate the model are of considerable interest in their own right. Readers interested in the Monte Carlo method can skip the physics and go to Monte Carlo Estimation. Readers interested in the physics can start with the section on Magnetism.
Definitions, theorems etc. are in bold and terminated by
.
Magnetism
Following Ziman (Ziman 1964) and Reif (Reif 2009), we assume that each atom in the ferromagnetic material behaves like a small magnet. According to Hund’s rules, we would expect unpaired electrons in the
and
shells for example in the transition elements and rare earths and these would supply the magnetic moment. However, the magnetic interaction between atoms is far too small to account for ferromagnetism. For Iron, for example, the Curie temperature is 1043K and the magnetic interaction between atoms cannot account for this by some margin. There is a quantum mechanical effect called the exchange interaction which is a consequence of the Pauli exclusion principle. Two electrons with the same spin on neighbouring atoms cannot get too close to each other. If the electrons have anti-parallel spins then the exclusion principle does not apply and there is no restriction on how close they can get to each other. Thus the electrostatic interaction between electrons on neighbouring atoms depends on whether spins are parallel or anti-parallel. We can thus write the Hamiltonian in the form:
Where
The notation
means we sum over all the nearest neighbours in the lattice;
is the applied magnetic field (note we use E for the Hamiltonian), for all of this article we will assume this to be
;
The range of each index is
where
is the total number of atoms;
And
the coupling constant expressing the strength of the interaction between neighboring spins and depending on the balance between the Pauli exclusion principle and the electrostatic interaction energy of the electrons, this may be positive corresponding to parallel spins (ferromagnetism which is the case we consider in this article) or negative corresponding to anti parallel spins (antiferromagnetism or ferrimagnetism which we consider no further).
Acknowledgments
This post uses the random-fu package for random number generation and has also benefitted from comments by the author of that package (James Cook).
All diagrams were drawn using the Haskell diagrams domain specific language; the inhabitants of #diagrams were extremely helpful in helping create these.
Internet sources too numerous to mention were used for the physics and Monte Carlo. Some are listed in the bibliography. Apologies if you recognize something which does not get its just acknowledgement. The advantage of blog posts is that this can easily be remedied by leaving a comment.
Haskell Preamble
Pragmas and imports to which only the over-enthusiastic reader need pay attention.
> {-# OPTIONS_GHC -Wall #-} > {-# OPTIONS_GHC -fno-warn-name-shadowing #-} > {-# OPTIONS_GHC -fno-warn-type-defaults #-} > {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} > {-# OPTIONS_GHC -fno-warn-missing-methods #-} > {-# OPTIONS_GHC -fno-warn-orphans #-}
> {-# LANGUAGE TypeFamilies #-} > {-# LANGUAGE NoMonomorphismRestriction #-} > {-# LANGUAGE TypeOperators #-} > {-# LANGUAGE ScopedTypeVariables #-}
> module Ising ( > energy > , magnetization > , McState(..) > , thinN > , gridSize > , nItt > , expDv > , tCrit > , singleUpdate > , randomUpdates > , initState > , multiUpdate > , temps > , initColdGrid > , exampleGrid > , notAperiodics > , main > ) where
We put all of our code for the diagrams in this blog post in a separate module to avoid clutter.
> import Diagrams
> import qualified Data.Vector.Unboxed as V > import qualified Data.Vector.Unboxed.Mutable as M
> import Data.Random.Source.PureMT > import Data.Random > import Control.Monad.State
> import Control.Parallel.Strategies
> import Graphics.Rendering.Chart.Backend.Cairo
> import Data.Array.Repa hiding ( map, (++), zipWith ) > import Data.Array.Repa.Algorithms.Matrix
> import PrettyPrint ()
> gridSize :: Int > gridSize = 20 > > exampleGrid :: Int -> V.Vector Int > exampleGrid gridSize = V.fromList $ f (gridSize * gridSize) > where > f m = > evalState (replicateM m (sample (uniform (0 :: Int) (1 :: Int)) >>= > \n -> return $ 2*n - 1)) > (pureMT 1)
> couplingConstant :: Double > couplingConstant = 1.0 > > kB :: Double > kB = 1.0 > > mu :: Double > mu = 1.0
The Boltzmann Distribution
Statistical physics is an extremely large subject but there needs to be some justification for the use of the Boltzmann distribution. For an excellent introduction to the subject of Statistical Physics (in which the Boltzmann distribution plays a pivotal role) see David Tong’s lecture notes (Tong (2011)).
Suppose we have we 3 boxes (we use the more modern nomenclature rather than the somewhat antiquated word urn) and 7 balls and we randomly assign the balls to boxes. Then it is far more likely that we will get an assignment of 2,2,3 rather than 0,0,7. When the numbers of boxes and balls become large (which is the case in statistical physics where we consider e.g.
numbers of atoms) then it becomes very, very, very likely that the balls (or atoms) will spread themselves out uniformly as in the example.
Now suppose we have
balls and
boxes and we associate an energy
with the
-th box but restrict the total energy to be constant. Thus we have two constraints:
The total number of balls
and
The total energy
.
Let us assume the balls are allocated to boxes in the most likely way and let us denote the values in each box for this distribution as
.
Let us now move 2 balls from box
, one to box
and one to box
. Note that both constraints are satisified by this move. We must therefore have
And let us start from the most likely distribution and move 1 ball from box
and 1 ball from box
into box
. Again both constraints are satisified by this move. Doing a similar calculation to the one above we get
From this we deduce that as
then
or that
for some constant
.
Telecsoping we can write
. Thus the probability of a ball being in box
is
If we now set
and
then we can re-write our distribution as
It should therefore be plausible that the probability of finding a system with a given energy
in a given state
is given by the Boltzmann distribution
where we have defined the temperature to be
with
being Boltzmann’s constant and
is another normalizing constant.
Specific Heat
Using the Boltzmann distribution we can calculate the average energy of the system
where it is understood that
depends on
.
If we let
be the specific heat per particle (at constant volume) then
We know that
So we can write
so if we can estimate the energy and the square of the energy then we can estimate the specific heat.
Monte Carlo Estimation
Although Ising himself developed an analytic solution in 1 dimension and Onsager later developed an analytic solution in 2 dimensions, no-one has (yet) found an analytic solution for 3 dimensions.
One way to determine an approximate answer is to use a Monte Carlo method.
Uniform Sampling
We could pick sample configurations at random according to the Boltzmann distribution
where the sum
is the temperature,
is Boltzmann’s constant,
is the energy of a given state
and
is a normalizing constant (Z for the German word Zustandssumme, “sum over states”)
We can evaluate the energy for one state easily enough as the Haskell below demonstrates. Note that we use so-called periodic boundary conditions which means our grid is actually a torus with no boundaries. In other words, we wrap the top of the grid on to the bottom and the left of the grid on to the right.
[As an aside, we represent each state by a Vector of Int. No doubt more efficient representations can be implemented. We also have to calculate offsets into the vector given a point’s grid co-ordinates.]
> energy :: (Fractional a, Integral b, M.Unbox b) => a -> V.Vector b -> a > energy j v = -0.5 * j * (fromIntegral $ V.sum energyAux) > where > > energyAux = V.generate l f > > l = V.length v > > f m = c * d > where > i = m `mod` gridSize > j = (m `mod` (gridSize * gridSize)) `div` gridSize > >)
But what about the normalizing constant
? Even for a modest grid size say
, the number of states that needs to be summed over is extremely large
.
Instead of summing the entire state space, we could draw R random samples
uniformly from the state space. We could then use
to estimate e.g. the magnetization
by
However we know from statistical physics that systems with large numbers of particles will occupy a small portion of the state space with any significant probability. And according to (MacKay 2003, chap. 29), a high dimensional distribution is often concentrated on small region of the state space known as its typical set
whose volume is given by
where
is the (Shannon) entropy of the (Boltzmann) distribution which for ease of exposition we temporarily denote by
.
If almost all the probability mass is located in
then the actual value of the (mean) magnetization will determined by the values that
takes on that set. So uniform sampling will only give a good estimate if we make
large enough that we hit
at least a small number of times. The total size of the state space is
and the
, so there is a probability of
of hitting
. Thus we need roughly
samples to hit
.
At high temperatures, the Boltzmann distribution flattens out so roughly all of the states have an equal likelihood of being occupied. We can calculate the (Shannon) entropy for this.
We can do a bit better than this. At high temperatures,
and taking
(as we have been assuming all along)
By definition
Thus
We can therefore re-write the partition function as
where the factor 2 is because we count the exchange interaction twice for each pair of atoms and the factor 4 is because each atom is assumed to only interact with 4 neighbours.
Since at high temperatures, by assumption, we have
then
also.
Thus
Calculating the free energy
From this we can determine the (Boltzmann) entropy
which agrees with our rather hand-wavy derivation of the (Shannon) entropy at high temperatures.
At low temperatures the story is quite different. We can calculate the ground state energy where all the spins are in the same direction.
And we can assume that at low temperatures that flipped spins are isolated from other flipped spins. The energy for an atom in the ground state is -4J and thus the energy change if it flips is 8J. Thus the energy at low temperatures is
The partition function is
Again we can calculate the free energy and since we are doing this calculation to get a rough estimate of the entropy we can approximate further.
From this we can determine the (Boltzmann) entropy. Using the fact that
and thus that
we have
The critical temperature (as we shall obtain by simulation) given by Onsager’s exact result in 2d is
Taking
> tCrit :: Double > tCrit = 2.0 * j / log (1.0 + sqrt 2.0) where j = 1
ghci> tCrit 2.269185314213022
Plugging this in we get
ghci> exp (-8.0/tCrit) * (1.0 + 8.0 / tCrit) 0.1332181153896559
Thus the (Shannon) entropy is about 0.13N at the interesting temperature and is about N at high temperatures. So uniform sampling would require
samples at high temperatures but
at temperatures of interest. Even for our modest
grid this is
samples!
Fortunately, Metropolis and his team (Metropolis et al. 1953) discovered a way of constructing a Markov chain with a limiting distribution of the distribution required which does not require the evaluation of the partition function and which converges in a reasonable time (although theoretical results substantiating this latter point seem to be hard to come by).
Markov Chains
Markov first studied the stochastic processes that came to be named after him in 1906.
We follow (Norris 1998), (Beichl and Sullivan 2000), (Diaconis and Saloff-Coste 1995), (Chib and Greenberg 1995) (Levin, Peres, and Wilmer 2008) and (Gravner 2011).
As usual we work on a probability measure space
(that is
). Although this may not be much in evidence, it is there lurking behind the scenes.
Let
be a finite set. In the case of an Ising model with
cells, this set will contain
elements (all possible configurations).
A Markov chain is a discrete time stochastic process
such that
That is, where a Markov chain goes next only depends on where it is not on its history.
A stochastic transition matrix is a matrix
such that
We can describe a Markov chain by its transition matrix
and initial distribution
. In the case we say a stochastic process
is Markov
.
We need to be able to discuss properties of Markov chains such as stationarity, irreducibility, recurrence and ergodicity.
Stationarity
A Markov chain has a stationary distribution
if
One question one might ask is whether a given Markov chain has such a distribution. For example, for the following chain, any distribution is a stationary distribution. That is
for any
.
Any distribution is a stationary distribution for the unit transition matrix.
The
-th transition matrix of a Markov chain is
. The corresponding matrix entries are
Another key question is, if there is a unique stationary distribution, will the
-th transition probabilities converge to that distribution, that is, when does,
as
.
Irreducibility
Write
We say that
leads to
and write
if
Theorem For distinct states
and
, the following are equivalent:
for some
This makes it clear that
is transitive and reflexive hence an equivalence relation. We can therefore partition the states into classes. If there is only one class then the chain is called irreducible.
For example,
has classes
,
and
so is not irreducible.
On the other hand
is irreducible.
Recurrence
Let
be a Markov chain. A state
is recurrent if
The first passage time is defined as
Note that the
is taken over
strictly greater than 1. Incidentally the first passage time is a stopping time but that any discussion of that would take this already long article even longer.
The expectation of the
-th first passage time starting from
is denoted
.
Theorem Let
be irreducible then the following are equivalent:
Every state is positive recurrent.
Some state is positive recurrent.
P has an invariant distribution
and in this case
.
A state
is aperiodic if
for all sufficiently large
.
For example, the chain with this transition matrix is not periodic:
as running the following program segment shows with the chain flip-flopping between the two states.
> notAperiodic0 :: Array U DIM2 Double > notAperiodic0 = fromListUnboxed (Z :. (2 :: Int) :. (2 :: Int)) ([0,1,1,0] :: [Double]) > notAperiodics :: [Array U DIM2 Double] > notAperiodics = scanl mmultS notAperiodic0 (replicate 4 notAperiodic0)
ghci> import Ising ghci> import PrettyPrint ghci> import Text.PrettyPrint.HughesPJClass ghci> pPrint notAperiodics [[0.0, 1.0] [1.0, 0.0], [1.0, 0.0] [0.0, 1.0], [0.0, 1.0] [1.0, 0.0], [1.0, 0.0] [0.0, 1.0], [0.0, 1.0] [1.0, 0.0]]
Theorem Let
be irreducible and aperiodic and suppose that
has an invariant distribution
. Let
be any distribution (on the state space???). Suppose that
is Markov
then
as
for all
A proof of this theorem uses coupling developed by Doeblin; see (Gravner 2011) for more details.
Corollary With the conditions of the preceding Theorem
as
for all
If the state space is infinite, the existence of a stationary distribution is not guaranteed even if the Markov chain is irreducible, see (Srikant 2009) for more details.
Detailed Balance
A stochastic matrix
and a distribution
are said to be in detailed balance if
Theorem If a stochastic matrix
and a distribution
are in detailed balance then
is a stationary distribution.
The Ergodic Theorem
Define the number of visits to
strictly before time
as
is the proportion of time before
spent in state
.
Theorem Let
be an irreducible Markov chain then
If further the chain is positive recurrent then for any bounded function
then
If further still the chain is aperiodic then it has a unique stationary distribution, which is also the limiting distribution
A Markov chain satisfying all three conditions is called ergodic.
The Metropolis Algorithm
Thus if we can find a Markov chain with the required stationary distribution and we sample a function of this chain we will get an estimate for the average value of the function. What Metropolis and his colleagues did was to provide a method of producing such a chain.
Algorithm Let
be a probability distribution on the state space
with
for all
and let
be an ergodic Markov chain on
with transition probabilities
(the latter condition is slightly stronger than it need be but we will not need fully general conditions).
Create a new (ergodic) Markov chain with transition probabilities
where
takes the maximum of its arguments.
Calculate the value of interest on the state space e.g. the total magnetization for each step produced by this new chain.
Repeat a sufficiently large number of times and take the average. This gives the estimate of the value of interest.
Let us first note that the Markov chain produced by this algorithm almost trivially satisfies the detailed balance condition, for example,
Secondly since we have specified that
is ergodic then clearly
is also ergodic (all the transition probabilities are
).
So we know the algorithm will converge to the unique distribution we specified to provide estimates of values of interest.
Two techniques that seem to be widespread in practical applications are burn in and thinning. Although neither have strong theoretical justification (“a thousand lemmings can’t be wrong”), we follow the practices in our implementation.
“Burn in” means run the chain for a certain number of iterations before sampling to allow it to forget the initial distribution.
“Thinning” means sampling the chain every
iterations rather than every iteration to prevent autocorrelation.
Haskell Implementation
Calculating the total magnetization is trivial; we just add up all the spins and multiply by the magnetic moment of the electron.
> magnetization :: (Num a, Integral b, M.Unbox b) => a -> V.Vector b -> a > magnetization mu = (mu *) . fromIntegral . V.sum
We keep the state of the Monte Carlo simulation in a record.
> data McState = McState { mcMagnetization :: !Double > , mcMAvg :: !Double > , mcEnergy :: !Double > , mcEAvg :: !Double > , mcEAvg2 :: !Double > , mcCount :: !Int > , mcNumSamples :: !Int > , mcGrid :: !(V.Vector Int) > } > deriving Show
As discussed above we sample every thinN iterations, a technique known as “thinning”.
> thinN :: Int > thinN = 100
The total number of iterations per Monte Carlo run.
> nItt :: Int > nItt = 1000000
There are only a very limited number of energy changes that can occur for each spin flip. Rather the recalculate the value of the Boltzmann distribution for every spin flip we can store these in a Vector.
For example if spin is up and all its surrounding spins are up and it flips to down then energy change is
and the corresponding value of the Boltzmann distribution is
.
Another example, the energy before is
and the energy after is
so the energy change is
.
> expDv :: Double -> Double -> Double -> V.Vector Double > expDv kB j t = V.generate 9 f > where > f n | odd n = 0.0 > f n = exp (j * ((fromIntegral (8 - n)) - 4.0) * 2.0 / (kB * t))
The most important function is the single step update of the Markov chain. We take an Int representing the amount of thinning we wish to perform, the vector of pre-calculated changes of the Boltzmann distribution, the current state, a value representing the randomly chosen co-ordinates of the grid element that will be updated and a value sampled from the uniform distribution which will decide whether the spin at the co-ordinates will be updated.
> singleUpdate :: Int -> V.Vector Double -> McState -> (Int, Int, Double) -> McState > singleUpdate thinN expDvT u (i, j, r) = > McState { mcMagnetization = magNew > , mcMAvg = mcMAvgNew > , mcEnergy = enNew > , mcEAvg = mcEAvgNew > , mcEAvg2 = mcEAvg2New > , mcCount = mcCount u + 1 > , mcNumSamples = mcNumSamplesNew > , mcGrid = gridNew > } > where > > (gridNew, magNew, enNew) = > if p > r > then ( V.modify (\v -> M.write v jc (-c)) v > , magOld - fromIntegral (2 * c) > , enOld + couplingConstant * fromIntegral (2 * c * d) > ) > else (v, magOld, enOld) > > magOld = mcMagnetization u > enOld = mcEnergy u > > (mcMAvgNew, mcEAvgNew, mcEAvg2New, mcNumSamplesNew) = > if (mcCount u) `mod` thinN == 0 > then ( mcMAvgOld + magNew > , mcEAvgOld + enNew > , mcEAvg2Old + enNew2 > , mcNumSamplesOld + 1 > ) > else (mcMAvgOld, mcEAvgOld, mcEAvg2Old, mcNumSamplesOld) > > enNew2 = enNew * enNew > > mcMAvgOld = mcMAvg u > mcEAvgOld = mcEAvg u > mcEAvg2Old = mcEAvg2 u > mcNumSamplesOld = mcNumSamples u > > v = mcGrid u > > p = expDvT V.! (4 + c * d) > >)
In order to drive our Markov chain we need a supply of random positions and samples from the uniform distribution.
> randomUpdates :: Int -> V.Vector (Int, Int, Double) > randomUpdates m = > V.fromList $ > evalState (replicateM m x) > (pureMT 1) > where > x = do r <- sample (uniform (0 :: Int) (gridSize - 1)) > c <- sample (uniform (0 :: Int) (gridSize - 1)) > v <- sample (uniform (0 :: Double) 1.0) > return (r, c, v)
To get things going, we need an initial state. We start with a cold grid, that is, one with all spins pointing down.
> initColdGrid :: V.Vector Int > initColdGrid = V.fromList $ replicate (gridSize * gridSize) (-1) > > initState :: McState > initState = McState { mcMagnetization = magnetization mu initColdGrid > , mcMAvg = 0.0 > , mcEnergy = energy couplingConstant initColdGrid > , mcEAvg = 0.0 > , mcEAvg2 = 0.0 > , mcCount = 0 > , mcNumSamples = 0 > , mcGrid = initColdGrid > }
We will want to run the simulation over a range of temperatures in order to determine where the phase transition occurs.
> temps :: [Double] > temps = getTemps 4.0 0.5 100 > where > getTemps :: Double -> Double -> Int -> [Double] > getTemps h l n = [ m * x + c | > w <- [1..n], > let x = fromIntegral w ] > where > m = (h - l) / (fromIntegral n - 1) > c = l - m
Now we can run a chain at a given temperature.
> multiUpdate :: McState -> Double -> V.Vector (Int, Int, Double) -> McState > multiUpdate s t = V.foldl (singleUpdate thinN (expDv kB couplingConstant t)) s
For example running the model at a temperature of
for 100, 1000 and 10,000 steps respectively shows disorder growing.
On the other hand running the model at a temperature of
shows a very limited disorder.
For any given state we can extract the magnetization, the energy and the square of the energy.
> magFn :: McState -> Double > magFn s = abs (mcMAvg s / (fromIntegral $ mcNumSamples s)) > > magFnNorm :: McState -> Double > magFnNorm s = magFn s / (fromIntegral (gridSize * gridSize)) > > enFn :: McState -> Double > enFn s = mcEAvg s / (fromIntegral $ mcNumSamples s) > > enFnNorm :: McState -> Double > enFnNorm s = enFn s / (fromIntegral (gridSize * gridSize))
> en2Fn :: McState -> Double > en2Fn s = mcEAvg2 s / (fromIntegral $ mcNumSamples s)
And we can also calculate the mean square error.
> meanSqErr :: McState -> Double > meanSqErr s = e2 - e*e > where > e = enFn s > e2 = en2Fn s > > meanSqErrNorm :: McState -> Double > meanSqErrNorm s = meanSqErr s / (fromIntegral (gridSize * gridSize))
Finally we can run our simulation in parallel using parMap rather than map (this is the one line change required to get parallelism).
> main :: IO () > main = do print "Start" > > let rs = parMap rpar f temps > where > f t = multiUpdate initState t (randomUpdates nItt) > > renderableToFile (FileOptions (500, 500) PNG) > (errChart temps rs magFnNorm enFnNorm meanSqErrNorm) > "diagrams/MagnetismAndEnergy.png" > > print "Done"
Performance and Parallelism
ghc -O2 Ising.lhs -threaded -o Ising -package-db=.cabal-sandbox/x86_64-osx-ghc-7.6.2-packages.conf.d/ -main-is Ising
time ./Ising +RTS -N1 "Start" "Done" real 0m14.879s user 0m14.508s sys 0m0.369s time ./Ising +RTS -N2 "Start" "Done" real 0m8.269s user 0m15.521s sys 0m0.389s time ./Ising +RTS -N4 "Start" "Done" real 0m5.444s user 0m19.386s sys 0m0.414s
Bibliography and Resources
The sources for this article can be downloaded here.
Beichl, Isabel, and Francis Sullivan. 2000. “The Metropolis Algorithm.” In Computing in Science and Engg., 2:65–69. 1. Piscataway, NJ, USA: IEEE Educational Activities Department. doi:10.1109/5992.814660.
Chib, Siddhartha, and Edward Greenberg. 1995. “Understanding the Metropolis-hastings Algorithm.” The American Statistician 49 (4) (November): 327–335..
Diaconis, Persi, and Laurent Saloff-Coste. 1995. “What Do We Know About the Metropolis Algorithm?” In Proceedings of the Twenty-seventh Annual ACM Symposium on Theory of Computing, 112–129. STOC ’95. New York, NY, USA: ACM. doi:10.1145/225058.225095..
Gravner, Janko. 2011. “MAT135A Probability.”.
Levin, David A., Yuval Peres, and Elizabeth L. Wilmer. 2008. Markov Chains and Mixing Times. American Mathematical Society..
MacKay, David J. C. 2003. Information Theory, Inference, and Learning Algorithms. Cambridge University Press..
Metropolis, Nicholas, Arianna W. Rosenbluth, Marshall N. Rosenbluth, Augusta H. Teller, and Edward Teller. 1953. “Equation of State Calculations by Fast Computing Machines.” Journal of Chemical Physics 21: 1087–1092.
Norris, James R. 1998. Markov Chains. Cambridge Series in Statistical and Probabilistic Mathematics. Cambridge University Press.
Reif, F. 2009. Fundamentals of Statistical and Thermal Physics. McGraw-hill Series in Fundamentals of Physics. Waveland Press, Incorporated..
Srikant, R. 2009. “ECE534 Random Processes.”.
Tong, David. 2011. “Lectures on Statistical Physcs.”.
Ziman, J.M. 1964. Principles of the Theory of Solids. London, England: Cambridge University Press.
4 thoughts on “Haskell, Ising, Markov & Metropolis”
Pingback: Bayesian Analysis: A Conjugate Prior and Markov Chain Monte Carlo | Idontgetoutmuch’s Weblog
Pingback: Gibbs Sampling in R, Haskell, Jags and Stan | Idontgetoutmuch’s Weblog
Pingback: Gibbs Sampling in Haskell | Idontgetoutmuch’s Weblog
Pingback: Ising model resources | Sp1nor | https://idontgetoutmuch.wordpress.com/2013/12/07/haskell-ising-markov-metropolis/ | CC-MAIN-2016-22 | refinedweb | 4,573 | 55.24 |
This article discusses the simplest way to write, configure and consume Windows Communication Foundation (WCF) service, using Visual Studio 2010. This would help gain a better understanding to WCF services which is slightly different from ASP.NET web services.
We would look into writing and consuming a simple service using VS2010. Scenario: Book store service that would fetch the book information.
At the end of the article, you would know:
DataGridView
XElement
Also, you might be interested in Why use MessageContract when DataContract is there?; an article that I wrote some time back. BTW, we will use both in this example.
Let's create a WCF Service Library project. Visual Studio 2010 stubs-in a default service which it calls Service1. Let's ignore this existing service for a while now. We would create a separate service that would return the list of books requested by the client end.
Service1
Note that to just to keep things simple, we would use XML file as our data store; taken from MSDN.
The XML has columns: Author, Title, Genre, Price, Publish Date, Description, and Book ID.
Author, Title, Genre, Price, Publish Date, Description, and Book ID.
The Book ID, which is a string shall be used as primary key to identify the book.
Book ID
string
We would add a book interface that shall define what this service provides as book service. So, we want to provide a service that returns the list of books found based upon user criteria.
Add a new item as interface called IBookService under namespace Store. Add the directive, using System.ServiceModel; Decorate the interface with service contract attribute as [ServiceContract].
IBookService
Store.
using System.ServiceModel;
[ServiceContract]
We want the following functionality as a scope of this sample:
ID
Title
Genre
Author
Note that we will also look into the .NET default/optional arguments functionality that is provided in C# v4.0, as a part of this sample while we implement the above methods.
The interface shall contain the methods.
Let’s define the operations for IBookService interface:
namespace Store
{
[ServiceContract]
interface IBookService
{
[OperationContract]
List GetAllBooks();//Get all books; returns list of books
[OperationContract]
List GetBookByID(string BookID);//Gets a(single) book by ID
[OperationContract]
List Filter(string Author, string Genre, string Title); //Returns list of
//books by specified filter
}
}
Let's add a Book type and define the attributes of the book that we want for the client to have. For now, it's all those attributes that are there in the XML data.
Book
Right click on the Book return type, and select Generate Class for Book. This shall generate the class of type Book. Note that you also write the attributes where it is to be used and VS shall add those attributes in the class automatically.
Book
Generate Class
If you select the generate new type, it will show the following window and provide you with the options about class. Its Access specifier, Kind (class, struct, etc.), and either to create a new file and stub the code in the current file. We would select a separate file.
class
struct
Right click on the Book return type and select Goto Definition.
Goto Definition
Add the directive using ServiceModel, and using System.Runtime.Serialization;. And DataContract attribute on Book class; it would look like the following:
ServiceModel
using System.Runtime.Serialization;
DataContract
In figure 3, note that the ID is of type string, ideally IDs should be of integer type, when using as primary keys, integers keys work faster than the string keys. The reason we are using the string type primary key is that we have string data in the XML data store.
string
Let's decorate theBook
class with DataContract attribute.
Book
A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.
Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts.
DateTime
XmlElement
Let's add the types that are required ID, Title, Author, Description, Genre, Price, and Publish Date and tag all members with[DataMember]
attribute.
ID, Title, Author, Description, Genre, Price, and Publish Date
[DataMember]
Now, we will add a class BookService that implements the IBookService interface;
BookService
The book service shall contain the definition.
Note, in case if you plan on using the database (and not the XML which is a part of this example), you can use Enterprise Library, Data Application Block for your data transactions; you will need to add a reference to the Data.dll file, generally available in the DRIVE:\Program Files\Microsoft Enterprise Library 4.1 - October 2008\Bin.
Now let's add the implementation of the methods. First, there this is a small GetDb() method, that loads the data from given XML and into the XDocument object.
GetDb()
XDocument
Then, since we interested in the book nodes, therefore we select all the books.
The select new Book() creates a new object and copies the data from book attribute into our defined book object attribute. So by the end of the book structure "}" is complete, we have our book object ready to be inserted into the List object.
select new Book()
}
List
Implementing both the methods using XDocument and LINQ, answers the question, how to convert XElement to custom object using LINQ.
XDocument
public List GetAllBooks()
{
XDocument db = GetDb();
List lstBooks
=
(from book in db.Descendants("book")
select new Book()
{
ID = book.Attribute("id").Value //Get attribute from XML and
//set into the Book object attribute.
,
Author = book.Element("author").Value
,
Genre = book.Element("genre").Value
,
Price = Convert.ToDecimal(book.Element("price").Value)
,
Description = book.Element("description").Value
,
PublishDate = Convert.ToDateTime(book.Element("publish_date").Value)
,
Title = book.Element("title").Value
}).ToList(); //Cast it into the list
return lstBooks;
}
The above is the method that gets all of the books in the datastore. Now, let's add the definition for GetBookByID(). The method is the same as get all books, except for the where clause. Note that this shall be only one book in this case, so the list shall contain only one item.
GetBookByID()
where
public List GetBookByID(string BookID)
{
XDocument db = GetDb();
//Howto: Convert XElements to Custom Object
List lstBooks =
(from book in db.Descendants("book")
where book.Attribute("id").Value.Equals(BookID)
select new Book() //Instantiate a new object
{
ID = book.Attribute("id").Value
,
Author = book.Element("author").Value
,
Genre = book.Element("genre").Value
,
Price = Convert.ToDecimal(book.Element("price").Value)
,
Description = book.Element("description").Value
,
PublishDate = Convert.ToDateTime(book.Element("publish_date").Value)
,
Title = book.Element("title").Value
}).ToList();
return lstBooks;
}
The above code gets a book given its ID using LINQ.
ID
Add the service definition in app.config file under system.serviceModel/services tag.
system.serviceModel/services
The system.serviceModel/services tag contains the classes, enumerations, and interfaces necessary to build service and client applications that can be used to build widely distributed applications.
<service name="Store.BookService">
<endpoint binding="basicHttpBinding" contract="Store.IBookService"></endpoint>
</service>
basicHttpBinding represents a binding that a service can use to configure and expose endpoints that are able to communicate with ASMX-based Web services and clients and other services that conform to the WS-I Basic Profile 1.1 [^] . Contract is the name of the interface that we expose.
basicHttpBinding
Contract
Note that a WCF service requires an application host, in order to run and be accessible to clients.
We have a couple of options here, for instance:
In our case, we would use IIS to simply publish the service.
IIS
Right click on the project and select Publish, would generate the following directory structure in IIS.
Publish
Just for your interest, if you are using a version prior to VS2010 to configure a WCF service, following is the manual process:
Fortunately, Visual Studio 2010 does that for us.
We also need to tell the IIS that our service is going to use the .NET Framework version 4.0, so that it does not use its default .NET framwork.
Fig 6 shows how to change the framework that IIS is going to use for our app.
In order to be able to be accessible to the outside world, we need to allow access. You can open the URL in IE and see it works. In my case, for instance, I have it under WCF folder.
Note the highlighted text in the above image. This requires a service behavior to be added in the config file, which Visual Studio 2010 stubs in for us automatically.
You will need to set the httpGetEnabled attribute to true, in order to publish your service metadata. It's a Boolean value that specifies whether to publish service metadata for retrieval using an HTTP/Get request. The default is false.
httpGetEnabled
true
HTTP
Get
false
To save and publish the service into IIS, click on Save, Publish.
Save
Now you can open the URL again in Internet Explorer, and you should be able to see your service's meta.
Quick way to see the wsdl, type ?wsdl in the address bar to see the wsdl, like:.
wsdl
?wsdl
We would create a small forms based client app that would show a couple of filter options, and provide a search button that requests the service for books based upon the filter provided by the user.
Add a Windows Forms project and design the form.
Windows Forms
To be able to consume the service, we will need to add a reference to that service. So when you try to add the service reference, the IDE discovers all the services on your system. Alternatively, you can provide the path that you have of the service.
Note that web services, by nature, are of public type. Though, WCF adds the Service, Message, and Data level contracts; but the service itself is public.
public
service
public
So right click on the WCF Client project and add a service reference. In your client app, add the service reference.
Add following as the service reference URI:. I would rename the reference to SvcBookstore.
SvcBookstore
Since, at this point, we have already added the service reference, therefore we can access it by adding the using directive in the forms class, and then declaring the object of the service; exactly similar to how we add/declare other .NET objects. Let's declare the service object in our form. And add using directives.
using
One important thing: What if you are in the middle of developing real world WCF Services, and now you want to test it. And while testing using a demo client app, your service is throwing exception that you have hell no idea of. So in that case, a "natural" scenario a developer wants is that you should able to "step into (F11)" the service code and see if for yourself. That is going be to a great help. So, if this is the case, you can always go back to your service configuration file and add a serviceDebug within behavior element.
step into (F11)
serviceDebug
<servicedebug includeexceptiondetailinfaults="True" />
serviceDebug allows the client app to receive exception details in faults for debugging purposes, when set to true. DO NOT forget to set to false before deployment to avoid disclosing exception information.
So, if you want to get the service related exception here at the client end, add a tag in service. Because, at this point, you might want to step into it.
So, let's add the final code that collects the filter specified by the user, and call the service. When the data is retrieved, you can simply just assign object array to .DataSource property to show on Grid. Following the output of the client.
.DataSource
Grid
private void button1_Click(object sender, EventArgs e)
{
//Get the combo choice, if there is any.
string strGenre = cbxGenre.SelectedIndex > -1 ?
cbxGenre.SelectedItem.ToString() : string.Empty;
//Declare the books array; though the actual return type is List<books />,
//it actually gets casted into
//Book[] array.
Book[] lstBooks = null;
//Discard other filters, if user has entered a book id
if (!string.IsNullOrEmpty(txtID.Text))
{
lstBooks = bookService.GetBookByID(txtID.Text);
}
else
{
//Lets get books by filter.
lstBooks = bookService.Filter(Author: txtAuthor.Text,
Title: TxtTitle.Text, Genre: strGenre);
}
//Set datasource, custom object.
dataGridView1.DataSource = lstBooks;
}
Did you notice bookService.Filter(Author: txtAuthor.Text, Title: TxtTitle.Text, Genre: strGenre); line in the code above?
bookService.Filter(Author: txtAuthor.Text, Title: TxtTitle.Text, Genre: strGenre);
That's what the named arguments are. Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. Named arguments can follow positional arguments.
As an example, if at some point, for this client app, user only provides the Author to look for, you can provide only the author to this method. Like: bookService.Filter(Author: "Paulo Coelho");
bookService.Filter(Author: "Paulo Coelho");
Note that you will have to update the Service's .Filter() method and provide the default arguments; for instance, like the following:
.Filter()
public List<book> Filter(string Author = "N/A", string Genre = "N/A",
string Title = "N/A")
Couple of things that I noticed is that WCF service is way different than an ASP.NET service. The file extensions are different as well. .asmx for ASP.NET and .svc for WCF. Also, after all that you have done above, and deployed your application and now you are wondering, WHY your service is taking time on the first load. Well, Why my service is slow on first access? might just help you.
Enjoy!"?>
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace MService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IMService
{
[OperationContract]
string GetTime(int timeStrength);
}
}
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/123067/A-Simple-Sample-WCF-Service?msg=4248738 | CC-MAIN-2015-40 | refinedweb | 2,461 | 57.67 |
How about this case [1,2,3,null,null,null,4] ?
The expected answer is "1(2)(3()(4))", not sure why we omit the other two "()()".
Thanks!
@Cornelius194968 For leaf nodes we only have to print the value of that node.
Good solution but a mirror mistake on iterative version: Since you use String Concatenation "+", every time you do a string concatenation, it declares a new string rather than add after the previous result string. It consumes lots of memory when the string grows. Should consider using StringBuilder/StringBuffer.
I have similar question as 'Cornelius194968'. For input [1,2,null,3,4], my answer is "1(2(3)(4))()", while the expected answer is "1(2(3)(4))". I think my answer is correct. Otherwise the input of [1,2,3,4] and [1,2,null,3,4] generates the same output. Obviously that's not correct.
My answer is the same as approach #1 but I get this error:
Line 15: TypeError: unsupported operand type(s) for +: 'int' and 'str'
Any ideas why?
/**
- Definition for a binary tree node.
- public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
- }
*/
class Solution {
String answer = "";
public String tree2str(TreeNode t) {
if (t==null)return ""; if (t.left == null && t.right==null){ return t.val+""; } if (t.right==null){ return t.val+"("+tree2str(t.left)+")"; }else return t.val+"("+tree2str(t.left)+")("+tree2str(t.right)+")"; }
}
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/91336/construct-string-from-binary-tree | CC-MAIN-2018-22 | refinedweb | 254 | 69.58 |
.
The aspect of overload resolution in C# I want to talk about today is really the fundamental rule by which one potential overload is judged to be better than another for a given call site: closer is always better than farther away. There are a number of ways to characterize “closeness” in C#. Let’s start with the closest and move our way out:
- A method first declared in a derived class is closer than a method first declared in a base class.
- A method in a nested class is closer than a method in a containing class.
- Any method of the receiving type is closer than any extension method.
- An extension method found in a class in a nested namespace is closer than an extension method found in a class in an outer namespace.
- An extension method found in a class in the current namespace is closer than an extension method found in a class in a namespace mentioned by a using directive.
- An extension method found in a class in a namespace mentioned in a using directive where the directive is in a nested namespace is closer than an extension method found in a class in a namespace mentioned in a using directive where the directive is in an outer namespace.
The overload resolution algorithm can be thought of as making a list of every method of a given name, ordering them by closeness using the above metrics, discarding all methods that are farther away than the closest method, and then doing additional tiebreakers on the methods that remain.[2. Of course that is not actually what the compiler does; if for example any instance method can be found then searching for extension methods is elided.]
Once you realize that this characterization of “closeness” is the first and deepest cut that the overload resolution algorithm makes, answers to other questions become clear:
- Why does overload resolution choose an inexact match declared in a derived class over an exact match in a base class? Because the method in the derived class is closer.
- If I have two similarly-named extension methods, how can I force one to be automatically better than the other? Put the using directive that brings the extension method’s class into action closer to the call site.
And with that, I’m done for 2013. This was an interesting and eventful year for me. New job, new blog location, new office, new product. I’m looking forward to things being a little more routine in 2014. Thanks all for your always-interesting comments and questions. See you for more fabulous adventures next year!
Missing: a match.com analogy. | http://ericlippert.com/2013/12/23/closer-is-better/ | CC-MAIN-2015-18 | refinedweb | 443 | 58.92 |
Major Updates 2007-03-05:
First off, if you're a developer in a hurry and here for a quick solution (i.e. you're not really interested in reading the article), you can skip down to the "Using the Code" section towards the bottom. That should provide an adequate Quick Start to implement this class & get your problem solved in a matter of minutes. That said, the rest of you wise and patient people, read on...
What follows is an analysis of what should be a dead-simple task: Insert text into an existing file. This all came about because a project of mine required good, byte-at-a-time file handling. Specifically, given a potentially very large file, I needed to be able to insert, overwrite, find, replace and delete text within that file. Overwriting, truncating and appending are easy, but conflicting opinions abound about how best to insert text into existing files. The obvious problem is that the BinaryWriter lacks an "insert" mode, so it overwrites anything in its path when you use it. Sure, Microsoft could have cobbled together a special-purpose StreamWriter that transparently handled all the mechanics of this, but they didn't, and it's probably just as well. Who knows... we might learn a thing or two as we create our own.
For a simple example, say we have a file containing "eggyung". We want to insert "foo" between "egg" and "yung." For convenience, I'll refer to the text before the insertion point ("egg") as the left-hand or LH segment, and the text after the insertion point ("yung") as the right-hand or RH segment.
All we need to do is move "yung" over to make room for "foo" in the target file. Some people do this by holding that RH text in some sort of buffer -- a temp file, a MemoryStream, a StringBuilders, maybe just a plain old string. Others do it by creating a new file and writing to it. First, the original LH segment, then the text being inserted, and finally the original RH segment. After all that, the original file is deleted or moved, and the new file is renamed to take over the original's identity.
Since my project needs to deal with potentially very large files, and because I rather dislike the thought of instantiating multi-gigabyte Strings and MemoryStreams, I dismissed the String buffer and RegEx search/replace approaches from the get-go. I also have an irrational (maybe even psychotic) aversion to temp files and file-name swapping; maybe I was attacked by a temp file as a child and I've suppressed the memory... I don't know. At any rate, I don't want to write any more data to disk than is necessary, which means not touching the LH segment at all and handling the RH segment as little as possible.
That said, let's dig into the solution...
A word about the "without temp files" bit in this article's title... these statements have not been evaluated by the FDA, and there's a bit of fine print: In some cases, data can be written to a temporary location that's neither in a temp file, a local variable, nor a MemoryStream. Where is it then? How about at the end of the target file itself! But the goal here is to accomplish the file modification with a minimum number of bytes written, meaning we buffer only as a last resort. So, after illustrating this simple "target-file-as-its-own-temp-space" trick, I'll describe several other techniques that eliminate the need for any temp buffering at all.
If the worst-case scenario involves handling the RH data twice, then the good news is that it's not always necessary to do that, even when using conventional file & stream techniques. If the text to be inserted is longer than the RH segment, then we know that the RH segment's post-insertion destination does not overlap its original position. This is good; it lets us take a shortcut around buffering: (a) Extend the EOF by the length of the inserted text, (b) copy the RH segment into the newly added space, and (c) write the text we're inserting at the insertion point, overwriting any remnants of the original RH data (Illustration 1):
Unfortunately, this doesn't work when the inserted text is shorter than the right-hand segment - at least not if we're copying byte-by-byte as above. In that situation, the RH segment's source and destination ranges overlap, which means we'd eventually start overwriting characters that we hadn't yet read if we continued along in this manner (Illustration 2):
The "normal" solution is to buffer the RH chunk somewhere, and for small to medium files, that absolutely makes sense. For very large files though, this isn't practical. Here's another approach: (a) add space equal to the size of the RH chunk to the end of the target file, (b) copy the RH chunk there, (c) write the text we're inserting at the insertion point, (d) copy the RH chunk back to where the newly inserted text ends, and lastly (e) truncate the file to the correct post-insertion length (Illustration 3):
This approach isn't ideal, but it keeps us from having to worry about managing temp files, dealing with lock collisions, or swapping filenames. But can't we do any better here? The better news is that, yes, we can do away with temp buffering altogether. Sound good? (Note: there's still an example routine in the source code for Illustration 3, called InsertBytesUsingEOFTemp.)
InsertBytesUsingEOFTemp
The method for doing this is easier than you might expect; it simply involves using a StreamReader and BinaryWriter to move backwards through a byte range to be copied. By stepping through the bytes in right-to-left order, we can copy any range to a destination overlapping its own right edge without ever overwriting yet-to-be-read source bytes. Illustration 4 shows how: Start with the Reader positioned at the end of the source range. The corresponding writer starts at the end of the destination range. Each read/write operation decrements the position of both, rather than advancing them as would usually be the case (Illustration 4):
So we've eliminated temp buffering at this point, but the forward-only nature of fast, non-cached StreamReaders imposes a hefty performance penalty when we reposition them backwards. The class conceals an internal buffer that has to be cleared before each backwards seek operation. However, a modest read/write buffer size will drastically cut down on the number of these expensive operations. Add that to our performance gains from never having to write the RH segment to disk more than once, and we're in pretty good shape. Illustration 5 shows the modified technique:
A quick word to those who are about to get pedantic with me about the read/write buffer: Yes, there is a "buffer" there, but a read/write buffer is very different from the temp buffers we set out to avoid, and I'm counting on the reader to recognize that distinction. For those who just can't go there with me, there's always the option of going back to Illustration 4 and doing things a byte at a time. You'll take a mean performance hit, but hopefully it will be worth feeling vindicated about that pesky read/write buffer.
We're doing better than before at this point, but we're still pitting memory allocation against seeking backwards with StreamReaders. When I started examining the performance of this approach, I found that peak performance depended on the server's available physical memory exceeding the number of the bytes to be moved. We can't count on this being true, so let's take another crack at improving performance some other way.
The main drags on performance in Illustration 4 come from two operations: Allocating large memory blocks, and repositioning a StreamReader backwards. Therefore, our solution parameters should include:
This leads to a pretty simple solution: Use two read/write buffers instead of one. We read into the 2nd buffer n bytes ahead of the write position, where n is the buffer's size, then copy the 2nd buffer's contents into the 1st buffer, then write the 1st buffer's (new) contents to the file. Lather, rinse and repeat until done, as Illustration 6 shows:
n
With this strategy, there's not much use in making your read/write buffer much bigger than half the bytes to be copied, by the way. The risks are far worse for using too large a buffer size than using one that's too small. If the buffer's too small, you may or may not see a bit of drag on performance. If the buffer's too large though, you could (a) run into an , or (b) have the runtime give you the memory only to page a bunch of data to disk in the process (just what we were trying to avoid in the first place).
Fortunately, this routine happens to perform best with surprisingly small buffer sizes. Now comes the task of finding the "optimal" size, and the demo code contains a number of performance tests to help us do just that. To make this easy to try at home, I will quickly explain the demo program before giving you the results of my own tests.
To run the demos, simply open the solution and hit F5. You don't even need any test files to get started; by default, the demo routines will create them on the fly. The first set of tests simply creates a small file and walks through the different Insert methods, using a <code>Find()</code /> routine to make sure the inserted text actually appears in the file afterwards.
After this, the demo program will ask if you want to run the long performance tests. If you respond with a "Y," you'll see a screen like the following:
Use one of the options above to create a large test file, or provide your own if you wish. The next question prompts you for an alternate drive if desired. If you have a separate physical drive from your system drive - especially if you have a RAID-0 array available - I highly recommend using it. A SATA-II RAID-0 array without contention outperformed my system drive by a 2:1 margin or better in almost every test I ran. If you don't have a PC with a fast RAID though, any halfway decent disk on a separate spindle from your system drive can still speed things up significantly.
Once your test file is ready, the next screen will prompt you for one final option before the tests run: the insert strategy. Option [1] represents the "target-as-its-own-temp-file" strategy from Illustration 3, Option [2] represents the "reverse traversal" method from Illustration 5, and Option [4] represents the "buffer swapping with forwards transposition" technique in Illustration 6. (If you make an invalid entry here, it will default to [2], using the <code>transposeReverse method).
Once you've made your choice and hit the [Enter] key, the tests will start running. Option 1 is not affected by buffer size, so only a single insert will be performed. Options 2 and 4 will run a series of tests using different buffer sizes to insert text at the very beginning of the target file. Note that the time estimate the program gives is a rough one, and it's only even approximately accurate when testing Option 2. Still, on most systems the Option 2 tests will finish in the estimated time or less, and the other options will finish even faster... Option 1 because it doesn't test multiple buffer sizes, and Option 4 because it's a speed demon.
When the test routines finish, the demo will first give you the opportunity to view the head of the modified test file, and then it will clean up after itself by deleting the temp file if you wish. After that, you'll have the choice to run another test series or quit.
If you inspect the sample code, you'll see a few routines default to a 32kB read/write buffer when none is specified by the caller. Feel free to experiment with that size; your mileage may vary, but I found that the transposeForward double-buffering approach was consistently the best performer, and 32kb was that algorithm's best or second best performing buffer size on every file size tested.
transposeForward
The following graph shows the average of about 25 different test runs of each algorithm on my system. My basic hardware setup was an AMD Athlon X2 3800 dual-core processor, 2GB RAM, and I wrote to a 1TB RAID-0 made of Seagate SATA II drives. The speed is shown in megabytes written per second for each given buffer size, and represents an average across target files from 32MB to 1GB.
transposeReverse's nature is to gain speed as buffer size increases up to a ceiling that is a function of available memory relative to the amount of data being moved. I found it fascinating that transposeForward always - regardless of file size - had its best performance when the buffer was between 16KB and 256KB, with a peak around 32k, and that it always had a pronounced valley with buffers between 512KB and 2MB.
transposeReverse
The "target-file-as-its-own-temp-space" strategy doesn't use an iterative read/write buffer, so its performance was a pretty flat 10MB/second across all trials.
A few observations about coding and performance tuning:
There's a good deal more to be learned about optimizing disk operations. If this topic interests you, a good place to start is Microsoft's white paper, Sequential File Programming Patterns and Performance with .NET.
The main class for the methods described in this article is simply called FileHelper. All the methods are static, and there are a few simple supporting routines that I'll just briefly describe. First is a WriteBytes routine that just wraps the basic functionality of a BinaryWriter... it seeks to a desired position in the target file and writes an array of bytes there. Next, SetFileLen encapsulates the FileStream class's SetLength method.
FileHelper
WriteBytes
SetFileLen
The work that's of interest to us happens mostly the routines InsertBytes, Transpose, transposeReverse, and transposeForward. (Public methods begin with initial capitals, while private ones are camelCase.)
InsertBytes
Transpose
InsertBytes forms the outer layer of this rig, while Transpose provides a convenient place for some minimal "smarts" while relying on the supporting routines above to do most of the work. Transpose gets a filename, an array of bytes to be inserted (simply named "bytes[]"), and an insertion position from InsertBytes. Armed with these, it compares the length of the RH segment with that of bytes[]. If the RH segment is shorter than bytes[], it skips buffering and uses the approach in Illustration 1. If the RH segment is longer, it calls on transposeForward to execute the buffer-swapping copy approach from Illustration 6.
InsertBytes
Transpose
transposeForward
public static void Transpose(string filename, long SourcePos, long DestPos,
long Len, int bfrSz)
{
if (DestPos > SourcePos && Len > (DestPos - SourcePos))
{
// Delegate work to transposeForward, telling it to use a
// specified read/write buffer size:
transposeForward(filename, SourcePos, DestPos, Len, bfrSz);
}
else
{.Position = SourcePos;
bw.BaseStream.Seek(DestPos, SeekOrigin.Begin);
for (long i = 0; i < Len; i++)
{
bw.Write((byte)sr.Read());
}
bw.Close();
sr.Close();
}
}
}
}
}
}
I'm skipping over an explanation of transposeReverse since it's only called from demo code; it's not really useful in production anyway, given how much better transposeForward's performance is. transposeForward takes the same arguments, and copies the source byte range to the destination position a-la Illustration 6:
private static void transposeForward(string filename, long SourcePos,
long DestPos, long Length, int bfrSz)
{
long distance = DestPos - SourcePos;
if (distance < 1)
{
throw new ArgumentOutOfRangeException
("DestPos", "DestPos is less than SourcePos," +
"and this method can only copy byte ranges to the" +
"right.\r\n" + "Use the public Transpose() " +
"method to copy a byte range to the left of itself.");}
long readPos = SourcePos;// +Length;
long writePos = DestPos;// +Length;
bfrSz = bfrSz < 1 ? 32 * KB :
(int)Math.Min(bfrSz, Length);
// Anything over ~40% of available memory poses a high risk
// of OutOfMemoryExceptions when allocating 2x buffer, and
// it just saps performance anyway:
bfrSz=(int)Math.Min(bfrSz,
(My.ComputerInfo.AvailablePhysicalMemory * .4));
long numReads = Length / bfrSz;
byte[] buff = new byte[bfrSz];
byte[] buff2 = new byte[bfrSz];
int remainingBytes = (int)Length % bfrSz;.Seek(readPos, SeekOrigin.Begin);
bw.BaseStream.Seek(writePos, SeekOrigin.Begin);
// prime Buffer B:
sr.BaseStream.Read(buff2, 0, bfrSz);
for (long i = 1; i < numReads; i++)
{
buff2.CopyTo(buff,0);
sr.BaseStream.Read(buff2, 0, bfrSz);
bw.Write(buff, 0, bfrSz);
}
buff2.CopyTo(buff,0);
if (remainingBytes > 0)
{
buff2 = new byte[remainingBytes];
sr.BaseStream.Read(buff2, 0, remainingBytes);
bw.Write(buff, 0, bfrSz);
bfrSz = remainingBytes;
buff = new byte[bfrSz];
buff2.CopyTo(buff,0);
}
bw.Write(buff, 0, bfrSz);
bw.Close();
sr.Close();
buff = null;
buff2 = null;
}
}
}
}
GC.Collect();
}
transposeForward and transposeReverse are both declared private, because the InsertBytes and Transpose methods form the public interface for these features, and those routines should conceal all this byte-shifting complexity from the caller. transposeForward will simply throw an ArgumentOutOfRangeException if you try to copy a byte range to the left with it.
These routines are well suited for finding and replacing text in files, since that's little more than a special case of transposition. You'll need to roll your own Replace method if you want one, but that's a cinch with the above ingredients. Using FileHelper's Find method, define the RH segment as starting at the end of the FindWhat occurrence in question. If the ReplaceWith text is shorter than the FindWhat text, you can use just steps 3, 4 and 5 from Illustration 3... simply write ReplaceWith starting at the position of FindWhat, then shift the RH segment left & truncate the file. When ReplaceWith is longer than FindWhat, then you'll have to move the RH segment just like when performing an insert, but accounting for the difference between the lengths of FindWhat and ReplaceWith when determining the RH segment's destination position.
Replace
Find
If you explore the FileHelper class, you'll see that I included a few other possibly useful routines. Among them are Head and Tail methods for inspecting the beginning or end of large files without having to try to open them in Notepad; an XML validation routine, some filesize-to-human-readable string conversions, and a method to check AvailalbePhysicalMemory (borrowed from VB.NET's "My" namespace).
Head
Tail
The code in FileOps.cs comprises everything described above, and also contains a TestCases class to demonstrate the routines on the included test files. You should only need minimal variations on the test routines to use this code in your project -- just include FileOps.cs in your project, pick the test routine most closely resembling your task, copy it -- editing a line or two to work with your own files -- and away you go. The combination of WriteBytes, InsertBytes, Transpose and SetFileLen are really all you need to accomplish most conceivable file manipulation tasks.
WriteBytes
For a really Quick Start, I recommend just downloading the solution and running it. It will jump into the FileOps.TestCases.RunDemo() routine right away, which will create its own test files to demonstrate the above routines in a console (as detailed in the preceding screenshots).
FileOps.TestCases.RunDemo()
For most projects, the above setup is more than adequate. Still, there may be areas ripe for significant optimization, and others where more minor improvements are possible.
The first glaring area that's ripe for optimizing is reducing how much we're moving these file chunks around. In the majority of cases, everything to the right of the inserted text will be written to disk once. If a file is large and you're inserting bytes near its beginning, this could mean moving a lot of data just to insert a little. The first question one should ask then is, does all this data really need to be in the same file to begin with? If not, the time to break it up is now, before the files start growing out of control and you have to change production code to accommodate a new file format.
Sometimes though, you really do need to confine all the data to a single file. When that's the case, you might want to consider whether your inserts really need to be at a specific (early) position in the file. Again, if not, you'll gain considerable performance by moving them as close to the EOF as possible.
When the types of inserts we're discussing are unavoidable, though, two harebrained ideas involving black magic in the filesystem come to my mind. First, if one could simulate a FileStream's SetLength method, but prepending the added space instead of creating it at the end of the file, this could speed up inserts left of the file's center. Free space at the beginning of the file would allow us to move and/or buffer the (shorter) LH segment instead of the (longer) RH one as we've been doing. This wouldn't be easy, though... the Win32 API has a SetEndOfFile method, but you'll have to make your own SetBeginningOfFile.
SetEndOfFile method
SetBeginningOfFile
An even more daring approach to minimizing disk writes could be to use low-level MFT manipulation to deliberately fragment the file into 3 pieces, 1 each containing, respectively, the LH segment, the inserted text, and the RH segment. I don't how feasible this is (I'm not Mark Russinovich after all), but it would probably be extremely efficient, given that it negates the need to rewrite any existing data. Defragmenting would happen as a normal part of disk maintenance. One would need some wicked error handling to manage the MFT for oneself, though, and that thought keeps me from pursuing this idea much further at the moment.
One last area that might be useful to optimize, depending on the usage profile, is the briefly-mentioned Find function, which brute-force searches a file for some given text. In some cases, a "smart" search algorithm such as Boyer-Moore, Turbo Boyer-Moore, Knuth-Morris-Pratt or Horspool will outperform the naive, brute-force method. This would be most beneficial in situations where long strings with high character uniqueness are being sought within large files. Searching wasn't dealt with at length here, but in practice, time spent doing find/replace work can represent a not insignificant portion of your total processing time.
I will leave these ideas as exercises for the reader. I'm sure there are other approaches to the suggestions I've mentioned, as well as areas for optimization that I didn't even think of. If you happen to be struck by a flash of genius and feel like tackling one of these, I hope you'll share your efforts with the rest of us!
The methods described above accomplish the original objective, which was to provide convenient text insertion into potentially large files, without using memory buffers, temp files or swap files. For many applications, this is more than enough. However, the right optimizations could yield a genuinely high-performance disk reading and writing utility, useful in applications like ORM systems, embedded databases, and just simple file-based data management tools that are free from external dependencies.
There seems to be a healthy interest in these sorts of topics here on CodeProject, with a growing number of articles on XML databases and even one describing a transactional filesystem. A simple, easy-to-implement utility like this one, in pure C# no less, could provide respectable scalability for such systems. I hope to work more on this myself in the future, and I hope others find it worthwhile to contribute their time, ingenuity and expertise as well.
Good luck and happy coding!
2007-03-05 :
2007-02-21 : First posted to CodeProject;2006-01-28 : Initial draft;
This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-ShareAlike 2.5 License
Input string: 1234567
Position: 1
Insert: ZXC
Buffer size: 2
Output should be: 1ZXC234567
But is: 1ZXC234537
1234567---
Buffers: 23 45
1234237---
Buffers: 45 37
12342345--
Buffers: 37
1234234537
true
StreamReader sr = new StreamReader(InStream, System.Text.Encoding.UTF8, true);
byte[]
char[]
BaseStreams
Read()
BaseStream
Transpose(string filename, long SourcePos, long DestPos, long Len, int bfrSz)
int sourcePos = 8; // in use, find CRLF with streamreader or such
Transpose("c:\myfile.dat", 8, 0, 14, null);
SetFileLen("c:\myfile.dat",10);
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/17716/Insert-Text-into-Existing-Files-in-C-Without-Temp?msg=2025633 | CC-MAIN-2014-52 | refinedweb | 4,198 | 57.91 |
An efficient implementation of integer sets.
Since many function names (but not the type name) clash with
Prelude names, this module is usually imported qualified, e.g.
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
The implementation is based on big-endian patricia trees. This data
structure performs especially well on binary operations like union
and intersection. However, my benchmarks show that it is also
(much) faster on insertions and deletions when compared to a generic
size-balanced set implementation (see Data.Set).
Many operations have a worst-case complexity of O(min(n,W)).
This means that the operation can become linear in the number of
elements with a maximum of W -- the number of bits in an Int
(32 or 64).
O(log n). The expression (split x set) is a pair (set1,set2)
where all elements in set1 are lower than x and all elements in
set2 larger than x.
split 3 (fromList [1..5]) == (fromList [1,2], fromList [3,4])
O(n*min(n,W)).
map f s is the set obtained by applying f to each element of s.
It's worth noting that the size of the result may be smaller if,
for some (x,y), x /= y && f x == f y
O(n). Fold over the elements of a set in an unspecified order.
sum set == fold (+) 0 set
elems set == fold (:) [] set | http://www.haskell.org/ghc/docs/6.6.1/html/libraries/base/Data-IntSet.html | crawl-003 | refinedweb | 232 | 65.73 |
Re-Imagining Linux Platforms to Meet the Needs of Cloud Service Providers
Watch→
Date: Sun, 20 Aug 2000 04:26:58 -0400
From: Theodore Ts'o tytso@mit.edu
To: linux-kernel@vger.kernel.org
Subject: Updated Linux 2.4 issues page
OK, here's the latest Linux 2.4 issues/bug list, to celebrate the
rebirth of the linux-kernel list. :-)
As always, please let me know if there are any corrections that need to
be made to this list, and remember that the version of at the web page may be more recent than this e-mail
Thanks!!
-.
Last modified: [tytso:20000820.0315EDT]
Hopefully up to date as of: test7-pre5
1. Should Be Fixed (Confirmation Wanted)
* Fbcon races (cursor problems when running continual streaming
output mixed with printk + races when switching from X while doing
continuous rapid printing --- Alan)
2. Capable Of Corrupting Your FS
*)
* Innd data corruption, probably caused by bug in filemap.c? (Rik
van Riel)
3. Security
* Fix module remove race bug (still to be done: TTY, ldisc, I2C,
video_device - Al Viro) (Rogier Wolff will handle ATM) (ipchains
modules -- Rusty)).
* Some Ultra-I sbus sparc64 systems fail to boot since 2.4.0-test3,
may be due to specific memory configurations.
* IBM Thinkpad 390 won't boot since 2.3.11 (See Decklin Foster for
more info)
5. Compile errors
* netfilter doesn't compile correctly (test7-pre3, reported by Pau
Aliagas)
* If all the ISO NLS's are modules, there can be an undefined ref to
CONFIG_NLS_DEFAULT in inode.c (Dale Amon))
* NCR5380 isnt smp safe (Frank Davis)
* DMFE is not SMP safe (Frank Davis)
* Audit all char and block drivers to ensure they are safe with the
2.3 locking - a lot of them are not especially on the
read()/write() path. (Frank Davis)
7. Obvious Projects For People (well if you have the hardware..)
* Make syncppp use new ppp code
* Fix SPX socket code
8.)
* Symbol clashes from ppp and irda compression code (Arjan van de
Ven))
* Kernel build has race conditions when building modversions.h
(Mikael Pettersson)
* Misc locking problems
+ drivers/pcmcia/ds.c: ds_read & ds_write. SMP locks are
missing, on UP the sleep_on() use is unsafe.
+ drivers/usb/*.c
o unsafe sleep_on in ibmcam and ov511 drivers
o usbpl_)
* Fix sysinfo interface so it is binary compatible with 2.2.x (i.e.
mem_unit=1), except when memory >= 4Gb (Erik Andersen)
* SCSI CD-ROM doesn't work on filesystems with < 2kb block size
(Jens Axboe will fix)
* Audit list of drivers that dereference ioremap's return (Abramo
Bagnara)
* 2.4.0-test2 breaks the behaviour of the ether=0,0,eth1 boot
parameter (dwguest)
* Writing to tapes > 2.4G causes tar to fail with EIO (using
2.4.0-test7-pre5; it works under 2.4.0-test1-ac18 --- Tigran
Aivazian)
* USB Pegasus driver explodes on disconnect (lots of printk and/or
OOPS spewage to the console. David Ford)
* Some people report 2.3.x serial problems
*')
Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. | https://www.linuxtoday.com/developer/2000082100204NWKN | CC-MAIN-2018-47 | refinedweb | 512 | 66.94 |
Graph shuffling package in python.
Project description
shuffle_graph
Graph shuffling package in python.
Installation
Installation can be done through pip. You must have python version >= 3.6.
pip install shuffle-graph
Usage
The statement to import the package:
from shuffle_graph_package import *
Example:
>>> calculate_number_of_shuffles_required_under_default_random_function(10000) 6 >>> from networkx.classes.graph import Graph >>> G = Graph({0: {1: {}}, 1: {0: {}, 2: {}}, 2: {1: {}, 3: {}}, 3: {2: {}, 4: {}}, 4: {3: {}}}) >>> shuffle_graph(G, 1, 65535).adj #Set seed to make the results repeatable. AdjacencyView({3: {2: {}, 4: {}}, 4: {3: {}}, 1: {0: {}, 2: {}}, 2: {3: {}, 1: {}}, 0: {1: {}}})
Project details
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/shuffle-graph/1.1.1/ | CC-MAIN-2019-51 | refinedweb | 115 | 59.6 |
Sorry Typing mistake.
The Question is :
Should we create an article about the instrumentation API here on JPF?
Sorry Typing mistake.
The Question is :
Should we create an article about the instrumentation API here on JPF?
is this an encoding issue??
if it is then how to verify which encoding is in use??? or in which encoding request is encoded??
Tell me where are you writing these SQL Queries?? I assume you may be using console. right?
Sorry for giving ambiguous info.
I'm trying to support all worldly language in my application, i.e. user can see and write in there local language :cool:
But I'm getting issues with certain...
Hi guys
I recently struck into an Issue, where I'm accepting CSV in a textarea( named=value) within a HTML FORM and method is POST.
Also I have a LanguageForm (extended from ActionForm) which...
that is what happened and I'm trying to uproot this and Yes I'm sending unique links per email.
I will keep trying new ways, and update here if I'm able to do it. meanwhile your comments or...
@copeg
I agree here, we can't stop them.
Yes, this approach is already implemented.
All I'm trying can we make it abstract??
Code you provided has something to with Database.
read here, it may help you.
Then Its time to teach them; we been through that stage of life. :cool:
Well lets get back to topic. Is there any way to achieve this???
Can we stop mail forwarding???
Actually I don't know...
I'm Glad you asked. my client usually give assignments online and he send access links to specific pupils only ( one which require it ) via emails, last time he caught his students cheating him, like...
Hi
Is it possible that when we send a link to something(say some online task) in mail, then that will work only if it is clicked from same mailbox whom it was sent?:confused:
let me elaborate...
Thank for your wonderful suggestion.
But Question Comes here that we should a article about the instrumentation API available in Java.
What do you say?
Hi
I want to check the memory allocation of my objects. As far as I know that java has a concept of agent which need to be passed to the JVM during startup.
Well I'm trying to use an API viz....
I have been known that there are many ways to connect to any database but I came into problems while trying to connect to Oracle XE database.
Database is freshly installed on local machine....
please explain what are you up to?
what i'm thinking is if round off that 9 then .304 will become .305 and eventually .31 for up two digits after (dot) decimal point.
well i'm glad that you have taken so much pain. thank you very...
Is this only solution to this problem?
well my value is 1174.304999999998 can be rounded to 1174.31 according to mathematics as if we try to remove any 9 then left digit to its right is increased...
1174.30499999998(which is the checking software reports) which must be rounded to 1174.31 i.e. upto two decimal points (required)
also if i replace
"Form.format(total)" with just "total" then same...
"total" is the variable which resides in getEstimate() called from main.
first line is given by "printf" statement.(resides in getEstimate() method)
next line is shown by "println" statement (also...
here is what my actual output:
C:\Documents and Settings\Administrator\Desktop\java>javac GroceryPlan.java
C:\Documents and Settings\Administrator\Desktop\java>java GroceryPlan
total amount :...
indeed, my code does, still it i'm not getting formatted output.(please refer to image provided)
please run my code and then compare output with the...
here is waht I'm tring to do:
and coding done by me
import java.text.DecimalFormat;
public class GroceryPlan {
static double[] test1 =...
good idea still how to get the power system to work as you suggested( i really liked the idea). I tried it but still one problem is that term of equation "5x2" means 5 times square of x that means...
Indeed, double.maximum is equals to 1.7976931348623157E308 very large number but here is the problem as yi=ou can see the decimal piont and "E308" the exponent part. All I want is how can I change...
:-s the only requirement is to display result in integers, double does this but it has decimal piont and exponent system. thats it. I will try with biginteger
biginterger is damn good but still... | http://www.javaprogrammingforums.com/search.php?s=08b9ab89a5020bde55468a44e1dd7cd2&searchid=1665404 | CC-MAIN-2015-32 | refinedweb | 773 | 77.64 |
0
Hello everybody,
I am trying to write a program consisting of two parts:
1. It lists of letters before and after a certain letter (if the user requested 2 letters regarding 'e', it would be cd and fg)
2. count the number of letters in each word of a sentence contained in a character array (word1 is xx letters, word2 is xx letters, etc.)
So far I have found a way a to find part 2, and have also found a better way of doing it using a string array (which to me seems much simpler). I was wondering if there is a tidier way of using a character array.
And for part 1, I am totally stumped. I am leaning to using a char array for the alphabet, and thats about it.
Here is my code
#include <iostream> #include <iomanip> #include <string> #include <stdio.h> #include <string.h> using namespace std; //prototypes void printNeighbors(int neighbor); //string array way //void printWordLengths(char sentence1[]); void printWordLengths(char sentence1[], char sentence2[], char sentence3[], char sentence4[], char sentence5[]); int main () { char choice; int count; do { cout << setfill ('-') << setw (40) << "-" << setfill (' ') << endl; cout << "N[eighbors]" << setw (10) << "W[ords]" << setw (10) << "Q[quit]" << endl; cout << "Enter your choice --> "; cin >> choice; if (choice == 'n' || choice == 'N') { cout << "Enter the letter of numbers to show: "; cin >> count; printNeighbors(count); } else if (choice == 'w' || choice == 'W') { //These classes are really, really easy! //character array way of doing it char These [] = "These"; char classes [] = "classes"; char are [] = "are"; char really [] = "really"; char easy [] = "easy"; printWordLengths(These, classes, are, really, easy); //string array of doing it //string troll[6] = {"These", "classes", "are", "really", "really", "easy"}; //printWordLengths(troll); } } while (choice != 'q' && choice != 'Q'); cout << "Bye!" << endl; system ("pause"); return 0; } void printNeighbors(int neighbor) { //for each letter between ’e’ and ’j’ (inclusive) //print the COUNT letters before and after each letter //char alphabet[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; cout << "The " << neighbor << " neighbors of 'e' are:" << endl; cout << "The " << neighbor << " neighbors of 'f' are:" << endl; cout << "The " << neighbor << " neighbors of 'g' are:" << endl; cout << "The " << neighbor << " neighbors of 'h' are:" << endl; cout << "The " << neighbor << " neighbors of 'i' are:" << endl; cout << "The " << neighbor << " neighbors of 'j' are:" << endl; } //string array //void printWordLengths(char sentence[]) void printWordLengths(char sentence1[], char sentence2[], char sentence3[], char sentence4[], char sentence5[]) { //string array //for(int i = 0; i < 6; i++) //{ // cout << "Word #"<< i+1 << " is " << sentence[i].size() << " characters." << endl; //} cout << "Word #1 is " << strlen(sentence1) << " characters." << endl; cout << "Word #2 is " << strlen(sentence2) << " characters." << endl; cout << "Word #3 is " << strlen(sentence3) << " characters." << endl; cout << "Word #4 is " << strlen(sentence4) << " characters." << endl; cout << "Word #5 is " << strlen(sentence5) << " characters." << endl; return; }
Thanks. | https://www.daniweb.com/programming/software-development/threads/413042/problems-with-char-arrays | CC-MAIN-2017-43 | refinedweb | 469 | 65.96 |
0
Hey all,
I have decided that in order to learn i will need to write code. So i am working on all the questions on my book. And as I am teaching myself i end up with no-one to scrutinize my code.
#include <iostream> /************Declarations of Functions*********/ void func1(); void func2(); //=============================================Tue 28 Apr 2009 18:37:48 IST// /* Global Test Variables */ int const max_length=18; int quest_count=0 ; char input_line[max_length]="???sky???"; int main() { func1();// Character string with While loop std::cout<<"No Of Question Marks = " << quest_count<< "\n"; quest_count=0; func2();//Pointer Based Passing. std::cout<<"No Of Question Marks(Pointer Based) = " << quest_count<< "\n"; } void func1() { int i=0; while(i<max_length) { if(input_line[i]=='?') quest_count++; i++; } } void func2() { char *ptr=input_line; while(*ptr!=0) { if(*ptr=='?') { quest_count++; } *ptr++; } }
The above program counts the number of "?" marks in a string passed to it.
I would like to recieve comments on the code :) and any improvements that can be made. | https://www.daniweb.com/programming/software-development/threads/189556/c-question-mark-counter-any-improvements-in-code | CC-MAIN-2017-26 | refinedweb | 162 | 74.29 |
Debugging Oddjob: Java Parallel Runtime Execs Running Serially Under Java 7
Debugging Oddjob: Java Parallel Runtime Execs Running Serially Under Java 7
Java’s native process support is notoriously flaky; updating to Java 7u80 fixes anomalous log messages with Oddjob.
Join the DZone community and get the full member experience.Join For Free
Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.
Several Oddjob users have reported that, when running several execs in parallel on Windows, they all appeared to wait for each other to complete. The issue was easy to reproduce using this Oddjob configuration:
<oddjob> <job> <parallel> <jobs> <exec redirectStderr="true"><![CDATA[TestJob.cmd 2]]></exec> <exec redirectStderr="true"><![CDATA[TestJob.cmd 10]]></exec> </jobs> </parallel> </job> </oddjob>
Where TestJob.cmd is:
ping -n %1 127.0.0.1 echo Finished pinging for %1. exit 0
The problem can be seen here:
From the console of the first Exec Job it has clearly finished but its icon is still showing as Executing.
Java’s native process support is notoriously flaky, especially on Windows, and was the prime suspect. However, first I had to eliminate Oddjob from the enquiry. Here is some simple Java code that reproduces the problem:
public class ExecMain { static class Exec implements Runnable { private final String waitSeconds; Exec(String waitSeconds) { this.waitSeconds = waitSeconds; } @Override public void run() { long startTime = System.currentTimeMillis(); final ByteArrayOutputStream captureOutput = new ByteArrayOutputStream(); ProcessBuilder processBuilder = new ProcessBuilder("TestJob.cmd", waitSeconds); processBuilder.redirectErrorStream(true); try { final Process process = processBuilder.start(); Thread t = new Thread(new Runnable() { @Override public void run() { copy(process.getInputStream(), captureOutput); } }); t.start(); process.waitFor(); System.out.println("Process for TestJob.cmd " + waitSeconds + " finished in " + secondsFrom(startTime) + " seconds."); t.join(); System.out.println("Output thread for TestJob.cmd " + waitSeconds + " joined after " + secondsFrom(startTime) + " seconds."); } catch (InterruptedException | IOException e) { throw new RuntimeException(e); } } void copy(InputStream from, OutputStream to) { byte[] buf = new byte[0x0400]; try { while (true) { int r = from.read(buf); if (r == -1) { break; } to.write(buf, 0, r); } } catch (IOException e) { throw new RuntimeException(e); } } int secondsFrom(long startMillis) { return Math.round((System.currentTimeMillis() - startMillis) / 1000); } } public static void main(String... args) { new Thread(new Exec("2")).start(); new Thread(new Exec("10")).start(); } }
And here’s the output:
Process for TestJob.cmd 2 finished in 1 seconds. Output thread for TestJob.cmd 2 joined after 9 seconds. Process for TestJob.cmd 10 finished in 9 seconds. Output thread for TestJob.cmd 10 joined after 9 seconds.
We can see that the process ends as expected after a second, but joining on the stream copying thread doesn’t happen until the sibling process has finished. This can only be if the first processes output stream isn’t being closed. Is it waiting for its siblings process output stream to close too?
Hours of Googling prove fruitless. Then by happenstance, I run my sample against Java 8. It works as expected. Off to the Java bug database – nothing obvious. Oddjob is currently supported on Java 7 and above so I downloaded the latest Java 7u80 release just to see, and it works to. Here is the correct output:
Process for TestJob.cmd 2 finished in 1 seconds. Output thread for TestJob.cmd 2 joined after 1 seconds. Process for TestJob.cmd 10 finished in 9 seconds. Output thread for TestJob.cmd 10 joined after 9 seconds
And now in Oddjob we can see the Exec Job completes when the process does:
So this is a story with a happy ending but a niggling loose end. What was the Java bug that caused this? If you have an idea, please post a comment for others to see!
Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat.
Published at DZone with permission of Rob Gordon , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/debugging-oddjob-java-parallel-runtime-execs-runni | CC-MAIN-2018-39 | refinedweb | 674 | 53.17 |
Some simple ST Monad examples
The.
import Control.Monad.ST import Data.STRef import Control.Monad import Data.Vector.Unboxed.Mutable as M import Data.Vector.Unboxed as V sumST :: Num a => [a] -> a sumST xs = runST $ do -- runST takes out stateful code and makes it pure again. n <- newSTRef 0 -- Create an STRef (place in memory to store values) Control.Monad.forM_ xs $ \x -> do -- For each element of xs .. modifySTRef n (+x) -- add it to what we have in n. readSTRef n -- read the value of n, and return it. makeArray = runST $ do n <- newSTRef [1,2,3] readSTRef n makeArray' = newSTRef 10 >>= readSTRef makeArray'' = do a <- newSTRef 10 b <- newSTRef 11 return (a,b) makeVec = runST $ do v <- M.replicate 3 (1.2::Double) write v 1 3.1 V.freeze v | http://www.philipzucker.com/simple-st-monad-examples/ | CC-MAIN-2021-10 | refinedweb | 135 | 70.9 |
The namespace folder contains identical numbers and size but the share drive at the other location does not.
4 Replies
· · ·
Feb 10, 2017 at 5:47 UTC
Any warnings / errors in DFSR logs?
0
· · ·
Feb 10, 2017 at 6:16 UTC
I've seen this before. Double check to ensure the DFS-Replication and DFS-Namespace are pointing to the same actual folder on the server in question.
0
· · ·
Feb 10, 2017 at 6:28 UTC
C:\Windows\system32>dfsrdiag replicationstate
Summary
Active inbound connections: 0
Updates received: 0
Active outbound connections: 0
Updates sent out: 0
Operation Succeeded
0
· · ·
Feb 10, 2017 at 6:39 UTC
The namespace needs to be setup on both servers or just one?
0 | https://community.spiceworks.com/topic/1964370-dfs-replication-discrepancy | CC-MAIN-2017-39 | refinedweb | 120 | 57.61 |
Okay, as suggested, I'm going to try using "Ogg" files instead of MP3 files. I've already found a free app that converts mp3 to ogg, so all I really need now is a way to play them! This is for background music, so ideally I would like to create a class with the following interface:
public class OggPlayer(){public void Load( string filename );public void Play( bool playLooped );public void Stop();public void SetVolume( int volume );}
Because this is background music, it obviously needs to loop automatically. And because I don't want it cutting off rudely mid-note, I would like to be able to fade it out as well (thus the "SetVolume" method).
So I know exactly what I want; my main difficulty is that I've never worked with ogg files in my life, and I'd never worked with DirectSound until about two weeks ago!
Can anyone post some code examples that would be helpful, or perhaps even a link to a tutorial or class that already does this I'm working with C# and managed DirectX, if that helps narrow the field at all... | http://databaseforum.info/9/501964.aspx | CC-MAIN-2017-17 | refinedweb | 191 | 57.64 |
Originally posted by pradeep arum: Hi all, I am trying to build a lexical analyser here,but when i try to do the below code ,i think i am unable to find an END OF FILE character ,please help thanks //i had only the text yy in the in.txt file //it goes into infinite loop,is there a problem with seek()? public class MARK { public static void main(String[] args) throws IOException { RandomAccessFile in = new RandomAccessFile("in.txt","r"); int c,i=0,flag_T=0,j=0; char cc; long pos=0; while ((c = in.read()) != -1){ System.out.println("ch="+(char)c); char ch=(char)c; while (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'){ pos=in.getFilePointer(); c=in.read(); } in.seek(pos); System.out.println("2"); }//while }//main }//MARK
i think i am unable to find an END OF FILE character | http://www.coderanch.com/t/372070/java/java/code | CC-MAIN-2014-10 | refinedweb | 149 | 59.94 |
Agenda
See also: IRC log
<Ralph> ScribeNick: aliman_scribe
<Ralph> Scribe: Alistair
<Ralph> previous meeting 2005-06-16
guus: proposed to accept minutes
above ...
... any corrections?
Elisa: second
guus: resolved.
<Ralph> ACTION: [DONE] Ralph post telecon date resolution to the list [recorded in]
2.1 Proposed resolution httpRange-14
ralph: tag found a solution that
does not rely on uri string syntax at all, but relies on http
result codes ...
... solution on the books for severalyears ...
... heard more support recently ...
... allow 3xx code as response for x other than a document ...
... asked coord group if there will be formal finding
... do not expect to publish a formal finding
... roy fieldings email deemed to be sufficient
... don't expect to see any more
guus: do we need to take any action? explain consequences?
david: vmtf talked a bit about it, tom posted report ...
<Ralph> [VM] Report of 2005-06-21 telecon [Tom Baker 2005-06-27]
david: thinks tom doesn't go far
enough
... we should clean up after this decision
... go back to each tf, ask them to fold in best practices comments around this issue
... VM started, others should do same
guus: discuss per tf, or as
general?
... hear preference for doing per tf
david: do it per tf *publication*
...
... as raised at last f2f
... cleaner for us to address piecemeal in docs, rather than as a wg note in general
guus: ok, per tf
<Zakim> dbooth, you wanted to say that the TAG resolution still seems to leave the question of identification somewhat open
<Guus> qw?
dbooth: each tf makes its own
recommendation re best practices ...
... ?
tag resolution still leaves open the recommended way to identify things
scribe: bp should be clear about
this
... not clear to me as a wg what we are recommending
<Zakim> Ralph, you wanted to warn TomB of muting
ralph: does wg need to make a
recommendation at all re what uris to use for naming
... unless we disagree with tag
... concern about trailing slash and trailing hash ...
... tag says yes, either is fine given the right response code
... so why legislate any more about identifiers?
... can point out reasons for doing it one way or another
... take davidbooths point that wg as a whole as to what each tf is discussing
... may need some coordination, but at this stage don't legislate
davidw: concern about not
addressing it in some doc, because TAG didn't address in some
document
... we don't have a canonical reference to point to
... needs to be clear to community what we're going to do about this
... vm porting wordnet rdftm tfs impacted by this decision
<Ralph> [Ah, I understand DavidW's point -- that _some_ recommendation is needed. We should recommend a Best Practice for using 303 See Other]
<Zakim> dbooth, you wanted to follow up
davidw: we can review per tf publications prior to publication
dbooth: worthwile to indicate
pros & cons in a doc
... person feeling is, tag resolution not entirely satisfactory
... doesn't apply equally well to RDF and non-RDF case
... so you're dependent on what document type you're dealing with
<Zakim> aliman_scribe, you wanted to comment on uris & naming
<Ralph> Alistair: we should include in per-TF documentation as our role is to explain TAG resolution
phil: what are we commenting
on?
... tag should come up with mechanism for resolving this issue, rahter than just saying hash or slash.
ralph: this WG should write up,
either endorse the use of 303 see also, or to disagree with
TAG
... and to explain how this isused in case of semweb
phil: is it best practise to bind
this mechanism to the concept of resource id
... singular mechanism for ???
... are there other circumstances that should be investigated?
... or are we happy with singular soultion?
<Zakim> dbooth, you wanted to disagree with us not legislating more than the TAG. Our purpose is to provide Best Practices guidelines.
dbooth: uncomfortable with not
legislating more than what TAG said
... entirely appropriate to give more guidance than TAG
guus: up to level not inconsistent with TAG
ralph: meant to focus on use of
particular URI syntax
... no reason for this wg to partition uri space
... right we do need to explain how to apply tag view to specific semweb case
phil: identified problem of good
or bad uris?
... feel that context is important.
ralph: phil's comments making
this a wider problem, lets focus on smaller first
... propose specific action, this wg should draft some sort of message as part of a note,
... says 'here's how we interpret tag's solution, here's how we intepret it for semweb'
... would like to see draft of such a doc, propose one of our tfs do it
... perhaps VM?
guus: short note, couple of pages?
ralph: not formal note just yet,
but we should have some formal on the record statement
... happy to leave it to some tf
... tomb?
tom: who would do that? don't want to volunteer someone.
What about danbri?
ralph: maybe between danbri and me?
davidw: 3 week special tf just to do this?
guus: propose ralph, davidb, davidw to take on an action
tom: willing to participate
davidw: should get short message from each of impacted tf leads, regarding what their issue was?
ralph: tfs don't care too much about what the solution was, although there were deployment issues
guus: propose two davids and ralph take on the action, take on feedback from others
ralph: accept
david & david: me too
<scribe> ACTION: ralph davidw and davidb to an initial draft of TAG httpRange-14 resolution impact on semweb application developers [recorded in]
chrisW: natasha alan and i had a
telecon, resolved all issues for n-ary relations note and
part-whole note, n-ary relations gone to review
... need another reviewer (ralph is one)
... simpe part-whole note, we have concrete actions, ready in 1 week
... spoke to jerry hobbs re owl time
<Ralph> ACTION: Ralph review new n-ary relations editor's draft [recorded in]
chrisW: almost ready
guus: need second reviewer for
n-ary relations
... timescale?
chris: asap
guus: agree to review
<Ralph> ACTION: Guus review new n-ary relations editor's draft [recorded in]
guus: any use of owl restrictions note i wrote?
chris: haven't looked at it yet
guus: difference between rdfs range and owl restrictions
elisa: let's look into it
davidw: continue
<Ralph> XSCD status from SemWeb CG telecon
ralph: it was brought up at the
cg,
... last call still open, not a high priority
... we still have time to comment
<Ralph> [[
<Ralph> Ralph: SWBP wants to know the status of XML Schema Component Designators
<Ralph> Liam: unsure, as the WG is busy with XML Schema 1.1
<Ralph> ... URIs for datatypes is likely to be a separate document rather than added to SCD
<Ralph> ... has SWBPD communicated its issue to XML Schema WG?
<Ralph> ... if so, feel free to ping them if you haven't had a response
<Ralph> ]]
ralph: jeremy & jeff
concerned that our comments on uris for datatypes had not been
heard or fully made
... liam said feel free to ask again
... but not a pressing matter, so still open for comments
... tag also talked about schema component designators
guus: leave liason issue on the agenda
ACTION DavidW ask about the XML Schema Component
<scribe> DONE
elisa: made some additions after
feedback from hp
... re addition of RDF graph and document model to RDF metamodel
... OMG decided to include changes, fo next revision
... everyone is agreed
... planning to submit one additional revision
... send out asap
... . some questions about business rules .
... agreed to ground logic in common logic
... work with pat hayes to make that happen, business rules community aligning around common logic with some extesinos possibly
... so no competition between ODM and business rules
... Terry halpin
<ekw> Terry Halpin
guus: will also comment on ODM
<scribe> ACTION: guus to comment on ODM [recorded in]
<Ralph> Elisa: Terry Halpin is working with Pat Hayes to ground Business Rules in Common Logic
<Ralph> Alistair: next SKOS review is scheduled for 17 July
<Ralph> ... would like two reviewers selected at the next WG telecon
<Ralph> ... w.r.t. httpRange-14 resolution, I tried to draft some text that could be included in SKOS Core Guide
<Ralph> ... says what you can/may do if you want to use http: URIs to name resources of type SKOS:Concept
<Ralph> ... would like comments on the text in 0074.html
<Ralph> ... DanBri only concerned about the role of SPARQL
<Ralph> ... people working on US Government standards brought up an issue that they are only permitted to use W3C Recommendations in their work
<Ralph> ... thus possible reason to put SKOS Core on Recommendation track
<Ralph> ... have had multiple requests for another SKOS syntax
<Ralph> Ralph: are any of these requests archived somewhere?
<Ralph> Alistair: no, in private mail. requests for an XSD-constrained syntax
<DeborahM> hi - i joined late but am on the phone and irc - deborah mcguinness
<Ralph> Alistair: Phil suggested that an XML Schema-constrained syntax for SKOS would not be a good idea
<Ralph> Ralph: please ask for use cases accompanying any feature request, such as for a new syntax
<Ralph> Phil: I've talked with Alistair off-line about this, will probably put the discussion into the mail archive soon
guus: met with aldo in greece to
move forward the data model
... hope to see some action soon
<Ralph> ACTION: Aldo to propose an update the Wordnet TF description [recorded in]
guus: asked brian to review, hope he will
<scribe> ... no progress yet, suggest to postpone
ACTION Aldo to propose an update the Wordnet TF description
CONTINUE
<Ralph> Report of 2005-06-21 VM telecon
<Ralph> Alistair: we decided to retire DanBri's note "Some Things that Hashless URIs can Name"
<Ralph> ... and include in our basic principles note an explanation of how to implement the TAG's solution
<Ralph> ... we also took another action to contact people whose namespaces end in '/' to make sure they do redirects in the future
<Ralph> ... Tom has the ball to do the next round of editing
guus: textual version of jeremy's presentation at ... would be great basis for a note
<Ralph> Meeting record: 2005-06-21 RDF-in-XHTML TF telecon
guus: having jeremy's content as a note would be excellent
<Ralph> ACTION: Ralph suggest to XHTML TF that Jeremy's WWW2005 Talk be turned into a document [recorded in]
Phil: jeff and I meeting
wednesayt to talk about updating tf description
... and discuss next note.
guus: reviewers are chris, benjamin
<scribe> ACTION: chris and benjamin to review SETF note [recorded in]
ralph: discussion about f2f in
galway based on andreas suggesting derry might be willing to
host it
... need to confirm that, for the dates we selected
guus: already talked about both
options with andreas
... should not be a problem
<scribe> ACTION: guus to contact andreas re f2f venue [recorded in]
guus: next telecon july 11 1700 UTC
<Ralph> Host Guidelines for W3C Face to Face Meetings
Change Log:
$Log: 27-swbp-minutes.html,v $ Revision 1.3 2005/07/14 13:34:23 swick Remove extraneous characters in 4 otherwise blank lines. Revision 1.2 2005/07/14 13:31:32 swick Undo 'draft'iness; add Benjamin Nguyen to (irc) attendees per his request. These minutes were accepted at the 11-Jul WG telecon. | http://www.w3.org/2005/06/27-swbp-minutes.html | CC-MAIN-2015-18 | refinedweb | 1,898 | 71.55 |
#include <wx/cursor.h>SetCursor() function is also available for MS Windows use.:
Default constructor.
Constructs a cursor by passing an array of bits (XBM data).
The parameters fg and bg have an effect only on GTK+, and force the cursor to use particular background and foreground colours.
If either hotSpotX or hotSpotY is -1, the hotspot will be the centre of the cursor image (Motif only).
wxPerl Note: In wxPerl use Wx::Cursor->newData(bits, width, height, hotSpotX = -1, hotSpotY = -1, maskBits = 0).).
Constructs a cursor using a cursor identifier.
Constructs a cursor from a wxImage.
If cursor are monochrome on the current platform, colors with the RGB elements all greater than 127 will be foreground, colors less than this background. The mask (if any) will be used to specify the transparent area.
In wxMSW the foreground will be white and the background black. If the cursor is larger than 32x32 it is resized.
In wxGTK, colour cursors and alpha channel are supported (starting from GTK+ 2.2). Otherwise the two most frequent colors will be used for foreground and background. In any case, the cursor will be displayed at the size of the image.
Under wxMac (Cocoa), large cursors are supported.
Notice that the image can define the cursor hot spot. To set it you need to use wxImage::SetOption() with
wxIMAGE_OPTION_CUR_HOTSPOT_X or
wxIMAGE_OPTION_CUR_HOTSPOT_Y, e.g.
Copy constructor, uses reference counting..
Returns the coordinates of the cursor hot spot.
The hot spot is the point at which the mouse is actually considered to be when this cursor is used.
This method is currently only implemented in wxMSW and wxGTK2+ and simply returns wxDefaultPosition in the other ports.
Returns true if cursor data is present.
Assignment operator, using reference counting. | https://docs.wxwidgets.org/3.1.0/classwx_cursor.html | CC-MAIN-2019-09 | refinedweb | 291 | 67.45 |
. Following the etymology, the inventor, Edward Fredkin, pronounces it /ˈtriː/ "tree".[1][2] However, it is pronounced /ˈtraɪ/ "try" by other authors.[1][2][3] or shapes. In particular, a bitwise trie is keyed on the individual bits making up a short, fixed size of bits such as an integer number or pointer to memory.
Unlike most other algorithms, tries have the peculiar feature that the code path, and hence the time required, is almost identical for insert, delete, and find operations. As a result, for situations where code is inserting, deleting and finding in equal measure, tries can handily beat binary search trees, as well as provide a better basis for the CPU's instruction and branch caches.
The following are the main advantages of tries over binary search trees (BSTs):
The following are the main advantages of tries over hash tables:
As mentioned, a trie has a number of advantages over binary search trees.[4] A trie can also be used to replace a hash table, over which it has the following advantages:
Tries do have some drawbacks as well:. This is because an acyclic deterministic finite automaton can compress identical branches from the trie which correspond to the same suffixes (or parts) of different words being stored.
Tries are also well suited for implementing approximate matching algorithms, including those used in spell checking and hyphenation[2] software. look up find(node, key): for char in key: if char not in node.children: return None else: node = node.children[char] return node.value
A simple Ruby version:
class Trie def initialize @root = Hash.new end def build(str) node = @root str.each_char do |ch| node[ch] ||= Hash.new node = node[ch] end node[:end] = true end def find(str) node = @root str.each_char do |ch| return nil unless node = node[ch] end node[:end] && true end end
A compiling Java version:
public class MinimalExample{ private interface Node { public static final Node EMPTY_NODE = new Node() { @Override public String getValue() { return ""; } @Override public boolean containsChildValue(char c) { return false; } @Override public Node getChild(char c) { return this; } }; public String getValue(); public boolean containsChildValue(char c); public Node getChild(char c); } public Node findValue(Node startNode, String value) { Node current = startNode; for (char c : value.toCharArray()) { if (current.containsChildValue(c)) { current = current.getChild(c); } else { current = Node.EMPTY_NODE; break; } } return current; } }
Lexicographic sorting of a set of keys can be accomplished with a simple trie-based algorithm as follows:
This algorithm is a form of radix sort.
A trie forms the fundamental data structure of Burstsort, currently (2007) the fastest known, memory/cache-based, string sorting algorithm.[6]
A parallel algorithm for sorting N keys based on tries is O(1) if there are N processors and the lengths of the keys have a constant upper bound. There is the potential that the keys might collide by having common prefixes or by being identical to one another, reducing or eliminating the speed advantage of having multiple processors operating in parallel.
A special kind of trie, called a suffix tree, can be used to index all suffixes in a text in order to carry out fast full text searches., and hence is becoming increasingly the algorithm of choice for code which does a lot of insertions and deletions such as memory allocators (e.g. recent versions of the famous Doug Lea's allocator (dlmalloc) and its descendents).
A reference implementation of bitwise tries in C and C++ useful for further study can be found at.. of the range of global lookups for comparing the common branches in the sparse trie.
The result of such compression may look similar to trying to transform the trie into a directed acyclic graph (DAG), because the reverse transform from a DAG to a trie is obvious and always possible, however it is constrained by the form of the key chosen to index the nodes.
Another compression approach is to "unravel" the data structure into a single byte array.[8] This approach eliminates the need for node pointers which reduces the memory requirements substantially and makes memory mapping possible which allows the virtual memory manager to load the data into memory very efficiently.
Another compression approach is to "pack" the trie.[2] Liang describes a space-efficient implementation of a sparse packed trie applied to hyphenation, in which the descendants of each node may be interleaved in memory.
This entry is from Wikipedia, the leading user-contributed encyclopedia. It may not have been reviewed by professional editors (see full disclaimer) | http://www.answers.com/topic/trie | crawl-003 | refinedweb | 753 | 52.09 |
We at techiesms studios, running a Series called AR with IoT and this is the fourth episode of that series. So till now we were easily able to control our Home Appliances over internet using Augmented Reality and Internet Of Things both using touch screen buttons and virtual buttons.
Now in this episode, we will try to read data from server and display that data in the Air using Augmented Reality.
Components Required
For Hardware part of the project you’ll need
- ESP32 / NodeMCU board
- DHT11 Sensor
For Software part you’ll need
- Blynk App
- Unity Hub
Hardware Connection Diagram
IoT part of the project
For the IoT part, I have used Blynk IoT Platform. In which, I just made a simple blynk project of displaying Temperature and Humidity data using Gauge widget. Here the temperature data is stored in virtual pin V0 and humidity data is stored in virtual pin V1
After that, we have made a code in which, the temperature data from DHT11 sensors gets pushed to virtual pin V0 and Humidity data is pushed to Virtual pin V1. You can copy and paste the code from below, just change the SSID name, Password and Blynk Auth token.
/*************************************************************: Tweets by blynk_app Blynk library is licensed under MIT license This example code is in public domain. ************************************************************* This example shows how value can be pushed from Arduino to the Blynk App. WARNING : For this example you'll need Adafruit DHT sensor libraries: App project setup: Value Display widget attached to V5 Value Display widget attached to V6 *************************************************************/ /*> #include <DHT.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; // Your WiFi credentials. // Set password to "" for open networks. char ssid[] = "YourNetworkName"; char pass[] = "YourPassword"; #define DHTPIN 2 // What digital pin we're connected to // Uncomment whatever type you're using! #define DHTTYPE DHT11 // DHT 11 //#define DHTTYPE DHT22 // DHT 22, AM2302, AM2321 //#define DHTTYPE DHT21 // DHT 21, AM2301 DHT dht(DHTPIN, DHTTYPE); BlynkTimer timer; // This function sends Arduino's up time every second to Virtual Pin (5). // In the app, Widget's reading frequency should be set to PUSH. This means // that you define how often to send data to Blynk App.1, h); Blynk.virtualWrite(V0, t); } void setup() { // Debug console Serial.begin(9600); Blynk.begin(auth, ssid, pass); dht.begin(); // Setup a function to be called every second timer.setInterval(1000L, sendSensor); } void loop() { Blynk.run(); timer.run(); }
Till this step, we will be easily able to monitor sensor’s data on the Blynk App. But we want to monitor that using API so that later on we can integrate it with AR. And the good news is that, Blynk do provide us APIs.
So to get the data to virtual pin of our blynk device, the format of API is something like this.
For example, If I want to read data_0<<
While Setting up unity, you’ll need four things, one is the target image, second is Button Image, third is Template Image and fourth is C# Script. All the things are provided below, so you can easily download and use them
using System.Collections; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; using Vuforia; public class click : MonoBehaviour { InputField field; InputField Hum; public VirtualButtonBehaviour Vb_on; void Start() { field = GameObject.Find("TextInputField").GetComponent<InputField>(); Hum = GameObject.Find("InputField1").GetComponent<InputField>(); Vb_on.RegisterOnButtonPressed(OnButtonPressed_on); // GameObject.Find("GetButton").GetComponent<Button>().onClick.AddListener(GetData); } public void OnButtonPressed_on(VirtualButtonBehaviour Vb_on) { GetData_tem(); GetData_hum(); Debug.Log("Click"); } void GetData_tem() => StartCoroutine(GetData_Coroutine1()); void GetData_hum() => StartCoroutine(GetData_Coroutine()); IEnumerator GetData_Coroutine1() { Debug.Log("Getting Data"); field.text = "Loading..."; string uri = ""; using(UnityWebRequest request = UnityWebRequest.Get(uri)) { yield return request.SendWebRequest(); if (request.isNetworkError || request.isHttpError) field.text = request.error; else { field.text = request.downloadHandler.text; field.text = field.text.Substring(2,2); } } } IEnumerator GetData_Coroutine() { Debug.Log("Getting Data"); Hum.text = "Loading..."; string uri = ""; using(UnityWebRequest request = UnityWebRequest.Get(uri)) { yield return request.SendWebRequest(); if (request.isNetworkError || request.isHttpError) Hum.text = request.error; else { Hum.text = request.downloadHandler.text; Hum.text = Hum.text.Substring(2,2); } } } }
You need to save this code with the name, Click.cs. | https://techiesms.com/iot-projects/monitoring-sensors-data-in-the-air-using-augmented-reality/ | CC-MAIN-2022-05 | refinedweb | 690 | 50.02 |
Hi On Sat, Jan 27, 2007 at 11:10:53AM +0100, Fran?ois Revol wrote: [...] > > also abs(AVERROR_*) if we do agree on them should have the same value > > as > > abs(E*) that way mapping from one to the other becomes much simpler > > Except E* don't have the same value on all platforms. > It pretty much falls down to my first idea which was > > /* os_support.h or whatever */ > #ifdef __BEOS__ that should be #if ENOMEM < 0 > # define FFERR(e) (e) > #else > # define FFERR(e) (-(e)) > #endif AVERR() as this should be an exportet macro (the user after all should be able to test for specific errors) > > > ... > return FFERR(ENOMEM); > ... [...] > > It suppresses the need for AVERROR_* leaving all the semantics attached > to the posix errors without folding them to 10 cases. (but we still > need to handle OSes which don't have some defined). are there any? do we really use such obscure E* ? > > For the time being we could keep AVERROR_* as #defined to FFERR(E*) possible > until we increment the versions. no, the major versions need to be bumped if the values: <> | http://ffmpeg.org/pipermail/ffmpeg-devel/2007-January/028121.html | CC-MAIN-2016-50 | refinedweb | 184 | 81.02 |
react-native-svg is built to provide a SVG interface to react native on both iOS and Android.
With Expo, this is pre-installed. Jump ahead to Usage
Install library from
npm
npm install react-native-svg --save
# NOTICE:
Link native code
react-native link react-native-svg
A bug in react-native currently links the tvOS library into the iOS project as well.
Until the fix is released:
Follow the instructions here:
import com.horcrux.svg.SvgPackage;to the imports at the top of the file
new SvgPackage()to the list returned by the
getPackages()method. Add a comma to the previous item if there's already something there.
To install react-native-svg on iOS visit the link referenced above or do the following:
Alternatively, you can use CocoaPods to manage your native (Objective-C and Swift) dependencies:
pod 'RNSVG', :path => '../node_modules/react-native-svg'>;}
The element is used to create a rectangle and variations of a rectangle shape:
Code explanation:
The element is used to create a circle:
Code explanation: element is an SVG basic shape, used to create a line connecting two points.
Code explanation:
The element is used to create a graphic that contains at least three sides. Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).
Code explanation:
The element is used to create any shape that consists of only straight lines:
Code explanation:
The
The following commands are available for path data:
Note: All of the commands above can also be expressed with lower letters. Capital letters means absolutely positioned, lower cases means relatively positioned.
The element is used to define text.
STROKED TEXT
In addition to text drawn in a straight line, SVG also includes the ability to place text along the shape of a
We go up and down,then up again.
The SVG element is used to define reusable symbols. The shapes nested inside a are not displayed unless referenced by a element.
The element is used to embed definitions that can be reused inside an SVG image. For instance, you can group SVG shapes together and reuse them as a single shape.
The element allows a raster image to be included in an Svg componenet.
HOGWARTS
The SVG element defines a clipping path. A clipping path is used/referenced using the clipPath property
Q:
Code explanation:
NOTICE: LinearGradient also supports percentage as prop:
This result is same as the example before. But it's recommend to use exact number instead; it has performance advantages over using percentages.
The element is used to define a radial gradient. The element must be nested within a <Defs> tag. The <Defs> tag is short for definitions and contains definition of special elements (such as gradients).
Code explanation:.
git clone react-native-svg-examplenpm i# run Android: react-native run-android# run iOS: react-native run-ios | https://www.npmjs.com/package/react-native-svg | CC-MAIN-2018-09 | refinedweb | 480 | 54.02 |
Waits for a connection, echos any data received back to the sender.
More...
#include <EchoBehavior.h>
Waits for a connection, echos any data received back to the sender.
Definition at line 9 of file EchoBehavior.h.
List of all members.
indicates one of the available data sinks: combinations of client/server and TCP/UDP
[protected]
server TCP
server UDP
client TCP
client UDP
total number of different connections available
Definition at line 46 of file EchoBehavior.h.
constructor
Definition at line 19 of file EchoBehavior.h.
destructor
Definition at line 31 of file EchoBehavior.h.
[private]
don't call (copy constructor)
[static]
called by wireless when there's new data
Definition at line 191 of file EchoBehavior.cc.
Referenced by doEvent().
Definition at line 201 of file EchoBehavior 57 of file EchoBehavior.cc..
Definition at line 19 of file EchoBehavior.cc.
May be overridden to cleanup when the behavior is shutting down. However events will automatically be unsubscribed, and by using addMotion(), motions will automatically be removed by stop(), so you may not need any cleanup.
Definition at line 25 of file EchoBehavior.cc.
Gives a short description of what this class of behaviors does... you should override this (but don't have to).
If you do override this, also consider overriding getDescription() to return it
Definition at line 37 of file EchoBehavior 42 of file EchoBehavior.h.
unsets bits of bits which aren't represented by arg
Definition at line 146 of file EchoBehavior.cc.
don't call (assignment operator)
called by one of the wireless callbacks to do processing
Definition at line 162 of file EchoBehavior.cc.
Referenced by client_callbackT(), client_callbackU(), server_callbackT(), and server_callbackU().
Definition at line 186 of file EchoBehavior.cc.
Referenced by setupNetwork().
Definition at line 196 of file EchoBehavior.cc.
initialize server ports
Definition at line 31 of file EchoBehavior.cc.
Referenced by doEvent(), and doStart().
close open connections
Definition at line 44 of file EchoBehavior.cc.
Referenced by doEvent(), and doStop().
the port to listen on for incoming UDP and TCP connections
Definition at line 12 of file EchoBehavior.h.
Referenced by doEvent(), getClassDescription(), and setupNetwork().
a table of bools indicating how data should be echoed -- if route[from][to] is set, route it
Definition at line 57 of file EchoBehavior.h.
Referenced by doEvent(), EchoBehavior(), and processCallback().
[static, protected]
{
"TCP Server", "UDP Server","TCP Client","UDP Client"
}
a user-readable name for each incoming or outgoing route
Definition at line 53 of file EchoBehavior.h.
an array of sockets, one for each incoming or outgoing route
Definition at line 55 of file EchoBehavior.h.
Referenced by doEvent(), EchoBehavior(), processCallback(), setupNetwork(), and teardownNetwork().
the system socket number for each of sockets, used to detect when a socket has been closed
Definition at line 56 of file EchoBehavior.h.
the singleton object (only one of these objects can be active at a time or they would conflict over ports)
Definition at line 11 of file EchoBehavior.h.
Referenced by client_callbackT(), client_callbackU(), EchoBehavior(), server_callbackT(), server_callbackU(), and ~EchoBehavior(). | http://tekkotsu.org/dox/classEchoBehavior.html | CC-MAIN-2018-34 | refinedweb | 501 | 50.23 |
asp.net-mvc-3 902
- Entity Framework 5 Updating a Record
- File Upload ASP.NET MVC 3.0
- How do I import a namespace in Razor View Page?
- Escape @ character in razor view engine
- Writing/outputting HTML strings unescaped
- How to use ternary operator in razor (specifically on HTML attributes)?
- Why is JsonRequestBehavior needed?
- How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?
- ASP.NET MVC 3 - Partial vs Display Template vs Editor Template
- What's the difference between ViewData and ViewBag?
- How to declare a local variable in Razor?
- How to set value of input text using jQuery
- Multiple types were found that match the controller named 'Home'
- Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine
- Using Ajax.BeginForm with ASP.NET MVC 3 Razor
- Multiple models in a view
- Returning a file to View/Download in ASP.NET MVC
- HTML.ActionLink vs Url.Action in ASP.NET Razor
- Html5 data-* with asp.net mvc TextboxFor html attributes
- ASP.NET MVC 3 Razor: Include JavaScript file in the head tag
- The type or namespace name does not exist in the namespace 'System.Web.Mvc'
- Replace line break characters with <br /> in ASP.NET MVC Razor view
- ReSharper warns: “Static field in generic type”
- What is the @Html.DisplayFor syntax for?
- ASP.NET MVC3 - textarea with @Html.EditorFor
- ViewBag, ViewData and TempData
- what is the function of webpages:Enabled in MVC 3 web.config
- How do I define a method in Razor?
- How to create a function in a cshtml template?
- Where and how is the _ViewStart.cshtml layout file linked?
- Prevent Caching in ASP.NET MVC for specific actions using an attribute
- Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method
- ASP.NET MVC 3 Razor - Adding class to EditorFor
- Non-static method requires a target
- Razor HtmlHelper Extensions (or other namespaces for views) Not Found
- Add CSS or JavaScript files to layout head from views or partial views
- “Parser Error Message: Could not load type” in Global.asax
- @media media query and ASP.NET MVC razor syntax clash
- Correct way to use _viewstart.cshtml and partial Razor views?
- Dynamic Anonymous type in Razor causes RuntimeBinderException
- Do asynchronous operations in ASP.NET MVC use a thread from ThreadPool on .NET 4
- Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor
- Access key value from Web.config in Razor View-MVC3 ASP.NET
- MVC 3: How to render a view without its layout page when loaded via ajax?
- Custom error pages on asp.net MVC3
- How to add extra namespaces to Razor pages instead of @using declaration?
- Why does Razor _layout.cshtml have a leading underscore in file name?
- ASP.NET: This method cannot be called during the application's pre-start initialization stage
- EF LINQ include multiple and nested entities
- How to use ? : if statements with Razor and inline code blocks | http://code.i-harness.com/en/tagged/asp.net-mvc-3 | CC-MAIN-2018-51 | refinedweb | 492 | 62.14 |
QML script provider similar to image provider
Hi, I have written a simple image provider which basically gets the images from the network. Is there something similar that can be done for javascript files as well? I want to be able to get the javascript resources from the network too using my custom code. Where would i have to make the change to do this?
Thanks,
Rohit
Hi,
To load an Image from Network in QML you can use
@
Image {
source: ""
}
@
And use import to get JavaScript from network. for eg.
@
import "" as Remote
Component.onCompleted: console.log(Remote.myFunction())
@
Remember that the Qualifier should start with a Capital letter.
Hi,
Thanks for the reply.
I needed to use custom code to get these javascript files. For example, for the images, i was able to do that using a custom Image provider where I can add some security and get the image id and i can get the image from my resource manager. I want to be able to do the same for scripts which i will obtain from the same resource manager. Is there a way to achieve that?
Thanks,
Rohit
Do you mean you want to download JavaScript files from C++ code ?
Yes, that is right. I want to be able to download the file from c++ and then use it. I am assuming i would have to make a change to or inherit from some Qt class.
Basically i want to have control over obtaining the javascript file, since i want to add a security layer. if there is a solution to do this from javascript, then that would work too.
Thanks,
Rohit
You can use "QNetworkAccessManager::get": to download the file. Checkout the examples for how to use it.
Ok. but how do i make Qt/QML use this code to download the file? Can it be done via a plugin?
I want to be able to use this custom code when someone writes:
import "some-uri" as Remote
At this point it should get the file using my plugin.
bq. but how do i make Qt/QML use this code to download the file?
From C++ did you check the examples of QNetworkAccessManager::get ?
You can call C++ functions from QML. Check "qtqml-cppintegration-topic": and especially "qtqml-cppintegration-exposecppattributes":
I'm not sure about the plugin as I have never used one.
@p3c0: Thanks. I get how to use the QNetworkAccessManager to download the file. But I need to be able to run this code whenever someone uses the import statement for external javascript files. Sorry for not being clear before.
Well then check "registering-an-instantiable-object-type":. Create a Q_INVOKABLE function in it where you download the file then you can call this function from QML after instantiating it.
@p3c0: I am not able to get the example you stated above to work actually
import "" as Remote
I have my own node.js file server running on 8030 which i am trying to access using the below import statement:
import "" as Browser
Sometimes it does send a request to my server and my server correctly responds too, but the app then exits for some reason. do you know why that is?
thanks,
Rohit
Sorry but i haven't used node.js. I have used it with particularly simple example like few JavaScript functions in sample.js and it works as expected.
Actually node.js is not the issue here..as the server does work when i try to access the file in the browser.
Do you know why the download would not work in QML? My app exits with an exit code 255.
Thanks
Can you try with some simple Javascript file which will contain just a few functions ?
i tried with an empty javascript file too and it did not seem to work
I tested it with apache server and it worked. The js file contains a simple function which returns a string.
sample.js
@
function myFunction() {
return "Hello Qt"
}
@
and the from QML
@
import "" as Remote
...
//and on some Button click calling it as
Remote.myFunction()
@
It seems to work when I create a Qt Quick Application project from Qt Creator and try to import the javascript file from the node js server.
However the import fails when I create a Qt Quick UI project. Is there a way to enable this behavior in a Qt Quick UI project? | https://forum.qt.io/topic/46763/qml-script-provider-similar-to-image-provider | CC-MAIN-2018-43 | refinedweb | 739 | 73.88 |
31 October 2012 01:30 [Source: ICIS news]
MEDELLIN, ?xml:namespace>
Net profit slumped to Colombian pesos (Ps) 3,220bn ($1.76bn, €1.36bn) from Ps4,150bn recorded in the same quarter last year, the Bogota-based company said during an earnings call with investors.
Third-quarter revenues were at Ps14,200bn, up from Ps14,100bn recorded last year, Pemex said.
Third-quarter earnings before interest, tax, depreciation and amortisation (EBITDA) were Ps6,900bn, down by 10% from the same period last year.
“2012 has been a year in which Ecopetrol and its affiliates and subsidiaries have maintained their rate of growth despite facing new challenges specific to the current industrial environment and our country,” said the company’s chief executive, Javier Gutierrez.
Ecopetrol said that it would maintain its 2012 oil production target of 780,000 bbl/day, despite investors' concerns as to how it would meet these targets.
The company produced an average of 743,000 bbl/day in the third quarter, up by 1.6% from a year earlier.
“Planned production increases in several key fields means our output target will be reached,” said Gutierrez.
The company also said that attacks by Colombian rebel groups on oil infrastructure had decreased significantly in October, meaning reduced disruption to operations.
Experts suggest that the reduction in attacks is because of peace negotiations between the Colombian government and the Revolutionary Armed Forces of Colombia (FARC), which officially started in
($1 = Ps1,831 | http://www.icis.com/Articles/2012/10/31/9609036/colombia-ecopetrol-q3-profit-falls-on-lower-sales-growth-higher-costs.html | CC-MAIN-2015-11 | refinedweb | 242 | 52.6 |
Since I can't possibly cover Windows programming to any depth within the confines of this book, I will now switch to a bird's-eye view of how one might approach the task of writing a Windows application. As before, I will concentrate on the two main challenges of Windows programming: how the program should work and look like, and how to encapsulate and categorize various APIs. The mere number of Windows APIs is so overwhelming that some kind of classification (with C++ classes and namespaces) is a must.
After reading this chapter, I strongly suggest browsing the source code and studying the details of the implementation.
Taking a command-line application, like our symbolic calculator, and making a minimal port to Windows could be quite easy. We have to find a way, other than std::cin, to get user input; and to display the results in a window. Error display could be dealt with using message boxes. A single dialog box with two edit fields--one for input and one for output--would suffice.
But this kind of port is not only primitive--it doesn't even cover the whole functionality of our original application. In the command-line calculator, the user was at least able to see some of his or her previous inputs--the history of the interaction. Also, in Windows, commands like load, save or quit are usually disengaged from text-based input and are available through menus, buttons, toolbars or accellerator keys. Finally, there are certain possibilities specific to Windows that can enhance the functionality of our program and are expected by the user. An obvious example would be the display the contents of the calculator's memory.
Some of these features don't require substantial changes to the calculator engine. Disengaging commands from text input will actually make the parsing simpler--the Scanner will have to recognize fewer tokens and the CommandParser object will become unnecessary. Other features, such as the display of memory, will require deeper changes inside the Calculator object (which, by the way, will play the role of a Model).
Whether it's porting or designing an application from scratch, the first step is to envision the user interface.
In our case, we obviously need an input field, where the user will type the expressions to be evaluated. We also need an output field, where the results of the calculations will appear. We'd also like to have one window for the history of user input, and another to display the contents of memory.
The design of the menu is a non-trivial problem. We know, more or less, what we will have there: Load, Save as well as the traditional About and Exit. We can also add one more command--Clear memory. The problem is how to organize these commands.
The traditional approach, which often leads to barely usable menu systems, is to follow the historical pattern. Menu commands are grouped under File, Edit, View, Tools, Window, Help, etc. Notice that some of these words are nouns, others verbs. Tradition also dictates arbitrarily that, for instance, Exit goes under File, About under Help, Search under Edit, Options under Tools, etc...
The more modern approach is to group commands under noun headings that describe objects upon which these command act. The headings are, as far as possible, ordered from general to specific. The first, most general menu item is Program. This is where you should put the commands About and Exit. The About command displays information about the Program, not the Help. Similarly, you Exit a Program, not a File.
The Program item is usually followed by such groups as Project, Document (or File); then View or Window, Edit and Search; then the elements of the particular display, such as All, Selection; and finally, Help. Even if the user is used to traditional groupings, he or she is likely to find this new arrangement more logical and easier to use.
In our calculator, we'll have the Program menu followed by the Memory menu. The operations one can apply to Memory are Clear, Save and Load. A more complete version would also have the Help menu.
Finally, it's nice to have a status bar at the bottom of the window to show the readiness of the calculator to accept user input, as well as little command help snippets when the user selects menu items.
Instead of showing you varius sketches, I'll present the final result--the actual screenshot of the calculator's user interface.
The calculator's main window is tiled with various sub-windows, or child windows. Some of these children--like the title bar, the menu bar, minimize/maximize buttons, etc.--are created and managed by Windows. Others are a programmer's responsibility.
A child window is owned by its parent window. Since there is often some confusion between the meaning of a "child" window vs. an "owned" window, here's a short summary.
You will probably want all windows in your applications to be owned by the top-level window. If, furthermore, you'd like them to be constrained to the client area of the top-level (or some other) window, you'll create them as children of their owners. (Examples of owned, but non-child, windows are dialog boxes and message boxes, about which I'll talk later.)
I introduced a separate class, Win::ChildMaker, derived from Win::Maker, to encapsulate the creation of child windows. You can have a child window based on any window class, as long as you know the class' name. For our purposes, however, we'll be creating windows based on classes that are pre-defined (and pre-registered) by Windows.
There are several useful window classes corresponding to standard controls. Instead of writing and testing new window procedures, we can get a lot of standard functionality by re-using these controls. That's why I created a subclass of Win::ChildMaker called Win::ControlMaker that can be used as base for the specialized contol makers, such as Win::EditMaker, Win::ListBoxMaker and Win::StatusBarMaker.
Before going into any more detail about controls, let's talk some more about the management of child windows. I made them part of the View object, whose constuctor uses various control makers to create them. There are two edit controls, one of them read-only. There are two listboxes that are particularly suited for displaying lists. Finally, there is a status bar control.
The first thing our program has to take care of is the proper positioning of these child windows. This is usually done in response to the WM_SIZE message sent to the top-level window. The first such message arrives just before the child windows are displayed, so that's a great time to size and position them for the first time. Then, every time the user resizes the top-level window, the WM_SIZE message is sent again. The parameters of WM_SIZE are the width and the height of the client area. All we have to do is to partition that rectangle among all the children. After doing some simple arithmetic, we tell the children to move to their new positions.
Next, we have to take care of the focus. Whenever the calculator is active, we would like the keyboard input to go directly to the input edit control. Since this doesn't happen automatically, we have to explicitly pass keyboard focus to this child window whenever the calculator gets focus. Fortunately, the top-level window is notified every time this happens. The WM_SETFOCUS message is sent to it whenever the window becomes active, including the time of its creation.
A Windows control is a window whose class and procedure--the major elements of behavior--are implemented by the system. Controls vary from extremely simple, like static text, to very complex, like ListView or TreeView. They are ubiquitous in dialog boxes (about which we'll talk soon), but they can also be created as stand-alone child windows. The application communicates with a control by sending it messages. Conversely, a control communicates with its parent by sending messages to it. In addition to common messages, each type of control has its own distinct set of messages it understands.
I defined a class Win::SimpleCtrl that combines the attributes common to all controls. Since a control is a window, Win::SimpleCtrl inherits from Win::Dow. Like all child windows, controls can be assigned numerical ids, so that their parent can distinguish between them (although it may also tell them apart by their window handles). If a control is created standalone, using an appropriate maker, we can initialize the corresponding SimpleCtrl object directly with its window handle. Otherwise, we initialize it with the parent's window handle and the child id (this pair is immediately translated to the window handle using the GetDlgItem API).
The simplest control is called static text. It displays text in a simple frame. The corresponding object, Win::StaticText, is the simplest descendant of Win::SimpleCtrl. The program can modify the text displayed in it by calling the SetText method that Win::StaticText inherits from Win::Dow.
A little more interesting is the edit control. Its read-only version behaves just like static text, except that you can copy text from it into the clipboard (by selecting it and pressing Ctrl-C). The full-blown edit control can be used not only to display text, but also to read user input. It also supports several editing functions, like delete, copy, cut, paste, etc. In fact, a multi-line edit control is the engine behind the Windows own Notepad.
The most important thing that an application may want to get from an edit control is the text that's been input there by the user. The class Win::Edit, another descendant of Win::SimpleCtrl, provides two different ways of doing that. The low-level method GetText takes a buffer and a count (you can use GetLen method to enquire about the length first). The high-level method GetText takes no arguments and returns a std::string.
Controls keep sending messages to their parent windows. The interesting ones are WM_COMMAND and, for the newer generation of controls, WM_NOTIFY. It so happens that, for some historical reason, WM_COMMAND is not only used by controls, but also by menus and accellerators. Our generic window procedure sorts them out and calls, respectively, OnControl or OnCommand. OnControl is passed the control's window handle, its numerical id and the id of the command. For instance, every time the user changes the text in an edit control, a command message is set to the parent, with the command id EN_CHANGE (applications usually ignore this message).
The main question with edit controls is when it's a good time to retrieve their text. The user must have some way of telling the program that the input is ready--in our case, that the whole expression has been entered. We could have added a special button "Evaluate" for the user to click on. But that's not what the user expects. He or she will most likely press the Enter key on the keyboard and expect the program to take it as a cue that the input is ready. Surprisingly, this very basic feature is not easy to implement. There is no simple way to tell the edit control to notify the parent when the Enter key is pressed.
So what are we to do? We'll have to use the back-door approach called window subclassing. We have to write our own window procedure and plug it into the edit control. Fortunately, our window procedure doesn't have to implement all the editing functionality from scratch. All it has to do is to intercept the few messages we're interested in and pass the rest to the original, Windows-defined procedure.
I have conveniently encapsulated window subclassing in two Win::Dow methods, SubClass and UnSubClass. The SubClass method takes a pointer to the SubController object. It substitutes a generic SubProcedure in place of the old window procedure. For every message, the SubProcedure first calls the SubController to process it. If the SubController doesn't process it (i.e., returns false), it calls the old window procedure. Notice how the procedures are chained together. Each of them either processes a message or calls the next, until the last one calls the default window procedure.
The subclassing of the edit control proceeds as follows. We define a subclass of Win::SubController, and call it EditController. It overrides only one method, OnKeyDown, and processes it only if the key code corresponds to the Enter key (VK_RETURN). On intercepting the Enter key, it sends a message to the parent window. I decided to use a standard control message, WM_CONTROL, which could be processed by the OnControl method of the parent window. I had to pack the wParam and lParam arguments to mimic the control messages sent by Windows. As the control id I chose the pre-defined constant IDOK (thus immitating the pressing of the OK button in dialog boxes).
To perform the subclassing, we call the SubClass method of the edit window, passing it the EditController. We have to override the OnControl method of our main controller to intercept the IDOK message and react appropriately. In fact that's where all the code from our old main went. We retrieve the string from the edit control, encapsulate it in a stream, create the scanner and the parser and evaluate the result. At this point we display the result and update the history and memory displays (in case the calculation changed memory).
Displaying history is very simple. We just tell the ListBox to add a line to its window containing the string that was input by the user. ListBox will than take care of storing the string, displaying it, as well as scrolling and re-painting when necessary. We don't have to do anyting else. That's the power of Window controls.
Displaying memory, on the other hand, is not so simple. That's because, in that case, the display has to reflect the state of a data structure that constantly changes. New variables are added and the values of old variables are modified as a result of user actions. Only the parser has any understanding of these actions. It decides whether an expression entered in the input window modifies the calculator's memory or not. Thus the display has to change in response to a change in the model.
There are two approaches in dealing with the model-view feedback loop. The shotgun approach assumes that every user action that may change the state of the model requires the refreshing of the particular part of the view. In this scheme, display changes are controller-driven. The controller tells the view to refresh itself, and the view queries the model for the changes to be displayed. The model has no dependency on the view, as it shouldn't.
The notification approach, on the other hand, assumes that the model will notify the view directly. A notification might simply tell the view to refresh itself, or it might provide the exact information about what and how should be changed. The problem with this scheme is that it introduces a circular dependency. The view depends on the model, because it has to know how to query for data to be displayed. The model depends on the view, because it has to know how to notify it about changes. Now, if you look back at our definition of the model, you'll find that it was supposed to be unaware of the details of the user interface. It seems like we'll have to abandon this nice subdivision of responsibilities and break the simple hierarchy of dependencies in favor of a more entangled (and complex) system.
Don't despair yet! I'll show you how you can have a cake of hierarchies and eat it too with notifications. The trick is to give the model only a very minimal glimpse of the view. All the model needs is a "notification sink," and object that expresses interest in being notified about certain events. The model will have no clue about how these notifications are used. Furthermore, it will have no knowledge of the existence of the class View.
A notification sink should be a separate class that will encapsulate only the notification interface. The model will have to know about this class, have access to an object of this class and call its methods. The view could simply inherit from the notification sink and implement its virtual methods. When the model sends a notification to its notification sink object, it really sends it to the view. But it still lives in a state of ignorance about the details of the UI.
The absence of the dependency loop in this scheme is best illustrated by the hierarchy of includes. The header file that defines the notification sink is at the top of the hierarchy. It has to be included in view.h, because class View inherits from class NotificationSink. Some of the files that constitute the implementation of the model (the Calculator object) will also have to include it, because they call methods of NotificationSink. View.cpp will have to include calc.h, because it needs data from the model. The important thing is that no model file will have to include view.h. The graph of dependencies is a DAG--a directed acyclic graph--the sign of a good design.
Now that you have an idea how to implement the optimal solution, you might be pleased to learn that in the implementation of our calculator I voted for the simpler, shotgun approach. The controller calls View::RefreshMemory every time a new expression is processed by the parser. As you might recall, this is done in response to the IDOK command sent by the edit control after detecting the enter key.
In order not to be really crude (and not to cause too much screen flicker), I chose to update the memory display line-by-line, and modify only these entries which have changed since the last refresh. So in our port to Windows, the changes to the calculator not only require a new interface for memory listing, but also some mechanism to mark (and unmark) individual memory entries. This snippet of code shows how it works:
void View::UpdateMemory () { int count = _memoryView.GetCount (); for (int i = 0; i < count; ++i) { int id = _memoryView.GetData (i); if (_calc.HasValueChanged (id)) { _calc.ResetChange (id); std::string varStr = FormatMemoryString (id); _memoryView.ReplaceString (i, varStr); _memoryView.SetData (i, id); } } int iNew; while ((iNew = _calc.FindNewVariable ()) != idNotFound) { _calc.ResetChange (iNew); std::string varStr = FormatMemoryString (iNew); int i = _memoryView.AddString (varStr); _memoryView.SetData (i, iNew); } }
The member _memoryView represent the ListBox control that displays the contents of the calculator's memory.
The other, and indeed more common, application of Window controls is in the construction of dialog boxes. A dialog box is a pre-fabricated window that provides a frame for various controls specified by the programmer. The type of controls and their positions are usually described in the resource script (the same where we described the icon). Here's an example of such a description:
IDD_ABOUT DIALOG DISCARDABLE 0, 0, 142, 70 STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION CAPTION "About Symbolic Calculator" FONT 8, "MS Sans Serif" BEGIN DEFPUSHBUTTON "OK",IDOK,46,49,50,14 CTEXT "Bartosz Milewski © 2000",IDC_STATIC,10,33,121,14 ICON IDI_MAIN,IDC_STATIC,60,7,20,20 END
You don't really have to learn the language of resource scripts, because their creation is normally handled by the resource editor. The above script corresponds to the following dialog box:
The "About" dialog of the Symbolic Calculator.
This dialog contains three controls, a default push button, a static text and a static icon. The button's id is IDOK, the two static controls have both the same id, IDC_STATIC. These particular ids are predefined, but in general you are free to assign your own ids to controls, as long as you define symbols for them in the resource header (resource.h, in our case).
The Load and Save dialogs (displayed after selecting Load or Save from the Memory menu) are a little more involved. They both have an OK button and a CANCEL button. The Save dialog, moreover, contains an edit control and the Load dialog has a ListBox. These are the same controls we used in the main window, but here it's up to the dialog box to create and position them according to the script. Not only that, the dialog makes sure that when the user presses the enter key, the result is the same as if he clicked on the OK button. There is no need for us to subclass the edit control in a dialog. You can also understand now why I chose the constant IDOK as the command identifier for the subclassed edit control in the main window.
Dialog box takes care of one more thing, the focus. In our main window, we had a very simple rule--the focus always went to the input edit control. It's not so simple when you can have more than one potentially active control. Suppose that you, as the user, have activated one of the controls (i.e., one of several edit boxes in the same dialog, for instance by typing something into it). You may want to temporarily switch focus to a different application, and then go back to finish the typing. You'd expect the focus to return to the same edit control you activated before. The dialog is supposed to remember which control had been active before losing focus, and give the focus back to it upon being reactivated. A dialog takes care of it, transparently. In contrast, if you arrange a few controls in an arbitrary (non-dialog) window, you'd have to add special logic to its controller, to take care of correct focus restoration.
There's more! A dialog provides means of navigation between various controls using the keyboard. You can move focus from one group to another by pressing the tab key, and you can move within one group (e.g., of radio buttons) by pressing the arrow keys.
So why, you might ask, didn't I make the top-level window of the calculator a dialog? It would have solved several problems all at once. Indeed, there are some applications that use a dialog as their main window--the Windows calculator comes to mind. But I wanted to write a more mainline Windows program, with a menu, a status bar and a resizable main window. Taking all this into account, it was simpler to just put together a few controls and stick them into a resizable parent window.
A dialog provides a generic way of handling all the controls it owns. But if you want the dialog to do something useful, you have to intercept some of the communications between the controls and the dialog. The least you can do is to end the dialog when the user presses the OK (or CANCEL) button. If there is some data the user inputs through the dialog, you might want to retrive it from one (or more) of its controls and pass it on to the caller. You might also want to mediate between some of the controls. All this is possible through the use of a dialog procedure.
A dialog procedure is a simplified version of a window procedure. All messages that the dialog receives from its controls are first filtered by this user-defined procedure. The main difference between a dialog procedure and a window procedure is that a dialog procedure doesn't call DefWindowProc, but instead returns FALSE when it doesn't care about a particular message. If, on the other hand, it does process a message, it is supposed to return TRUE. Notice that these are Windows-defined Boolean values, not the C++ true and false.
That's the theory behind dialogs--now we have to come up with a way to encapsulate them into something easier to use and less error-prone. A dialog is like a function that uses UI to get its data. You "call" a dialog with some initial data (the arguments) and it returns a result, presumbly obtained from the user. We can always encapsulate the in- and out- data into some user-defined data structure. But we also have to define the active part, some kind of a controller that could be plugged into the generic dialog procedure. We can even combine the in/out data with this controller, so that it can operate on them in response to control messages.
Here's the simplest example of how one may use this abstraction in order to display the About dialog.
AboutCtrl ctrl; Dialog::Modal dialog (_win, IDD_ABOUT, ctrl);
The dialog object takes three arguments, the owner window (here, it's the top-level window), the dialog id (to identify the script in the resources), and the controller object. The controller is derived from the library class, Dialog::ModalController. In this absolutely minimal implementation, it only overrides the OnCommand method to intercept the OK button press.
bool AboutCtrl::OnCommand (int ctrlId, int notifyCode) throw (Win::Exception) { if (ctrlId == IDOK) { EndOk (); return true; } return false; }
The Save dialog has some more functionality. It contains a string, _path, that will store the path to be returned by the dialog. It has a Win::Edit object which it uses to communicate with the edit control present in the dialog box. The OK handler retrieves the string from the edit control and copies it into _path. The CANCEL handler just terminates the dialog by calling the method Dialog::ModalController::EndCancel.
bool SaveCtrl::OnCommand (int ctrlId, int notifyCode) throw (Win::Exception) { if (ctrlId == IDOK) { SetPath (_edit.GetText ()); EndOk (); return true; } else if (ctrlId == IDCANCEL) { EndCancel (); return true; } return false; }The caller can distinguish between a successful input (OK was pressed) and an aborted input (CANCEL was pressed) by calling the method IsOk.
SaveCtrl ctrl; Dialog::Modal dialog (_win, IDD_SAVE, ctrl); if (dialog.IsOk ()) { std::string const & path = ctrl.GetPath (); Serializer out (path); _calc.Serialize (out); }
The controller must also initialize the _edit object by providing it with the dialog window (which is the parent to this edit control) and a control id. This is done inside the OnInit method.
void SaveCtrl::OnInitDialog () throw (Win::Exception) { _edit.Init (GetWindow (), IDC_EDIT); }
Notice that we are using the same Win::Edit class that we used in the top-level window to encapsulate its edit control. The only difference is that here we don't use a maker to create the edit control. The dialog creates the control, and we can retrieve its window handle by calling GetDlgItem inside Win::Edit::Init.
The Load dialog is even more advanced. It has a ListBox control which is used to display the list of files in the current directory. It also has a static text control which is used by the ListBox to display the path to current directory. The ListDirectory method of the Win::ListBox takes care of the listing of the directory and the initialization of the static text.
void LoadCtrl::OnInitDialog () throw (Win::Exception) { _listBox.Init (GetWindow (), IDC_LIST); _listBox.ListDirectory (GetWindow (), GetBuffer (), IDC_STATICPATH); }
When the user clicks the OK button or double-clicks on an item, we try retrieve the full path of the selection from the ListBox. The method, GetSelectedPath, fills the buffer with data and returns true if the selection was a directory (not a file). If it's a directory, we change the current directory and re-initialize the ListBox. If it's a file, we end the dialog and let the caller retrieve the path from the buffer.
bool LoadCtrl::OnCommand (int ctrlId, int notifyCode) throw (Win::Exception) { if (ctrlId == IDOK || ctrlId == IDC_LIST && notifyCode == LBN_DBLCLK) { if (_listBox.GetSelectedPath (GetWindow (), GetBuffer (), GetBufLen ())) { // directory selected ChangeDirectory (); } else if (_listBox.IsSelection ()) EndOk (); else EndCancel (); return true; } else if (ctrlId == IDCANCEL) { EndCancel (); return true; } return false; }
I must admit that this type of UI for retrieving files is somehow obsolete. For one, it doesn't display long file names. Also, navigation between directories is not very intuitive. There is a Windows API, called GetOpenFileName, which has all the functionality of our Load dialog and a much better user interface. I chose the old-fashioned way (still used in some applications) only to illustrate the use of dialog boxes with non-trivial controls.
Pointers to members.
In the command-line version of our program we had to use a special parser to decipher user commands. In Windows it is much simpler. Commands are entered mainly by making menu selections. The obvious advantage of such an approach is that the user doesn't have to remember the exact name and syntax of each command. They are listed and nicely organized in a system of menus. Even if a program offers other means of entering commands, like keyboard shortcuts or toolbars, menus still play an important role in teaching a newcomer what functionality is available.
It's relatively easy to equip a Windows program with a menu. You can define it in the resource script, which can be made really easy by using a resource editor. You give the menu a name, which you then pass to the Win::ClassMaker, or to each individual Win::Maker.
Each menu item is given a unique id, called command id. This id becomes one of the arguments to the WM_COMMAND message, which is sent whenever the user selects a menu item. All you have to do is to implement the OnCommand method of the top-level controller to respond to these commands.
The obvious implementation of OnCommand would be to write a big switch statement with a case for each command. Did I hear "switch"? Can't we come up with something better? Can we hide the switch in the library, just like we did with the window procedure? Not really--unlike Windows messages which are defined up-front by Windows and are not supposed to change, each menu comes with its own completely different set of commands and command ids.
On the other hand, a menu command doesn't come with a variable number and type of arguments. In fact a menu command has no arguments--the arguments, if needed, are later picked up by dialog boxes. So why not organize all commands into an array of pointers to functions that take no arguments, just like we organized built-in functions in the calculator. There is only one problem in such a scheme--commands would have to be free functions. On the other hand, most of them need to have access to the model (the Calculator). We don't want to make the calculator a global object and give commands the knowledge of its name. Such implicit dependency through global objects is a sign of bad design and will cause maintenance nightmares in more complex programs.
How about creating a separate object, Commander, whose methods would be the commands? Such an object can be made a member of TopController and be initialized in the controller's OnCreate method. We could easily give it access to the Calculator without making it global. We could create a vector of pointers to Commander methods, and use it for dispatching menu commands. This is the same scheme that we used for dispatching function calls in the calculator.
But what is a pointer to method? Unlike a free function, a (non-static) method can only be called in the context of an object, which becomes the provider of the this pointer. Also, a definition of a pointer to method must specify the class, whose method it might point to. A pointer to a Controller method is a different beast altogether than a pointer to a Commander method. This requirement is reflected in the declaration of a pointer to member. For instance, a pointer to the Commander method, pCmdMethod, that takes no arguments and has no return value will be declared like this:
void (Commander::*pCmdMethod) ();
Such a pointer can be initialized to point to a particular method, e.g. Program_About, of the Commander.
pCmdMethod = &Commander::Program_About;
Given an object, _commander, of the class Commander, we can call its method through the pointer to member.
(_commander.*pCmdMethod) ();
Similarly, if _commander is a pointer rather than an object (or reference), the syntax changes to:
(_commander->*pCmdMethod) ();
Let's define all the commands as members of Commander and give them names corresponding to their positions in the menu. The definition and initialization of the command vector would look something like this:
typedef void (Commander::*CmdMethod) (); const CmdMethod CmdTable [] = { &Commander::Program_About, &Commander::Program_Exit, &Commander::Memory_Clear, &Commander::Memory_Save, &Commander::Memory_Load, 0 // sentinel };
So how would our CmdTable work with a menu system? What happens when the user selects a menu item? First, the message WM_COMMAND is sent to the generic window procedure, which calls the OnCommand method of our TopController. This method should somehow translate the command id (defined in the resource script together with the menu) to the appropriate index into the CmdTable, and execute the corresponding method.
(_commander->*CmdTable [idx]) ();
The translation from command id to an index is the weakest point of this scheme. In fact, the whole idea of defining your menu in the resource file is not as convenient as you might think. A reasonably complex application will require dynamic changes to the menu depending on the current state of the program. The simplest example is the Memory>Save item in the calculator. It would make sense for it to be inactive (grayed out) as long as there has been no user-defined variable added to memory. We could try to somehow re-activate this menu item when a variable is added to memory. But that would require the model to know something about the user interface--the menu. We could still save the day by making use of the notification sink. However, there is a better and more general approach--dynamic menus.
First, let's generalize and extend the idea of a command table. We already know that we need there a pointer to member through which we can execute commands. We can also add another pointer to member through which we can quickly test the availability of a given command--this will enable us to dynamically gray out some of the items. A short help string for each command would be nice, too. Finally, I decided that it will be more general to give commands string names, rather than integer identifiers. Granted, searching through strings is slower than finding an item by id, but usually there aren't that many menu items to make a perceptible difference. Moreover, when the program grows to include not only menus, but also accelerators and toolbars; being able to specify commands by name rather than by offset is a great maintainability win.
So here's the definition of a command item, the building block of a command table.
namespace Cmd { template <class T> class Item { public: char const * _name; // official name void (T::*_exec)(); // execute command Status (T::*_test)() const; // test commnad status char const * _help; // help string }; }
If we want to reuse Cmd::Item we have to make it a template. The parameter of the template is the class of the particular commander whose methods we want to access.
This is how the client creates a command table and initializes it with appropriate strings and pointers to members.
namespace Cmd { const Cmd::Item<Commander> Table [] = { { "Program_About", &Commander::Program_About, &Commander::can_Program_About, "About this program"}, { "Program_Exit", &Commander::Program_Exit, &Commander::can_Program_Exit, "Exit program"}, { "Memory_Clear", &Commander::Memory_Clear, &Commander::can_Memory_Clear, "Clear memory"}, { "Memory_Save", &Commander::Memory_Save, &Commander::can_Memory_Save, "Save memory to file"}, { "Memory_Load", &Commander::Memory_Load, &Commander::can_Memory_Load, "Load memory from file"}, { 0, 0, 0} }; }
Here, Commander is the name of the commander class defined in the calculator.
Command table is used to initialize the actual command vector, Cmd::VectorExec, which adds functionality to this data structure. The relationship between Cmd::Table and Cmd::VectorExec is analogous to the relationship between Function::Array and Function::Table inside the calculator. As before, this scheme makes it very easy to add new items to the table--new commands to our program.
Cmd::VectorExec has to be a template, for the same reason Cmd::Items have. However, in order not to templatize everything else that makes use of this vector (in particular, the menu system) I derived it from a non-template class, Cmd::Vector, that defines a few pure virtual functions and some generic functionality, like searching commands by name using a map.
The menu provides acces to the command vector. In a dynamic menu system, we initialize the menu from a table. The table is organized hierarchicaly: menu bar items point to popup menus which contain commands. For instance, this is what the initialization table for our calculator menu looks like (notice that command that require further user input--a dialog--are followed by three dots):
namespace Menu { const Item programItems [] = { {CMD, "&About...", "Program_About"}, {SEPARATOR, 0, 0}, {CMD, "E&xit", "Program_Exit"}, {END, 0, 0} }; const Item memoryItems [] = { {CMD, "&Clear", "Memory_Clear"}, {SEPARATOR, 0, 0}, {CMD, "&Save...", "Memory_Save"}, {CMD, "&Load...", "Memory_Load"}, {END, 0, 0} }; //---- Menu bar ---- const BarItem barItems [] = { {POP, "P&rogram", "Program", programItems}, {POP, "&Memory", "Memory", memoryItems}, {END, 0, 0, 0} }; }
Note that each item contains the display name with an embedded ampersand. This ampersand is translated by Windows into a keyboard shortcut (not to be confused with a keyboard accellerator). The ampersand itself is not displayed, but the letter following it will be underlined. The user will then be able to select a given menu item by pressing the key corresponding to that letter while holdnig the Alt key. All items also specify command names--for popup items, these are the same strings that were used in the naming of commands. Menu bar items are also named, but they don't have commands associated with them. Finally, menu bar items have pointers to the corresponding popup tables.
Similar tables can be used for the initialization of accelerators and toolbars.
The actual menu object, of the class Menu::DropDown, is created in the constructor of the View. It is initialized with the table of menu bar items, Menu::barItems, shown above; and a Cmd::Vector object (initialized using Cmd::Table). The rest is conveniently encapsulated in the library.
You might be interested to know that, since a menu is a resource (released using DestroyMenu API), the class Menu::Maker has transfer semantics. For instance, when we create a menu bar, all the popup menus are transfered to Menu::BarMaker, one by one.
But that's not the end of the story. We want to be able to dynamically activate or deactivate particular menu items. We already have Commander methods for testing the availability of particular commands--they are in fact accessible through the command vector. The question remains, what is the best time to call these methods? It turns out that Windows sends a message, WM_INITMENUPOPUP, right before opening up a popup menu. The handler for this message is called OnInitPopup. We can use that opportunity to manipulate the menu while testing for the availability of particular commands. In fact, since the library class Menu::DropDown has access to the command vector, it can implement the RefreshPopup method once and for all. No need for the client to write any additional code.
Displaying short help for each selected menu item is also versy simple. When the user moves the mouse cursor to a popup menu item, Windows sends us the message, WM_MENUSELECT, which we can process in the controller's method, OnMenuSelect. We just call the GetHelp method of the command vector and send the help string to the status bar.
Let's now review the whole task from the point of view of the client. What code must the client write to make use of our dynamic menu system? To begin with, he has to implement the commander, which is just a repository of all commands available in the particular program. Two methods must be implemented for each command: one to execute it and one to test for its availability.
The role of the commander is:
Once the commander is in place, the client has to create and statically initialize a table of commands. In this table all commands are given names and assigned short help strings. This table is then used in the initialization of the command vector.
The menu system is likewise initialized by a table. This table contains command names, display names for menu items and markers differentiating between commands, separators and bar items. Once the menu bar is ready, it has to be attached to the top-level window. However, don't try to attach the menu inside the constructor of View. Both View and Controller must be fully constructed before adding the menu. Menu attachment results in a series of messages sent to the top level window (most notably, to resize its client area), so the whole controller has to be ready to process them in an orderly manner.
Finally, the user must provide a simple implementations of OnInitPopup and, if needed, OnMenuSelect, to refresh a popup menu and to display short help, respectively.
Because major data structures in the menu system are initialized by tables, it is very easy to change them. For instance, reorganizing the menu or renaming menu items requires changes only to a single file--the one that contains the menu table. Modifying the behavior of commands requires only changes to the commander object. Finally, adding a new command can be done in three independent stages: adding the appropriate methods to the commander, adding an entry to the command table, and adding an item to the menu table. It can hardly be made simpler and less error-prone.
Fig 1. shows the relationships and dependencies between various elements of the controller.
Fig 1. The relationships between various elements of the controller.
Because Commander doesn't have access to View, it has no direct way to force the refreshing of the display after such commands as Memory_Clear or Memory_Load. Again, we can only solve this problem by brute force (refresh memory display after every command) or some kind of notifications. I decided to use the most generic notification mechanism--sending a Windows message. In order to force the clearing of the calculator's memory display, the Commander sends a special user-defined message MSG_MEMCLEAR to the top-level window.
Remember, a message is just a number. You are free to define your own messages, as long as you assign them numbers that won't conflict with any messages used by Windows. There is a special identifier WM_USER which defines a number that is guaranteed to be larger than that of any Windows-specific message.
To process user-defined messages, I added a new handler, OnUserMessage, to the generic Win::Controller. This handler is called whenever the message is larger or equal to WM_USER.
One more change is necessary in order to make the menus work correctly. We have to expand the message loop to call TranslateMessage before DispatchMessage. TranslateMessage filters out these keyboard messages that have to be translated into menu shortcuts and turns them into WM_COMMAND messages. If you are also planning on adding keyboard accelerators (not to be confused with keyboard shortcuts that are processed directly by the menu system)--for instance, Ctrl-L to load memory--you'll have to further expand the message loop to call TranslateAccellerator.
Although we won't discuss modeless dialogs here, you might be interested to know that they also require a pre-processing step, the call to IsDialogMessage, in the message loop. It makes sense to stick all these accellerators and modeless dialog handles in a separate preprocessor object, of the class Win::MessagePrepro. It's method Pump enters the message loop and returns only when the top-level window is destroyed. One usually passes the preprocessor object to the top-level controller, to make it possible to dynamically switch accellerator tables or create and destroy modeless dialogs.
Next Section: Software Project | http://www.relisoft.com/book/win/4app.html | crawl-001 | refinedweb | 7,393 | 54.42 |
DTP Message Bundle Conversion Tool
Contents
- 1 Introduction
- 2 Improvements
- 3 Benefits
- 4 Conversion
Introduction
Starting from eclipse 3.1, a new type of resource bundle story is used to improve performance and provide other benefits such as: easily catch missing keys, and find unused keys. The eclipse platform core team provided a tool to aid the developers and I’ve made some improvements to it, which you can find at: I've used it in DTP to convert message bundles in some SQL Dev Tools plug-ins. This document gives an overview of how the converter can be used. You can find more about the new message bundle itself from this URL: Eclipse 3.1 Message Bundles NOTE: this is not an official product release, and will be moved to platform core team or removed in the future. See here
Improvements
You can download the modified converter from here. (If you're using Eclipse 3.5, please download the version modified by Anton Leherbauer at: here ) I have modified the tool in the following ways:
File comments
Keep the original legal declaration.
Default resouce bundle
Whenever you invoke the converter actions on a resource bundle class, a dialog will popup for you to select the corresponding resource bundle. The new tools will automatically select the messages.properties resource bundle in the same package to save your time.
Find missing keys
A new action Check missing keys... is added to the context menu when you right click on a resource bundle class. This action will compare the class with the resource bundle to search the fields that exist in the class but not in the resource bundle. If such missing keys are found, a dialog will popup with all the missing keys and you can copy them into the resource bundle to define the values.
Catch exceptions
Sometimes the refactor can not be performed successfully. The old tool just fails silently in such cases. The new tool will catch the exceptions during refactoring so that the conversion can continue. Of course, when the refactoring is done, you will find errors, which needs your manual modification.
Benefits
Using the conversion tool, it’s easy to identify the following problems:
Find duplicate keys
After the conversion, if you have duplicate keys, you will find duplicate field declarations in the resource bundle class, which shows as compilation errors.
Missing keys
During the refactoring, all the
Messages.getString("abc") calls are converted into
Messages.abc, If you haven’t defined such a resource in the resource bundle, you will get compilation errors.
Incorrect resource bundle calls
If the conversion can not proceed successfully, it may due to incorrect resource bundle calls, such as
getString(""), which doesn’t use any key as the parameter.
Incorrect resource bundle reference
If you have multiple Messages.java in different packages, it’s easy to reference the wrong resource bundle using the standard Java ResourceBundles approach. But with the new approach, you will easily find this problem.
Conversion
Preparation
Note that the message bundle access class is replaced when the tool is run. If you define extra code, constants, etc in that class then please read the notes below to ensure that you don't have problems.
Backup
The easiest way to protect your work is to backup before you proceed.
Extra helper methods:
Change the method body to be:
return NLS.bind(getString(key), binding);
Select the method name and from the context menu choose the "Inline" refactoring. This will replace calls to this method in your code with calls to the code in step 1. A small tip: the accelerator key for "Inline" is ALT+SHIFT+I.
Compilation errors
Please fix all compilation errors before using the tool, otherwise the refactoring will fail.
Steps
Here are the steps to use when converting your code. Download the modified version of the convertion tool and install the plug-in. Run Eclipse. Synchronize with the repository. (you will be using the Synchronize view as your compare browser to view changes) Select your message bundle access class. (e.g. the class which has the #getString(String) method in it) From the context menu, choose "Convert to New Bundle". Choose the class's associated .properties file from the resulting "Open Resource..." dialog. Use the Synchronize view to review the changes. Release the new code.
Post Processing
Editor messages
Actions extending
org.eclipse.ui.texteditor.ResourceAction need a resource bundle as the parameter to the constructor. In this case, you need to separate the messages into 2 resource bundles. E.g. one is called "messages.properties", which holds messages used by the fields in the resource bundle access class; the other is called "ConstructedEditorMessages.properties", which holds messages used by the
ResourceActions. Below is the code snippet in the resource bundle access class:
public final class Messages extends NLS { private static final String BUNDLE_FOR_CONSTRUCTED_KEYS= "org.eclipse.datatools.sqltools.internal.sqlscrapbook.editor.ConstructedEditorMessages";//$NON-NLS-1$ private static ResourceBundle fgBundleForConstructedKeys= ResourceBundle.getBundle(BUNDLE_FOR_CONSTRUCTED_KEYS); /** * Returns the message bundle which contains constructed keys. * * @return the message bundle */ public static ResourceBundle getBundleForConstructedKeys() { return fgBundleForConstructedKeys; } private static final String BUNDLE_NAME = "org.eclipse.datatools.sqltools.internal.sqlscrapbook.editor.messages";//$NON-NLS-1$...
Dynamic constructed keys
Sometimes we need to construct a key dynamically, such as:
getString("key" + i), where i is an integer. We have 2 ways to handle this problem: reflection and switch case. The following is a code snippet of the reflection approach:
/** * Gets a resource string by field name. This is useful when the field name is constructed ad hoc. * @param fieldName * @return */ public static String getString(String fieldName) { Class c = Messages.class; try { Field field = c.getDeclaredField(fieldName); return (String)field.get(null); } catch (Exception e) { return "!" + fieldName + "!"; } } | http://wiki.eclipse.org/Message_Bundle_Conversion_Tool | CC-MAIN-2018-09 | refinedweb | 953 | 57.16 |
DB2 9 introduces new features and mechanisms for managing, storing, and querying XML data:
- XML data type enables DB2 to store XML documents in it's native hierarchical format.
- XML query language support is based on industry standards, including new XML extensions to SQL (also called SQL/XML).
- Support for validating XML data based on user-supplied schemas, which allows application developers and database administrators to enforce data integrity constraints for XML data stored in DB2. The DB2 Visual Studio 2005 Add-in is used for the examples in this article.
Code samples in this article refer to the CARPOOL table, which tracks carpool information for San Francisco and San Jose. Listing 1 shows how this table is defined. Also ensure that the database is XML-enabled..
During DB2 installation, ensure are given a choice to create the DB2 SAMPLE database. Do so, accept the defaults, but be sure to select the XML and SQL objects and data option.
To check whether your system setup is successful, start Visual Studio .NET 2005. From the Visual Studio .NET, navigate to File > New > Project. In the New Project dialog box, you should see
IBM Projects in the left panel. Close the dialog box. In. CARPOOL table definition
We have two XML schemas, CarpoolInfo.xsd and USAddressType.xsd, where CarpoolInfo.xsd is referencing on USAddressType.
Listing 2. XML schema to be used for validating the XML document in CARPOOL table (CarpoolInfo.xsd)
Listing 3. CarpoolInfo's dependent XML schema (USAddress.xsd)
CARPOOL table contains columns based on both SQL data types and one column based on the new DB2 XML data type. This latter column, CARPOOLINFO, stores XML documents that include information such as a carpooler's address and start time. Figure 1 shows sample carpoolnfo XML document.
Figure 1. Sample XML document to be stored in the CARPOOL table.
You will now see how to insert, update, and validate an XML document in the CARPOOLINFO column. Listing 2 shows XML schema that is used for the purpose of validating an XML document before insertion into the CARPOOLINFO column.
To compile and run any .Net application, you need to create a new Visual Studio .Net project. If you've never worked with Visual Studio .Net before, here's a quick overview of how to accomplish those tasks:
- Launch the Visual Studio 2005.
- Create a new project. Select File > New > Project. Select Visual C# > Windows Application.
- Make a reference to the DB2 .Net data provider IBM.Data.DB2. Right-click on the References node in
DB2 9 enables users to register XML schemas and validate input documents against these schemas prior to insertion. XML schemas are part of the World Wide Web Consortium (W3C) industry standard; they enable users to specify the desired structure of compliant XML documents, such as the order and data types of acceptable XML elements, and the use of specific XML namespaces. DB2 Visual Studio 2005 Add-in tooling provides an easy way to register XML schema using a simple registration designer, but this article shows you how XML schema can be registered using .Net code. Once XML the schema is registered in the DB2 XML schema repository, it can be used for validating XML documents. Listing 5 shows one way of registering XML schema using the .Net code.
Listing 5. Register XML schema
Insert and validate XML data
Now that you have established DB2 connection and registered your XML schema, you can write SQL INSERT or UPDATE statements to write new XML data to tables that contain XML columns, and at the same time let DB2 validate XML data before insertion. DB2 can store any well-formed XML document up to 2GB. Listing 6 shows one way of inserting a row into the CARPOOL table. In this case, the XML document for the CARPOOL info column is read from the string.
Listing 6. Method to insert and update XML data
Now examine this code. After establishing a database connection, the method creates three DB2Commands; one for insert, one for update, and one for delete. Insert and update commands contain four parameter markers for the regular column values and the fifth parameter marker for the XML column, the method also uses the DB2 XMLVALIDATE function and passes Carpoolinfo XML schema to it for validation.
Now that you have stored data in the CARPOOLINFO table, you are ready to query it. DB2 enables you to write different types of queries to extract both relational and XML data. You can write a simple query that retrieves entire XML documents, or a query that retrieves portions of XML documents based on XML and relational query predicates. This article demonstrates a query that:
- Filters data based on XML predicates
- Retrieves portions of qualifying XML documents along with data stored in a traditional SQL column
In this article, DB2's XMLExists()function is being used. The sample application in this article uses XMLExists() to illustrate a common programming task: retrieving portions of XML documents. The example shown in Listing 7 returns the carpool information for carpoolers who live in the city of San Francisco or San Jose. As such, this example projects and restricts both traditional SQL and XML data.
Listing 7. Query XML data
The WHERE clause uses DB2's XMLExists() function to restrict the data to be returned. It specifies that returned XML documents include only those found in rows in which the CARPOOLINFO's city is of a certain value (San Francisco or San Jose). In this sample query, XMLExists() instructs DB2 to determine if a given XML document contains a CARPOOL address that includes the specified city. The PASSING clause specifies where XML documents can be found (in the carpoolinfo column).
IBM DB2 enables programmers to update and delete XML data using familiar SQL statements. To update and delete XML data stored in DB2, you use SQL UPDATE and DELETE statements. These statements can include SQL/XML functions that restrict the target rows and columns based on the XML element values stored within XML columns. For example, you can delete rows containing information about carpoolers who live in a specific city or update XML (and non-XML data) only for carpoolers whose carpool's start time is within in a given time. Because the syntax for using SQL/XML functions in UPDATE and DELETE statements is the same syntax for using them in SELECT statements, the full code samples won't be repeated.
Learn
- "Develop proof-of-concept .NET applications" (developerWorks): Create proof-of-concept applications to access relational and XML data in DB2 9, using Microsoft Visual Studio .NET 2005.
- "Develop proof-of-concept .NET applications, Part 1: Create database objects in DB2 Viper using .NET" (developerWorks, May 2006): Find the application specifications, database design, and how to create DB2 relational database objects required in the applications.
- "Develop proof-of-concept .NET applications, Part 2: Wire DB2 data to Windows applications" (developerWorks, June 2006): Create a Windows desktop application in .NET to consume the DB2 data.
- "Develop proof-of-concept .NET applications, Part 3: Wire DB2 data to Web applications" (developerWorks, June 2006): Create a Web application in ASP.NET and wiring the DB2 data to the Web application running in a browser.
- DB2 9 product site: Get more information about DB2 9, the new data server (formerly known as Viper) that seamlessly integrates XML and relational data.
- DB2 for .NET: Learn more about DB2 Add-ins for Visual Studio .NET.
- IBM DB2 Database for Linux, UNIX, and Windows Information Center: Find information that you need to use the DB2 Information Management family of products and features.
- Visual Studio 2005 Developer Center: MSDN resources for Microsoft Visual Studio .NET 2005.
-.
- Participate in developerWorks blogs and get involved in the developerWorks community. | http://www.ibm.com/developerworks/data/library/techarticle/dm-0611farahbod2/index.html | crawl-003 | refinedweb | 1,291 | 55.03 |
Photo by Ferenc Almasi on Unsplash
React is known for its performance by using the Virtual DOM (VDOM). It only triggers an update for the parts of the real DOM that have changed. In my opinion, it is important to know when React triggers a re-rendering of a component to be able to debug performance issues and develop fast and efficient components.
After reading this article, you should have a good understanding of how React rendering mechanism is working and how you can debug re-rendering issues.
Table of Contents
- What is rendering?
- Virtual DOM
- What causes a render in React?
- Debug why a component rendered
- Conclusion
What is rendering?
First, we need to understand what rendering in the context of a web application means.
If you open a website in the browser, what you see on your screen is described by the DOM (Document Object Model) and represented through HTML (Hypertext Markup Language).
The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.
DOM nodes are created by React if the JSX code is converted. We should be aware that real DOM updates are slow as they cause a re-drawing of the UI. This becomes a problem if React components become too big or are nested on multiple levels. Each time a component is re-rendered its JSX is converted to DOM nodes which takes extra computation time and power. This is where React’s Virtual DOM comes into the game.
Virtual DOM
React uses a Virtual DOM (VDOM) as an additional abstraction layer on top of the DOM which reduces real DOM updates. If we change the state in our application, these changes are first applied to the VDOM. The React DOM library is used to efficiently check what parts of the UI really need to be visually updated in the real DOM. This process is called diffing and is based on these steps:
- VDOM gets updated by a state change in the application.
- New VDOM is compared against a previous VDOM snapshot.
- Only the parts of the real DOM are updated which have changed. There is no DOM update if nothing has changed.
More details about this mechanism can be found in React’s documentation about reconciliation.
What causes a render in React?
A rendering in React is caused by
- changing the state
- passing props
- using Context API
React is extremely careful and re-renders “everything all the same time”. Losing information by not rendering after a state change could be very dramatic this is why re-rendering is the safer alternative.
I created a demo project on StackBlitz which I will use in this article to demonstrate React’s rendering behavior:
The project contains a parent component, which basically consists of two child components where one component receives props and the other not:
class Parent extends React.Component { render() { console.warn('RENDERED -> Parent'); return ( <div> <Child /> <Child name={name} /> </div> ); } }
As you can see, we log a warning message in the console each time the component’s
render function is called. In our example, we use functional components and therefore the execution of the whole function is similar to the
render function of class components.
If you take a look at the console output of the StackBlitz demo, you can see that the render method is called three times:
- Render
Parentcomponent
- Render
Childeven if it has no props
- Render
Childwith
namevalue from state as prop
If you now modify the name in the input field we trigger a state change for each new value. Each state change in the parent component triggers a re-rendering of the child components even if they did not receive any props.
Does it mean that React re-renders the real DOM each time we call the
render function? No, React only updates the part of the UI that changed. A render is scheduled by React each time the state of a component is modified. For example, updating state via the
setStatehook will not happen immediately but React will execute it at the best possible moment.
But calling the
render function has some side-effects even if the real DOM is not re-rendered:
- the code inside the render function is executed each time, which can be time-consuming depending on its content
- the diffing algorithm is executed for each component to be able to determine if the UI needs to be updated
Visualize rendering
It is possible to visualize React’s VDOM as well as the native DOM rendering in the web browser.
To show the React’s virtual render you need to install React DevTools in your browser. You can then enable this feature under
Components -> View Settings -> Highlight updated when component render. This way we can see when React calls the render method of a component as it highlights the border of this component. This is similar to the console logs in my demo application.
Now we want to see what gets updated in the real DOM, therefore we can use the Chrome DevTools. Open it via
F12, go to the three-dot menu on right and select
More tools -> Rendering -> Paint flashing:
Debug why a component rendered
In our small example, it was quite easy to analyze what action caused a component to render. In larger applications, this can be more tricky as components tend to be more complex. Luckily, we can use some tools which help us to debug what caused a component to render.
React DevTools
We can again use the Profiler of the React DevTools. This feature records why each component rendered while the profiling was active. You can enable it in the React DevTools Profiler tab:
If we now start the profiling, trigger a state change, and stop the profiling we can see that information:
But as you can see, we only get the information that the component rendered because of a state change triggered by hook but we still don’t know why this hook caused a rendering.
Why did you render?
To debug why a hook caused a React component to render we can use the npm package Why Did You Render.
It monkey patches React to notify you about avoidable re-renders.
So it is very useful to track when and why a certain component re-renders.
I included the npm package in my demo project on StackBlitz, to enable it you need to enable it inside the
Parent.jsx component:
Parent.whyDidYouRender = true;
If we now trigger a parent re-rendering by toggling the “Toggle Context API” checkbox we can see additional console logs from the library:
The console output is:
{Parent: ƒ} Re-rendered because the props object itself changed but its values are all equal. This could have been avoided by making the component pure, or by preventing its father from re-rendering. More info at prev props: {} !== {} :next props {App: ƒ} Re-rendered because of hook changes: different objects. (more info at) {prev : false} !== {next : true}
As you can see from the output we get detailed information on what caused the re-rendering (for example if it was a prop or hook change) and which data were compared, for example, which props and state were used for the diffing.
Conclusion
In this article, I explained why React re-renders a component and how you can visualize and debug this behavior. I learned a lot while writing this article and building the demo application. I also hope that you got a better understanding of how React rendering works and that you now know how to debug your re-rendering issues.
In the future, I will write more about React, so follow me on Twitter to get notified about the latest articles.
Discussion (2)
I think it's worth noting that for the most part re-renders are a feature, not a bug in React applications. It's very standard to see complex components render 3-4 times for certain changes (especially big ones that bare side effects). Slow renders are the real pain point, and usually those should be addressed (either by memoization or smarter component hierarchy).
Agreed.
Sometimes it helps to move several connected hooks to a new custom hook. That way costly re-renders can be decreased. | https://dev.to/mokkapps/debug-why-react-re-renders-a-component-3i8e | CC-MAIN-2021-17 | refinedweb | 1,395 | 60.04 |
Psithon Tutorial: Using PSI4 as an Executable¶
Note
Psithon and PsiAPI refer to two modes of interacting with PSI4. In
Psithon mode, you write an input file in our domain-specific language
(not quite Python) where commands don’t have
psi4. in front, then
submit it to the executable
psi4 which processes the Psithon into
pure Python and runs it internally. In PsiAPI mode, you write a pure
Python script with
import psi4 at the top and commands are behind
the
psi4. namespace, then submit it to the
python interpreter.
Both modes are equally powerful. This tutorial covers the Psithon
mode.
Note
Some PSI4 functions and keywords have aliases. For example,
frequency(),
frequencies(), and
freq() all work to
obtain vibrational frequencies.
Basic Input File Structure¶
PSI:
If you give an input name but no output name, then the output name will be the same as the input name (replacing any ”.in” or ”.dat” extension by ”.out”).
Sample Input Files¶
Below, we will provide a few simple input files as examples. A large number of sample input files, covering everything from single-point energies using density-functional theory to response properties from coupled-cluster theory, can be found in the psi4/samples directory.
Running a Basic Hartree–Fock Calculation¶
In our first example, we will consider a Hartree–Fock SCF computation for the water molecule using a cc-pVDZ basis set. We will specify the geometry of our water molecule using a standard Z-matrix.
# Any line starting with the # character is a comment line #! Sample HF/cc-pVDZ H2O computation memory 600 mb molecule h2o { O H 1 0.96 H 1 0.96 2 104.5 } set basis cc-pVDZ energy('scf')
Note
The memory and basis set specifications are placed before the energy function is called. Any user options need to be set before the procedure they are meant to affect.
For your convenience, the above example can be found in tu1-h2o-energy. You can run it if you wish. Once PSI4 is in your path (see the User Configuration section of the installation instructions), you can run this computation by typing
If everything goes well, the computation should complete and should report a final restricted Hartree–Fock energy in a section like this: Sec. Compiling and Installing from Source).
This very simple input is sufficient to run the requested information. Notice that we didn’t tell the program some otherwise useful information like the charge electrons are paired. For example, let’s run a computation
on methylene (CH2), given
at the end of the Z-matrix specification.
#! Sample UHF/6-31G** CH2 computation molecule ch2 { 0 3 C H 1 R H 1 R 2 A R = 1.075 A = 133.93 } set basis 6-31G** set reference uhf energy ('scf')
This sample input can be found in
tu2-ch2-energy and as
before it can be run through the command
psi4 input.dat output.dat
(actually, because
psi4 by default looks for an input file named
input.dat and writes by default to a file called
output.dat, in this
case one could also just type
psi4). If it works, it should print
the final energy as
Notice we added a new keyword,
set reference uhf, to the input.).
Geometry Optimization and Vibrational Frequency Analysis¶
The above examples were simple single-point energy computations
(as specified by the
energy() function). Of course there are other
kinds of computations to perform, such as geometry optimizations and
vibrational frequency computations. These can be specified by replacing
energy() with
optimize() or
frequency(), respectively.
Here’s an example of optimizing the H2O molecule using Hartree–Fock with a cc-pVDZ basis set (located in tu3-h2o-opt).
#! Optimize H2O HF/cc-pVDZ molecule h2o { O H 1 0.96 H 1 0.96 2 104.5 } set basis cc-pVDZ optimize('scf')
This should perform a series of gradient computations. The gradient points
which way is downhill in energy, and the optimizer then modifies the
geometry to follow the gradient. After a few cycles, the geometry should
converge with a message like
Optimization is).
To get harmonic vibrational frequencies, it’s important to keep in mind that the values of the vibrational frequencies are a function of the molecular geometry. Therefore, it’s important to obtain the vibrational frequencies at the OPTIMIZED GEOMETRY. We could set up a second input file to perform the vibrational frequency analysis, being very careful to copy over the optimized geometry from the bottom of the output file for the geometry optimization. This geometry could be specified in either z-matrix or Cartesian formats. However, there’s a much easier way to do this. If we specify a vibrational frequency analysis in the same input file as the optimization, after the optimization function has been called, then the optimized geometry will automatically be carried over.
So, it’s easiset to do the optimization and vibrational frequency analysis together. This can be specified as follows (see test case tu4-h2o-freq):
#! Optimization followed by frequencies H2O HF/cc-pVDZ molecule h2o { O H 1 0.96 H 1 0.96 2 104.5 } set basis cc-pVDZ optimize('scf') scf_e, scf_wfn = frequencies('scf', return_wfn=True, dertype=1)
The program will do the same optimization as in our previous example, but then it will follow it with some computations to obtain the Hessian (second derivative matrix) of the electronic energy with respect to nuclear displacements. From this, it can obtain the harmonic vibrational frequencies, given below (roundoff errors of around 0.1 cm-1 may exist):
Notice that the symmetry type of the normal modes is specified (A1, A1, B2). The program also prints out the normal modes in terms of Cartesian coordinates of each atom. For example, the normal mode at 1776 cm-1 is:. The vibrational frequencies are sufficient to obtain vibrational contributions to enthalpy (H), entropy (S), and Gibbs free energy (G). Similarly, the molecular geometry is used to obtain rotational constants, which are then used to obtain rotational contributions to H, S, and G.:
Here’s the second half of the input, where we specify the computation options:
Before, we have been setting keywords individually with commands like
set basis cc-pVDZ. Because we have a few more options now, it’s
convenient to place them together into the
set
block, bounded by
{...}. This
will set all of these options as “global” options (meaning that they are
visible to all parts of the program). Most common PSI4 options can be
set in a globals section like this. If an option needs to be visible
only to one part of the program (e.g., we only want to increase the
energy convergence in the SCF code, but not the rest of the
code), it can be placed in a section of input visible to that part of the
program (e.g.,
set scf e_convergence 1.0E-8). with
scf_type DF. with
freeze_core True. The SAPT
procedure is invoked with the simple call,
energy('sapt0'). This
call later in this-1
(
Elst10,r where the 1 indicates the first-order
perturbation theory result with respect to the intermolecular interaction,
and the 0 indicates zeroth-order with respect to intramolecular electron
correlation). The next most attractive contribution is the
Disp20
term (2nd order intermolecular dispersion, which looks like an MP2 in which
one excitation is placed on each monomer), contributing an attraction of
-1.21 kcal mol-1..
Potential Surface Scans and Counterpoise Correction Made Easy with Psithon¶
Finally, let’s consider an example that shows how the Python driver in PSI4 simplifies some routine tasks. PSI4 can interpret valid Python code in addition to the computational chemistry directives we’ve seen in the previous examples; we call this mixture Psithon. The Python computer language is very easy to pick up, and even users previously unfamiliar with Python can use it to simplify tasks by modifying some of the example input files supplied with PSI4 in the psi4/samples directory.
Suppose you want to do a limited potential energy surface scan, such as
computing the interaction energy between two neon atoms at various
interatomic distances. One simple but unappealing way to do this is to
create separate input files for each distance to be studied. Most of
these input files are identical, except that the interatomic distance is
different. Psithon lets you specify all this in a single input file,
looping over the different distances with an array like this:
Rvals=[2.5, 3.0, 4.0].
Let’s also counter
molecule block can be used to separate monomers.
So, we’re going to do counterpoise-corrected CCSD(T) energies for Ne2 at a series of different interatomic distances. And let’s print out a table of the interatomic distances we’ve considered, and the CP-corrected CCSD(T) interaction energies (in kcal mol-1) at each geometry. Doing all this in a single input is surprisingly easy in PSI4. Here’s the input (available as tu6-cp-ne2).
#! Example potential energy surface scan and CP-correction for Ne2 molecule dimer { Ne -- Ne 1 R } Rvals=[2.5, 3.0, 4.0] set basis aug-cc-pVDZ set freeze_core True # Initialize a blank dictionary of counterpoise corrected energies # (Need this for the syntax below to work) ecp = {} for R in Rvals: dimer.R = R ecp[R] = energy('ccsd(t)', bsse_type = 'cp') psi4.print_out("\n") psi4.print_out("CP-corrected CCSD(T)/aug-cc-pVDZ interaction energies\n\n") psi4.print_out(" R [Ang] E_int [kcal/mol] \n") psi4.print_out("-----------------------------------------------------\n") for R in Rvals: e = ecp[R] * psi_hartree2kcalmol psi4.print_out(" %3.1f %10.6f\n" % (R, e))
First, you can see the
molecule block has a couple dashes to
separate the monomers from each other. Also note we’ve used a Z-matrix to
specify the geometry, and we’ve used a variable (
R) as the
interatomic distance. We have not specified the value of
R in
the
molecule block like we normally would. That’s because we’re
going to vary it during the scan across the potential energy surface.
Below the
molecule block, you can see the
Rvals array
specified. This is a Python array holding the interatomic distances we
want to consider. In Python, arrays are surrounded by square brackets, and
elements are separated by commas.
The next lines,
set basis aug-cc-pVDZ and
set freeze_core True,
are familiar from previous test cases. Next comes a slightly
unusual-looking line,
ecp = {}. This is Python’s way of initializing
a “dictionary”. We’re going to use this dictionary to store the
counterpoise-corrected energies as they become available. A dictionary is
like an array, but we can index it using strings or floating-point numbers
instead of integers if we want. Here, we will index it using
floating-point numbers, namely, the
R values. This winds up being
slightly more elegant than a regular array in later parts of the input
file.
The next section, beginning with
for R in Rvals:, loops over the
interatomic distances,
R, in our array
Rvals. In Python,
loops need to be indented, and each line in the loop has to be indented
by the same amount. The first line in the loop,
dimer.R = R,
sets the Z-matrix variable
R of the molecule called
dimer
to the
R value extracted from the
Rvals array. The next line,
ecp[R] = energy('ccsd(t)', bsse_type='cp'), computes the counterpoise-corrected
CCSD(T) energy and places it in the
ecp dictionary with
R as
the index. Note we didn’t need to specify ghost atoms, and we didn’t need
to call the monomer and dimer computations separately. The built-in
Psithon function
nbody_gufunc() does it all for us, automatically.
Near the very end of the output file,):
And that’s it! The only remaining part of the example input is a little table
of the different R values and the CP-corrected CCSD(T) energies, converted from
atomic units (Hartree) to kcal mol-1 by multiplying by the
automatically-defined conversion factor
psi_hartree2kcalmol. PSI4
provides several built-in physical constants and conversion factors, as
described in section Physical Constants.
Notice the loop over \(R\) to create
the table looks just like the loop over
R to run the different
computations, and the CP-corrected energies
ecp[R] are accessed the same
way they were stored. The
Our table is printed at the very end of the output file, and looks like this
The following section goes over Psithon in much more detail, but hopefully this example already makes it clear that many complex tasks can be done very easily in PSI4. | http://psicode.org/psi4manual/1.1/tutorial.html | CC-MAIN-2018-47 | refinedweb | 2,112 | 55.03 |
ViliVili
Vili is an open source dashboard for managing deployments to a Kubernetes cluster. It is built to:
- Manage both manual and continuous deployments
- Gate production deployments through our QA process
- Provide transparency into the current state of our infrastructure
Is Vili right for you?Is Vili right for you?
Vili is opinionated, to be able to set it up you need to:
- use GitHub for version control
- build Docker images to ship code and tag them with the Git SHA and branch they were built from
- push these Docker images to Quay.io
- use Kubernetes namespaces to manage environments
- use Kubernetes replication controllers to deploy applications
- use Slack for team messaging
What does Vili mean anyway?What does Vili mean anyway?
Vili is a brother of Odin in Norse mythology, and he gives intelligence to the first humans.
SetupSetup
To setup Vili on your Kubernetes cluster, follow these steps:
- Select a domain name to host Vili under, such as vili.mydomain.com. Create an Okta app with a redirect URL that points to vili.mydomain.com/login/callback. Write down the Okta entrypoint and the certificate.
- Create Quay.io repositories for your applications. Also create a Quay.io API application and generate a bearer token following instructions here. Write down your Quay organization or user name and your bearer token.
- Create a new Firebase app. Set the "Firebase rules" to match this. Write down the Firebase app's URL and secret.
- Create a GitHub repo with a directory that holds your replication controller templates, pod templates, and environment variables following this example. Also create a GitHub access token following instructions here. Write down your GitHub organization or user name, the path to the directory created above and the authentication token.
- Create a Slack bot integration. Write down the API token from the integration settings page.
- Create a secret in your Kubernetes cluster that stores your GitHub, Quay, Firebase, and Slack tokens, and your Okta certificate following this example. Populate the values in the secret using the Okta, Quay.io, GitHub, Firebase, and Slack information you wrote down in the previous steps. Don't forget to base64 encode them as required by Kubernetes!
- Create a replication controller in your Kubernetes cluster following this example. Populate the environment variables using the Okta, Quay.io, GitHub, Firebase, and Slack information you wrote down in the previous steps.
- Create a service for this replication controller, and allow external access to this service under the domain name you chose in step 1.
You are all set! Vili will use the GitHub and Quay.io APIs to discover your apps and help you deploy them.
ConceptsConcepts
Environment: A namespace in Kubernetes that runs an isolated set of apps and jobs.
App: A stateless application controlled by a replication controller in Kubernetes, run continuously, and deployed with no downtime.
Job: A pod in Kubernetes that runs to completion.
Template: YAML configuration files for controllers and pods, using single curly brackets (
{}) to denote variables.
Variable: Environment variables used to populate controller and pod templates.
Approval: An indication by the QA team that a certain build is deployable to prod. | https://libraries.io/go/github.com%2Fairware%2Fvili%2Fenvironments | CC-MAIN-2020-50 | refinedweb | 522 | 58.28 |
Code should execute sequentially if run in a Jupyter notebook
- See the set up page to install Jupyter, Python and all necessary libraries
- Please direct feedback to contact@quantecon.org or the discourse forum
Co-author: Natasha Watkins
In addition to what’s in Anaconda, this lecture will need the following libraries:
!pip install --upgrade quantecon
Overview¶
This lecture creates non-stochastic and stochastic versions of Paul Samuelson’s celebrated multiplier accelerator model [Sam39].
In doing so, we extend the example of the Solow model class in our second OOP lecture.
Our objectives are to
- provide a more detailed example of OOP and classes
- review a famous model
- review linear difference equations, both deterministic and stochastic
Samuelson’s Model¶
Samuelson used a second-order linear difference equation to represent a model of national output based on three components:
- a national output identity asserting that national outcome is the sum of consumption plus investment plus government purchases.
- a Keynesian consumption function asserting that consumption at time $ t $ is equal to a constant times national output at time $ t-1 $.
- an investment accelerator asserting that investment at time $ t $ equals a constant called the accelerator coefficient times the difference in output between period $ t-1 $ and $ t-2 $.
- the idea that consumption plus investment plus government purchases constitute aggregate demand, which automatically calls forth an equal amount of aggregate supply.
(To read about linear difference equations see here or chapter IX of [Sar87])
Samuelson used the model to analyze how particular values of the marginal propensity to consume and the accelerator coefficient might give rise to transient business cycles in national output.
Possible dynamic properties include
- smooth convergence to a constant level of output
- damped business cycles that eventually converge to a constant level of output
- persistent business cycles that neither dampen nor explode
Later we present an extension that adds a random shock to the right side of the national income identity representing random fluctuations in aggregate demand.
This modification makes national output become governed by a second-order stochastic linear difference equation that, with appropriate parameter values, gives rise to recurrent irregular business cycles.
(To read about stochastic linear difference equations see chapter XI of [Sar87])
Details¶
Let’s assume that
- $ \{G_t\} $ is a sequence of levels of government expenditures – we’ll start by setting $ G_t = G $ for all $ t $.
- $ \{C_t\} $ is a sequence of levels of aggregate consumption expenditures, a key endogenous variable in the model.
- $ \{I_t\} $ is a sequence of rates of investment, another key endogenous variable.
- $ \{Y_t\} $ is a sequence of levels of national income, yet another endogenous variable.
- $ a $ is the marginal propensity to consume in the Keynesian consumption function $ C_t = a Y_{t-1} + \gamma $.
- $ b $ is the “accelerator coefficient” in the “investment accelerator” $ I\_t = b (Y\_{t-1} - Y\_{t-2}) $.
- $ \{\epsilon_{t}\} $ is an IID sequence standard normal random variables.
- $ \sigma \geq 0 $ is a “volatility” parameter — setting $ \sigma = 0 $ recovers the non-stochastic case that we’ll start with.
The model combines the consumption function
$$ C_t = a Y_{t-1} + \gamma \tag{1} $$
with the investment accelerator
$$ I_t = b (Y_{t-1} - Y_{t-2}) \tag{2} $$
and the national income identity
$$ Y_t = C_t + I_t + G_t \tag{3} $$
- The parameter $ a $ is peoples’ marginal propensity to consume out of income - equation (1) asserts that people consume a fraction of math:a in (0,1) of each additional dollar of income.
- The parameter $ b > 0 $ is the investment accelerator coefficient - equation (2) asserts that people invest in physical capital when income is increasing and disinvest when it is decreasing.
Equations (1), (2), and (3) imply the following second-order linear difference equation for national income:$$ Y_t = (a+b) Y_{t-1} - b Y_{t-2} + (\gamma + G_t) $$
or
$$ Y_t = \rho_1 Y_{t-1} + \rho_2 Y_{t-2} + (\gamma + G_t) \tag{4} $$
where $ \rho_1 = (a+b) $ and $ \rho_2 = -b $.
To complete the model, we require two initial conditions.
If the model is to generate time series for $ t=0, \ldots, T $, we require initial values$$ Y_{-1} = \bar Y_{-1}, \quad Y_{-2} = \bar Y_{-2} $$
We’ll ordinarily set the parameters $ (a,b) $ so that starting from an arbitrary pair of initial conditions $ (\bar Y_{-1}, \bar Y_{-2}) $, national income $ Y\_t $ converges to a constant value as $ t $ becomes large.
We are interested in studying
- the transient fluctuations in $ Y_t $ as it converges to its steady state level
- the rate at which it converges to a steady state level
The deterministic version of the model described so far — meaning that no random shocks hit aggregate demand — has only transient fluctuations.
We can convert the model to one that has persistent irregular fluctuations by adding a random shock to aggregate demand.
Stochastic Version of the Model¶
We create a random or stochastic version of the model by adding a random process of shocks or disturbances $ \{\sigma \epsilon_t \} $ to the right side of equation (4), leading to the second-order scalar linear stochastic difference equation:
$$ Y_t = G_t + a (1-b) Y_{t-1} - a b Y_{t-2} + \sigma \epsilon_{t} \tag{5} $$
Mathematical Analysis of the Model¶
To get started, let’s set $ G_t \equiv 0 $, $ \sigma = 0 $, and $ \gamma = 0 $.
Then we can write equation (5) as$$ Y_t = \rho_1 Y_{t-1} + \rho_2 Y_{t-2} $$
or
$$ Y_{t+2} - \rho_1 Y_{t+1} - \rho_2 Y_t = 0 \tag{6} $$
To discover the properties of the solution of (6), it is useful first to form the characteristic polynomial for (6):
$$ z^2 - \rho_1 z - \rho_2 \tag{7} $$
where $ z $ is possibly a complex number.
We want to find the two zeros (a.k.a. roots) – namely $ \lambda_1, \lambda_2 $ – of the characteristic polynomial.
These are two special values of $ z $, say $ z= \lambda_1 $ and $ z= \lambda_2 $, such that if we set $ z $ equal to one of these values in expression (7), the characteristic polynomial (7) equals zero:
$$ z^2 - \rho_1 z - \rho_2 = (z- \lambda_1 ) (z -\lambda_2) = 0 \tag{8} $$
Equation (8) is said to factor the characteristic polynomial.
When the roots are complex, they will occur as a complex conjugate pair.
When the roots are complex, it is convenient to represent them in the polar form$$ \lambda_1 = r e^{i \omega}, \ \lambda_2 = r e^{-i \omega} $$
where $ r $ is the amplitude of the complex number and $ \omega $ is its angle or phase.
These can also be represented as$$ \lambda_1 = r (cos (\omega) + i \sin (\omega)) $$$$ \lambda_2 = r (cos (\omega) - i \sin(\omega)) $$
(To read about the polar form, see here)
Given initial conditions $ Y_{-1}, Y_{-2} $, we want to generate a solution of the difference equation (6).
It can be represented as$$ Y_t = \lambda_1^t c_1 + \lambda_2^t c_2 $$
where $ c_1 $ and $ c_2 $ are constants that depend on the two initial conditions and on $ \rho_1, \rho_2 $.
When the roots are complex, it is useful to pursue the following calculations.
Notice that$$ \begin{aligned} Y_t & = & c_1 (r e^{i \omega})^t + c_2 (r e^{-i \omega})^t \\ & = & c_1 r^t e^{i\omega t} + c_2 r^t e^{-i \omega t} \\ & = & c_1 r^t [\cos(\omega t) + i \sin(\omega t) ] + c_2 r^t [\cos(\omega t) - i \sin(\omega t) ] \\ & = & (c_1 + c_2) r^t \cos(\omega t) + i (c_1 - c_2) r^t \sin(\omega t) \end{aligned} $$
The only way that $ Y_t $ can be a real number for each $ t $ is if $ c_1 + c_2 $ is a real number and $ c_1 - c_2 $ is an imaginary number.
This happens only when $ c_1 $ and $ c_2 $ are complex conjugates, in which case they can be written in the polar forms$$ c_1 = v e^{i \theta}, \ \ c_2 = v e^{- i \theta} $$
So we can write$$ \begin{aligned} Y_t & = & v e^{i \theta} r^t e^{i \omega t} + v e ^{- i \theta} r^t e^{-i \omega t} \\ & = & v r^t [ e^{i(\omega t + \theta)} + e^{-i (\omega t +\theta)}] \\ & = & 2 v r^t \cos (\omega t + \theta) \end{aligned} $$
where $ v $ and $ \theta $ are constants that must be chosen to satisfy initial conditions for $ Y_{-1}, Y_{-2} $.
This formula shows that when the roots are complex, $ Y_t $ displays oscillations with period $ \check p = \frac{2 \pi}{\omega} $ and damping factor $ r $.
We say that $ \check p $ is the period because in that amount of time the cosine wave $ \cos(\omega t + \theta) $ goes through exactly one complete cycles.
(Draw a cosine function to convince yourself of this please)
Remark: Following [Sam39], we want to choose the parameters $ a, b $ of the model so that the absolute values (of the possibly complex) roots $ \lambda_1, \lambda_2 $ of the characteristic polynomial are both strictly less than one:$$ | \lambda_j | < 1 \quad \quad \text{for } j = 1, 2 $$
Remark: When both roots $ \lambda_1, \lambda_2 $ of the characteristic polynomial have absolute values strictly less than one, the absolute value of the larger one governs the rate of convergence to the steady state of the non stochastic version of the model.
Things This Lecture Does¶
We write a function to generate simulations of a $ \{Y_t\} $ sequence as a function of time.
The function requires that we put in initial conditions for $ Y_{-1}, Y_{-2} $.
The function checks that $ a, b $ are set so that $ \lambda_1, \lambda_2 $ are less than unity in absolute value (also called “modulus”).
The function also tells us whether the roots are complex, and, if they are complex, returns both their real and complex parts.
If the roots are both real, the function returns their values.
We use our function written to simulate paths that are stochastic (when $ \sigma >0 $).
We have written the function in a way that allows us to input $ \{G_t\} $ paths of a few simple forms, e.g.,
- one time jumps in $ G $ at some time
- a permanent jump in $ G $ that occurs at some time
We proceed to use the Samuelson multiplier-accelerator model as a laboratory to make a simple OOP example.
The “state” that determines next period’s $ Y_{t+1} $ is now not just the current value $ Y_t $ but also the once lagged value $ Y_{t-1} $.
This involves a little more bookkeeping than is required in the Solow model class definition.
We use the Samuelson multiplier-accelerator model as a vehicle for teaching how we can gradually add more features to the class.
We want to have a method in the class that automatically generates a simulation, either non-stochastic ($ \sigma=0 $) or stochastic ($ \sigma > 0 $).
We also show how to map the Samuelson model into a simple instance of the
LinearStateSpace class described here.
We can use a
LinearStateSpace instance to do various things that we did above with our homemade function and class.
Among other things, we show by example that the eigenvalues of the matrix $ A $ that we use to form the instance of the
LinearStateSpace class for the Samuelson model equal the roots of the characteristic polynomial (7) for the Samuelson multiplier accelerator model.
Here is the formula for the matrix $ A $ in the linear state space system in the case that government expenditures are a constant $ G $:$$ A = \begin{bmatrix} 1 & 0 & 0 \cr \gamma + G & \rho_1 & \rho_2 \cr 0 & 1 & 0 \end{bmatrix} $$
import numpy as np import matplotlib.pyplot as plt %matplotlib inline def param_plot(): """this function creates the graph on page 189 of Sargent Macroeconomic Theory, second edition, 1987""" fig, ax = plt.subplots(figsize=(10, 6)) ax.set_aspect('equal') # Set axis xmin, ymin = -3, -2 xmax, ymax = -xmin, -ymin plt.axis([xmin, xmax, ymin, ymax]) # Set axis labels ax.set(xticks=[], yticks=[]) ax.set_xlabel(r'$\rho_2$', fontsize=16) ax.xaxis.set_label_position('top') ax.set_ylabel(r'$\rho_1$', rotation=0, fontsize=16) ax.yaxis.set_label_position('right') # Draw (t1, t2) points ρ1 = np.linspace(-2, 2, 100) ax.plot(ρ1, -abs(ρ1) + 1, c='black') ax.plot(ρ1, np.ones_like(ρ1) * -1, c='black') ax.plot(ρ1, -(ρ1**2 / 4), c='black') # Turn normal axes off for spine in ['left', 'bottom', 'top', 'right']: ax.spines[spine].set_visible(False) # Add arrows to represent axes axes_arrows = {'arrowstyle': '<|-|>', 'lw': 1.3} ax.annotate('', xy=(xmin, 0), xytext=(xmax, 0), arrowprops=axes_arrows) ax.annotate('', xy=(0, ymin), xytext=(0, ymax), arrowprops=axes_arrows) # Annotate the plot with equations plot_arrowsl = {'arrowstyle': '-|>', 'connectionstyle': "arc3, rad=-0.2"} plot_arrowsr = {'arrowstyle': '-|>', 'connectionstyle': "arc3, rad=0.2"} ax.annotate(r'$\rho_1 + \rho_2 < 1$', xy=(0.5, 0.3), xytext=(0.8, 0.6), arrowprops=plot_arrowsr, fontsize='12') ax.annotate(r'$\rho_1 + \rho_2 = 1$', xy=(0.38, 0.6), xytext=(0.6, 0.8), arrowprops=plot_arrowsr, fontsize='12') ax.annotate(r'$\rho_2 < 1 + \rho_1$', xy=(-0.5, 0.3), xytext=(-1.3, 0.6), arrowprops=plot_arrowsl, fontsize='12') ax.annotate(r'$\rho_2 = 1 + \rho_1$', xy=(-0.38, 0.6), xytext=(-1, 0.8), arrowprops=plot_arrowsl, fontsize='12') ax.annotate(r'$\rho_2 = -1$', xy=(1.5, -1), xytext=(1.8, -1.3), arrowprops=plot_arrowsl, fontsize='12') ax.annotate(r'${\rho_1}^2 + 4\rho_2 = 0$', xy=(1.15, -0.35), xytext=(1.5, -0.3), arrowprops=plot_arrowsr, fontsize='12') ax.annotate(r'${\rho_1}^2 + 4\rho_2 < 0$', xy=(1.4, -0.7), xytext=(1.8, -0.6), arrowprops=plot_arrowsr, fontsize='12') # Label categories of solutions ax.text(1.5, 1, 'Explosive\n growth', ha='center', fontsize=16) ax.text(-1.5, 1, 'Explosive\n oscillations', ha='center', fontsize=16) ax.text(0.05, -1.5, 'Explosive oscillations', ha='center', fontsize=16) ax.text(0.09, -0.5, 'Damped oscillations', ha='center', fontsize=16) # Add small marker to y-axis ax.axhline(y=1.005, xmin=0.495, xmax=0.505, c='black') ax.text(-0.12, -1.12, '-1', fontsize=10) ax.text(-0.12, 0.98, '1', fontsize=10) return fig param_plot() plt.show()
The graph portrays regions in which the $ (\lambda_1, \lambda_2) $ root pairs implied by the $ (\rho_1 = (a+b), \rho_2 = - b) $ difference equation parameter pairs in the Samuelson model are such that:
- $ (\lambda_1, \lambda_2) $ are complex with modulus less than $ 1 $ - in this case, the $ \{Y_t\} $ sequence displays damped oscillations.
- $ (\lambda_1, \lambda_2) $ are both real, but one is strictly greater than $ 1 $ - this leads to explosive growth.
- $ (\lambda_1, \lambda_2) $ are both real, but one is strictly less than $ -1 $ - this leads to explosive oscillations.
- $ (\lambda_1, \lambda_2) $ are both real and both are less than $ 1 $ in absolute value - in this case, there is smooth convergence to the steady state without damped cycles.
Later we’ll present the graph with a red mark showing the particular point implied by the setting of $ (a,b) $.
def categorize_solution(ρ1, ρ2): """this function takes values of ρ1 and ρ2 and uses them to classify the type of solution""" discriminant = ρ1 ** 2 + 4 * ρ2 if ρ2 > 1 + ρ1 or ρ2 < -1: print('Explosive oscillations') elif ρ1 + ρ2 > 1: print('Explosive growth') elif discriminant < 0: print('Roots are complex with modulus less than one; therefore damped oscillations') else: print('Roots are real and absolute values are less than one; therefore get smooth convergence to a steady state')
### Test the categorize_solution function categorize_solution(1.3, -.4)
Roots are real and absolute values are less than one; therefore get smooth convergence to a steady state
def plot_y(function=None): """function plots path of Y_t""" plt.subplots(figsize=(10, 6)) plt.plot(function) plt.xlabel('Time $t$') plt.ylabel('$Y_t$', rotation=0) plt.grid() plt.show()
from cmath import sqrt ##=== This is a 'manual' method ===# def y_nonstochastic(y_0=100, y_1=80, α=.92, β=.5, γ=10, n=80): """Takes values of parameters and computes the roots of characteristic polynomial. It tells whether they are real or complex and whether they are less than unity in absolute value. It also computes a simulation of length n starting from the two given initial conditions for national income""" roots = [] ρ1 = α + β ρ2 = -β print(f'ρ_1 is {ρ1}') print(f'ρ_2 is {ρ2}') discriminant = ρ1 ** 2 + 4 * ρ2 if discriminant == 0: roots.append(-ρ1 / 2) print('Single real root: ') print(''.join(str(roots))) elif discriminant > 0: roots.append((-ρ1 + sqrt(discriminant).real) / 2) roots.append((-ρ1 - sqrt(discriminant).real) / 2) print('Two real roots: ') print(''.join(str(roots))) else: roots.append((-ρ1 + sqrt(discriminant)) / 2) roots.append((-ρ1 - sqrt(discriminant)) / 2) print('Two complex roots: ') print(''.join(str(roots))) if all(abs(root) < 1 for root in roots): print('Absolute values of roots are less than one') else: print('Absolute values of roots are not less than one') def transition(x, t): return ρ1 * x[t - 1] + ρ2 * x[t - 2] + γ y_t = [y_0, y_1] for t in range(2, n): y_t.append(transition(y_t, t)) return y_t plot_y(y_nonstochastic())
ρ_1 is 1.42 ρ_2 is -0.5 Two real roots: [-0.6459687576256715, -0.7740312423743284] Absolute values of roots are less than one
Reverse-Engineering Parameters to Generate Damped Cycles¶
The next cell writes code that takes as inputs the modulus $ r $ and phase $ \phi $ of a conjugate pair of complex numbers in polar form$$ \lambda_1 = r \exp(i \phi), \quad \lambda_2 = r \exp(- i \phi) $$
- The code assumes that these two complex numbers are the roots of the characteristic polynomial
- It then reverse-engineers $ (a,b) $ and $ (\rho_1, \rho_2) $, pairs that would generate those roots
### code to reverse-engineer a cycle ### y_t = r^t (c_1 cos(ϕ t) + c2 sin(ϕ t)) ### import cmath import math def f(r, ϕ): """ Takes modulus r and angle ϕ of complex number r exp(j ϕ) and creates ρ1 and ρ2 of characteristic polynomial for which r exp(j ϕ) and r exp(- j ϕ) are complex roots. Returns the multiplier coefficient a and the accelerator coefficient b that verifies those roots. """ g1 = cmath.rect(r, ϕ) # Generate two complex roots g2 = cmath.rect(r, -ϕ) ρ1 = g1 + g2 # Implied ρ1, ρ2 ρ2 = -g1 * g2 b = -ρ2 # Reverse-engineer a and b that validate these a = ρ1 - b return ρ1, ρ2, a, b ## Now let's use the function in an example ## Here are the example parameters r = .95 period = 10 # Length of cycle in units of time ϕ = 2 * math.pi/period ## Apply the function ρ1, ρ2, a, b = f(r, ϕ) print(f"a, b = {a}, {b}") print(f"ρ1, ρ2 = {ρ1}, {ρ2}")
a, b = (0.6346322893124001+0j), (0.9024999999999999-0j) ρ1, ρ2 = (1.5371322893124+0j), (-0.9024999999999999+0j)
## Print the real components of ρ1 and ρ2 ρ1 = ρ1.real ρ2 = ρ2.real ρ1, ρ2
(1.5371322893124, -0.9024999999999999)
r1, r2 = np.roots([1, -ρ1, -ρ2]) p1 = cmath.polar(r1) p2 = cmath.polar(r2) print(f"r, ϕ = {r}, {ϕ}") print(f"p1, p2 = {p1}, {p2}") # print(f"g1, g2 = {g1}, {g2}") print(f"a, b = {a}, {b}") print(f"ρ1, ρ2 = {ρ1}, {ρ2}")
r, ϕ = 0.95, 0.6283185307179586 p1, p2 = (0.95, 0.6283185307179586), (0.95, -0.6283185307179586) a, b = (0.6346322893124001+0j), (0.9024999999999999-0j) ρ1, ρ2 = 1.5371322893124, -0.9024999999999999
##=== This method uses numpy to calculate roots ===# def y_nonstochastic(y_0=100, y_1=80, α=.9, β=.8, γ=10, n=80): """ Rather than computing the roots of the characteristic polynomial by hand as we did earlier, this function enlists numpy to do the work for us """ # Useful constants ρ1 = α + β ρ2 = -β categorize_solution(ρ1, ρ2) # Find roots of polynomial roots = np.roots([1, -ρ1, -ρ2]) print(f'Roots are ') # Define transition equation def transition(x, t): return ρ1 * x[t - 1] + ρ2 * x[t - 2] + γ # Set initial conditions y_t = [y_0, y_1] # Generate y_t series for t in range(2, n): y_t.append(transition(y_t, t)) return y_t plot_y(y_nonstochastic())
Roots are complex with modulus less than one; therefore damped oscillations Roots are [0.85+0.27838822j 0.85-0.27838822j] Roots are complex Roots are less than one
r = 1 # generates undamped, nonexplosive cycles}") ytemp = y_nonstochastic(α=a, β=b, y_0=20, y_1=30) plot_y(ytemp)
a, b = 0.6180339887498949, 1.0 Roots are complex with modulus less than one; therefore damped oscillations Roots are [0.80901699+0.58778525j 0.80901699-0.58778525j] Roots are complex Roots are less than one
import sympy from sympy import Symbol, init_printing init_printing() r1 = Symbol("ρ_1") r2 = Symbol("ρ_2") z = Symbol("z") sympy.solve(z**2 - r1*z - r2, z)
a = Symbol("α") b = Symbol("β") r1 = a + b r2 = -b sympy.solve(z**2 - r1*z - r2, z)
def y_stochastic(y_0=0, y_1=0, α=0.8, β=0.2, γ=10, n=100, σ=5): """This function takes parameters of a stochastic version of the model and proceeds to analyze the roots of the characteristic polynomial and also generate a simulation""" #) # Define transition equation def transition(x, t): return ρ1 * \ x[t - 1] + ρ2 * x[t - 2] + γ + σ * ϵ[t] # Set initial conditions y_t = [y_0, y_1] # Generate y_t series for t in range(2, n): y_t.append(transition(y_t, t)) return y_t plot_y(y_stochastic())
Roots are real and absolute values are less than one; therefore get smooth convergence to a steady state [0.7236068 0.2763932] Roots are real Roots are less than one
Let’s do a simulation in which there are shocks and the characteristic polynomial has complex roots
r = .97}") plot_y(y_stochastic(y_0=40, y_1 = 42, α=a, β=b, σ=2, n=100))
a, b = 0.6285929690873979, 0.9409000000000001 Roots are complex with modulus less than one; therefore damped oscillations [0.78474648+0.57015169j 0.78474648-0.57015169j] Roots are complex Roots are less than one
def y_stochastic_g(y_0=20, y_1=20, α=0.8, β=0.2, γ=10, n=100, σ=2, g=0, g_t=0, duration='permanent'): """This program computes a response to a permanent increase in government expenditures that occurs at time 20""" #) def transition(x, t, g): # Non-stochastic - separated to avoid generating random series when not needed if σ == 0: return ρ1 * x[t - 1] + ρ2 * x[t - 2] + γ + g # Stochastic else: ϵ = np.random.normal(0, 1, n) return ρ1 * x[t - 1] + ρ2 * x[t - 2] + γ + g + σ * ϵ[t] # Create list and set initial conditions y_t = [y_0, y_1] # Generate y_t series for t in range(2, n): # No government spending if g == 0: y_t.append(transition(y_t, t)) # Government spending (no shock) elif g != 0 and duration == None: y_t.append(transition(y_t, t)) # Permanent government spending shock elif duration == 'permanent': if t < g_t: y_t.append(transition(y_t, t, g=0)) else: y_t.append(transition(y_t, t, g=g)) # One-off government spending shock elif duration == 'one-off': if t == g_t: y_t.append(transition(y_t, t, g=g)) else: y_t.append(transition(y_t, t, g=0)) return y_t
A permanent government spending shock can be simulated as follows
plot_y(y_stochastic_g(g=10, g_t=20, duration='permanent'))
Roots are real and absolute values are less than one; therefore get smooth convergence to a steady state [0.7236068 0.2763932] Roots are real Roots are less than one
We can also see the response to a one time jump in government expenditures
plot_y(y_stochastic_g(g=500, g_t=50, duration='one-off'))
Roots are real and absolute values are less than one; therefore get smooth convergence to a steady state [0.7236068 0.2763932] Roots are real Roots are less than one
class Samuelson(): r"""This class represents the Samuelson model, otherwise known as the multiple-accelerator model. The model combines the Keynesian multiplier with the accelerator theory of investment. The path of output is governed by a linear second-order difference equation .. math:: Y_t = + \alpha (1 + \beta) Y_{t-1} - \alpha \beta Y_{t-2} Parameters ---------- y_0 : scalar Initial condition for Y_0 y_1 : scalar Initial condition for Y_1 α : scalar Marginal propensity to consume β : scalar Accelerator coefficient n : int Number of iterations σ : scalar Volatility parameter. It must be greater than or equal to 0. Set equal to 0 for a non-stochastic model. g : scalar Government spending shock g_t : int Time at which government spending shock occurs. Must be specified when duration != None. duration : {None, 'permanent', 'one-off'} Specifies type of government spending shock. If none, government spending equal to g for all t. """ def __init__(self, y_0=100, y_1=50, α=1.3, β=0.2, γ=10, n=100, σ=0, g=0, g_t=0, duration=None): self.y_0, self.y_1, self.α, self.β = y_0, y_1, α, β self.n, self.g, self.g_t, self.duration = n, g, g_t, duration self.γ, self.σ = γ, σ self.ρ1 = α + β self.ρ2 = -β self.roots = np.roots([1, -self.ρ1, -self.ρ2]) def root_type(self): if all(isinstance(root, complex) for root in self.roots): return 'Complex conjugate' elif len(self.roots) > 1: return 'Double real' else: return 'Single real' def root_less_than_one(self): if all(abs(root) < 1 for root in self.roots): return True def solution_type(self): ρ1, ρ2 = self.ρ1, self.ρ2 discriminant = ρ1 ** 2 + 4 * ρ2 if ρ2 >= 1 + ρ1 or ρ2 <= -1: return 'Explosive oscillations' elif ρ1 + ρ2 >= 1: return 'Explosive growth' elif discriminant < 0: return 'Damped oscillations' else: return 'Steady state' def _transition(self, x, t, g): # Non-stochastic - separated to avoid generating random series when not needed if self.σ == 0: return self.ρ1 * x[t - 1] + self.ρ2 * x[t - 2] + self.γ + g # Stochastic else: ϵ = np.random.normal(0, 1, self.n) return self.ρ1 * x[t - 1] + self.ρ2 * x[t - 2] + self.γ + g + self.σ * ϵ[t] def generate_series(self): # Create list and set initial conditions y_t = [self.y_0, self.y_1] # Generate y_t series for t in range(2, self.n): # No government spending if self.g == 0: y_t.append(self._transition(y_t, t)) # Government spending (no shock) elif self.g != 0 and self.duration == None: y_t.append(self._transition(y_t, t)) # Permanent government spending shock elif self.duration == 'permanent': if t < self.g_t: y_t.append(self._transition(y_t, t, g=0)) else: y_t.append(self._transition(y_t, t, g=self.g)) # One-off government spending shock elif self.duration == 'one-off': if t == self.g_t: y_t.append(self._transition(y_t, t, g=self.g)) else: y_t.append(self._transition(y_t, t, g=0)) return y_t def summary(self): print('Summary\n' + '-' * 50) print(f'Root type: {self.root_type()}') print(f'Solution type: {self.solution_type()}') print(f'Roots: {str(self.roots)}') if self.root_less_than_one() == True: print('Absolute value of roots is less than one') else: print('Absolute value of roots is not less than one') if self.σ > 0: print('Stochastic series with σ = ' + str(self.σ)) else: print('Non-stochastic series') if self.g != 0: print('Government spending equal to ' + str(self.g)) if self.duration != None: print(self.duration.capitalize() + ' government spending shock at t = ' + str(self.g_t)) def plot(self): fig, ax = plt.subplots(figsize=(10, 6)) ax.plot(self.generate_series()) ax.set(xlabel='Iteration', xlim=(0, self.n)) ax.set_ylabel('$Y_t$', rotation=0) ax.grid() # Add parameter values to plot paramstr = f'$\\alpha={self.α:.2f}$ \n $\\beta={self.β:.2f}$ \n $\\gamma={self.γ:.2f}$ \n \ $\\sigma={self.σ:.2f}$ \n $\\rho_1={self.ρ1:.2f}$ \n $\\rho_2={self.ρ2:.2f}$' props = dict(fc='white', pad=10, alpha=0.5) ax.text(0.87, 0.05, paramstr, transform=ax.transAxes, fontsize=12, bbox=props, va='bottom') return fig def param_plot(self): # Uses the param_plot() function defined earlier (it is then able # to be used standalone or as part of the model) fig = param_plot() ax = fig.gca() # Add λ values to legend for i, root in enumerate(self.roots): if isinstance(root, complex): operator = ['+', ''] # Need to fill operator for positive as string is split apart label = rf'$\lambda_{i+1} = {sam.roots[i].real:.2f} {operator[i]} {sam.roots[i].imag:.2f}i$' else: label = rf'$\lambda_{i+1} = {sam.roots[i].real:.2f}$' ax.scatter(0, 0, 0, label=label) # dummy to add to legend # Add ρ pair to plot ax.scatter(self.ρ1, self.ρ2, 100, 'red', '+', label=r'$(\ \rho_1, \ \rho_2 \ )$', zorder=5) plt.legend(fontsize=12, loc=3) return fig
sam = Samuelson(α=0.8, β=0.5, σ=2, g=10, g_t=20, duration='permanent') sam.summary()
Summary -------------------------------------------------- Root type: Complex conjugate Solution type: Damped oscillations Roots: [0.65+0.27838822j 0.65-0.27838822j] Absolute value of roots is less than one Stochastic series with σ = 2 Government spending equal to 10 Permanent government spending shock at t = 20
sam.plot() plt.show()
sam.param_plot() plt.show()
Using the LinearStateSpace Class¶
It turns out that we can use the QuantEcon.py LinearStateSpace class to do much of the work that we have done from scratch above.
Here is how we map the Samuelson model into an instance of a
LinearStateSpace class
from quantecon import LinearStateSpace """ This script maps the Samuelson model in the the ``LinearStateSpace`` class""" α = 0.8 β = 0.9 ρ1 = α + β ρ2 = -β γ = 10 σ = 1 g = 10 n = 100 A = [[1, 0, 0], [γ + g, ρ1, ρ2], [0, 1, 0]] G = [[γ + g, ρ1, ρ2], # this is Y_{t+1} [γ, α, 0], # this is C_{t+1} [0, β, -β]] # this is I_{t+1} μ_0 = [1, 100, 100] C = np.zeros((3,1)) C[1] = σ # stochastic sam_t = LinearStateSpace(A, C, G, mu_0=μ_0) x, y = sam_t.simulate(ts_length=n)') plt.show()
imres = sam_t.impulse_response() imres = np.asarray(imres) y1 = imres[:, :, 0] y2 = imres[:, :, 1] y1.shape
Now let’s compute the zeros of the characteristic polynomial by simply calculating the eigenvalues of $ A $
A = np.asarray(A) w, v = np.linalg.eig(A) print(w)
[0.85+0.42130749j 0.85-0.42130749j 1. +0.j ]
class SamuelsonLSS(LinearStateSpace): """ this subclass creates a Samuelson multiplier-accelerator model as a linear state space system """ def __init__(self, y_0=100, y_1=100, α=0.8, β=0.9, γ=10, σ=1, g=10): self.α, self.β = α, β self.y_0, self.y_1, self.g = y_0, y_1, g self.γ, self.σ = γ, σ # Define intial conditions self.μ_0 = [1, y_0, y_1] self.ρ1 = α + β self.ρ2 = -β # Define transition matrix self.A = [[1, 0, 0], [γ + g, self.ρ1, self.ρ2], [0, 1, 0]] # Define output matrix self.G = [[γ + g, self.ρ1, self.ρ2], # this is Y_{t+1} [γ, α, 0], # this is C_{t+1} [0, β, -β]] # this is I_{t+1} self.C = np.zeros((3, 1)) self.C[1] = σ # stochastic # Initialize LSS with parameters from Samuelson model LinearStateSpace.__init__(self, self.A, self.C, self.G, mu_0=self.μ_0) def plot_simulation(self, ts_length=100, stationary=True): # Temporarily store original parameters temp_μ = self.μ_0 temp_Σ = self.Sigma_0 # Set distribution parameters equal to their stationary values for simulation if stationary == True: try: self.μ_x, self.μ_y, self.σ_x, self.σ_y = self.stationary_distributions() self.μ_0 = self.μ_y self.Σ_0 = self.σ_y # Exception where no convergence achieved when calculating stationary distributions except ValueError: print('Stationary distribution does not exist') x, y = self.simulate(ts_length)') # Reset distribution parameters to their initial values self.μ_0 = temp_μ self.Sigma_0 = temp_Σ return fig def plot_irf(self, j=5): x, y = self.impulse_response(j) # Reshape into 3 x j matrix for plotting purposes yimf = np.array(y).flatten().reshape(j+1, 3).T fig, axes = plt.subplots(3, 1, sharex=True, figsize=(12, 8)) labels = ['$Y_t$', '$C_t$', '$I_t$'] colors = ['darkblue', 'red', 'purple'] for ax, series, label, color in zip(axes, yimf, labels, colors): ax.plot(series, color=color) ax.set(xlim=(0, j)) ax.set_ylabel(label, rotation=0, fontsize=14, labelpad=10) ax.grid() axes[0].set_title('Impulse Response Functions') axes[-1].set_xlabel('Iteration') return fig def multipliers(self, j=5): x, y = self.impulse_response(j) return np.sum(np.array(y).flatten().reshape(j+1, 3), axis=0)
samlss = SamuelsonLSS()
samlss.plot_simulation(100, stationary=False) plt.show()
samlss.plot_simulation(100, stationary=True) plt.show()
samlss.plot_irf(100) plt.show()
samlss.multipliers()
array([7.414389, 6.835896, 0.578493])
pure_multiplier = SamuelsonLSS(α=0.95, β=0)
pure_multiplier.plot_simulation()
Stationary distribution does not exist
pure_multiplier = SamuelsonLSS(α=0.8, β=0)
pure_multiplier.plot_simulation()
pure_multiplier.plot_irf(100)
Summary¶
In this lecture, we wrote functions and classes to represent non-stochastic and stochastic versions of the Samuelson (1939) multiplier-accelerator model, described in [Sam39].
We saw that different parameter values led to different output paths, which could either be stationary, explosive, or oscillating.
We also were able to represent the model using the QuantEcon.py LinearStateSpace class. | https://lectures.quantecon.org/py/samuelson.html | CC-MAIN-2019-35 | refinedweb | 5,374 | 56.66 |
0
I'm modifying a 10-year old open-source utility written in C, even though I'm a PHP programmer, so the whole pointer business for working with strings is giving me a headache. Can anyone advise on why this string conversion snippet is not converting case?
#include <ctype.h> int set_keysig (s, ks, init) char s[]; struct KEYSTR *ks; int init; { int sf, ok, l, rc; char w[81], *c, *r; int ktype, add_pitch, root, root_acc; c = s; /* ... omitting irrelevant, working code here ... */ /* this is where the word w is supposed to be extracted from the line of text c* and also converted to lowercase. The word gets extracted correctly in all cases, but it does not get converted to lowercase - each letter in the word is mysteriously remaining in its original case. */ r = w; *r++ = *c++; while (*c && (*c != ' ') && (*c != '+') && (*c != '-')) *r++ = tolower(*c++); *r ='\0'; /* the next line is how I'm checking whether the above lines worked */ if (verbose>=20) printf ("word: <%s>\n", w); }
More context: I'm now compiling this code using gcc 4.2 in XCode 3.1 on an Intel Mac. This code used to work fine when I previously compiled it years ago using gcc 3 in XCode 2 on either a PowerPC Mac or an Intel Mac.
Any ideas? | https://www.daniweb.com/programming/software-development/threads/186574/why-is-this-case-conversion-loop-failing | CC-MAIN-2018-43 | refinedweb | 220 | 77.77 |
I want to call some jQuery function targeting div with table. That table is populated with
ng-repeat.
When I call it on
$(document).ready()
I have no result.
Also
$scope.$on('$viewContentLoaded', myFunc);
doesn't help.
Is there any way to execute function right after ng-repeat population completes? I've read an advice about using custom
directive, but I have no clue how to use it with ng-repeat and my div...
Indeed, you should use directives, and there is no event tied to the end of a ng-Repeat loop (as each element is constructed individually, and has it's own event). But a) using directives might be all you need and b) there are a few ng-Repeat specific properties you can use to make your "on ngRepeat finished" event.
Specifically, if all you want is to style/add events to the whole of the table, you can do so using in a directive that encompasses all the ngRepeat elements. On the other hand, if you want to address each element specifically, you can use a directive within the ngRepeat, and it will act on each element, after it is created.
Then, there are the
$index,
$first,
$middle and
$last properties you can use to trigger events. So for this HTML:
<div ng-controller="Ctrl" my-main-directive> <div ng-repeat="thing in things" my-repeat-directive> thing {{thing}} </div> </div>
You can use directives like so:
angular.module('myApp', []) .directive('myRepeatDirective', function() { return function(scope, element, attrs) { angular.element(element).css('color','blue'); if (scope.$last){ window.alert("im the last!"); } }; }) .directive('myMainDirective', function() { return function(scope, element, attrs) { angular.element(element).css('border','5px solid red'); }; });
See it in action in this Plunker. Hope it helps!
If you simply want to execute some code at the end of the loop, here's a slightly simpler variation that doesn't require extra event handling:
<div ng- <div class="thing" ng-repeat="thing in things" my-post-repeat-directive> thing {{thing}} </div> </div>
function Ctrl($scope) { $scope.things = [ 'A', 'B', 'C' ]; } angular.module('myApp', []) .directive('myPostRepeatDirective', function() { return function(scope, element, attrs) { if (scope.$last){ // iteration is complete, do whatever post-processing // is necessary element.parent().css('border', '1px solid black'); } }; });
There is no need of creating a directive especially just to have a
ng-repeat complete event.
ng-init does the magic for you.
<div ng-
the
$last makes sure, that
finished only gets fired, when the last element has been rendered to the DOM.
Do not forget to create
$scope.finished event.
Happy Coding!!
EDIT: 23 Oct 2016
In case you also want to call the
finished function when there is no item in the array then you may use the following workaround
<div style="display:none" ng-</div> //or <div ng-</div>
Just add the above line on the top of the
ng-repeat element. It will check if the array is not having any value and call the function accordingly.
E.g.
<div ng-</div> <div ng-
Here is a repeat-done directive that calls a specified function when true. I have found that the called function must use $timeout with interval=0 before doing DOM manipulation, such as initializing tooltips on the rendered elements. jsFiddle:
In $scope.layoutDone, try commenting out the $timeout line and uncommenting the "NOT CORRECT!" line to see the difference in the tooltips.
<ul> <li ng-{{feed | strip_http}}</a> </li> </ul>
JS:
angular.module('Repeat_Demo', []) .directive('repeatDone', function() { return function(scope, element, attrs) { if (scope.$last) { // all are rendered scope.$eval(attrs.repeatDone); } } }) .filter('strip_http', function() { return function(str) { var http = "http://"; return (str.indexOf(http) == 0) ? str.substr(http.length) : str; } }) .filter('hostName', function() { return function(str) { var urlParser = document.createElement('a'); urlParser.href = str; return urlParser.hostname; } }) .controller('AppCtrl', function($scope, $timeout) { $scope.feedList = [ '', '', '', '', '', '', '' ]; $scope.layoutDone = function() { //$('a[data-toggle="tooltip"]').tooltip(); // NOT CORRECT! $timeout(function() { $('a[data-toggle="tooltip"]').tooltip(); }, 0); // wait... } })
Here's a simple approach using
ng-init that doesn't even require a custom directive. It's worked well for me in certain scenarios e.g. needing to auto-scroll a div of ng-repeated items to a particular item on page load, so the scrolling function needs to wait until the
ng-repeat has finished rendering to the DOM before it can fire.
<div ng- <div ng- thing: {{ thing }} </div> <div ng-</div> </div>
myModule.controller('MyCtrl', function($scope, $timeout){ $scope.things = ['A', 'B', 'C']; $scope.fireEvent = function(){ // This will only run after the ng-repeat has rendered its things to the DOM $timeout(function(){ $scope.$broadcast('thingsRendered'); }, 0); }; });
Note that this is only useful for functions you need to call one time after the ng-repeat renders initially. If you need to call a function whenever the ng-repeat contents are updated then you'll have to use one of the other answers on this thread with a custom directive.
Complementing Pavel's answer, something more readable and easily understandable would be:
<ul> <li ng-{{item}}</li> </ul>
Why else do you think
angular.noop is there in the first place...?
Advantages:
You don't have to write a directive for this...
Maybe a bit simpler approach with
ngInit and Lodash's
debounce method without the need of custom directive:
Controller:
$scope.items = [1, 2, 3, 4]; $scope.refresh = _.debounce(function() { // Debounce has timeout and prevents multiple calls, so this will be called // once the iteration finishes console.log('we are done'); }, 0);
Template:
<ul> <li ng-{{item}}</li> </ul>
There is even simpler pure AngularJS solution using ternary operator:
Template:
<ul> <li ng-{{item}}</li> </ul>
Be aware that ngInit uses pre-link compilation phase - i.e. the expression is invoked before child directives are processed. This means that still an asynchronous processing might be required.
It may also be necessary when you check the
scope.$last variable to wrap your trigger with a
setTimeout(someFn, 0). A
setTimeout 0 is an accepted technique in javascript and it was imperative for my
directive to run correctly.
This is an improvement of the ideas expressed in other answers in order to show how to gain access to the ngRepeat properties ($index, $first, $middle, $last, $even, $odd) when using declarative syntax and isolate scope (Google recommended best practice) with an element-directive. Note the primary difference:
scope.$parent.$last.
angular.module('myApp', []) .directive('myRepeatDirective', function() { return { restrict: 'E', scope: { someAttr: '=' }, link: function(scope, element, attrs) { angular.element(element).css('color','blue'); if (scope.$parent.$last){ window.alert("im the last!"); } } }; });
<div ng- <label>{{i.Name}}</label> <div ng-</div> </div>
My solution was to add a div to call a function if the item was the last in a repeat.
i would like to add another answer, since the preceding answers takes it that the code needed to run after the ngRepeat is done is an angular code, which in that case all answers above give a great and simple solution, some more generic than others, and in case its important the digest life cycle stage you can take a look at Ben Nadel's blog about it, with the exception of using $parse instead of $eval.
but in my experience, as the OP states, its usually running some JQuery plugins or methods on the finnaly compiled DOM, which in that case i found that the most simple solution is to create a directive with a
I did it this way.
Create the directive
function finRepeat() { return function(scope, element, attrs) { if (scope.$last){ // Here is where already executes the jquery $(document).ready(function(){ $('.materialboxed').materialbox(); $('.tooltipped').tooltip({delay: 50}); }); } } } angular .module("app") .directive("finRepeat", finRepeat);
After you add it on the label where this ng-repeat
<ul> <li ng-repeat="(key, value) in data" fin-repeat> {{ value }} </li> </ul>
And ready with that will be run at the end of the ng-repeat.
I had to render formulas using MathJax after ng-repeat ends, none of the above answers solved my problem, so I made like below. It's not a nice solution, but worked for me...
<div ng- <div>{{formula.string}}</div> {{$last ? controller.render_formulas() : ""}} </div>
I found an answer here well practiced, but it was still necessary to add a delay
Create the following directive:
angular.module('MyApp').directive('emitLastRepeaterElement', function() { return function(scope) { if (scope.$last){ scope.$emit('LastRepeaterElement'); } }; });
Add it to your repeater as an attribute, like this:
<div ng-repeat="item in items" emit-last-repeater-element></div>
According to Radu,:
$scope.eventoSelecionado.internamento_evolucoes.forEach(ie => {mycode});
For me it works, but I still need to add a setTimeout
$scope.eventoSelecionado.internamento_evolucoes.forEach(ie => { setTimeout(function() { mycode }, 100); });
If you simply wants to change the class name so it will rendered differently, below code would do the trick.
<div> <div ng- <div id="{{i.status}}" class="{{i.status}}"> <div class="listitems">{{i.item}}</div> <div class="listitems">{{i.qty}}</div> <div class="listitems">{{i.date}}</div> <div class="listbutton"> <button ng-<span>Done</span></button> <button ng-<span>Remove</span></button> </div> <hr> </div>
This code worked for me when I had a similar requirement to render the shopped item in my shopping list in Strick trough font. | https://javascriptinfo.com/view/11030/ng-repeat-finish-event | CC-MAIN-2020-40 | refinedweb | 1,535 | 56.96 |
Download presentation
Presentation is loading. Please wait.
Published byBrennan Wilcutt Modified over 2 years ago
1
Getting Started in Tenpin Bowling / Presentation
2
Getting Started / Safety
Warm up (stretch) before bowling is a must to avoid bowling cold and straining the muscles that haven't been used since you last bowled. When walking around the center always be careful just where you are and make certain you are not behind someone swinging a ball. Always wear the correct footwear when bowling (bowling shoes), not your own runners or street shoes. When bowling you need a slide step as you bowl, otherwise you will stop far to quick and this will result in a miss-thrown ball and a fall or strained leg muscle. Beware walking in ANY form of liquid as you bowl - Sudden and Painful stopping will occur at the end of the approach.
3
Getting Started / Choosing a House Ball
The most important is the thumbhole, as the thumb controls the ball. It should not be a sloppy fit but a loose fit is better than too tight a fit - we don't want the ball to stay on your hand and take you down the lane! Each bowling center has staff members ready and willing to help new players find a ball suitable for their enjoyment. Most house balls are color coded for weight, and if not the weight is marked on the ball 3
4
Getting Started / Picking up the Ball
First, the action of picking the ball up, some balls are 16lbs in weight and many people will pick this up one handed with their fingers already inserted, not recommended. You pick a ball up between 11 and 23 times and if you pick an average of about times and multiply that by the weight you’ll find that is a lot of pounds on the fingers/wrist/arm and that can lead to strain injuries. The second area here is just as important, make sure you pick the ball up across the return (outside of the ball…not between the balls) and not with the hand between your ball and the return - if you get a finger trapped between the balls it is quite amazing how painful this is. 4
5
Getting Started / Cradle the ball after Picking up the Ball
Pick the ball up two handed without inserting the fingers, do this while holding the ball cradled in the opposite arm. This cuts the strain down by at least 50%. 5
6
Getting Started / Lane Courtesy
You should never bowl with someone on the lane next to yours bowling at the same time. (Watch some bowlers stretch a leg over the next lane or even wander across the next lane after they have released the ball). When bowling make sure you never cross the foul line, the lane is oiled right from the edge and the inevitable result will be a fall, also the next time you bowl you will have oil on the soles of your shoes. 6
7
Getting Started / The Lane
7
8
Getting Started / The Stance
Stance: (Physical Pose) Proper alignment and good body position will reduce tension and allow for maximum natural athleticism. Stance: (Physical Pose) Slow ball speed hold the ball higher than waist Medium ball speed hold the ball at the waist Faster ball speed hold the ball below the waist
9
Getting Started / The Stance
Side View of Stance; Knees slightly bent Forward body tilt Relaxed wrist
10
Components: Ball Start Approach / Tempo Armswing Wrist position
Getting Started : With the Approach Components: Ball Start Approach / Tempo Armswing Wrist position Release Finish position 10
11
Getting Started / Ball Position:
Ball Waist high Ball positioned between shoulder & chin
12
Getting Started / Placing the ball in motion
Length of ball start 65% arm extension Ball generally moves out with initial step with ball side foot Separation between ball and shoulders Force Exerted Ball and body must be in sync and move as one Aggressive movement or force exerted to the ball will result in ball affecting body motion Ball Start movement is enough to initiate armswing Vertical Movement Direction is out or downward Excessive upward movement will tighten up arm muscles in order to lift the ball Excessive upward motion adds length and distance that the ball will travel
13
Getting Started / 4 Step Approach
How to determine the length of the Approach Take 4 ½ steps from the foul line (back towards the ball return) Position feet and ball in stance The pushaway (ball movement) begins with the first step Right handed bowlers - right foot steps first Left handed bowlers – left foot steps first (The first step is the shortest step.)
14
Getting Started / The Approach
4 Step Approach
15
Getting Started / The Approach
Steps in the delivery – Four Step delivery The ball should be down and at the knee in the second step Each step is progressively longer The ball is at the top of the back swing at the end of the third step The ball side foot slides to the opposite side The follow through is relaxed.
16
Wrist Broken (Bent downward)
Getting Started / Wrist Positions Wrist cupped Wrist straight Thumb at 12:00, fingers at 6:00. Wrist Broken (Bent downward) 16
17
The Key to Accuracy When it is set free
Getting Started / Armswing The Key to Accuracy When it is set free 17
18
Start OUT / Ball IN / Swing OUT
Getting Started / Armswing SWING PLANE Start OUT / Ball IN / Swing OUT 18
19
Getting Started / Follow-through
Follow-Through: Continue the swing of your arm until pointing at the pins. Left arm extended for balance, hips and shoulders square towards target. . Don’t open your hand when releasing the ball... Keep your fingers in the grip position 19
20
Getting Started / Follow-through
The Thumb passes through the target, fingers finish outside of the target at the end of the follow-thru. The line through the elbow, wrist, and thumb is the direction (trajectory) the ball will travel down the lane. 20
21
TEAM CANADA A Step Above
"Risk more than others think is safe. Care more than others think is wise. Dream more than others think is practical. Expect more than others think is possible" TEAM CANADA A Step Above
Similar presentations
© 2017 SlidePlayer.com Inc. | http://slideplayer.com/slide/1554039/ | CC-MAIN-2017-17 | refinedweb | 1,056 | 61.63 |
Marcos Duarte
Laboratory of Biomechanics and Motor Control ()
Federal University of ABC, Brazil
The sine and cosine functions (with the same amplitude and frequency) are different only by a constant phase $(^\pi/_2)$:$$\cos(t)=\sin(t+^\pi/_2) \quad , \quad \sin(t)=\cos(t-^\pi/_2)$$
This means for instance that we can use only sines to represent both sines and cosines. Because of that we can refer to both sine and cosine waves as sinusoids. The relation between the sine and cosine functions can be verified using the trigonometric identities, for example:$$ \sin(\alpha + ^\pi/_2) = \sin{\alpha} \cos{^\pi/_2} + \cos{\alpha} \sin{^\pi/_2} = \cos{\alpha} $$$$ \cos(\alpha - ^\pi/_2) = \cos{\alpha} \cos{^\pi/_2} + \sin{\alpha} \sin{^\pi/_2} = \sin{\alpha} $$
Sinusoids are periodic functions, that is, if their period is $T$, then $ x(t+T) = x(t)$.
A cosine is an even function and the sine an odd function, as illustrated next.
In the XIX century, the French mathematician Jean-Baptiste Joseph Fourier made the discovery that any (in fact, almost any) complicated but periodic function could be represented as a sum of sines and cosines with varying amplitudes and frequencies, which are known as the Fourier series, in his honor.
Based on the Fourier series, he also proposed a mathematical transformation to transform functions between time (or spatial) domain and frequency domain, known as the Fourier transform.
Nowadays, the Fourier transform is typically implemented employing an algorithm known as the Fast Fourier Transform (FFT).
Let's look at some basic concepts about sinusoids and then we will look at the Fourier series.
You should be familiar with basic trigonometry and the basic properties of signals before proceeding.
import numpy as np %matplotlib inline import matplotlib.pyplot as plt import sys sys.path.insert(1, r'./../functions') # directory of BMC Python functions
from even_odd_plot import even_odd_plot ax = even_odd_plot()
The integral of a sine or cosine function over one period (as matter of fact, over any integer multiple of the period) is zero:$$ \int_{t_0}^{t_0+T} \sin(k \frac{2 \pi}{T} t) \:\mathrm{d}t = 0 $$$$ \int_{t_0}^{t_0+T} \cos(k \frac{2 \pi}{T} t) \:\mathrm{d}t = 0 $$
Where $k$ is an integer and $ \sin(k2\pi t/T) $ or $ \cos(k2\pi t/T) $ are the harmonics with periodicities $T/k$.
This means that the total area over one period under the sine or cosine curve is zero; in other words, the average value of these functions is zero (the average value is the integral (area) over one period divided by the period), as illustrated in the next figure.
from sinusoid_int_plot import sinusoid_int_plot ax = sinusoid_int_plot()
Another important property of sinusoids is that they are orthogonal at different frequencies and cosines and sines are always orthogonal to each other. That is, if we multiply two sinusoids and integrate over one period the value is zero if the frequencies are different:$$ \int_{t_0}^{t_0+T} \sin(m \frac{2 \pi}{T} t)\sin(n \frac{2 \pi}{T} t) \:\mathrm{d}t = \left\{ \begin{array}{l l} 0 & \quad \text{if } m \neq n \\ T/2 & \quad \text{if } m = n \neq 0 \end{array} \right. $$$$ \int_{t_0}^{t_0+T} \cos(m \frac{2 \pi}{T} t)\cos(n \frac{2 \pi}{T} t) \:\mathrm{d}t = \left\{ \begin{array}{l l} 0 & \quad \text{if } m \neq n \\ T/2 & \quad \text{if } m = n \neq 0 \end{array} \right. $$
And:$$ \int_{t_0}^{t_0+T} \sin(m \frac{2 \pi}{T} t)\cos(n \frac{2 \pi}{T} t) \:\mathrm{d}t = \begin{array}{l l} 0, & \quad \quad \text{for all } n, m \end{array} $$
The term orthogonal here means independent and has a similar meaning as in linear algebra. It's not that cosines and sines are geometrically perpendicular to each other as are two orthogonal vectors in 3D space, but rather the fact that one vector (or sinusoid) cannot be expressed in terms of the other. For example, the following set forms an orthogonal set:$$ 1, \cos x, \sin x, cos 2x, \sin 2x, \dots $$
From linear algebra, we know that three orthogonal vectors in 3D space can form a basis, a set of linearly independent vectors that, in a linear combination, can represent every vector. In this sense, cosines and sines can also form a basis and they can be used in a linear combination to represent other mathematical functions. This is the essence of the Fourier series.
There is an interesting relationship between the sine, cosine, and exponential functions and complex numbers, known as the Euler's formula:$$ e^{i\theta} = \cos \theta + i \sin \theta $$
Where $e$ is the Napier's constant or Euler's number ($e=2.71828...$, the limit of $(1 + 1/n)^n$ as $n$ approaches infinity, and it's also the inverse of the natural logarithm function: $ln(e)=1$) and $i$ is the imaginary unit ($\sqrt{-1}=i$).
Using the Euler's formula, we can express the cosine and sine functions as:
Of note, a special case of the Euler's formula, known as the Euler's identity, has been referred as one of the most beautiful equations [1]:$$ e^{i\pi} + 1 = 0 $$
It may sound strange why one would use exponential functions and complex numbers instead of the 'simpler' sine and cosine functions, but it turns out that calculating the Fourier series is simpler with the exponential form.
Without further ado, a periodic function can be represented as a sum of sines and cosines, known as the Fourier series:$$ x(t) \sim \sum_{k=0}^\infty a_k \cos\left(k\frac{2\pi}{T}t\right) + b_k \sin\left(k\frac{2\pi}{T}t\right) $$
Where $a_k$ and $b_k$ are the Fourier coefficients.
When $k=0$, $\cos(0t)=1$ and $\sin(0t)=0$, then the Fourier series can be written as:$$ x(t) \sim a_0 + \sum_{k=1}^\infty a_k \cos\left(k\frac{2\pi}{T}t\right) + b_k \sin\left(k\frac{2\pi}{T}t\right) $$
Let's deduce how to calculate the Fourier coefficients $a_0$, $a_k$, and $b_k$.
The coefficient $a_0$ can be computed if we integrate the Fourier series over one period:
On the right side, the first term is the integral of a constant and the integral of the summation is zero because it's the integral over one period of sines and cosines. Then:$$ a_0 = \frac{1}{T} \int_{t_0}^{t_0+T} x(t) \:\mathrm{d}t $$
Which is the average value of the function $x(t)$ over the period $T$.
The coefficients $a_n$ and $b_n$ can be computed if we multiply the Fourier series respectively by $cos(\cdot)$ and $sin(\cdot)$ and integrate over one period (deduction not shown):$$ a_k = \frac{2}{T} \int_{t_0}^{t_0+T} x(t) \cos\left(k\frac{2\pi}{T}t\right) \:\mathrm{d}t $$$$ b_k = \frac{2}{T} \int_{t_0}^{t_0+T} x(t) \sin\left(k\frac{2\pi}{T}t\right) \:\mathrm{d}t $$
Note that $a_n$ and $b_n$ have the integrals multiplied by 2 while $a_0$ does not have this multiplication. Because of that, to make the equation for $a_0$ consistent with the equations for $a_n$ and $b_n$, it's common to also multiply by 2 the equation for $a_0$ and then express the Fourier series as:$$ x(t) \sim \frac{a_0}{2} + \sum_{k=1}^\infty a_k \cos\left(k\frac{2\pi}{T}t\right) + b_k \sin\left(k\frac{2\pi}{T}t\right) $$
The Fourier series is an expansion of a function and the following theorem states that the Fourier series actually converges to the function:
$$ \frac{1}{2}\left[f(x^+) + f(x^-)\right] $$$$ \frac{1}{2}\left[f(x^+) + f(x^-)\right] $$
The Fourier series of a piecewise continuous function $f(x)$ converges for all values of $x$ where $f(x)$ is continuous. At the values where $f(x)$ is discontinuous, the Fourier series is equal to the average of the right and left limits of $f(x)$:
Consider the following periodic function (a square wave with period $T=2\:s$):$$ x(t) = \left\{ \begin{array}{l l} -1 & \quad \text{if } -1 \leq t < 0\\ +1 & \quad \text{if } 0 \leq t < +1 \end{array} \right. $$$$ x(t + 2) = x(t), \quad \text{for all } t$$
Note that this function is discontinuous at $ t=\dots,-3,-2,-1,\;0,\;1,\;2,\;3,\dots$.
Which has the following plot:
from square_wave_plot import square_wave_plot ax = square_wave_plot() %config InlineBackend.close_figures=False # hold plot for next cell
The Fourier coefficients are given by ($a_0=0$ because the average value of $x(t)$ is zero):$$ a_k = \frac{2}{2}\left[\int_{-1}^0 -\cos\left(k\frac{2\pi}{2}t\right) \:\mathrm{d}t + \int_{0}^1 \cos\left(k\frac{2\pi}{2}t\right) \:\mathrm{d}t \right] $$$$ b_k = \frac{2}{2}\left[\int_{-1}^0 -\sin\left(k\frac{2\pi}{2}t\right) \:\mathrm{d}t + \int_{0}^1 \sin\left(k\frac{2\pi}{2}t\right) \:\mathrm{d}t \right] $$
Which results in:$$ a_k = 0 $$$$ b_k = \left\{ \begin{array}{c l} 0 & \quad \text{if k is even} \\ \frac{4}{k\pi} & \quad \text{if k is odd} \end{array} \right. $$
Then, the Fourier series for $x(t)$ is:$$ x(t) = \frac{4}{\pi} \left[ \sin(\pi t) + \frac{\sin(3\pi t)}{3} + \frac{\sin(5\pi t)}{5} + \frac{\sin(7\pi t)}{7} + \frac{\sin(9\pi t)}{9} + \dots \right] $$
The fact that the Fourier series of the given square wave has only sines is expected because the given square wave is an odd function, $x(t) = -x(-t)$. Then, its Fourier series should have only odd functions (sines).
Let's plot it:
t = np.linspace(-3, 3, 1000) x = 4/np.pi*(np.sin(1*np.pi*t)/1 + np.sin(3*np.pi*t)/3 + np.sin(5*np.pi*t)/5 + np.sin(7*np.pi*t)/7 + np.sin(9*np.pi*t)/9) ax.plot(t, x, color='r', linewidth=2, label='Fourier series') ax.set_title('Square wave function and the first 5 non-zero terms of its Fourier series', fontsize=14) %config InlineBackend.close_figures=True # hold off the figure plt.show()
And here are plots for each of the first five non-zero components:
t = np.linspace(-3, 3, 100) fig, axs = plt.subplots(5, 2, figsize=(9, 5), sharex=True, sharey=True, squeeze=True) axs = axs.flat x2 = t*0 for k, ax in enumerate(axs): if ~k%2: xf = 4/np.pi*np.sin((k+1)*np.pi*t)/(k+1) ax.plot(t, xf, 'r', linewidth=2) x2 = x2 + xf else: ax.plot(t, x2, 'r', linewidth=2) ax.xaxis.set_ticks_position('bottom') ax.set_ylim(-2, 2) ax.set_yticks([-1.5, 0, 1.5]) ax.grid() ax.set_xlabel('Time (s)', fontsize=16) axs[-2].set_xlabel('Time (s)', fontsize=16) axs[4].set_ylabel('Amplitude', fontsize=16) axs[0].set_title('First five harmonics') axs[1].set_title('Sum of the harmonics') fig.tight_layout() plt.subplots_adjust(hspace=0)
This animation resumes the steps we have done to compute the Fourier series of a square wave function:
Consider the following periodic function (a triangular wave with period $T=2\pi$):$$ x(t) = \left\{ \begin{array}{l l} 1+t/\pi & \quad \text{if } -\pi \leq t < 0\\ 1-t/\pi & \quad \text{if } 0 \leq t < +\pi \end{array} \right. $$$$ x(t + 2\pi) = x(t), \quad \text{for all } t$$
Which has the following plot:
from triangular_wave_plot import triangular_wave_plot ax = triangular_wave_plot() %config InlineBackend.close_figures=False # hold plot for next cell
The Fourier coefficients are given by:$$ a_0 = \frac{1}{2\pi} \left[ \int_{-\pi}^0 \left(1+t/\pi\right) \:\mathrm{d}t + \int_{0}^{\pi} \left(1-t/\pi\right) \:\mathrm{d}t \right] $$$$ a_k = \frac{1}{\pi} \left[ \int_{-\pi}^0 \left(1+t/\pi\right)\cos\left(k\frac{2\pi}{T}t\right) \:\mathrm{d}t + \int_{0}^{\pi} \left(1-t/\pi\right)\cos\left(k\frac{2\pi}{T}t\right) \:\mathrm{d}t \right] $$$$ b_k = \frac{1}{\pi} \left[ \int_{-pi}^0 \left(1+t/\pi\right)\sin\left(k\frac{2\pi}{T}t\right) \mathrm{d}t + \int_{0}^{\pi} \left(1-t/\pi\right)\sin\left(k\frac{2\pi}{T}t\right) \:\mathrm{d}t \right] $$
Which results in:$$ a_0 = 1/2 $$$$ a_k = \left\{ \begin{array}{c l} \frac{4}{k^2\pi^2} & \quad \text{if k is odd} \\ 0 & \quad \text{if k is even} \end{array} \right. $$$$ b_k = 0 $$
Then, the Fourier series for $x(t)$ is:$$ x(t) = \frac{1}{2} + \frac{4}{\pi^2} \left[ \cos(t) + \frac{\cos(3 t)}{3^2} + \frac{\cos(5 t)}{5^2} + \frac{\cos(7 t)}{7^2} + \frac{\cos(9 t)}{9^2} + \dots \right] $$
The given triangular wave is an even function, $x(t)=x(-t)$, and then its Fourier series has only even functions (cosines).
Let's plot it:
t = np.linspace(-3*np.pi, 3*np.pi, 1000) x = 1/2 + 4/np.pi**2*(np.cos(t) + np.cos(3*t)/9 + np.cos(5*t)/25 + np.cos(7*t)/49 + np.cos(9*t)/81) ax.plot(t, x, color='r', linewidth=2, label='Fourier series') ax.set_title('Triangular wave function and the first 6 non-zero terms of its Fourier series', fontsize=14) #ax.legend(frameon=False, loc='center right', framealpha=.5, fontsize=14) %config InlineBackend.close_figures=True # hold off the figure plt.show()
And here are plots for each of the first six non-zero components:
t = np.linspace(-3*np.pi, 3*np.pi, 100) fig, axs = plt.subplots(6, 2, figsize=(9, 5), sharex=True, squeeze=True) axs = axs.flat for k, ax in enumerate(axs): if k == 0: x2 = .5*t/t ax.plot(t, x2, 'r', linewidth=2) ax.set_ylim(-.65, .65) ax.set_yticks([-.5, 0, .5]) elif ~k%2: xf = 4/((k-1)*np.pi)**2*np.cos((k-1)*t) ax.plot(t, xf, 'r', linewidth=2) x2 = x2 + xf ax.set_ylim(-.65, .65) ax.set_yticks([-.5, 0, .5]) else: ax.plot(t, x2, 'r', linewidth=2) ax.set_ylim(-.15, 1.15) ax.set_yticks([0, 0.5, 1]) ax.xaxis.set_ticks_position('bottom') ax.set_xlim((-3*np.pi, 3*np.pi)) ax.grid() ax.set_xticks(np.linspace(-3*np.pi-0.1, 3*np.pi+0.1, 7)) ax.set_xticklabels(['$-3\pi$', '$-2\pi$', '$-\pi$', '$0$', '$\pi$', '$2\pi$', '$3\pi$']) ax.set_xlabel('Time (s)', fontsize=16) axs[-2].set_xlabel('Time (s)', fontsize=16) axs[4].set_ylabel('Amplitude', fontsize=16) axs[0].set_title('Average value and first five harmonics') axs[1].set_title('Sum of the harmonics') fig.tight_layout() plt.subplots_adjust(hspace=0)
The $a_k$ and $b_k$ coefficients are the amplitudes of the sine and cosine terms, each with frequency $k/T$, of the Fourier series.
We can express the Fourier series in a more explicit form with a single amplitude and phase using the trigonometric identities:
or$$ x(t) = c_0 + \sum_{k=1}^\infty c_k \cos\left(k\frac{2\pi}{T}t - \theta_k \right) $$
Where:$$ c_0=a_0 \quad , \quad c_k = \sqrt{a_k^2 + b_k^2} \quad , \quad \theta_k = \tan^{-1}\left(\frac{b_k}{a_k}\right) $$
The energy or power of each harmonic, which is proportional to the amplitude squared, is given by:$$ P_k = c_k^2 = a_k^2 + b_k^2 $$
The plot of the amplitude (or power) and phase of each harmonic as a function of the corresponding frequency is called the amplitude (or power) spectrum and phase spectrum, respectively. These spectra are very useful to visualize the frequency content of a function.
Using the Euler's formula, the complex form of the Fourier series is:$$ x(t) \sim \sum_{k=-\infty}^\infty c_k \exp\left(ik\frac{2\pi}{T}t\right) $$
It can be shown that the relation between $c_k$, $a_k$, and $b_k$ coefficients is:$$ c_0 = \frac{a_0}{2} \quad , \quad c_k = \frac{a_k-i b_k}{2} \quad , \quad c_{-k} = \frac{a_k+i b_k}{2}$$
And: $$ a_k = 2\text{ Real}\{c_k\} \quad \text{and} \quad b_k = -2\text{ Imag}\{c_k\} $$
The complex Fourier coefficients, $c_k$, can be determined similarly to $a_k$ and $b_k$:$$ c_k = \frac{1}{T} \int_{t_0}^{t_0+T} x(t)\exp\left(-ik\frac{2\pi}{T}t\right) \:\mathrm{d}t $$
And the amplitudes and phases of the Fourier series in complex form are given by:$$ |c_k| \, = \, |c_{-k}| \, = \, \frac{1}{2}\sqrt{a_k^2 + b_k^2} \quad , \quad \phi_k \, = \, \tan^{-1}\left(-\frac{b_k}{a_k}\right)\,=\, \tan^{-1}\left(\frac{\text{Imag}\{c_k\}}{\text{Real}\{c_k\}}\right)$$
The complex form is more often used to express the Fourier series and in the calculation of the amplitude (or power) and phase spectra.
Let's calculate again the Fourier series of the square wave function but now using the complex form.
The $c_k$ coefficients are given by ($c_0=0$ because the average value of $x(t)$ is zero):$$ c_k = \frac{1}{2}\left[ \int_{-1}^0 -\exp\left(-ik\frac{2\pi}{2}t\right) \:\mathrm{d}t + \int_{0}^1 \exp\left(-ik\frac{2\pi}{2}t\right) \:\mathrm{d}t\right] $$$$ = \frac{i\:exp(-ik\pi)-i}{k\pi} $$$$ = \frac{i}{k\pi}\left(\cos(k\pi) - 1\right) $$
Which results in:$$ c_k = \left\{ \begin{array}{c l} 0 & \quad \text{if k is even} \\ -\frac{2i}{k\pi} & \quad \text{if k is odd} \end{array} \right. $$
If you compare with the previous calculation you will notice some differences.
First, now the expression is multiplied by 2 instead of by 4. But remember that now $k$ goes from $-\infty$ to $\infty$, i.e., we will now add terms for $k=\pm1,\pm2,\pm3,\dots$, meaning that the expression above will be counted twice for each $|k|$.
Second, the $c_k$ coefficients are purely imaginary; the imaginary part is negative when $k$ is positive and positive when $k$ is negative.
So, the amplitude $\text{A}_k$ and phase $\phi_k$ of each Fourier coefficient for $k > 0$ are:$$ \text{A}_k = \left\{ \begin{array}{c l} 0 & \quad \text{if k is even} \\ \frac{2}{k\pi} & \quad \text{if k is odd} \end{array} \right. $$$$ \phi_k = \left\{ \begin{array}{c l} 0 & \quad \text{if k is even} \\ -\frac{\pi}{2} & \quad \text{if k is odd} \end{array} \right. $$
And the negative of these expressions for $k < 0$.
Let's plot the corresponding amplitude and phase spectra:
k = np.arange(-9,10) fk = k/2 ampk = 2/(k*np.pi) ampk[1::2] = 0 phik = -np.pi/2*(k+.1)/abs(k+.1)*180/np.pi phik[1::2] = 0 fig, ax = plt.subplots(2, 1, figsize=(9, 5), sharex=True) ax[0].stem(fk, ampk, markerfmt='ro', linefmt='r-') ax[0].set_ylim(-.7, .7) ax[0].annotate('Frequency (Hz)', xy=(3, -.3), xycoords = 'data', color='k', size=14, xytext=(0, 0), textcoords = 'offset points') ax[0].set_title('Amplitude', fontsize=16) ax[1].stem(fk, phik, markerfmt='ro', linefmt='r-') ax[1].set_title('Phase ( $^o$)', fontsize=16) ax[1].set_xlim(-4.55, 4.55) ax[1].set_ylim(-120, 120) ax[1].set_yticks([-90, 0, 90]) ax[1].annotate('Frequency (Hz)', xy=(3, 15), xycoords = 'data', color='k', size=14, xytext=(0, 0), textcoords = 'offset points') for axi in ax: axi.spines['left'].set_position('zero') axi.spines['right'].set_color('none') axi.spines['bottom'].set_position('zero') axi.spines['top'].set_color('none') axi.spines['right'].set_color('none') axi.xaxis.set_ticks_position('bottom') axi.yaxis.set_ticks_position('left') axi.tick_params(axis='both', direction='inout', which='both', length=5) axi.locator_params(axis='y', nbins=4) fig.tight_layout() plt.subplots_adjust(hspace=0.2)
C:\Miniconda3\lib\site-packages\ipykernel_launcher.py:3: RuntimeWarning: divide by zero encountered in true_divide This is separate from the ipykernel package so we can avoid doing imports until
Usually we don't care for the negative frequencies of real signals and we are more interested in the power of the signal:
Pk = ampk[int((ampk.size)/2):]**2 fig, ax = plt.subplots(1, 1, figsize=(9, 3)) ax.stem(fk[int((fk.size)/2):], Pk, markerfmt='ro', linefmt='r-') ax.plot(fk[int((fk.size)/2):], Pk, 'ro', clip_on=False) ax.set_ylabel('Power', fontsize=16) ax.set_xlabel('Frequency (Hz)', fontsize=16) ax.set_xlim(0, 4.55) ax.grid() fig.tight_layout() | https://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/FourierSeries.ipynb | CC-MAIN-2021-25 | refinedweb | 3,411 | 51.78 |
badidea wrote:I think I got another addition. There seems to be no .. page. Don't know if it has a name.
Indeed. To compare, in C++ there is '::' scope resolution operator, and '.' member access operator. In fbc we use '.' (dot) operator for both, for example:
Code: Select all
namespace N1
dim X as integer
end namespace
namespace N2
dim X as integer
end namespace
using N1 '' import namespace
using N2 '' import namespace
print N1.X '' OK '.' operator resolves scope
print N2.X '' OK '.' operator resolves scope
print X '' error: abiguous symbol access
But, '.' operator on its own does not let us resolve scope to global namespace. To refer to the global namespace, we have '..' operator. For example:
Code: Select all
sub proc()
print "global proc()"
end sub
namespace N
const false as integer = 111
const true as integer = 999
sub proc()
print "N.proc()"
end sub
sub test()
proc() '' call N.proc()
..proc() '' call global proc()
'' N.false, N.true
print false, true
'' global false, true
print ..false, ..true
end sub
end namespace
N.test()
I suggest new page KeyPgOpScope for an additional page on '.', and KeyPgOpGlobalScope for undocumented '..', but whatever you guys think. The existing KeyPgOpMemberAccess is about an operator that works on expression, but '.' & '..' for scope resolution operates on symbol names.
Also, not sure if this is a bug or a side effect of shadowing, or just a bad example on my part:
Code: Select all
'' not quite the same for variables
dim y as integer = 1
scope
dim y as integer = 2
print y '' prints 2
print ..y '' prints 2
end scope | https://www.freebasic.net/forum/viewtopic.php?f=9&t=26254&start=180 | CC-MAIN-2019-30 | refinedweb | 266 | 68.57 |
The QScreenDriverFactory class creates screen drivers in Qt for Embedded Linux. More...
#include <QScreenDriverFactory>
The QScreenDriverFactory class creates screen drivers in Qt for Embedded Linux.
Note that this class is only available in Qt for Embedded Linux.
QScreenDriverFactory is used to detect and instantiate the available screen drivers, allowing Qt for Embedded Linux to load the preferred driver into the server application at runtime. The create() function returns a QScreen object representing the screen driver identified by a given key. The valid keys (i.e. the supported drivers) can be retrieved using the keys() function.
Qt for Embedded Linux provides several built-in screen drivers. In addition, custom screen drivers can be added using Qt's plugin mechanism, i.e. by subclassing the QScreen class and creating a screen driver plugin (QScreenDriverPlugin). See the display management documentation for details.
See also QScreen and QScreenDriverPlugin.
Creates the screen driver specified by the given key, using the display specified by the given displayId.
Note that the keys are case-insensitive.
Returns the list of valid keys, i.e. the available screen drivers. | http://doc.trolltech.com/main-snapshot/qscreendriverfactory.html#create | crawl-003 | refinedweb | 180 | 51.95 |
Opened 11 years ago
Closed 11 years ago
Last modified 10 years ago
#398 closed enhancement (wontfix)
[patch] {%define VAR as%}VALUE{%in%} tag
Description
I submit two patches.
The first patch modifies Parser.parse() to optionally pass its parse_until
context to the do_* callbacks. This allows template tags to have scopes
which are ended implicitly by the end of the enclosing scope.
The second patch defines a {% define VAR as %} VALUE {% in %} construct.
A typical use is:
{% define title_var as%} {% block title %}The default title{% endblock %} {% in %} <html> <head> <title>{{title_var}}</title> </head> <body> <h1>{{title_var}}</h1> ...
Here, by redefining the title block, a template can set the title BOTH in the <head> and the <body> of the page. Many other uses are possible. Note that this is not an attempt to turn the Django template system into a full-fledged programming language, it's just sometimes convenient to declare a name for a value and refer to it later.
I have put the define-tag in defaulttags.py because I feel that, as a
language construct, defining new variable bindings is at the same level as
FOR loops and IF statements.
If you do not agree, I hope you will still
accept the first patch, because it will allow me to put this define-tag
in my own apps and still use them with a standard Django installation.
(The define-tag uses the implicit ending feature introduced by the
first patch.)
Attachments (2)
Change History (7)
Changed 11 years ago by
Changed 11 years ago by
patch for new {%define VAR as%}VALUE{%in%} tag
comment:1 Changed 11 years ago by
why not {% define var %}<var value>{% in %}<body using definition>{% enddefine %} - that would be much more like other tags in the django template language. This "implicit end" looks ugly to me. And it would be a tag that's similar with the structure of if-else-endif for example.
comment:2 Changed 11 years ago by
I'd like to have another feature :)
{% set var_name1 as var_name2 %}
Example (in form):
{% set form.poll as f %}
label: {{ f }}
{% if f.errors %} {{ f.errors }} {% endif %}
... Other common things with f.* ...
Then copy-paste such element and change only first line
comment:3 Changed 11 years ago by
Hugo, for and if really need endfor and endif.
However, notice that {%extends%} for instance, doesn't.
It just takes control of the rest of the template.
If you define something, you are usually mostly thinking of what you are defining.
Where the definition ends does not really make a difference.
I find it a nuisance to have to go to the end of the file just because I added a definition at the beginning. However, you have a point, it should probably be possible to end the scope explictly
if needed.
mr_little, that is indeed a good idea. I'll see if I can create a new patch with support for something like {%define VAR as SOMETHING in%}BODY.
I explicitly avoided the word "set", because it suggests that I am somehow changing the context, rather than create a new, improved context. Hugo is right that including an {%enddefine%} would make that even more clear.
comment:4 Changed 11 years ago by
I'm a Smarty junkie/user, so bear with me... In a lot of my templates, I use the 'assign' function, which does what you are saying. I try to keep them to a minimal and set things within the site's actual code, to keep as much a separation between code and layout, but there *are* times when it is handy to have, to either simplify the readability of the template or to a temporary value if/when it is needed. (Sometimes, it is.)
I propose, to make it as simple as what Smarty has, but Django-like, rather like the 'cycle' function:
{% assign new_value as var_name %}
Then, if you wanted to hold a block chuck in a var:
{% assign_block as var_name %}...{% endassign %}
comment:5 Changed 11 years ago by
I'm marking this as a wontfix because the template system isn't intended to be a full programming language. Of course, there's nothing stopping you from using this as a custom tag on your own.
Patch for Parser.parse() to pass parse_until to do_* callbacks | https://code.djangoproject.com/ticket/398 | CC-MAIN-2017-04 | refinedweb | 720 | 70.73 |
MouseDown is called when the user has pressed the mouse button while over the Collider.
This event is sent to all scripts of the GameObject with Collider or GUIElement. Scripts of the parent or child objects do not receive this event.
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement;
public class ExampleClass : MonoBehaviour { void OnMouseDown() { // Destroy the gameObject after clicking on it Destroy(gameObject); } }
This function is not called on objects that belong to Ignore Raycast layer.
This function is called on Colliders marked as Trigger if and only if Physics.queriesHitTriggers is true.
OnMouseDown can be a coroutine.
Did you find this page useful? Please give it a rating: | https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html | CC-MAIN-2020-16 | refinedweb | 110 | 61.73 |
A command queue, used to execute command lists on the GPU. More...
#include <reshade_api_device.hpp>
A command queue, used to execute command lists on the GPU.
Functionally equivalent to the immediate 'ID3D11DeviceContext' or a 'ID3D12CommandQueue' or 'VkQueue'.
This class may NOT be used concurrently from multiple threads!
Opens a debug event region in the command queue.
Closes the current debug event region (the last one opened with begin_debug_event).
Flushes and executes the special immediate command list returned by get_immediate_command_list immediately. This can be used to force commands to execute right away instead of waiting for the runtime to flush it automatically at some point.
Gets a special command list, on which all issued commands are executed as soon as possible (or right before the application executes its next command list on this queue). This only exists on command queues that contain the command_queue_type::graphics flag, on other queues
nullptr is returned.
Gets the type of the command queue, which specifies what commands can be executed on it.
Inserts a debug marker into the command queue.
Waits for all issued GPU operations on this queue to finish before returning. This can be used to ensure that e.g. resources are no longer in use on the GPU before destroying them. | https://crosire.github.io/reshade-docs/structreshade_1_1api_1_1command__queue.html | CC-MAIN-2022-27 | refinedweb | 209 | 57.57 |
Join two Sets in Python
In this article, we will learn to join two or more sets in Python. We will use some built-in functions, some simple approaches, and some custom codes as well to better understand the topic. Let's first have a quick look over what is a set and how it is different from a list in Python.
Python Set
Python has a built-in data type called set. It is a collection of unordered data values. Due to the unordered dataset, the user is not sure of the order in which data values appear. An unordered dataset leads to unindexed values. Set values cannot be accessed using index number as we did in the list. Set values are immutable which means we cannot alter the values after their creation. Data inside the set can be of any type say, integer, string, or float value. The set uses comma-separated values within curly brackets
{}to store data. Sets can be defined using any variable name and then assigning different values to the set in the curly bracket. The set is unordered, unchangeable, and does not allows duplicate values.
set1 = {"Ram","Arun","Kiran"} set2 = {16,78,32,67} set3 = {"apple","mango",16,"cherry",3}
Join two Sets in Python
Joining two or more sets in Python basically means the union of all the sets. As we learned in mathematics that union combines all the elements from different sets into one set. We know that set does not allow duplicate members, so after the union of sets, only unique elements will be printed. This is a class of operation called a "set operation", which Python sets provide convenient tools for.
Let us look at the below examples and learn what are the different ways to join or combine two or multiple sets into one set.
- Using union() function
- Using update() function
- Using " | " operator
- Using reduce() function
- Using itertools.chain() function
- Using " * " operator
- By converting sets to lists
Example: Join sets using union() function
This method uses
union() to join two or more sets. It returns the union of sets A and B. It does not modify set A in place but returns a new resultant set. The union is the smallest set of all the input sets taken and it does not allow any duplicate elements too.
set1 = {"a", "b" , "c"} set2 = {1, 2, 3} #new set set3 = set1.union(set2) print(set3)
{"a","b","c",1,2,3}
union() function can also be used in a different way. Look at the below example-
Example 2
set1 = {1, 3} set2 = {5} set3 = {7, 9} new_set = set().union(set1).union(set2).union(set3) print(new_set)
{1,3,5,7,9}
Example: Join sets using the" | " Operator
This operator is called the union operator and works similarly to the
union() function. It joins two or more sets and returns a new set of unique elements.
set1 = {'a', 'c', 'd'} set2 = {'c', 'd', 2 } set3 = {1, 2, 3} print('Join set1 and set2- ', set1 | set2) print('Join set2 and set3 =', set2 | set3) print('Join set1 ,set2, and set3- ', set1 | set2 | set3)
Join set1 and set2- {"a", "c", "d", 2}
Join set2 and set3- {"c", "d", 2 , 3}
Join set1, set2 and set3- {"a", "c", "d", 2, 1, 3}
Example: Join sets using update() Function
The
update() method inserts all the items from one set into another and automatically does not allow duplicate elements to enter. This method joins two sets at a time.
set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set1.update(set2) print(set1)
{1, 2, 3, 'c', 'a', 'b'}
In this case, if you want to create a new set, you first need to use the copy() function on the first set and then store the result in a new set. Apply update function on this new set and a second input set was taken.
set1 = {1, 4, 2, 5} set2 = {8, 2, 1, 6} set3 = set1.copy() set3.update(set2) print(set3)
{1,4,2,5,8,6}
Example: Join sets using reduce() Function
This reduce function imports
operator and we need to use
functools.reduce module to join two sets in Python. It returns the bitwise
or of set1 and set2 which is similar to the union function in mathematical language.
import operator from functools import reduce set1 = {4, 5, 6, 7} set2 = {6, 7, 8, 9} print(reduce(operator.or_, [set1, set2]))
{4, 5, 6, 7, 8, 9}
Example: Join sets using itertools.chain() Function
The
itertools module provides several useful functions to create iterators for efficient looping. In this case, we use its
chain() function to join two or more sets together as shown below in the example.
import itertools set1 = {1, 3} set2 = {5} set3 = {7, 9} new_set = set(itertools.chain(set1, set2, set3)) print(new_set)
{1, 3, 5, 7, 9}
Example: Join sets using " * " Operator
With Python 3.5, you can use the
Unpacking is where an iterable (e.g. a set or list) is represented as every item it yields because the set can only contain unique items.
*iterable unpacking operator for joining multiple sets. It is called the unpacking operator because * unpack the set.
import itertools set1 = {1, 3} set2 = {5} set3 = {7, 9} new_set = (*set1, *set2, *set3) print(new_set)
{1, 3, 5, 7, 9}
Conclusion
In this article, we learned to join two or more sets by using several built-in functions such as
update(),
union(),
reduce() and operators like
|,
*etc and we used some custom codes as well. We learned about the difference between lists and sets and how we can convert a set to a list. We saw several examples of the sets showing that it is an unordered data type. | https://www.studytonight.com/python-howtos/join-two-sets-in-python | CC-MAIN-2022-21 | refinedweb | 954 | 70.23 |
The code and tips here, are all included in the new pyzmail library. More samples and tips can be found in the API documentation.
Welcome to this series of two small articles about how to parse emails using Python. This first one is about mail header. The second one is about mail content.
A lot of programs and libraries commonly used to send emails don't comply with RFC. Ignore such kind of email is not an option because all mails are important. It is important to do it best when parsing emails, like does most popular MUA.
Python's has one of the best library to parse emails: the email package.
Regarding RFC 2047 non ascii text in the header must be encoded. RFC 2822 make the difference between different kind of header. *text field like Subject: or address fields like To:, each with different encoding rules. This is because RFC 822 forbids the use of some ascii characters at some place because they have some meaning, but these ascii characters can be used when they are encoded because the encoded version don't disturb the parsing of string.
Python provides email.Header.decode_header() for decoding header. The function decode each atom and return a list of tuples ( text, encoding ) that you still have to decode and join to get the full text. This is done in my getmailheader() function.
For addresses, Python provides email.utils.getaddresses() that split addresses in a list of tuple ( display-name, address ). display-name need to be decoded too and addresses must match the RFC2822 syntax. The function getmailaddresses() does all the job.
Here are the functions in actions.
import re import email from email.Utils import parseaddr from email.Header import decode_header # email address REGEX matching the RFC 2822 spec # from perlfaq9 #}; # # Python translation atom_rfc2822=r"[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+" atom_posfix_restricted=r"[a-zA-Z0-9_#\$&'*+/=?\^`{}~|\-]+" # without '!' and '%' atom=atom_rfc2822 dot_atom=atom + r"(?:\." + atom + ")*" quoted=r'"(?:\\[^\r\n]|[^\\"])*"' local="(?:" + dot_atom + "|" + quoted + ")" domain_lit=r"\[(?:\\\S|[\x21-\x5a\x5e-\x7e])*\]" domain="(?:" + dot_atom + "|" + domain_lit + ")" addr_spec=local + "\@" + domain email_address_re=re.compile('^'+addr_spec+'$') raw="""MIME-Version: 1.0 Received: by 10.229.233.76 with HTTP; Sat, 2 Jul 2011 04:30:31 -0700 (PDT) Date: Sat, 2 Jul 2011 13:30:31 +0200 Delivered-To: alain.spineux@gmail.com Message-ID: <CAAJL_=kPAJZ=fryb21wBOALp8-XOEL-h9j84s3SjpXYQjN3Z3A@mail.gmail.com> Subject: =?ISO-8859-1?Q?Dr.=20Pointcarr=E9?= From: Alain Spineux <alain.spineux@gmail.com> To: =?ISO-8859-1?Q?Dr=2E_Pointcarr=E9?= <alain.spineux@gmail.com> Content-Type: multipart/alternative; boundary=000e0cd68f223dea3904a714768b --000e0cd68f223dea3904a714768b Content-Type: text/plain; charset=ISO-8859-1 -- Alain Spineux --000e0cd68f223dea3904a714768b Content-Type: text/html; charset=ISO-8859-1And the ouput:
--
Alain Spineux
--000e0cd68f223dea3904a714768b-- """ def getmailheader(header_text, default="ascii"): """Decode header_text if needed""" try: headers=decode_header(header_text) except email.Errors.HeaderParseError: # This already append in email.base64mime.decode() # instead return a sanitized ascii string return header_text.encode('ascii', 'replace').decode('ascii') else: for i, (text, charset) in enumerate(headers): try: headers[i]=unicode(text, charset or default, errors='replace') except LookupError: # if the charset is unknown, force default headers[i]=unicode(text, default, errors='replace') return u"".join(headers) def getmailaddresses(msg, name): """retrieve From:, To: and Cc: addresses""" addrs=email.utils.getaddresses(msg.get_all(name, [])) for i, (name, addr) in enumerate(addrs): if not name and addr: # only one string! Is it the address or is it the name ? # use the same for both and see later name=addr try: # address must be ascii only addr=addr.encode('ascii') except UnicodeError: addr='' else: # address must match adress regex if not email_address_re.match(addr): addr='' addrs[i]=(getmailheader(name), addr) return addrs msg=email.message_from_string(raw) subject=getmailheader(msg.get('Subject', '')) from_=getmailaddresses(msg, 'from') from_=('', '') if not from_ else from_[0] tos=getmailaddresses(msg, 'to') print 'Subject: %r' % subject print 'From: %r' % (from_, ) print 'To: %r' % (tos, )
Subject: u'Dr. Pointcarr\xe9' From: (u'Alain Spineux', 'alain.spineux@gmail.com') To: [(u'Dr. Pointcarr\xe9', 'alain.spineux@gmail.com')]
tweety (not verified)
Wed, 07/06/2011 - 19:52
Permalink
get Email Content
Thanks! But what should I do if I want to get the email content ? Any suggestions?
aspineux
Thu, 07/07/2011 - 00:51
Permalink
Part 2 will speak about mail content
This is the object of coming part 2.
tweety (not verified)
Thu, 07/07/2011 - 12:59
Permalink
Thanks, will look forward for
Thanks, will look forward for it. Currently Im using email parser to get the content by using -
msg = email.message_from_string(raw_message)
But in case of multiparts or if the content type in the email header is not defined well, then it does not always return correct results.
I hope your next tutorial would help with this. Thanks again! :-)
Terry Bates (not verified)
Mon, 10/29/2012 - 04:43
Permalink
Thank you for this code. I
Thank you for this code. I was mucking about with O'Reilly's new book "Agile Data." There is an Open Feedback system that one can use to read the book before it is published. It talked about using code to download Gmail folder contents, but did not provide the code I would need to parse it. I think I will be using this snippet in the future.
Add new comment | http://blog.magiksys.net/parsing-email-using-python-header | CC-MAIN-2020-40 | refinedweb | 880 | 59.4 |
Rearranging spaces between words in Python
In this tutorial, we will be solving a Leet code weekly contest problem in which we are required to rearrange the spaces between a given string text using Python programming.
Assume that we are given a string that has a bit of text and in between those words we find that there are a number of unhealthy spaces between them. This means that instead of conventionally having a single space character in between words, the spaces may be more than that.
Our goal can be thought of as something similar to text formatting. We will be required to parse through the text and split the spaces equally between the words such that the number of space characters between any two words in a given text will be equal.
Procedure:
If we are mathematically unable to perform such an operation, we are allowed to put the extra spaces in the end. I have solved the problem in the manner given below and used Python for its implementation.
In a variable a, we extract the words alone and store it in a list which is achieved by the line:
a=text.split()
Counting spaces:
Our first goal would be to count the number of spaces in the given text. I handle texts with only one word in an easier fashion since all you’ve got to do it just add those extra spaces at the front to the back. This done using this following block of code:
for i in list(text): if(i==" "): spaces+=1
Splitting the spaces:
If the text contains more than one words, again the first thing I do is to count the number of total number of spaces. Next step is to count if the even split is possible. If there are enough words to split the spaces between the words, we can easily reconstruct the correct string with the number of spaces between each word calculated as spaces / (len(a)-1), where len(a) represents the number of words.
if(spaces%(len(a)-1)==0): for j in a: mystr+=j + int((spaces/(len(a)-1)))*" " return (mystr[0:len(mystr)-int((spaces/(len(a)-1)))])
The format of every word should be
word + equal number of spaces.
The number of spaces after every word should be n = (spaces/(len(a)-1)). This space must not be added after the last word.
The above block of code does the job when spaces can be equally split between the words. We check for the condition if it’s possible to split spaces among words equally. This is carried out using the if statement. After that, we append to the empty string, each word and the number of spaces that need to follow it. The variable j represents the word and (spaces/(len(a)-1)) indicates the number of spaces. We use len(a)-1 because the spaces have to be split between the words. For eg., if there are 2 words, there is only 1 position in between 2 words for the spaces to fit in.
After that, we see that for the last word also we have added the spacing which needs to be removed before returning. Therefore in the return statement, we exclude the last n spaces using string slicing.
Extraspaces:
If this is not the case, we will have to add the extra spaces towards the end which can be calculated as the reminder of the above operation. The new string is reconstructed as per this format i.e. by splitting the spaces equally and finally adding the remaining spaces towards the end. This logic has been implemented in the Python code*" ")
In the above block of code, we first calculate the number of spaces we need to add towards the end as the reminder of the total number of spaces when divided by the no. of positions between words. Now the total number of spaces that we need to split equally between the words comes down to spaces – extraspaces. As usual we split the new spaces equally and construct the string. We are not done yet. We need to add the extraspaces towards the end as extraspaces*” “. This is done in the return statement.
Examples:
Input:
welcome everyone
Output:
welcome everyone
Input:
" this is a sentence "
Output:
"this is a sentence"
We see that we have split the spaces (9) equally between the three words.
Input:
"Code Speedy Tech"
Output:
"Code Speedy Tech "
Here, we have 5 spaces and 3 words. We can not equally split them. There is one extra space. So we places two spaces after every word and after the last word, place the extra space.
Here is the complete Python code to the above logic:
class Solution: def reorderSpaces(self, text: str) -> str: spaces=0 print(list(text)) a=text.split() print(a) if(len(a)==1): if(text[0]==" "): for k in text: if(k==" "): spaces+=1 return str(a[0])+ spaces*" " else: for i in list(text): if(i==" "): spaces+=1 mystr="" if(spaces%(len(a)-1)==0): #Condition when spaces can be equally split between the words for j in a: mystr+=j + int((spaces/(len(a)-1)))*" " #For every word, add the required number of spaces after it return (mystr[0:len(mystr)-int((spaces/(len(a)-1)))])*" ") | https://www.codespeedy.com/rearranging-spaces-between-words-in-python/ | CC-MAIN-2021-43 | refinedweb | 889 | 68.7 |
There are a number of new features and some bugs fixed in the Windows Imaging Component for Windows 8. With the installation of KB 2670838 this new version of WIC is also available on Windows 7 Service Pack 1.
The Windows 8.0 SDK contains the latest version of the headers needed to build with the new version of WIC. The behavior of
wincodec.h changes depending your build-settings. If you build with
_WIN32_WINNT set to 0x602 or later, then
WINCODEC_SDK_VERSION,
CLSID_WICImagingFactory, and
CLSID_WICPngDecoder are set to use "WIC2" by default. Otherwise, it uses the old "WIC1" version. This means Windows Store apps and Win32 desktop applications built for Windows 8 only are already using the new version of WIC. No muss. No fuss. Win32 desktop applications built for older versions of Windows continue to use "WIC1" and the old behaviors are maintained.
If, however, you want to use "WIC2" when it is available but successfully fall back to "WIC1" on Windows Vista or Windows 7 without the KB 2670838 update, then things get a little tricky. The
_WIN7_PLATFORM_UPDATE define 'opts-in' to the Windows 8 header behavior without requiring you set your
_WIN32_WINNT define in a way that doesn't support older versions of Windows. You will want to avoid using
WINCODEC_SDK_VERSION,
CLSID_WICImagingFactory, and
CLSID_WICPngDecoder and instead use the explicit 'version' ones. You also need to be careful when using the four new WIC pixel format GUIDs (
GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat96bppRGBFloat, and
GUID_WICPixelFormat64bppPRGBAHalf) as they are not valid for use with "WIC1" APIs.
For example, here is how you should be creating the WIC factory for Win32 desktop applications that support older versions of Windows:
#define _WIN7_PLATFORM_UPDATE
#include <wincodec.h>
// CoInitializeEx needs called at some point before this
IWICImagingFactory* wicFactory = nullptr;
HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory2, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory2), reinterpret_cast<LPVOID*>( &wicFactory ) );
if ( SUCCEEDED(hr) )
{
// WIC2 is available on Windows 8 and Windows 7 SP1 with KB 2670838 installed
// Note you only need to QI IWICImagingFactory2 if you need to call CreateImageEncoder
}
else
{
hr = CoCreateInstance(CLSID_WICImagingFactory1, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory), reinterpret_cast<LPVOID*>( &wicFactory ) );
}
This results in the application using the new "WIC2" behaviors when available, but falls back to the older versions of WIC when it's not available.
DirectXTK and DirectXTex were both recently updated to support "WIC2" when it is available. This includes use of new WIC pixel formats (
GUID_WICPixelFormat96bppRGBFloat is the most useful since it matches
DXGI_FORMAT_R32G32B32_FLOAT ), opts into the new Windows BMP
BITMAPV5HEADER support (which encodes 32-bit with alpha channels for
GUID_WICPixelFormat32bppBGRA and reads such BMP files as well), and can make use of the fix to the TIFF decoder for 96bpp floating-point images (which load as
GUID_WICPixelFormat96bppRGBFloat).
Windows phone: Note that the Windows phone 8.0 platform does not support the WIC API, but Windows phone 8.1 does include it.
Xbox One: The Xbox One platform includes "WIC2". The HD Photo / JPEG XR codec is not currently supported for Xbox One XDK development.
VS 2012 Update 1: When building with the "v110_xp" Platform Toolset, the WIC2 header content is not available so avoid the use of
_WIN7_PLATFORM_UPDATE for these configurations.
Windows 8.1: There are a few additional changes to WIC with Windows 8.1 including support for a limited DDS codec. See MSDN.
Hi Chuck,
A user of SharpDX has reported that using WIC in multithreading to decode JPEG image in // is producing some corrupted images.
Do you know if WIC is actually thread-safe?
Thanks
Which OS are you using? According to this page, WIC CODECS at least should be thread-safe. | https://blogs.msdn.microsoft.com/chuckw/2012/11/19/windows-imaging-component-and-windows-8/ | CC-MAIN-2018-13 | refinedweb | 593 | 52.19 |
Lance got me to dig out my initial stab at a tar-file class, which got
me to thinking about sequences again. "pseudo-sequence" is the wrong
name: they DO always present the Abstract Data Type of a sequence, and
they often really ARE sequences, ( a tar-file certainly IS a sequence )
though they are sometimes not represented internally as a sequence, or
at least, not as the SAME sequence that they present to the outside
world.
Often, the primary reason for casting them as a sequence is so that
they can easily be processed sequentially by 'for'.
Some time ago, I posted an example of how to implement a sequence of
indefinite length by "promising" one more element that the current
length, until the end. ( And if the class reads-ahead one token, then
it doesn't even have to lie about it! ) This produces a stream like
sequence with initially one element, which attempts to produce or
evaluate more elements on demand.
For extremely large tar-files, I was considering a further
modification of this technique, where only an N-deep cache is kept.
Rather than growing full size when it had been processed to the end,
it would expand to a limit and stay there, throwing away previously
used values.
Using this in conjunction with 'filter' seemed like a good idea for
my tar-file class: the complete tar-file might be tens or hundreds of
megabytes, but a particular "interesting" subset might easily fit into
memory. And 'filter' could be used to produce a (real) list from the
sequence class.
So, I dusted off my old example, "flines.py" and appended a couple of
lines at the end to test it with 'filter' :
( I also had to change "builtin" to "__builtin__" . )
# Class Flines
#
# This is a demonstration/test of a class that "lazily" coerces
# the lines of a file into a sequence.
# It was written mostly to test the technique of lying about
# the length of the sequence by +1, except at the end.
# It has the feature that it will continue to try to read
# file when it gets to eof, so even if file continues to grow,
# so that:
# for x in flines_obj: print x[:-1]
# will always print whatever is currently available.
# ( But that also means that flines_obj[-1] is very context sensitive! )
#
# <sdm7g@Virginia.EDU>
#
import posix
import __builtin__
def rdopen( fname ): # open file or pipe for reading
if fname[-1] == '|' :
open = posix.popen
fname = fname[:-1]
else: open = __builtin__.open
return open( fname, 'r' )
class Flines:
def _lie( self ): return self._len + 1
def _get1( self ):
if self._cache[-1]:
self._cache.append( self._file.readline() )
self._len = self._len + 1
else:
self._cache[-1] = self._file.readline()
def __init__( self, fname ):
self._file = rdopen( fname )
self._cache = [ self._file.readline() ]
self._len = 1
def __len__( self ):
if self._cache[-1]:
return self._lie()
else:
self._get1()
if self._cache[-1]: return self._lie()
else: return self._len
def __getitem__( self, j ):
if j < 0 :
self._get1()
elif j >= self._len :
for index in range( self._len, j+1 ): self._get1()
return self._cache[j]
def __del__(self):
self._file.close()
def __getslice__( self, i, j ):
return self._cache[i:j]
F=Flines('nl -ba flines.py|' )
print '# Test me once...'
for x in F : print len(F),F._len, x[:-1]
print '# Test me twice ... '
for x in F : print len(F),F._len, x[:-1]
# test 'filter' --
# find all of the lines containing either "def" or "class" :
#
from string import find
print "--- test 3"
for x in filter( lambda s: (find(s, 'def') > -1 ) or (find(s,'class') > -1), F ) :
print x[:-1]
print "--- test 4"
for x in filter( lambda s: (find(s, 'def') > -1 ) or (find(s,'class') > -1), Flines( 'nl -ba flines2.py|') ) :
print x[:-1]
--------------------------
Test-3, using an already fully evaluated sequence, produced the
correct output, but Test-4 produced NOTHING.
A look at bltinmodule.c gives the answer: Unlike 'for', which evaluates
the length each time thru the loop ( which fact is what suggested the
trick to me in the first place! ), filter gets the length once and
then uses that length in a C 'for' loop to process the entire sequence.
A change of:
< for (i = j = 0; i < len; ++i) {
to:
> for (i = j = 0; i < (len = (*sqf->sq_length)(seq)) ; ++i) {
Almost did the trick, but produced an attribute error. The output
sequence is initially allocated to the size of the input sequence,
and then at the end, any excess elements are set to nulls.
I made to other changes:
(1) If setlistitem() fails, filter now tries addlistitem() to append
to the list. The fixes the attribute error problem.
(2) I preceeded the update of the len by a "( i < len ) ||" test,
so that filtering a sequence of fixed length will not incur the
excess overhead of evaluating the length again.
# --- diffs for bltinmodule.c:
110c110
< for (i = j = 0; i < len; ++i) {
--- > for (i = j = 0; (i < len) || (i < (len = (*sqf->sq_length)(seq))) ; ++i) { 134c134,135 < if (setlistitem(result, j++, item) < 0)--- > if (setlistitem(result, j++, item) < 0) { > if ( addlistitem( result, item ) < 0 ) 135a137 > }
With these mods, filter of an indefinite length sequence will work, and test-4 in flines.py (above) will produce the same output as test-3. ( And when I rewrite the tarfile class to take advantage of it, you will be able to scan thru a tape with: MyFiles = filter( Predicate, TarFile( '/dev/rmt0' ) where Predicate is a function that returns True on the desired combination of attributes. )
- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU> - UVA Department of Molecular Physiology and Biological Physics
[ I wonder whether 'for' can be optimized to NOT always evaluate the length ? ] | http://www.python.org/search/hypermail/python-1994q1/0178.html | CC-MAIN-2013-20 | refinedweb | 961 | 72.97 |
I have a little game written in C#. It uses a database as back-end. It's a trading card game, and I wanted to implement the function of the cards as a script.
What I mean is that I essentially have an interface,
ICard, which a card class implements (
public class Card056 : ICard) and which contains function that are called by the game.
Now, to make the thing maintainable/moddable, I would like to have the class for each card as source code in the database and essentially compile it on first use. So when I have to add/change a card, I'll just add it to the database and tell my application to refresh, without needing any assembly deployment (especially since we would be talking about 1 assembly per card which means hundreds of assemblies).
Is that possible? Register a class from a source file and then instantiate it, etc.
ICard Cards[current] = new MyGame.CardLibrary.Card056(); Cards[current].OnEnterPlay(ref currentGameState);
The language is C#, but extra bonus if it's possible to write the script in any .NET language.
2016年12月02日45分05秒
2016年12月02日45分05秒
You might be able to use IronRuby for that.
Otherwise I'd suggest you have a directory where you place precompiled assemblies. Then you could have a reference in the DB to the assembly and class, and use reflection to load the proper assemblies at runtime.
If you really want to compile at run-time you could use the CodeDOM, then you could use reflection to load the dynamic assembly. MSDN article which might help.
2016年12月02日45分05秒
You could use any of the DLR languages, which provide a way to really easily host your own scripting platform. However, you don't have to use a scripting language for this. You could use C# and compile it with the C# code provider. As long as you load it in its own AppDomain, you can load and unload it to your heart's content.
2016年12月02日45分05秒
I'd suggest using LuaInterface as it has fully implemented Lua where it appears that Nua is not complete and likely does not implement some very useful functionality (coroutines, etc).
If you want to use some of the outside prepacked Lua modules, I'd suggest using something along the lines of 1.5.x as opposed to the 2.x series that builds fully managed code and cannot expose the necessary C API.
2016年12月02日45分05秒
If you don't want to use the DLR you can use Boo (which has an interpreter) or you could consider the Script.NET (S#) project on CodePlex. With the Boo solution you can choose between compiled scripts or using the interpreter, and Boo makes a nice scripting language, has a flexible syntax and an extensible language via its open compiler architecture. Script.NET looks nice too, though, and you could easily extend that language as well as its an open source project and uses a very friendly Compiler Generator (Irony.net).
2016年12月02日45分05秒
The main application that my division sells does something very similar to provide client customisations (which means that I can't post any source). We have a C# application that loads dynamic VB.NET scripts (although any .NET language could be easily supported - VB was chosen because the customisation team came from an ASP background).
Using .NET's CodeDom we compile the scripts from the database, using the VB
CodeDomProvider (annoyingly it defaults to .NET 2, if you want to support 3.5 features you need to pass a dictionary with "CompilerVersion" = "v3.5" to its constructor). Use the
CodeDomProvider.CompileAssemblyFromSource method to compile it (you can pass settings to force it to compile in memory only.
This would result in hundreds of assemblies in memory, but you could put all the dynamic classes' code together into a single assembly, and recompile the whole lot when any change. This has the advantage that you could add a flag to compile on disk with a PDB for when you're testing, allowing you to debug through the dynamic code.
2016年12月02日45分05秒
Yes, I thought about that, but I soon figured out that another Domain-Specific-Language (DSL) would be a bit too much.
Essentially, they need to interact with my gamestate in possibly unpredictable ways. For example, a card could have a rule "When this cards enter play, all your undead minions gain +3 attack against flying enemies, except when the enemy is blessed". As trading card games are turn based, the GameState Manager will fire OnStageX events and let the cards modify other cards or the GameState in whatever way the card needs.
If I try to create a DSL, I have to implement a rather large feature set and possibly constantly update it, which shifts the maintenance work to another part without actually removing it.
That's why I wanted to stay with a "real" .NET language to essentially be able to just fire the event and let the card manipulate the gamestate in whatever way (within the limits of the code access security).
2016年12月02日45分05秒
I'm using LuaInterface1.3 + Lua 5.0 for NET1.1 application.
The issue with Boo is that everytime you parse/compile/eval your code on the fly, it creates a set of boo classes so you will get memory leaks.
Lua in the other hand, does not do that, so it's very very stable and works wonderful (I can pass objects from C# to Lua and backwards).
So far I havent put it in PROD yet, but seems very promising.
UPDATE: I did have memory leaks issues in PROD using LuaInterface + Lua 5.0, therefore I used Lua 5.2 and linked directly into C# with DllImport. The memory leaks were inside the LuaInterface library.
Lua 5.2: from and
Once I did this, all my memory leaks were gone and the app was very stable.
2016年12月02日45分05秒
The next version of .NET (5.0?) has had a lot of talk about opening the "compiler as a service" which would make things like direct script evaluation possible.
2016年12月02日45分05秒 | http://www.91r.net/ask/278.html | CC-MAIN-2016-50 | refinedweb | 1,009 | 71.85 |
1 /* BufferedSeekInputStreamTest2 *3 * Created on September 18, 20064 *5 * Copyright (C) 2006 Internet Archive.6 *7 * This file is part of the Heritrix web crawler (crawler.archive.org).8 *9 * Heritrix is free software; you can redistribute it and/or modify10 * it under the terms of the GNU Lesser Public License as published by11 * the Free Software Foundation; either version 2.1 of the License, or12 * any later version.13 *14 * Heritrix is distributed in the hope that it will be useful,15 * but WITHOUT ANY WARRANTY; without even the implied warranty of16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the17 * GNU Lesser Public License for more details.18 *19 * You should have received a copy of the GNU Lesser Public License20 * along with Heritrix; if not, write to the Free Software21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA22 */23 package org.archive.io;24 25 import java.util.Random ;26 27 import junit.framework.TestCase;28 29 30 /**31 * Unit test for BufferedSeekInputStream. The tests do some random 32 * repositioning in the stream to make sure the buffer is always valid.33 * 34 * @author pjack35 */36 public class BufferedSeekInputStreamTest extends TestCase {37 38 39 private static byte[] TEST_DATA = makeTestData();40 41 public void testPosition() throws Exception {42 Random random = new Random (); 43 ArraySeekInputStream asis = new ArraySeekInputStream(TEST_DATA);44 BufferedSeekInputStream bsis = new BufferedSeekInputStream(asis, 11);45 for (int i = 0; i < TEST_DATA.length; i++) {46 byte b = (byte)bsis.read();47 assertEquals(TEST_DATA[i], b);48 }49 for (int i = 0; i < 1000; i++) {50 int index = random.nextInt(TEST_DATA.length);51 bsis.position(index);52 char expected = (char)((int)TEST_DATA[index] & 0xFF);53 char read = (char)(bsis.read() & 0xFF);54 assertEquals(expected, read);55 }56 } 57 58 59 private static byte[] makeTestData() {60 String s = "If the dull substance of my flesh were thought\n"61 + "Injurious distance could not stop my way\n"62 + "For then, despite of space, I would be brought\n"63 + "From limits far remote where thou dost stay.\n";64 byte[] r = new byte[s.length()];65 for (int i = 0; i < r.length; i++) {66 r[i] = (byte)s.charAt(i);67 // r[i] = (byte)s.charAt(i);68 }69 return r;70 }71 }72
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/org/archive/io/BufferedSeekInputStreamTest.java.htm | CC-MAIN-2016-44 | refinedweb | 394 | 57.16 |
Linear regression in plain English
A gentle introduction to linear regression - explanation + Python codes
Linear regression is one of the simplest machine learning modelling techniques.
Take a look at the diagram below:
There are two variables in this diagram - X and Y.
A linear equation is created and fit on the dataset. This equation will predict variable Y given variable X.
Variable Y is called the dependent variable, and X is the independent variable.
The dependent variable is predicted by the independent variable.
For example: Tom wants to predict house prices given their area. In this case, the house price is the dependent variable, and the area is the independent variable.
Simple vs Multiple Linear Regression
A simple linear regression model only involves one dependent variable and one independent variable.
Example: Predicting house price based on its area.
In a multiple linear regression model, there are more than one independent variables.
Example: Predicting house price based on its area, number of bedrooms, floors, etc.
Linear Function
Take a look at the above diagram again.
The equation of this line is y = mx + c. This is called a linear function.
Here, y is the dependent variable, x is the independent variable, m is the slope of the line, and c is the y intercept.
If you plug in any value of x into this equation, you can come up with the output prediction y.
How is this line fit onto the data?
The linear function is also called the line of best fit.
We want a line that fits all the data points as well as possible so that we can come up with accurate predictions.
The most common method of fitting this line onto data is called the least-squares method.
Take a look at the image above.
The least-squares method will fit the red line onto the data such that the sum of squared error between the predictions and true values are minimized.
For example, take the first data point in the diagram. Its true y value is 17, and the predicted value on the line is around 14.
For the second data point, the true y value is around 5, and the predicted value is around 16.
The difference of all these values will be obtained, and that is the error. Then, we square these errors and take its sum, which looks like this:
(17-14)2 + (5-16)2 + (21-17)2 + ...
The result that we get should be as small as possible, as we want to minimize these residuals as much as we can.
If you've built a linear regression model using computer packages in the past, the linear function is inbuilt into these programs. All you have to do is run a few lines of code, and the program will calculate the best fit line for you. This will be demonstrated with code snippets in this tutorial.
When to use linear regression?
Only use linear regression when there is a linear relationship between your dependent and independent variable.
To identify whether the variables X and Y have a linear relationship, first create a scatterplot to visualize the data.
Scenario 1
Taking a look at the picture above, we can see that there is a linear relationship between these two variables. We can make highly accurate predictions of Y given values of X.
Scenario 2
In this diagram, however, we can see that there is no linear relationship between these two variables. In this case, a linear regression model will probably not perform too well.
Later in this tutorial, Python codes to create a scatterplot will be provided.
Another useful measure to see if variables have a strong linear relationship is correlation.
If variables are highly correlated, then the independent variable is useful in predicting the dependent variable.
Correlation
Correlation quantifies the strength of the relationship between variables X and Y.
If two variables X and Y have high correlation, it means that the relationship between these variables are stronger.
The correlation coefficient ranges from -1 to 1. A value of 0 indicates that X and Y have no correlation at all, and there is no linear relationship.
A value of -1 indicates that there is a perfect negative linear relationship between X and Y.
A value of +1 indicates that there is a perfect positive linear relationship between X and Y.
This means that the closer the correlation coefficient is to zero, the weaker the relationship between variables.
The closer the correlation coefficient is to +1 or -1, the stronger the relationship between the variables.
Example:
a) The correlation coefficient between X and Y in this diagram is zero. There is no linear relationship here.
b) The correlation coefficient between X and Y in this case is +1. There is a perfect positive linear relationship between the variables.
c) The correlation coefficient between X and Y in this case is -1. There is a perfect negative linear relationship between the variables.
R-Squared
The square of the correlation coefficient is the R-squared value.
This value tells us how much of the variance in Y (the dependent variable) can be explained by the variance in X (the independent variable).
For example, if the correlation coefficient between X and Y is 0.8, then the R-squared value is 80%. This means that 80% of the variation in Y can be explained by the variation in X.
The R-squared value can be defined by the following formula:
Here, RSS is the sum of square of residuals, and TSS is the total sum of squares.
RSS is the same as SSE, or sum or squared error that we computed earlier.
It is defined as the sum of squares of predicted values minus their true value.
TSS, or the total sum of squares is defined as the sum of squares of true values minus their mean.
In other words, we find the true Y values of all the data points, and then subtract with the average of all these Y values.
The equation to find the total sum of squares looks like this:
If you want to find out how good the independent variable is at explaining the variance of the dependent variables, then all you need to do is compute the R-squared value.
This value can be computed with just one line of code using R/Python packages, so you won't have to do any of this manual calculation by hand.
Linear Regression in Python
Now, we will build a linear regression model in Python. You can use this tutorial as starter code for future regression problems.
We will be doing an example to get acquainted with all the concepts you have learnt so far in this tutorial.
Here is a link to the dataset we will be using. Make sure to download the dataset before starting the tutorial.
Pre-requisites
The following Python libraries will be used in this tutorial - Pandas, Numpy and Scikit-Learn.
Make sure to have these installed before you start to code along.
Step 1: Imports
First, lets import all the necessary libraries:
import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error import math
Step 2: Read the data
Now, read the .csv file into a dataframe with Pandas:
import pandas as pd df = pd.read_csv('winequality-red.csv',sep=';')
Step 3: Examining the data
Lets first check the head of the dataframe. We want to get an understanding of all the different variables present.
df.head()
Observe that there are 12 variables in the dataframe.
Independent variables: fixed acidity, volatile acidity, citric acid, residual sugar, chlorides, free sulfur dioxide, total sulfur dioxide, density, pH, sulphates, alcohol.
Dependent variable: quality
All other variables in the dataset will be used to predict wine quality.
Step 4: Feature Selection
Sometimes, not all features in the dataset are useful in explaining the dependent variable.
Feature selection is the most important step towards building any machine learning model, since a model is only as good as the features used to create it.
In this case, we will do feature selection with a concept we learnt about earlier - correlation.
We will take a look at the correlation between every independent variable and wine quality.
Then, we can choose to keep variables that have high correlation with wine quality, and drop the rest.
This is a simple feature selection technique, but is very helpful in eliminating features that aren't useful in explaining the target variable. Reducing the feature space also helps to save time and cost, especially when dealing with large datasets.
Finding the correlation between all independent variables and wine quality:
correlations = df.corr()['quality'].drop('quality') print(correlations)
You should see the following output:
From here, we can see that alcohol has the highest correlation with the target variable.
Remember that correlation values can range from -1 to +1, where -1 indicates perfect negative correlation and +1 indicates perfect positive correlation. This is called Pearson's correlation coefficient.
Now, lets write some code removes variables with weak correlations.
For this model, I will define weak correlation as follows:
- Variables that have a correlation coefficient ranging from 0 to 0.10 (weak positive correlation)
- Variables that have a correlation coefficient ranging from -0.10 to 0 (weak negative correlation)
list1 = [] for i in range(len(correlations)): if((correlations[i]>=0) & (correlations[i]<=0.10)): list1.append(i) elif((correlations[i]<=0) & (correlations[i]>=-0.10)): list1.append(i) print(list1)
The codes above should render the following list as output: [3, 5, 8].
This means that variables 3, 5 and 8 (residual sugar, free sulfur dioxide, pH) have low correlations with the output, and aren't very useful towards predicting wine quality.
We need to drop these variables before building the model.
Step 5: Model Building
First, lets split the data into train and test datasets. Remember, we need to drop the variables with low correlation first:
X = df.drop(['quality','residual sugar','free sulfur dioxide','pH'],axis=1) y = df['quality'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
Now, lets instantiate a linear regression model and fit it onto the training set:
lm = LinearRegression() lm.fit(X_train, y_train)
Then, we can make predictions on the test set with this data:
preds = lm.predict(X_test)
Step 6: Evaluation
Now, we can evaluate the performance of the model we just built.
There are many different metrics we can use to do this, some of which we learnt in previous sections (such as R-squared and SSE).
Here, we will look at a metric called the Root Mean Squared Error (RMSE).
The Root Mean Squared Error looks at the squared difference between the true and predicted value. Then, it takes the average difference across the entire dataset and squares it.
The formula for calculating the Root Mean Squared Error is as follows:
Now, lets write some code to calculate the RMSE of our model:
mse = mean_squared_error(y_test, preds) print(math.sqrt(mse))
You should get a RMSE value of around 0.65.
Additional Resources
There is a lot more to linear regression than what was explained in this article. If you are interested in learning more about regression techniques, I suggest the following learning resources:
Introductory
- Krish Naik's video explaining the intuition behind linear regression
- The different metrics used to evaluate a regression model
- Explanation of R-squared and Adjusted R-squared value
- Multiple Linear Regression with Python and Scikit-Learn | https://www.natasshaselvaraj.com/a-gentle-introduction-to-linear-regression/ | CC-MAIN-2022-27 | refinedweb | 1,928 | 55.64 |
Feedback
Getting Started
Discussions
Site operation discussions
Recent Posts
(new topic)
Departments
Courses
Research Papers
Design Docs
Quotations
Genealogical Diagrams
Archives
A pretty funny video by Gary Bernhardt on some surprising behaviour in Ruby and JavaScript. I think Wat as a term of art for this phenomenon is quite appropriate.
There's also a follow-up blog post by Adam Iley explaining some of the behaviours in JS seen in that video, if anyone wants to understand the underlying semantics behind these behaviours.
Since we're all PL enthusiasts here, I expect everyone here will have their own lessons to take from this 4 minute video. Myself, it seems a perfect example of the dangers of implicit conversions and overloading. Stuff like this makes we want to crawl back to OCaml where overloading is forbidden.
Implicit conversion, because it's applied in a context-free manner, is what's nasty. Overloading without implicit conversion is not really a problem, except for people who suffer from wearing particularly tight static-typing straitjackets.
Overloading without implicit conversion is not really a problem
I disagree. An example was in the video, where the commutativity of addition is violated. Even if you eliminate the implicit conversions, providing different overloads for X+Y and Y+X would still cause problems.
Actually, in "{}+[]" there's no addition -- it's parsed as an empty block followed by the expression "+[]".
{}+[]
+[]
So, think it's more accurate to say that the problem is with JavaScript's weird syntax ("{}" can be either an empty code block or an object literal, depending on the context), not overloading.
{}
Ah, good call. I was wondering why all three of these printed different things:
{} + [] + {}
0[object Object]
({} + []) + {}
[object Object][object Object]
{} + ([] + {})
NaN
Arguably, using + for string concatenation in the first place is a bad idea. But yes, it's always safer to write ({}) to generate a fresh object, and I do it when generating JavaScript code (but not when writing it by hand).
Yeah, if it were not to mention that, too, which depending on my mood-of-the-day I found myself thinking it to be one of the coolest things or among the nastiest, actually:
(Also : ECMA-262, 15.2.4.4 - valueOf)
Note: when it has nasty effects, I usually blame myself, not the language ... for my overlooking something I was supposed to know already, though. :)
(@ above Mozilla link)
"You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.[...]When you create a custom object, you can override Object.valueOf to call a custom method instead of the default Object method."
Ah, ok! Now I know who I can really blame: the dude who did that (in bold, above) in his library (that I'm using) and didn't bother to document his initiative...
"Hmph" :)
Overloading can also be problematic in the presence of inheritance.
I recently learned about C++'s terrible 'name hiding' behavior, but I think that's a C++ specific problem. Is there another way overloading+inheritance is problematic?
It seems that the case of combining method overloading with inheritance/polymorphism is regularly more-or-less of a challenge in language design.
Here's a C#-specific pitfall to be aware of, for instance:
1) Overloading
Which I remember to have actually stumbled upon a couple times.
It is not possible to avoid problems in a programming language regarding the meaning of names. When you're using a subset of implicit conversion, overloading, polymorphism, and complex scoping rules the interactions can always be difficult.
You cannot escape these features in a programming system. If you eliminate most of these features from the language translator, as in C for example, in a clash free large scale environment, you need a search engine and help system just to figure out the name of the entity you require, or learn what some complicated name used in code actually means.
In turn this need for constant mental lookup destroys the mental pattern matching needed to comprehend programs. Provide some ambiguity and simplify the names, the comprehension and uncertainty increase together.
The best solution here I think is to provide for some redundancy, and obviously type annotations are one of the popular ways to do this if the ambiguity is type based, and scope control operators if the ambiguity is namespace based.
Ambiguity is core. The best example is, of course, the ability to write 1 + 2 + 3 due to the associative law: it's ambiguous but it doesn't matter so we can gloss over it! Nothing new. Mathematics is the art of making stuff as ambiguous as possible!
Ambiguity with human readable names is unavoidable (see Zooko's Triangle), but programming languages manage this complexity using scoping mechanisms. Lexical scoping is tried and true. What other scoping mechanisms are usable for humans is still open.
My recent work gets away from lexical scoping. Jonathan Edwards says it best in in Subtext paper "names are too rich in meaning to be wasted on compilers." The alternative is to link symbols directly into code using some kind of search/selection mechanism, but then we no longer have a simple textual language in which to read/understand code.
I expect to work in C shops -- or a near moral equivalent: C++ or Java -- for the rest of my career, and some things won't fly. Absence of a text version of code, for example, would just get me laughed at. It's not as friendly as it sounds. I don't want to give you negative feedback, but you might want to internalize models of incredulous coworkers. I'll try not to be too funny, but here's a few to think about. (You seem like a nice guy, so I don'twant to accidentally give an impression of being critical here. Imagine me with a good attitude.) None of these guys are real people; these are abstractions whose behavior may appear in real colleagues though.
Zeb always goes last, and just says, "Hangin's too good for him." He wears bib overalls and a straw hat, and chews a weed while glaring at you squinty-eyed.
Capone is Robert Deniro doing an Al Capone impression, who goes directly into a more-in-sorrow-than-anger routine while looking around for a baseball bat. He usually opens with, "I trusted you, and gave you this responsibility, and this is how you repay me?"
Your manager is a guy named Jer with a mohawk, who wears a red and blue striped tie with a pristine white button-down shirt. He was wild and crazy when young, but now wants to project a corporate image. Jer would never dream of being critical, and instead acts like you're joking, and laughingly says, "Stop kidding around. What were you really planning?"
A close coworker named Tex takes a break each time you have an odd idea, kicking up feet on a desk and reaching for a big black cowboy hat while grinning hugely. He says, "Tell it again, I needed a break anyway."
Here's how it goes down with a plan for code with no text version:
You: Instead of text, the runtime is emitted from this other stuff.
Tex: (reaching for hat) That's hilarious! I love these breaks from real work.
Capone: This is what I get for letting you be involved?
Jer: (chuckling) Such a kidder. Come on, what were you really thinking?
Zeb: Hangin's too good for him.
You can see how I'd go to some trouble to avoid that. Is your plan necessary?
Hehe, now this was funny. :)
You're really with your feet on earth!
This goes over my head, but that's ok.
Normally I resist creative urges. Sorry, I meant to say when you have a really novel idea, there's a problem with acceptance, and getting along with teams is a high priority. A development team camps in a local code stack with known problems (analogy: bears at Yosemite), and the further you go from camp the weirder you sound, until you go beyond the pale (cf ancient fence technology). I was trying to give body to patterns in negativity, perhaps uselessly.
Jules' observation the old school will eventually go away is well taken. But it doesn't help the near term.
I can ask constructive questions about the non-text approach instead. In source code, text or not, things refer to one another. What creates identity? How is change over time managed? Can any of the old tool stack survive in a useful role if diffs require large graph to graph comparisons?
Here is a (draft?) paper on the topic of programming language adoption. By lmeyerov of LtU fame. Unfortunately because it's a difficult problem it is more a paper that lists the pertinent questions rather than one that provides the silver bullet.
For non ASCII-array programming in particular it seems hard to design it into an existing system. But you could still optimize the other points in the paper, for example by making it really easy to try out and by focusing on one small domain first.
I wasn't offended at all, no worries.
There are lots of points in between text-only and structured editing. If we just want to innovate with naming we could always have very long globally unique names (think Wiki) where a smart editor optimized the presentation and inputs of these names (show a short non-unique name and allow for input by that name if context allows for easy disambiguation); we are then just one step displaced from a pure text representation. This is already fairly disruptive, of course, but its not a huge step, existing tools still somewhat work since they don't really care about name length.
When you're using a subset of implicit conversion, overloading, polymorphism, and complex scoping rules the interactions can always be difficult.
I'd use stronger language there...
You cannot escape these features in a programming system.
I disagree. You don't need implicit conversion, it's evil. You don't need ad-hoc overloading, if at all do it with (type) class. And baroque scoping rules are a definite sign of language design gone wrong. The only thing from your list that is really indispensable is polymorphism.
All fair points. Back to the OP's post let's check as to how that works out in the case of JavaScript:
Polymorphism ... Check. Well, the object prototype-based flavor of it anyway.
Baroque scoping rules ... Check. And it's not just about the this keyword and/or the global object; help yourself:
Implicit conversions ... Sort of check. valueOf is automatically called whenever the adjacent sub expression context involves one of the basic "types" (those for which +, -, *, etc have a default meaning to start with)
Overloading ... Hmm, not quite check. Sure, call sites in JavaScript just don't give a dime to how many parameters the methods expect. Plus, the latter always have a handy arguments object to play with, no matter are the formal parameters of the definition. I don't think this quite counts as "overloading" though, since usually it's meant to denote distinguishing methods with a same name but different signatures from call sites, and not by/via callee objects' cleverness to do the dispatch themselves.
Along with it being highly dynamic (you can attach code to an instance reference (almost) any time and from (almost) anywhere, I mean, c'mon!) all this would a priori make JavaScript a poor contender for broad acceptance and productive use... large scale, that is. Let alone innovative or novel.
Recall that some were all focused on targetting C, C++, or Java maybe for more "noble" language's compilers. But I never read anywhere about any even remote contemplation (modulo perfs concerns that'd have been expressed) to target JavaScript a decade ago.
(Corporate-wise, I knew a dev manager who had decided once for all to remain uneasy, reluctant, to say the least, to give JavaScript anything but trivial client side validation tasks, though we could obviously do more, as soon as he had learnt JavaScript doesn't require more than the simplest text editor to code in it and not a $$$ IDE suite. I know. As much as it doesn't make any sense.)
Yet, the language re discovery literally exploded about 6 years ago, after 10 or so first years of rather mediocre use -on average, from what I saw in the industry- (or not super exciting anyway). So, people finally bothered to leave the condescending attitude and start to actually look at what was in there. Better late than never as they say, I suppose.
It's becoming so ubiquituous its even being used on the side one wasn't quite expecting a decade ago. Servers. And not just as an applicative PL, also as codegen target for other languages as alluded to, above.
How come? Is it just thanks to well informed people like Crockford, Flannagan, and others?
Besides saying its simple functional features certainly contributed to the boost lately, it's still mostly unclear to me (I had seen its nice usefulness even on the command line for backend tasks 12 years ago already, and I'm not really that smarter than your average, seriously. Though people would find me odd not to stick to tedious and sucky Windows batch files syntax. Oh well)
If your point is that bad design decisions don't prevent widespread adoption, then sure, I agree with you. Language adoption is due to many factors, technical superiority being relatively far down the list.
(Btw, JavaScript has overloading, in the sense that e.g. + does something completely different when applied to strings, etc. In an untyped language, it's the callee who has to make the case distinction. Polymorphism is vacuously present for any untyped language. Scoping is horrible in JS, but ES6 will at least provide cleaner alternatives.)
Coming from a non-dynamic and typed languages setting/culture, I tend to stick to seeing overloading in the "traditional" sense of C++/C#.
I guess it's time I update my nomenclature.
Btw, my point was more that, conversely, it's maybe rather regrettable that (the few, though quite powerful) nice design features of JavaScript have taken "so long" to be noticed or considered as they deserved.
YMMV, but AFAIC, I can cite what I've always liked from the start (or as soon as I got myself familiar enough with):
simple, intuitive, C-like syntax
prototype-based extension of objects behavior (though it takes a while to be properly understood vs. the class-based guys)
enough of syntax and semantic support for FP style (i.e., incl. anonymous functions at minima) for whoever cares enough
overall simplicity combined with a good flexibility, mostly thanks to its dynamic nature, allowing for quite a wide range of programming styles, or also, easy experiments with internal DSLs, even.
(well, granted: once you got "The Good Parts" right, to put this at work, at least, & *wink* to some book :)
Hmm... and ???
well, I did say it was a short list. :)
However, should I have to compare JavaScript to some other, supposedly expected & so-called "competitors", some wannabe-in-the-same-ballpark (initially) as JavaScript, after a first, oh-so-naive and unattentive glance at them, say, like VBScript ...
... Well, on my end, it's a no-brainer : no personal offense meant to VBScript's designers, but JavaScript with all its own flaws had won, and by large, more than a decade & half ago!
JavaScript wasn't successful because it's nicer than other languages. It's simply because it was the first and only on the web, worked well enough, and the web got huge.
I think you're right, that pretty much sums it up, for what I can recall.
The especially important part of your sentence not to leave out is "worked well enough" (and that it was about web pages, as rendered on the client).
Strictly chronologically speaking, some have had different hopes earlier, though.
(@skaller)
Good points, and:
Mathematics is the art of making stuff as ambiguous as possible!
That's a cute way to put it, I'd tend to agree. :)
But by that, I take it you actually meant "... as ambiguous as bearable" (?)
;-) | http://lambda-the-ultimate.org/node/4528 | CC-MAIN-2022-40 | refinedweb | 2,742 | 62.78 |
In this tutorial we'll cover setting up a very simple plasma applet in Python, and how to install it and run it, basically the edit, install, run and debug cycle. To follow this you will need to have KDE 4.2 or later installed, and also the python-python" applet. Create a directory on somewhere called hello-python which in turn contains a content directory which then contains a code directory. This command below will do all this.
mkdir -p hello-python/content/code
This creates a simple directory structure which also matches the package structure expect by the plasmapkg command. More on this later.
In the hello-python directory create a file called metadata.desktop and open it in your text editor. Copy the following code into metadata.desktop.
[Desktop Entry]
Encoding=UTF-8
Name=Hello Python
Name[nl]=Hallo Python
Type=Service
ServiceTypes=Plasma/Applet
Icon=chronometer
X-Plasma-API=python
X-Plasma-MainScript=code/main.py
X-KDE-PluginInfo-Author=Simon Edwards
X-KDE-PluginInfo-Email=simon@simonzone.com
X-KDE-PluginInfo-Name=hello-python
X-KDE-PluginInfo-Version=1.0
X-KDE-PluginInfo-Website=
X-KDE- PluginInfo-Category=Examples
X-KDE- PluginInfo-Depends=
X-KDE- PluginInfo-Depends content/code directory called main.py, open it up in your text editor and put this code in it and save it.
from PyQt4.QtCore import * from PyQt4.QtGui import * from PyKDE4.plasma import Plasma from PyKDE4 import plasmascript
class HelloPython(plasmascript.Applet):
def __init__(self,parent,args=None): plasmascript.Applet.__init__(self,parent)
def init(self): self.setHasConfigurationInterface(False) self.resize(125, 125) self.setAspectRatioMode(Plasma.Square)
def paintInterface(self, painter, option, rect): painter.save() painter.setPen(Qt.white) painter.drawText(rect, Qt.AlignVCenter | Qt.AlignHCenter, "Hello Python!") painter.restore()
def CreateApplet(parent):
return HelloPython(parent)
This is basically the simplest applet which actually does something. The code starts out with the usual copyright notice and license information which I've actually left out for now.
Next up is a bunch of imports. The Python support in Plasma is an extension of PyQt and PyKDE. So here we pull in a couple of PyQt and PyKDE modules which we will need. There are two plasma related modules which we use. The first, PyKDE4.plasma, are the bindings straight on top of the Plasma C++ API. This gives us access to most of the APIs we need, but not all. To create applets which can be packaged and delivered to users across the network via KDE's Get Hot New Stuff (GHNS) framework, we need to use some extra Python specific classes which are in PyKDE4.plasmascript.
Now we define our main applet class. This is our Hello Python applet and it must be a subclass of plasma.Applet. In the __init__() method we need to make sure that we give the super class constructor a chance to run. Note that it is recommended to put most of the initialisation code inside the init() method and not in the _ Python".
The CreateApplet() function is needed to create an instance of our applet. When Plasma loads a Python based applet it will expect there to be a CreateApplet() function which it will call. The task of the CreateApplet() function is to create and instance of the applet and pass it back to Plasma.
Aside from this way, you can create applets using specialized Plasma widgets fit for the purpose. You can find how in this tutorial-python directory.
zip -r ../hello-python.zip .
This will create the hello-python.zip file in the directory just above the hello-python directory. Go to this directory in the shell and run this plasmapkg command to install our little hello-python applet.
plasmapkg -i hello-python-python
You should now be able to see the fruits of your labor.
To uninstall our applet we use plasmapkg again with its -r option.
plasmapkg -r hello-python
This tutorial covers very basics of developing Plasma applets using Python. Most of the material discussed here is boring but important "boilerplate" stuff which stays mostly the same between every applet project. In future tutorials we can move on to move exciting things than just displaying a single line of static text.
Aside from the way shown here (e.g. using paintInterface to display your applet), you can create applets using specialized Plasma widgets fit for the purpose. You can find how in this tutorial. | http://techbase.kde.org/index.php?title=Development/Tutorials/Plasma/Python/GettingStarted&oldid=37500 | CC-MAIN-2014-10 | refinedweb | 739 | 50.94 |
Here's the position paper for the XML-SIG's Developer's Day session. The issues I'd most like to see resolved are: * Should we switch to 4DOM? Or should I seriously start pushing on implementing DOM Level 2? Attendees are encouraged to look at 4DOM's code, so they can form some opinions of its quality. * Are there any issues about a SAX2 Python binding that we should discuss? * What about xmllib.py? (I raise this issue with some trepidation :) ) Some things on the list are quite simple; for example, consensus seemed to be that qp_xml.py should go into the tree. Greg, you want to go ahead and check it in? -- A.M. Kuchling "Don't try anything." "It's all right; I won't hurt you." -- Unnamed thug and Liz Shaw, in "The Ambassadors of Death" The XML-SIG has been mostly drifting for the last year, with little attempt made to push out a 1.0 version. Part of this stemmed from external forces (little development on a Python Unicode type, no namespace support in SAX or DOM), and part stemmed from internal reasons (my getting distracted, few people having time to work on it). We need to finish a 1.0 version as soon as possible. Paul Prescod listed some standards that should be supported: XML SAX Unicode XPath XPointer DOM XSLT. XSLT seems too far afield, but the rest are probably worthwhile candidates. (Can we prioritize them?) Issues remaining: DOM Level 2 support =================== Should we switch to 4Thought's implementations of DOM, XPath, and XPointer? Participants should try to at least read through some of 4Thought's code, so they can form an opinion of its quality. Pros: * An existing DOM Level 2 implementation. * Maintainers use it actively for real work; PyDOM maintainer has short attention span. * Has XPath and XSLT tools built on top of it. (Paul Prescod wrote a few weeks ago that "Ideally we would have one (or at most two!) implementation of each of the major specs: XML, SAX, Unicode, XPath, XPointer, XSLT, DOM"; if you take 4DOM + 4XSL + 4Path, this would mean that Unicode is the only missing piece.) * Faster than PyDOM * Potential for CORBA support by adding some extra bits Cons: * Does anyone other than the maintainers have any experience with it? Any comments? (If you don't want to slag it off publicly, you can send me unfavorable comments privately, and I'll preserve your anonymity.) * Uses Ft.Dom package name, not xml.dom * Potential incompatibilities with existing code, Sean's book, etc. (But probably a bit of glue code will let us smooth over such problems.) * Requires releasing nodes explicitly * Requires that 4Suite base be added to XML-SIG distribution (But the only dependency, at least in the DOM, seems to be on Ft.Lib.TraceOut.) SAX Namespace support ===================== This requires that XML-DEV converges to some consensus on SAX2. Has it done so? Are there issues facing a SAX2 binding that we should discuss? Unicode ======= We've been waiting on the official Python solution. M.-A. Lemburg is implementing a proposal () but it hasn't reached the Python CVS tree yet. Therefore, we still haven't dropped wstrop. My inclination is to do this as soon as Unicode is reasonably stable in the CVS tree. Adding qp_xml.py ================ To the xml.parser package, presumably? xmllib.py ========= A touchy catfight ensued on the xml-sig mailing about xmllib.py's standards compliance (with or without sgmlop). Should xmllib.py be dropped? Can we do an xmllib.py compatible class on top of Expat? Glue for Java and COM parsers ============================= We don't have any particular support for Java-based parsers, or Microsoft's XML-parsing COM component, but we probably should. (Still, this is probably a low priority.) | https://mail.python.org/pipermail/xml-sig/2000-January/001823.html | CC-MAIN-2014-10 | refinedweb | 633 | 75.61 |
README: Docutils
Contents
Quick-Start
This is for those who want to get up & running quickly. Read on for complete details.
Get and install the latest release of Python, available from
Python 2.2 or later [1] is required; Python 2.2.2 or later is recommended.
Use the latest Docutils code. Get the code from Subversion or from the snapshot:
See Releases & Snapshots below for details.
Unpack the tarball in a temporary directory (not directly in Python's site-packages) and run install.py with admin rights. On Windows systems it may be sufficient to double-click install.py. On Unix or Mac OS X, type:
su (enter admin password) ./install.py
See Installation below for details. LaTeX. Support for the following sources has been implemented:
- Standalone files.
- PEPs (Python Enhancement Proposals).
Support for the following sources is planned:
- Inline documentation from Python modules and packages, extracted with namespace context.
- Wikis, with global reference lookups of "wiki links".
- Compound documents, such as multiple chapter files merged into a book.
- And others as discovered.
Releases & Snapshots):
- Snapshot of Docutils code, documentation, front-end tools, and tests:
- Snapshot of the Sandbox (experimental, contributed code):
To keep up to date on the latest developments, download fresh copies of the snapshots regularly. New functionality is being added weekly, sometimes daily. (There's also the Subversion repository.)
Requirements
To run the code, Python 2.2 or later [1] must already be installed. The latest release is recommended. Python is available from.
The Python Imaging Library, or PIL, is used for some image manipulation operations if it is installed.
Project Files & Directories
- README.txt: You're reading it.
- COPYING.txt: Public Domain Dedication and copyright details for non-public-domain files (most are PD).
- FAQ.txt: Frequently Asked Questions (with answers!).
- RELEASE-NOTES.txt: Summary of the major changes in recent releases.
- HISTORY.txt: A detailed change log, for the current and all previous project releases.
- BUGS.txt: Known bugs, and how to report a bug.
- THANKS.txt: List of contributors.
- .tgz archive in a temporary directory (not directly in Python's site-packages). It contains a distutils setup file "setup.py". OS-specific installation instructions follow.
GNU/Linux, BSDs, Unix, Mac OS X, etc.
Open a shell.
Go to the directory created by expanding the archive:
cd <archive_directory_path>. Please include all relevant output, information about your operating system, Python version, and Docutils version. To see the Docutils version, use these commands in the shell:
cd ../tools ./quicktest.py --version
Windows users type these commands:
cd ..\tools python quicktest.py --version
Getting Help
If you have questions or need assistance with Docutils or reStructuredText, please post a message to the Docutils-users mailing list. | https://bitbucket.org/mirror/docutils/src/7abea8d67dc7/?at=subdocs | CC-MAIN-2016-07 | refinedweb | 449 | 53.58 |
Spam detection is an everyday problem that can be solved in many different ways, for example using statistical methods. Here we will create a spam detection based on Python and the Keras library. Keras is a high level API for deep learning that can use Tensorflow, Theanos or CNTK under the hood. It was created to provide a consistent and user friendly way to prototype neural networks. We will first show how to transform the given text data into a format that can be processed by a deep learning algorithm. Then we will create a rather naive model, train it with the given training data and test it against a separate set of test data.
I am neither an experienced Python developer nor an expert in the field of deep learning. In my everyday job I develop Java enterprise applications and have been doing this for almost 20 years. In my free time I like to experiment with new technologies, often a little off the beaten track. So feel free to follow me in exploring this new technology and don't hold back with questions or corrections.
I don't go into details of installing Python, Keras or Tensorflow here not to mention configurations to run the stuff on a GPU. There are plenty of installation recipes on the web. I have based my own installation on Anaconda and tried it both on Mac OS and on Windows. For our simple model and small amount of training data there is no need to install and configure the infrastructure for GPU computations.
The input data for our contest task is a single text file containing training and test data in an alphanumeric format. It consists of 3 blocks of data, two training blocks containing Spam and Ham (means no Spam) examples and one block of mixed spam/ham to test our solution. The blocks are divided by header lines. Each data line starts with a label (spam or ham) followed by the text to evaluate.
# Spam training data
Spam,<p>But could then once pomp to nor that glee glorious of deigned ...</p>
Spam,<p>His honeyed and land vile are so and native from ah to ah it ...</p>
...
# Ham training data
Ham,<p>Nights chamber with off it nearly i and thing entrance name. Into ...</p>
Ham,<p>Chamber bust me. Above the lenore and stern by on. Have shall ah ...</p>
...
# Test data
Ham,<p>Bust by this expressing at stepped and. My my dreary a and. Shaven we ...</p>
...
Spam,<p>So his chaste my. Mote way fabled as of aye from like old. Goodly rill ...</p>
...
First we will separate the training lines from the test lines, preserving the original line format. We will use the comment # Test data for this separation. We will also shuffle the training and test data.
'''
Read the file with the training and test data and return
it as two separate lists. Both lists will be shuffled before
they are returned.
'''
def read_lines():
train_lines = []
test_lines = []
current_lines = []
with open('SpamDetectionData.txt') as f:
for line in f.readlines():
if line.startswith('# Test data', 0):
train_lines = current_lines
current_lines = test_lines
elif line.startswith('#', 0):
'''
Ignore comment lines
'''
elif line == '\n':
'''
Ignore empty lines
'''
else:
current_lines.append(line)
test_lines = current_lines
seed(1337)
shuffle(train_lines)
shuffle(test_lines)
print('Read training lines: ', len(train_lines))
print('Read test lines: ', len(test_lines))
return train_lines, test_lines
# First split train lines from test lines
train_lines, test_lines = read_lines()
Second we will split the two blocks into labels and data. We will remove some formatting information but keep the alphanumeric format for now. This is still plain Python.
'''
Take a list of lines from the original input file (train or test), remove
paragraphs and line breaks and split into label and data by using the comma
as divider. Return as two separate lists preserving the sort order.
'''
def split_lines(lines):
data = []
labels = []
maxtokens = 0
for line in lines:
label_part, data_part = line.replace('<p>','').replace('</p>','').replace('\n', '').split(',')
data.append(data_part)
labels.append(label_part)
if (len(data_part)>maxtokens):
maxtokens=len(data_part)
print('maxlen ', maxtokens)
return data, labels
# Split data from label for each line
train_data_raw, train_labels_raw = split_lines(train_lines)
test_data_raw, test_labels_raw = split_lines(test_lines)
Now Keras joins the game. We use the Tokenizer class from the preprocessing package to vectorize our texts. The tokenizer is initialized using our training data (only the text part). fit_on_text will create a dictionary of all words used in the training data, along with a rank (index number) for each word. You can look into this dictionary by calling t.word_index.
# Use Keras Tokenizer to vectorize text:
# fit_on_texts will setup the internal vocabulary using all words
# from the training data and attaching indices to them
# texts_to_sequences will transform each text into sequence of
# integer
tokenizer = Tokenizer()
tokenizer.fit_on_texts(train_data_raw)
train_data_seq = tokenizer.texts_to_sequences(train_data_raw)
test_data_seq = tokenizer.texts_to_sequences(test_data_raw)
With a call to t.texts_to_sequences() we will transform our text data to a list of word indices.
If we would do it with only one sample text it would look like this:
sample_text = 'But could then once pomp to nor that glee glorious of deigned'
dictionary = {'but':1,'could':2,'then':3,'once':4,'pomp':5,'to':6,'nor':7,'that':8,'glee':9,'glorious':10,'of':11,'deigned':12}
sample_idx = [1,2,3,4,5,6,7,8,9,10,11,12]
Then we will convert this list of lists of indices to a binary numpy matrix. The matrix columns represent the words in the text data, the rows represent the text lines.
'''
While processing the data with Keras each original text will converted
to a list of indices. These indices point to words in a dictionary
of all words contained in the training data. We convert this to a binary
matrix. The value 1 in the matrix says that a word (x in the matrix) is
contained in a given text (y in the matrix)
'''
def vectorize_sequences(sequences, dimension=4000):
results = zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1.
return results
# Finally the integer sequences are converted to a binary (numpy)
# matrix where rows are for the text lines, columns are for
# the words. 1 = word is inside text, 0 = word is not inside
x_train = vectorize_sequences(train_data_seq, 4000)
print('Lines of training data: ', len(x_train))
x_test = vectorize_sequences(test_data_seq, 4000)
print('Lines of test data: ', len(x_test))
Using the index values from the last step we can create a binary matrix as follows:
chamber nearly thing lenore shall ... glorious
line 1 1.0 1.0 1.0 0.0 0.0 ... 0.0
line 2 1.0 0.0 0.0 1.0 1.0 ... 0.0
...
line 2000 0.0 0.00 0.0 0.0 0.0 ... 1.0
As you can see, the matrix reduces our data to the mere existence of words in a text. We give up the sequence of words or recurring word patterns that could indicate spam. This maybe a disadvantage when trying to identify spam, but it is easy to compute.
We will create a second numpy matrix for the test data. In this case we will only use the vocabulary from the training data, as our model will be trained on this. So the second matrix has the same columns as the one created from the training data and binary flags created from the test set.
Finally we will transform the labels to a numeric format. As we have exactly one label per line
we will create a binary vector where 1.0 stands for Spam and 0.0 stands for Ham. We will also do
this for training and test labels.
'''
The label vectorization is quite simple:
the value 1 is for spam,
the value 0 is for ham
'''
def vectorize_labels(labels):
results = zeros(len(labels))
for i, label in enumerate(labels):
if (label.lower() == 'spam'):
results[i] = 1
return results
# The labels are also converted to a binary vector.
# 1 means spam, 0 means ham
y_train = vectorize_labels(train_labels_raw)
print('Lines of training results: ', len(y_train))
y_test = vectorize_labels(test_labels_raw)
print('Lines of test results: ', len(y_test))
So finally we have four pieces of data:
We will use 1. and 3. to train our neural network and 2. and 4. to test and evaluate it.
As you can see the preparation of the input data can cause a certain amount of effort.
Now we want to create the neural network using Keras. A neural network consists of a set of layers that transform the input data to a prediction. Every layer uses a set of weights as parameters for the transformation. The prediction is compared to the expected value ('training label' in the diagram) using a loss function. In each iteration an optimizer is used to improve the weights (parameters). So learning means minimizing the loss of a model by iteratively changing model parameters.
Our simple sequential model will use an input layer with 4000 input neurons (in fact we only have 3691 different words in the training data), two hidden layers for internal transformation and one output layer that gives us a scalar prediction value indicating if we have spam or ham.
# Now we build the Keras model
model = models.Sequential()
model.add(layers.Dense(8, activation='relu', input_shape=(4000,)))
model.add(layers.Dense(8, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy'])
We use so called dense layers for our network, so a neuron on one layer is connected with each neuron on the next layer. Our network looks like this (okay, there are not exactly 4000 neurons in the first layer, but you get the idea):
style="width: 640px; height: 494px" data-src="" class="lazyload" data-sizes="auto" data->
In Keras you can define so-called activation functions to each layer. If you don't, a neuron will be computed as a linear combination of all weighted inputs. By setting functions you can add non-linear behaviour.
For the hidden layers we use the 'relu' function, which is like f(x) = max(0, x).
For the output layer we use the 'sigmoid' function, which will transform the output into a (0,1) interval and is non linear.
We use 'binary_crossentropy' as loss-function and 'rmsprop' as optimizer.
After calling compile the model is ready to be trained.
Now we will use the training data to train our neural network model. The training is done by calling fit with the following parameters:
# Train the model
history = model.fit(x_train,y_train,epochs=8,batch_size=100,validation_split=0.3)
The training will give us output for every epoch, so we can see how the model behaves. Ideally the accuracy should increase while the loss will decrease. Because we defined a validation_split, we will also have a validation phase at the end of each epoch, giving us additional val_loss and val_acc.
Train on 1400 samples, validate on 600 samples
Epoch 1/8
1400/1400 [==============================] - 0s 249us/step - loss: 0.3301 - acc: 0.9536 - val_loss: 0.1725 - val_acc: 1.0000
Epoch 2/8
1400/1400 [==============================] - 0s 79us/step - loss: 0.1124 - acc: 1.0000 - val_loss: 0.0747 - val_acc: 1.0000
Epoch 3/8
1400/1400 [==============================] - 0s 79us/step - loss: 0.0491 - acc: 1.0000 - val_loss: 0.0342 - val_acc: 1.0000
Epoch 4/8
1400/1400 [==============================] - 0s 80us/step - loss: 0.0227 - acc: 1.0000 - val_loss: 0.0167 - val_acc: 1.0000
Epoch 5/8
1400/1400 [==============================] - 0s 81us/step - loss: 0.0110 - acc: 1.0000 - val_loss: 0.0084 - val_acc: 1.0000
Epoch 6/8
1400/1400 [==============================] - 0s 79us/step - loss: 0.0053 - acc: 1.0000 - val_loss: 0.0042 - val_acc: 1.0000
Epoch 7/8
1400/1400 [==============================] - 0s 79us/step - loss: 0.0026 - acc: 1.0000 - val_loss: 0.0022 - val_acc: 1.0000
Epoch 8/8
1400/1400 [==============================] - 0s 79us/step - loss: 0.0013 - acc: 1.0000 - val_loss: 0.0012 - val_acc: 1.0000
100/100 [==============================] - 0s 60us/step
The fit operation will return this data as 'history'. We can use it to plot diagrams using matplotlib.
def plot_accuracy(history):
pyplot.plot(history.history['acc'])
pyplot.plot(history.history['val_acc'])
pyplot.title('model accuracy')
pyplot.ylabel('accuracy')
pyplot.xlabel('epoch')
pyplot.legend(['training', 'validation'], loc='lower right')
pyplot.show()
def plot_loss(history):
pyplot.plot(history.history['loss'])
pyplot.plot(history.history['val_loss'])
pyplot.title('model loss')
pyplot.ylabel('loss')
pyplot.xlabel('epoch')
pyplot.legend(['training', 'validation'], loc='upper right')
pyplot.show()
# summarize history for accuracy
plot_accuracy(history)
# summarize history for loss
plot_loss(history)
As you can see the accuracy of our model increases very fast to 1.0.
style="width: 640px; height: 466px" data-src="" class="lazyload" data-sizes="auto" data->
The loss of our model will decrease with each epoch, going to almost 0.
style="width: 640px; height: 466px" data-src="" class="lazyload" data-sizes="auto" data->
Finally we want to evaluate the model using our test data. We can call evaluate to do this and use our test data and test labels to check the model.
# Evaluate the model
results = model.evaluate(x_test, y_test)
print(model.metrics_names)
print('Test result: ', results)
It will return a result containing loss and accuracy. In our case the loss seems to be very low and the accuracy is 100%.
['loss', 'acc']
Test result: [0.00056361835027928463, 1.0]
If you want to check single records of the test data or use your model with new data (maybe from incoming mail), you can do it using the predict operation. Here we define a small function test_predict which will convert our test text to its vectorized form and call predict. If our prediction value is > 50% we will call it Spam, else we will call it Ham. We compare our predicted value with the expected label.
def test_predict(model, testtext, expected_label):
testtext_list = []
testtext_list.append(testtext)
testtext_sequence = tokenizer.texts_to_sequences(testtext_list)
x_testtext = vectorize_sequences(testtext_sequence)
prediction = model.predict(x_testtext)[0][0]
print("Sentiment: %.3f" % prediction, 'Expected ', expected_label)
if prediction > 0.5:
if expected_label == 'Spam':
return True
else:
if expected_label == 'Ham':
return True
return False
# Manual test over all test records
correct = 0
wrong = 0
for input_text, expected_label in zip(test_data_raw, test_labels_raw):
if test_predict(model, input_text, expected_label):
correct = correct + 1
else:
wrong = wrong + 1
print('Predictions correct ', correct, ', wrong ', wrong)
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
seed(1337)
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Articles/1232040/Spam-classification-using-Python-and-Keras | CC-MAIN-2020-24 | refinedweb | 2,419 | 58.48 |
29518/hyperledger-cello-operator-dashboard-stuck-at-loading
When I try to open operator dashboard on localhost:8080 it keeps loading.
localhost:8080 keeps loading and shows waiting for localhost....
I tried make all also but still it does not work.
I followed the tutorial from their official tutorial website
Any help would be appreciated.
Run these commands:
$ sudo su
$ cd cello
$ make stop
$ make dockerhub-pull
$ make start
reboot the system and it should work
This may be due to some inconsistency in local file. If you are using Linux OS, then you may run `make reset`, and then follow the tutorial's steps to reconfig and start.
The function name should be in Args ...READ MORE
Hyperledger incubates a plethora of business blockchain ...READ MORE
By default, the docs are at your ...READ MORE
This link might help you: ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
To read and add data you can ...READ MORE
You are getting this error probably because ...READ MORE
I know it is a bit late ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/29518/hyperledger-cello-operator-dashboard-stuck-at-loading | CC-MAIN-2021-17 | refinedweb | 202 | 68.87 |
universal app for video recording with MediaCapture using Imaging SDK Filters
Revision as of 04:07, 8 June 2014
Note: This is an entry in the Nokia Original Effect Wiki Challenge 2014Q2. The media player is loading... Recorded video using Nokia Imaging SDK with MagicPenFilter.
Template:ArticleMetaData v1.0....
C++ Universal Component
The Media Foundation Transform must be coded in C++ and the interfaces that must be implemented within the transform class are quite complicated. Thankfully, there exist several samples of a Media Foundation transform that do not require much modification for our purposes. A good sample to start with is the MediaExtensions sample from the Univeral Apps sample set from Microsoft. The sample contains a GrayscaleTransform component from which this app's transform is based.
Preparing the C++ Component
Add Media Foundation Libraries
Next, the Media Foundation libraries need to be added to the linker. For each C++ project (WP8.1 and Win8), right-click on the project name and select properties. Expand the Linker group and select Input. Change the Configuration (at the top) from Active to All Configurations and change Platform from Active to All Platforms so that the following changes are applied to every configuration and platform.
To the end of the "Additional Dependencies" block, add mfplat.lib and mfuuid.lib separated by a semi-colon(;).
Add Common Folder from sample & Include Directories
At the root of the sample app (this app or the MediaExtensions app) is a folder labeled Common which contains several C++ header files (AsyncCB.h, CritSec.h, ExtensionsDefs.h, etc) . These are necessary for the media transform code to compile. Copy the entire Common folder to the root of your own solution.
Next, go to the property page for each C++ project in your app and change the configuration and platform to all as before. Expand the C/C++ menu and click on General. To the end of the Addition Include Directories, add a semicolon (;) and the path "..\..\Common" so that VS2013 can find the header files we just copied.
Modify pch.h
Replace the contents of your pch.h file with the following:
#pragma once
#include <collection.h>
#include <ppltasks.h>
// Windows Header Files:
#include <windows.h>
#include <mfapi.h>
#include <mfidl.h>
#include <mfapi.h>
#include <mferror.h>
#include <d3d11.h>
#include <D2d1helper.h>
#include <assert.h>
#include <tchar.h>
#include <Strsafe.h>
#include <objidl.h>
#include <new>
#include <wrl\client.h>
#include <wrl\implements.h>
#include <wrl\ftm.h>
#include <wrl\event.h>
#include <wrl\wrappers\corewrappers.h>
#include <windows.media.h>
#include <ppltasks.h>
#include <ExtensionsDefs.h>
using namespace Platform;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
Add the Nokia Imaging SDK
Add the Nokia Imaging SDK to all projects in the solution using NuGet. You do NOT have to manually add a reference to the Imaging SDK to the C++ projects. They will not appear as a reference under the properties, but they will be included in the project anyways.
Add NativeBuffer.h
This class is copied entirely from galazzo 's article here:
The Transform Class
To the Shared C++ project Add both a .h header and .cpp c++ file. Creating these two files from scratch is beyond the scope of this article. Instead copy the contents of the ImagingEffect.cpp and ImagingEffect.h from the sample to your project. (These files are too large to post directly in this article.) There are several functions within this class that this article will highlight in the next section so that you can modify or add to this class..
ApplyingImagingFilters function
CImagingEffect::SetProperties
This function allows the C++ transform to receive data from the C# portion of the app. When the transform is applied to the MediaCapture class via AddEffectAsync, only a string variable is passes_altFilterParams.data());
}
else
{
ThrowException(E_UNEXPECTED);
}.
Summary. | http://developer.nokia.com/community/wiki/index.php?title=Template_universal_app_for_video_recording_with_MediaCapture_using_Imaging_SDK_Filters&curid=40855&diff=220683&oldid=220682 | CC-MAIN-2015-14 | refinedweb | 634 | 61.43 |
ANONYMOUS FUNCTIONS AND LAMBDA EXPRESSIONS
Not all functions are important enough to have a name. C# has supported anonymous functions since version 2.0, and a second syntactic variation — lambda expressions — was introduced in version 3.0. Generally speaking, these are functions that don’t live on the class level and that don’t have names. References to such functions are stored in variables, so effectively the function can be called wherever the reference to it is available.
Technically speaking, there are certain restrictions in place on anonymous functions. One is particularly unfortunate, and that’s the fact that they can’t be generic (more on generics in Chapter 4). They also can’t be used to implement iterators (more on iterators in Chapter 5), which is another desirable thing. But apart from that, anonymous functions can do almost everything “normal” methods can do. The term anonymous functions is a bit diluted because it can be a general term that encompasses all types of functions that don’t have names, but it can also be used as a name for the C# 2.0 feature specifically. The feature was really called anonymous methods, but anonymous functions is widely used as an exchangeable term.
Here’s what one of the earlier comparison functions could look like in C# 2.0 syntax:
static void AnonymousMethods( ) {
Bubblesorter.IsAGreaterThanBDelegate compareInt =
delegate(object a, object b) {
return ((int) a) > ((int) b);
};
}
As you can see, the keyword delegate ...
No credit card required | https://www.oreilly.com/library/view/functional-programming-in/9780470971109/xhtml/sec13.html | CC-MAIN-2019-13 | refinedweb | 247 | 56.66 |
On Thu, 2007-02-22 at 15:18 +0100, Christoph Nodes wrote:
> On 2/22/07, mail <lists@×××××.net> wrote:
> >
> > I am still having the same problem.
> > Anybody know what this could be?
>
> The error results from "extra tokens at end of #endif directive" in
> /usr/lib/glib/include/glibconfig.h.
> What does "sed -n 39p /usr/lib/glib/include/glibconfig.h" give you?
>
> The compiler flag -Werror is not very reasonable for most packages as
> it issues an error on any warning (like the "extra tokens"-warning).
> Did you set this flag in your CFLAGS variable?
Thanks, this compile stuff is a bit foggy to me...
here is the result of your command
# sed -n 39p /usr/lib/glib/include/glibconfig.h
#endif#define G_HAVE_GINT64 1 | https://archives.gentoo.org/gentoo-desktop/message/a500e6dbae6acf94d8cdb1fc2f741416 | CC-MAIN-2016-30 | refinedweb | 127 | 70.29 |
Issue with Android config.xmlbyronlevi Sep 15, 2016 10:13 PM
Hi All,
I am working with a team and we are more familiar with builds for iOS.
We created this config.xml for the Android build, however, when we try downloading and testing it on devices, it crashes after opening.
I am guessing the config.xml document may contain errors causing this.
Could you review the below config.xml for Android and provide your thoughts or even a base config.xml we could use?
<?xml version="1.0" encoding="UTF-8" ?>
<widget xmlns = ""
xmlns:gap = ""
xmlns:
<name>APPNAME</name>
<description>Description Here.</description>
<author href="" email="none@none.com">AuthorName</author>
<preference name="phonegap-version" value="cli-6.3.0" />
<preference name="android-build-tool" value="gradle" />
<preference name="orientation" value="default" />
<preference name="fullscreen" value="false" />
<preference name="target-device" value="handset" />
<preference name="webviewbounce" value="false" />
<preference name="prerendered-icon" value="false" />
<preference name="stay-in-webview" value="false" />
<preference name="detect-data-types" value="true" />
<preference name="exit-on-suspend" value="false" />
<preference name="show-splash-screen-spinner" value="false" />
<preference name="auto-hide-splash-screen" value="false" />
<preference name="FadeSplashScreen " value="true" />
<preference name="EnableViewportScale" value="true" />
<preference name="MediaPlaybackRequiresUserAction" value="false" />
<preference name="AllowInlineMediaPlayback" value="true" />
<preference name="BackupWebStorage" value="none" />
<preference name="TopActivityIndicator" value="white" />
<preference name="KeyboardDisplayRequiresUserAction" value="false" />
<preference name="KeyboardShrinksView " value="true" />
<preference name="HideKeyboardFormAccessoryBar" value="false" />
<preference name="SuppressesIncrementalRendering" value="false" />
<preference name="windows-identity-name" value="" />
<preference name="android-minSdkVersion" value="0" />
<preference name="android-targetSdkVersion" value="14" />
<preference name="android-maxSdkVersion" value="16" />
<preference name="android-installLocation" value="auto" />
<preference name="SplashScreenDelay" value="1000" />
<preference name="ErrorUrl" value="null" />
<preference name="BackgroundColor" value="0x000000" />
<preference name="DisallowOverscroll" value="true" />
<preference name="LoadingDialog" value="," />
<preference name="LoadUrlTimeoutValue" value="null" />
>
Thank you for your help!
1. Re: Issue with Android config.xmlVectorP Sep 16, 2016 12:31 AM (in response to byronlevi)
1. Change this to value=15:
<preference name="android-minSdkVersion" value="0" />
2. Change this to a value between 15 and 24:
<preference name="android-targetSdkVersion" value="14" />
3. Change this to a value >=16 and >= targetSdkVersion
<preference name="android-maxSdkVersion" value="16" />
4. This combination makes no sense, since yu are saying: "don't hide my splash automatically, and do so after 1 second".:
<preference name="auto-hide-splash-screen" value="false" />
<preference name="SplashScreenDelay" value="1000" />
5. Your whitelist rules won't work, since you are missing the whitelist plugin.
Add <plugin name="cordova-plugin-whitelist" />
6. You may want to add splashes for xxhdpi and xxxhdpi.
How does your app 'crash'? Do you get any error messages? Is external content not loaded?
2. Re: Issue with Android config.xmlbyronlevi Sep 16, 2016 7:27 AM (in response to VectorP)
Thanks for your help!
I went ahead and made the updates you mention above.
The app still crashes when we try opening it on our provisioned test devices.
Any other updates we could try?
3. Re: Issue with Android config.xmlVectorP Sep 16, 2016 7:47 AM (in response to byronlevi)1 person found this helpful
Again:
How does your app 'crash'? Do you get any error messages? Is external content not loaded?
Also, I'm not sure what you mean with 'provisioned test devices'. We are talking Android, aren't we?
4. Re: Issue with Android config.xmlkerrishotts
Sep 16, 2016 8:34 AM (in response to byronlevi)1 person found this helpful
It would help to see what's being logged to your device's console when the crash occurs. "adb logcat" is the way I'd normally do it, but you may not have this installed since you are using PGB. IIRC, there are apps on the Play store that let you see what's in the logs, though. Those might require root access, though -- not sure.
Chances are good the console logs will indicate the reason the app is crashing.
I'd suggest using Chrome's remote debugging tools, but if your app is crashing immediately after open, I doubt you'd ever get the chance to start up a debug session.
5. Re: Issue with Android config.xmlChris W. Griffith Sep 17, 2016 11:29 AM (in response to byronlevi)1 person found this helpful
Here is a minimal Android config.xml based off
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns="" xmlns:
<name>TEST APP NAME</name>
<description>Description Here.</description>
<author href="" email="none@none.com">AuthorName</author>
<preference name="phonegap-version" value="cli-6.3.0"/>
<preference name="android-build-tool" value="gradle"/>
<preference name="orientation" value="default"/>
<preference name="fullscreen" value="false"/>
<preference name="android-minSdkVersion" value="14"/>
<preference name="android-targetSdkVersion" value="14"/>
<preference name="android-installLocation" value="auto"/>
<!--<preference name="SplashScreenDelay" value="1000"/>-->
<!--<preference name="BackgroundColor" value="0x000000"/>-->
<preference name="DisallowOverscroll" value="true"/>
>
I have compiled a test app and this config.xml is fine.
I would recommend including the full icon suite, as well as the splash screens for higher densities.
The Splashscreen is commented out, as the test app did not handle it.
The Background color is turned off as well, as you don't need it.
The other preferences that were removed are either for other platforms or set with default values. Until you need to change a preference, don't add it in.
The app can be found at: GitHub - chrisgriffith/PhoneGapBuild-Android_test
Chris
6. Re: Issue with Android config.xmlVectorP Sep 17, 2016 12:04 PM (in response to Chris W. Griffith)1 person found this helpful
Hi Chris.
I may be misunderstanding several things about this config, of which you claim
... and this config.xml is fine.
1. What is the reason to specify namespace xmlns:gap, which you don't use?
2. How do you get the allow-intent rules to take effect, without whitelist plugin?
3. Why did you include an empty
<platform name="android"></platform>
when you already have such element for the splashes?
4. Since you have default orientation, what would be the dimensions of the splash graphics?
7. Re: Issue with Android config.xmlChris W. Griffith Sep 17, 2016 12:54 PM (in response to VectorP)1 person found this helpful
This sample config.xml file was solely based off the original poster's version. I did not try to improve beyond getting it to 'useable' state for them.
But to answer your questions:
1) No particular reason.
2) The source config.xml had them. I did not want to include it. In part, figured get them to the first step of not having the app crash at start.
3) A platform needed to be defined, and this was how the source was.
4) For Android ,you do not include dimensions in the tags. The Git repo has sample images.
The goal was simply to get a working version for this poster. If there were only a tool to help PhoneGap Build users create config.xml files....
Chris
8. Re: Issue with Android config.xmlVectorP Sep 18, 2016 12:18 AM (in response to Chris W. Griffith)1 person found this helpful
If there were only a tool to help PhoneGap Build users create config.xml files.
Wouldn't that be awesome, Chris?
Oh, wait...!
:-)
My questions were somewhat retorical. The point was, that a 'minimal working config' should be as correct as possible, because people would read your post and have little doubt that this would finally be a proper template. They would use it without considering reading the PGB Docs (as we see so often).
Specifically this:
4. Since you have default orientation, what would be the dimensions of the splash graphics?
4) For Android ,you do not include dimensions in the tags.
True, but please read again. You have default orientation, which means both landscape and portrait.
Now, suppose you have indeed separate images for these orientations, AND you have specified
<splash src="anroidh.png" density="hdpi"/>
then what is this? The landscape image? The portrait image? Is it a squared image, which has to be pressed into a recatngular device screen?
Or would it be better to always combine 'orientation=default' with
<splash src="anroidhp.png" qualifier="port-hdpi"/>
<splash src="anroidhl.png" qualifier="land-hdpi"/>
?
9. Re: Issue with Android config.xmlbyronlevi Sep 26, 2016 10:42 AM (in response to VectorP)
Thank you for your help with this! Our config.xml file is now working. I really appreciate your suggestions! | https://forums.adobe.com/thread/2209552 | CC-MAIN-2018-22 | refinedweb | 1,414 | 51.85 |
.
Back in the day when I was a kid and I had to walk to school uphill
(both ways!) in the snow to school,
open() only had two arguments, and it
was enough for us. Since then
open() is a lot more rich and
feature full. Indeed, it is so rich that it gets its own tutorial,
perlopentut, and it's perlfunc entry is almost 400 lines long (which is a
lot longer than this article).
Before starting, I have a bit of a challenge for you which lets me
skip talking about a part of
open() and leave that up to you. There is a
one argument form of open. Do you know what it is, and can you give an
example of how you would use it? I'll answer this next month. It does
have a useful application, but you have to keep in mind Perl's origins to
be in the right mindset.
When I started in Perl,
Filehandle identifiers don't get a special sigil, so they appear as
barewords. Since they appear as barewords, Perl's convention was to
completely capitalize them. They certainly stood out in the program text.
open( FILE, "README" ) || die "Could not open README! $!";
We ran into problems when we wanted to pass around filehandle around. If
I want to open a filehandle in one place but use it in another, I had to
do a lot of ugly typing. For instance, to pass a filehandle to a
subroutine, I pass its typeglob, or even a reference to it. In the
subroutine, I saved that in a scalar and let
print() figure it out (even
if I or the maintenance programmers had to scratch our heads).
open( LOG, ">> logfile" ) || die "Could not write to logfile: $!"; here_i_am( *LOG ); log_this( \*LOG, "Hey, I'm done!" ); sub here_i_am { local $fh = shift; print $fh "Here I am!\n"; } sub log_this { local *FILE = shift; print FILE @_; }
In 5.6, Perl got smart enough to skip the typeglob step. I could create
a filehandle in a scalar variable directly as an "indirect filehandle".
This looks a lot better. I don't have to explain typeglobs or references
to typeglobs, or why some people use one or the other. This works when
the variable, in this case
$fh, is undefined.
open( $fh, ">> logfile" ) || die "Could not write to logfile: $!"; print "$fh\n"; # something like GLOB(...)
That variable has to be uninitialized. The following example doesn't do
what I want because
$fh doesn't end up with a filehandle reference since it
is already defined.
my $> logfile" ) || die "Could not write to logfile: $!"; print "$fh\n"; # prints "I'm not a filehandle!"
Luckily, Perl convention gets around this by declaring the variable
directly in the
open(). All of your other variables are lexicals, right?
So why not this one too?
open( my $fh, ">> logfile" ) || die "Could not write to logfile: $!";
That's much nicer. I can now simply pass around scalar variables, and most people already know how to do that. This is one of the telling marks of the intermediate Perl programmer. We don't talk about this in Learning Perl because we want to get people to open files the fastest (in student time) way possible, then introduce better programming idioms once they understand the quick-and-dirty way.
That didn't fix all of the problems though. There was this thing known as "magic open" that was obscure enough to be a Final Jeopardy question. Perl does some guessing on what we want it to do. For instance, in my previous example, Perl looks at the second argument and pulls it apart to figure out what to do. It sees the >> and guesses that we mean to open something in append mode, and that we don't mean to read from the file named ">> foo" (and yes, I can create a file with that name). After the >> it keeps guessing, and it figures that the leading whitespace is not part of the filename (and, yes, I can create a filename with leading whitespace). Moving on, it gets the name of the file, "logfile":
open( my $fh, ">> logfile" ) || die "Could not write to logfile: $!";
This magic also discards trailing whitespace too, so all of these open the same file. Perl does what is common, and file names " logfile", "logfile ", and " logfile " aren't common, or at least they should be. If you really want to annoy someone, put files with a trailing space in their directory and watch how long it takes them to delete it (especially if you make it so they can't use a glob. Don't tell anyone I told you about this.):
open( my $fh, ">>logfile" ); open( my $fh, ">> logfile" ); open( my $fh, ">>logfile " ); open( my $fh, ">> logfile " );
Sometimes, however, we don't want this magic open. We can use Perl's three
argument form. Instead of lumping a bunch of things together in the second
argument, I break apart the
open() mode and the filename. When I do that,
the filename is exactly what I specify, whitespace and all:
open( my $fh, ">>", "logfile " );
Okay, three arguments should be enough for anyone, right? Not really. Magic
open() often causes problems because we're opening things in a pipe. Just
like
system() and
exec() have list forms where they don't let the shell
handle special characters as special characters. The example in the perlfunc
has five arguments:
open(FOO, '-|', "cat", '-n', $file);
Now that you know that
open() is a lot more special than the two argument
form that you may be used to, get ready to take it to a whole other level
with new "plumbing" (in the words of perlopentut) for the IO framework.
With PerlIO, I can think about IO in layers. The first layer is the
sequence of bytes in the file, the second layer is the stuff that perl
reads, and another layer is the stuff that ends up in my program. With
PerlIO, I can do different things to the layers. For instance, I can read
a gzipped file but end up with the uncompressed output when I read from
it. No fuss no muss! Well, I do have to install the
PerlIO::gzip module,
but that's not a big deal.
For instance,
CPAN.pm uses a couple of files (02packages.details.txt.gz,
03modlist.data.gz) to figure out where distributions are and how to
install them. CPAN distributes these are gzipped files to cut down on
space since an installer utility needs to download these files to start
its work.
Without PerlIO, I'd have to un-zip them myself, or provide some way to
read them as a stream and uncompress them on the fly. That's a huge pain.
Without PerlIO, this doesn't work like I want it to. It thinks it's
opening a text file and reading until the first newline (or whatever is
in
$/). It reads quite a bit of data and prints a bunch of gook to my
screen:
open( my $fh, "/MINICPAN/modules/03modlist.data.gz" ); print scalar <$fh>;
With PerlIO, I just need to stick in another layer. The
PerlIO::gzip module
can unzip the data on the fly and give it back to me as the uncompressed
text with almost no work on my part. In the second argument, when Perl
sees the "
:gzip", it automatically looks for and loads
PerlIO::gzip:
open( my $fh, "<:gzip", "/MINICPAN/modules/03modlist.data.gz" ); print scalar <$fh>;
Instead of gobbledygook, I get the first line of uncompressed text:
File: 03modlist.data
There are many other pre-existing filters for PerlIO. Don't like all
those DOS CRLF pairs? No problem. You don't have to run dos2unix on the
file. Just use the built-in
PerlIO::crlf filter. The PerlIO will
automatically convert line endings:
open( my $fh, "<:crlf", "dosfile1.txt" );
Do you want to get the raw data, rather than some unicode-aware layer
that knows about wide characters? Use
PerlIO::byte:
open( my $fh, "<:bytes", "dosfile1.txt" );
Want to turn on binmode directly in the
open()? Use
PerlIO::raw:
open( my $fh, "<:raw", "brian.jpg" );
Although I've shown examples for reading data, these work the other way
too. Besides the layers that you see in the PerlIO man page, there are
many extra ones on CPAN in either the PerlIO or the
PerlIO::via
namespaces. If you don't find what you need, you can even crib off one
that is already there to create your own.
So
open() has come a long way since I started using Perl, and the kids
today have it much easier--not only do you get more arguments, but the
arguments can do more. You don't even have to know you are doing complex
IO transformations when PerlIO does them for you. Maybe in 10 years
you'll look back on these fancy features and complain about how hard it
was it your day and how easy kids have it.
TPJ | http://www.drdobbs.com/web-development/get-more-out-of-open/184416229 | CC-MAIN-2014-52 | refinedweb | 1,508 | 81.02 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.