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
This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project. Noel Yap wrote:- > I don't see this as too big a problem. Just output a > file like: > #if COND > /* contents of header file > #endif > > In fact, doing it this way has the advantage that > several builds, not necessarily agreeing on the value > of COND, can use the file. Hmm, and what about header guards? Infinite recursion? > I think one needn't preprocess everything perfectly in > order to gain significant advantages. Would you say > that what I suggest is better than what we have now? Correctness is paramount; if it's not correct it's no good. Neil.
http://gcc.gnu.org/ml/gcc/2002-08/msg00514.html
CC-MAIN-2015-27
refinedweb
115
74.69
I am looking for advice on anything in the code below which could be beneficial in some way. Anything that could be added or changed etc: Code:/*A car and a train are both traveling toward a railroad crossing on a collision course. The train is 1200 feet from the crossing and traveling at a constant speed of 40 feet per second. The car is 1500 feet away and traveling at 55 feet per second. Write a program to calculate and print each vehicles distance from the crossing at one-second intervals. If the car gets to the crossing first, print "Made it." If the train gets to the crossing first, print "Crash". */ #include <cstdlib> #include <iostream> #include <string> using namespace std; int main(int argc, char *argv[]) { int Train_Distance = 1200, Car_Distance = 1500, Train_Speed = 40, Car_Speed = 55, Seconds_Passed = 0; std::cout<< "The train and the car race to the cross the intersection. Which will win?" << endl << "Seconds Passed = " << Seconds_Passed << " Train Distance = " << Train_Distance << " feet" << " Car Distance = " << Car_Distance << " feet" << endl; while(Train_Distance >= 0 && Car_Distance >= 0) { std::cout<< "Seconds Passed = " << ++Seconds_Passed << " Train Distance = " << (Train_Distance -= Train_Speed) << " feet" << " Car Distance = " << (Car_Distance -= Car_Speed) << " feet" << endl; } string winner = "Made it."; if(Train_Distance < Car_Distance) winner = "Crash."; std::cout<< winner << endl; std::cin.get(); return EXIT_SUCCESS; }
http://cboard.cprogramming.com/cplusplus-programming/118402-suggestions.html
CC-MAIN-2014-42
refinedweb
207
72.97
CPSC 225, Spring 2003 About the g++ Compiler For this course, you will be using the Linux g++ compiler. The textbook includes a copy of Microsoft's Visual C++, which you are welcome to try. However, I will not offer any support for using it. Visual C++ will work for many of the programs that you will write, although a few programs will use features that are specific to Linux. In any case, all programs must be in your Linux account to be graded and must work under Linux. To use the g++ compiler, you can write your program using a standard text editor such as nedit. The name of the file should end in ".cc" (or one of a half-dozen other extensions such as cpp, C, and cxx). If the file is named myprog.cc, then I recommend that you compile it with the commandg++ -g -Wall -omyprog myprog.cc If no errors are found in the program, this will produce an executable program named myprog. You can run the program simply by typing in the name of the executable, myprog, as a command. In this command, "-g", "-Wall", and "-omyprog" are all optional, although they are recommended. The "-g" tells the compiler to add debugging information to the executable. This information can be used by a debugger program to help find bugs in the program. A release version of a program is ordinarily compiled without this debugging information. The "-Wall" tells the compiler to give warning messages about all constructions that the compiler considers suspicious. These warnings are not errors and will not stop the compiler from producing an executable. They indicate possible errors in programming logic, but can be ignored if you know that your code is correct. The "-omyprog" tells the compiler to output an executable program named "myprog". You can use any name you want, although it is common to give the executable the same name as the source code, without the .cc. If you leave out this option, the executable will be named a.out, and you can run the program by entering a.out as a command. (In fact, I generally let the executable name default to a.out, since it's easy enough to rename the file when I have something I want to keep.) Since it's easy to become lazy about including the "-g -Wall", you might want to create a command that includes these options automatically. To do this, edit the .bashrc file in your home directory and add this line to the file:alias c="g++ -g -Wall" No spaces are allowed around the "=" sign! This defines "c" as an alias or abbreviation for "g++ -g -Wall", so that you can compile a program myprog.cc with "c myprog.cc" or with "c -omyprog myprog.cc". (The "." at the beginning of the filename ".bashrc" makes it a hidden file that you won't see in a directory window. To edit it, use the command nedit .bashrc on the command line.) You can define other aliases by adding them to .bashrc, if you want. Note that a change to .bashrc only becomes effective the next time you log in. Later in the course, you will encounter other options that can be used with the g++ command, and you will learn how to use it to compile a program that is defined in several source code files. Note about the std namespace: The "std" namespace is a recent addition to C++. It is used consistently in our textbook. The g++ compiler allows the use of std, but it does not require its use. All the examples in the textbook will work under g++, but they will also work if you omit all references to std. In general, I will try to remember to say "using std" in my programs, since it is part of the C++ standard. I encourage you to do the same.
http://math.hws.edu/eck/cs225/s03/compiler.html
crawl-002
refinedweb
655
74.59
lofigchain.3alc - Man Page creates a netlist in terms of connectors on signals Synopsis #include "mlo.h" void lofigchain(ptfig) lofig_list ∗ptfig; Parameter - ptfig Pointer to a lofig_list Description The lofigchain function creates the dual representation of natural mbk netlists. In mbk, netlists are described in terms of signal attached to connectors. With lofigchain, one can have the dual sight : connectors attached to signals. This can be very useful, depending on the application, but it's also memory consuming on big netlists, since two views of the same thing are present in memory at the same time. The information resulting of a call to lofigchain is present in the USER field of all signals of the figure, accessible through ptfig->LOSIG. The USER field has a ptype typed LOFIGCHAIN, that points on a chain_list whose DATA points on each locon being connected to the given signal. Error "∗∗∗ mbk error ∗∗∗ lofigchain impossible : figure ptfig->NAME is interface only" In order to be valid, the netlist resulting of a call to lofigchain must be done on a figure entirely loaded in ram. See getlofig for details. Example #include "mut.h" #include "mlo.h" void print_netlist(p) lofig_list ∗p; { losig_list ∗s; chain_list ∗c; lofigchain(p); for (s = p->LOSIG; s; s = s->NEXT){ (void)fprintf(stdout, "signal : index = %ld name = %s\n", s->INDEX, getsigname(s)); c = (chain_list ∗)(getptype(s->USER, (long)LOFIGCHAIN)->DATA); while (c) { fprintf(stdout, "conname : %s\n", (locon_list ∗)(c->DATA)->NAME); c = c->NEXT; } } } See Also mbk(1), lofig(3), locon(3), losig(3), getlofig(3), loadlofig(3). Referenced By losig.3alc(3), unflattenlofig.3alc(3).
https://www.mankier.com/3/lofigchain.3alc
CC-MAIN-2022-40
refinedweb
267
61.87
PIPE(2) BSD Programmer's Manual PIPE(2) pipe - create descriptor pair for interprocess communication #include <unistd.h> int pipe(int fildes[2]);. On successful creation of the pipe, zero is returned. Otherwise, a value of -1 is returned and the variable errno set to indicate the error. The pipe() call will fail if: [EMFILE] Too many descriptors are active. [ENFILE] The system file table is full. [EFAULT] The fildes buffer is in an invalid area of the process's address space. sh(1), fork(2), read(2), socketpair(2), write(2) The pipe() function conforms to IEEE Std 1003.1-1988 ("POSIX"). As an extension, the pipe provided is actually capable of moving data bi- directionally. This is compatible with SVR4. However, this is non-POSIX behaviour which should not be relied on, for reasons of portability. A pipe() function call appeared in Version 3 AT&T UNIX..
https://www.mirbsd.org/htman/i386/man2/pipe.htm
CC-MAIN-2015-48
refinedweb
149
60.21
#include <iostream> #include <string> using namespace std; int main() { string names[4] = {"Anna" , "Jenny", "George" , "Michael"}; int score[4]; for(int i = 0; i < 3; i++) { cout << names[i] << ": "; cin >> score[i]; cin.ignore(); } //sort by score for ( int i = 0; i < 3; i++ ) { score[i]; for ( int j = 0; j < 3; j++ ) { if( score[i] < score[j] ) { string tmp_string; int temp; temp = score[i]; tmp_string = names[i]; score[i] = score[j]; names[i] = names[j]; score[j] = temp; names[j] = tmp_string; } } } for ( int k = 0; k < 3; k++ ) { cout << endl; cout <<names[k] << " = "<< score[k] << " "; } system("pause"); } I've compiled it (with dev-c++), and it runs well. I just need a few minor things. 1. I need it to sort descendingly, not ascendingly. 2. I need to know how to either print the output, or get the output sent to a word processor so it can be printed. 3. When the output is displayed, is there a way to clear the screen before-hand, so the input is cleared? --thanks a million, guys.
https://www.daniweb.com/programming/software-development/threads/90543/what-i-have-so-far
CC-MAIN-2017-17
refinedweb
175
74.83
TGeoTrack - Class for user-defined tracks attached to a geometry. Tracks are 3D objects made of points and they store a pointer to a TParticle. The geometry manager holds a list of all tracks that will be deleted on destruction of gGeoManager. Constructor. Destructor. Add a daughter track to this. Add a daughter and return its index. Returns distance to track primitive for picking. Draw this track overimposed on a geometry, according to option. Options (case sensitive): default : track without daughters /D : track and first level descendents only /* : track and all descendents /Ntype : descendents of this track with particle name matching input type. Options can appear only once but can be combined : e.g. Draw("/D /Npion-") Time range for visible track segments can be set via TGeoManager::SetTminTmax() Event treatment. Get some info about the track. Get coordinates for point I on the track. Return the pointer to the array of points starting with index I. Return the index of point on track having closest TOF smaller than the input value. Output POINT is filled with the interpolated value. Return the number of points within the time interval specified by TGeoManager class and the corresponding indices. Search index of track point having the closest time tag smaller than TIME. Optional start index can be provided. Set drawing bits for this track Reset data for this track. {return (GetNdaughters()>0)?kTRUE:kFALSE;}
http://root.cern.ch/root/html520/TGeoTrack.html
crawl-003
refinedweb
232
59.5
Abstraction (training) Please help me to understand how inheritance works in the context of work with abstract classes and their heirs, to challenge the methods and designers of both, and to identify a specific example with me. There's an abstract class. Animaland there's his descendant. Monkey♪ abstract public class Animal { public int nLegs = 0; public void numLegs(int nLegs) { this.nLegs = nLegs; } public abstract int getLegs(); //Constructor public Animal (int nLegs) { numLegs(nLegs) } public class Monkey extends Animals { public int getLegs(){ return this.nLegs; } public monkey(){ super(2); } public void saySome(){ System.out.println("Hello, I am a monkey!"); } ♪ Animal Yes. переменная nLegs(legs) метод numLegs, the requisition of this variable, геттер getLegsto obtain its meaning and конструктор, rear value переменной nLegsby метода numLegs♪ ♪ Monkey We are. реализуем геттер(exhaustive method to be implemented), создаем конструкторwhich causes конструктор Animal, assigning its local variable value 2I'm also writing an extra one. метод saySomethat puts the line in the console. Is that right? Then let's go on. In the main class, write: public class MainClass{ public static void main(String []args){ Animal jay = new Monkey (); System.out.println(jay.nLegs); /* jay.saySome()*/ ((Monkey) jay).saySome(); } Issues: What does that mean when the object is jay? Monkey♪ But how do I read the logic of that expression? Animal jaylike, = new Monkey (); Класса Animal объект jay = новый объект jay класса Monkey Why is the method I've jay.saySome()doesn't work? Why does it work? ((Monkey) jay).saySome();? The ghetter is not reappointed but is being implemented. ♪ AnimalIt's only declared but not implemented. ♪ MonkeyYou do it. Use the right terms, they don't just exist. Like the designer, he's not gonna work like a designer. Animal"and he's inside just calling the designer. Animal♪ Expression Animal jay = new Monkey();means you're creating an object. Monkeyand assign it to a variable type Animalbecause MonkeyIt's too. Animal♪ And then you work with the variable. jayc Animaland in the head knowing that it's actually true. Monkey♪ The commented method doesn't work exactly because jay- it's common. Animalwithout specifying. In class AnimalNo method saySome♪ But since you know that jayYes Monkey, you clearly lead the type and cause the method from class. Monkey UPD Responses to questions from the commentary: (2) For the object of the class, the descendant inherits all the fields of the ancestor class and the object of the class is both the object of the descendant class and the object of the ancestor class (I don't get Class(), you don't need to know this at the current stage). The class in the declaration of a variable can be understood as a type, yes. (3) He cannot inherit both structures. He has one of his own, his own, as described in the class. Monkeyand he inherits the fields and methods of the class. Animal♪ (4) Monkey jay = new Monkey();- that's why not. The question is what you want. For example, if you have another class, Elephant extends Animalit also implemented the method getLegsand you'll want to put all the animals on the same list in your code and then find out how many legs they have: List<Animal> animals = fillList(); //Заполним список как-нибудь for(Animal animal : animals){ System.out.println(animal.getLegs()); } In this piece of code, you don't care where the elephant is, and where the monkey is, you just know what they have in common (all have legs) and you use it. In case within the cycle animalit'll be a elephant, it'll be a elephant. getLegsClass Elephantif animalIt'll be a monkey, it'll be called. getLegsClass Monkey♪ Suggested Topics How to validate that user is not able to enter any data in the given field using selenium java Automated Testing • • Kadir - - What's the difference between the "abstract factory" and the "builder" pattern? Software Programming • • Trenton Should an unimplemented method of an abstract class be abstract? Software Programming • • chanisef - - - - - - Makes a mistake about the abstract class, and I don't understand that I'm not. Software Programming • • shizuka Has some real use when implementing non-abstract methods in an abstract class Software Programming • • fbio - -
https://software-testing.com/topic/888156/abstraction-training
CC-MAIN-2022-21
refinedweb
703
65.32
1. Escape WikiTalk functions and page includes in MessagePosts. 2. Enable the Preview function for MessagePosts. 3. Move complex WikiTalk from MessagePost output to a separate ForumLibrary to be referenced using ":With:". 4. Move javascript to a separate file and include in default.aspx. Logged In: YES user_id=1602893 Originator: YES Build 2.0.0.233 (SVN r1010) Convert sequences like @@WikiTalk@@ or {{IncludeFile}} to be escaped by enclosing in a pair of double -quotes as shown; ""@@WikiTalk@@"" and ""{{IncludeFile}}""; for MessagePost output only. Enabled the Preview function for MessagePost. Moved javascript code for thread management to WikiThreads.js and include in output of default.aspx. Moved Wikitalk for forum support to a library called ForumLibrary. Created a new namespace called WikiTalkLibrary and referenced this new namespace in flexwiki.config.template. This library has been added to the svn controlled files and will be included in the distribution. ReflectionLibrary, BlogSupportLibrary and PictureGalleryLibrary are also included in this namespace. Logged In: YES user_id=1602893 Originator: YES Build 2.0.0.234 Needed to add MessagePost.js to enable preview in MessagePost
http://sourceforge.net/p/flexwiki/feature-requests/192/
CC-MAIN-2014-23
refinedweb
180
52.46
There's low traffic in the eap forum, so if you have some time left, check this statement: return format(rec.getMinX() + "," + format(rec.getMinY() + " - " + format(rec.getMaxX() + "," + format(rec.getMaxY() + " w=" + format(rec.getWidth() + " h=" + format(rec.getHeight(); obviously there are some closing brackets missing. What I did was doing a replace on the original statement, which looked like this: return (long) rec.getMinX() ... So I replaced (long) by format( which of coursed leaded to missing closing brackets. -> so this leads to the first possible improvement that comes to my mind: if I could make the replace like this: replace "(long) $EXPRESSION" with "format($EXPRESSION)" I guess it's not that trivial - but you get the IDEA ;) -> second possible improvement: if you take the first statement above and try shift-ctrl-enter (complete statement)I with it, you'll see it fail gracefully ;) it just ends a lot of braces at the very end of the statement. So, what kind of intellig(j)ence would be required to place the correct closing braces automatically? I'm aware that it might not be 100% determinable. But what about this: first do the current logic, then find out that the resulting statement causes compiler failure. Then try the other logic = directly add a closing bracket after each format(rec.getMinX() -> find out that after it, the compiler is green and leave it that way. Would sth. like this be yet possible by current open APIs? It can't be that difficult... ;) There's low traffic in the eap forum, so if you have some Michael Damberger wrote: This first part is what Structured Search and Replace is for, I think. It's a new feature. Haven't used it myself, but this is a clear case for it. -- Rob Harwood Software Developer JetBrains Inc. "Develop with pleasure!" The first item could also be accomplished with regular expressions and replacement groups. I've used to often to handle just this case: converting one method call to another, preserving the arguments. Michael Damberger wrote: Using Pallada you could do this with Strutural Search and Replace. Try defining the template as "(long) $exp$" and the replacement as "format($exp$)". Ciao, Gordon -- Gordon Tyler (Software Developer) Quest Software <> 260 King Street East, Toronto, Ontario M5A 4L5, Canada Voice: 416-643-4846 | Fax: 416-594-1919
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206952195-intellijent-code-completion
CC-MAIN-2020-05
refinedweb
390
64.91
07 June 2010 08:51 [Source: ICIS news] SINGAPORE (ICIS news)--China’s purified terephthalic acid (PTA) and monoethylene glycol (MEG) spot prices both dived to eight-month low on Monday as a reaction to a plunge in PTA futures pricing on the Zhengzhou Commodity Exchange (ZCE), market source said on Monday. PTA spot prices fell to around $800-830/tonne (€672-697/tonne) CFR (cost and freight) China Main Port (CMP), down by $30/tonne from last Friday, according to global chemical market intelligence service ICIS pricing. Buying indications were heard at $820/tonne CFR CMP for Taiwanese PTA and $800/tonne CFR CMP for Korean PTA, traders said. “We didn’t expect PTA prices to drop such sharply given its relatively balanced market,” a major trader said. Most sellers for PTA remained silent as they preferred to sell after the market calms down. Less confidence was shown for the MEG market due to a severe oversupply. Bids for MEG dipped by $30-40/tonne from last Friday to $680-690/tonne CFR CMP, after a deal was fixed at $700/tonne CFR CMP in late morning, traders added. “Market sentiment is in panic, rather than bearish as we didn’t see any signs that prices will bottom out under current market conditions,” said a trader who deals with ?xml:namespace> The Chinese domestic prices also dropped sharply today, some traders said. Deals for MEG and PTA were made at yuan (CNY) 5,900/tonne ($864/tonne) ex-tank and CNY6,900/tonne ex-warehouse respectively, down by CNY200-250/tonne from last Friday, they added. ($1 = €0.84 /
http://www.icis.com/Articles/2010/06/07/9365399/chinas-pta-and-meg-prices-hit-8-mth-low-on-panic-sentiment.html
CC-MAIN-2014-42
refinedweb
270
63.93
Why MVC? That is a reasonable question. Model–View–Controller (MVC) is an architectural pattern used in software engineering. This is different from Web Forms (Traditional ASP.NET Web. Think in terms of URLS calling Methods – No mapping to html or aspx or jsp, etc URL of the request includes information that the MVC framework uses to invoke an action method A primary goal of MVC is to architect maintainable applications. The pattern isolates “domain logic” (the application logic for the user) from input and presentation (GUI), permitting independent development, testing and maintenance of each. The MVC offers a clear separation of concerns. Other key facts include: - The model is the domain-specific representation of the data upon which the application operates. - Domain logic adds meaning to raw data (for example, calculating whether today is the user’s birthday, or the totals, taxes, and shipping charges for shopping cart items). - When a model changes its state, it notifies its associated views so they can refresh. Model The object that represents the data being operated on or requested View Transforms the Model into a format appropriate for sending to the user Controller Coordinates the request The ASP.NET MVC Application is Microsoft’s implementation of this architectural pattern.. - When the concept of dependency injection is used, it decouples high-level modules from low-level services. - The result is called the dependency inversion principle. MVC is just another form of a web application - MVC is often seen in web applications where the view is the HTML or XHTML generated by the app. - The controller receives GET or POST input and decides what to do with it, handing over to domain objects (i.e. the model) that contain the business rules and know how to carry out specific tasks such as processing a new subscription.) - Control ecosystem – there is a very developed and rich “pre-built” controls you can purchase. It is an entire industry. - State management – http is stateless. It is hard to program with cookies and control state. - Design time support – great integration with Visual Studio. MVC - Do it yourself – you have full control. More work. - Separation of concerns – more maintainable. - Test Driven Development – write your tests first - Extensibility everywhere – you have full control. More work, more power. ASP.NET offers great features to both Web Forms and MVC - Services - Caching - Routing - Localization You can watch a presentation about how you would choose between using Web forms versus MVC. Choosing between ASP.NET Web Forms and MVC – MIX Videos Extensibility - One key characteristic is extensibility, allowing you to swap out parts of the framework, such as the view engine. - Here is blog discussing how to replace the “View” engine - Use the view engine of your choice - - You get jQuery included in-box - But you can use YUI, Google Web Toolkit, etc. - Key Aspect of Platform is URL Routing - This allows you to create “friendly” and “pretty” URLs such as that map to arbitrary controller actions - This gives you more control over how visitors to your site use URLs, freeing the developer to abstract the underlying web architecture, which is typically evident in the urls being tied to specific aspx or html files. - Afterall, users surely don’t care how you architected your web site or web application. Test-driven development (TDD) -. - Test-driven development is related to the test-first programming concepts of extreme programming, begun in 1999, but more recently has created more general interest in its own right. - Programmers also apply the concept to improving and debugging legacy code developed with older techniques. Blog posts and videos by team members: - ScottGu: ASP.NET MVC Framework (Part 0): What is it? - ScottGu: ASP.NET MVC Framework (Part 1): Building an MVC Application - ScottGu: ASP.NET MVC Framework (Part 2): URL Routing - ScottGu: ASP.NET MVC Framework (Part 3): Passing ViewData from Controllers to Views - ScottGu: ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios - Scott Hanselman: Scott Hanselman’s ASP.NET MVC First Look Screencast - Phil Haack: TDD and Dependency Injection with the ASP.NET MVC Framework - Phil Haack: Writing Unit Tests for Controller Actions - Nikhil Kothari: Ajax with the ASP.NET MVC Framework - Brad Abrams: RSS Feed with the new ASP.NET MVC Framework: - What do the different classes represent once you use Visual Studio 2010 Beta 2 to create a new project - Provide some code snippets to help you learn how to program it - Learn about the built in tooling in Visual Studio 2010 Beta 2 The next few screens will demonstrate how to create a blank new project of type: - File, New Project - Project Type = ASP.NET MVC 2 Web Application - Name = “HelloWorld” (folder = c:\devprojects\mvc) - Create Unit Tests = “Yes” - TestProjectName = HelloWorld.Tests - Framework used = Visual Studio Unit Test - Solution Explorer shows 2 projects - Project 1 = The MVC Project - Project 2 = The Unit Tests - The MVC Project has several key folders with code - Content - Controllers - Models - Scripts - Views Figure above : File, New Project (starting from scratch) Figure above: ASP.NET MVC 2 Web Application (a plain old new project) Figure above: Solution Explorer (default project) Controller Class (One of three main categories of objects/classes) Let’s focus on the HomeController class. What is the job of the controller? - The controller receives input and initiates a response by making calls on model objects. - The controller handles the input event from the user interface, often via a registered handler or callback and converts the event into appropriate user action, understandable for the model. -. - As a reminder… - The model abstracts away the data access layer and the view renders the data abstracted away within the model.. - using System; - using System.Collections.Generic; - using System.Linq; - using System.Web; - using System.Web.Mvc; - - namespace HelloWorld.Controllers - { - [HandleError] - public class HomeController : Controller - { - public ActionResult Index() - { - ViewData["Message"] = "Welcome to ASP.NET MVC From Bruno!"; - - return View(); - } - - public ActionResult About() - { - return View(); - } - } - } What the default application looks like. Notice I added “From Bruno!” This diagram speaks well to the architecture. Notice that the url ends in “/Home/About”. - This URL gets parsed by the .NET runtime and mapped to specific classes and methods. - In the default project generated by Visual Studio 2010, HomeController.cs is the class called upon by the runtime because of the “Home” in HomeController.cs and the “Home” in “/Home/Abuot”. - Note that “public ActoinResult About()” gets called. The “About()” method gets called because of “/Home/About”. - The “About()” method will return a “View()” object, which results in an additional mapping to “About.aspx”, which is in the folder “Views / Home - Notice the URL above uses a very “hard-coded” approach to calling web pages. - Using MVC you can take that same url and “re-route” to a specific controller/action combination. - This is called ASP.NET Routing. - URLs coming into your MVC application get mapped to a controller action, such as “About()” getting called as a method inside of HomeController.cs. More examples of how parsing works - For example, consider the following URL: - /Brakes/Disc/3 - This URL is parsed into three parameters like this: - Controller = Brakes, Action = Disc, Id = 3 - Default Behavior - But there are defaults: Default Controller = Home Default Action = Index ID = Empty String - - Controller = Home, Action = Index, Id = ?? - /Manager - This URL is parsed into three parameters like this: - Controller = Manager, Action = Index, Id = ?? Code Snippet that shows the default routing tables being setup - using System; - using System.Collections.Generic; - using System.Linq; - using System.Web; - using System.Web.Mvc; - using System.Web.Routing; - - namespace HelloWorld - { - //); - } - } - } I like the asp code on.
https://blogs.msdn.microsoft.com/brunoterkaly/2010/01/23/getting-started-with-the-asp-net-mvc-framework-installation-and-hello-world/
CC-MAIN-2016-40
refinedweb
1,261
56.66
Day. This afternoon was spent on some more detailed presentations (and yes Nick, my badge does say Microsoft). First up was a session on performance tuning GlassFish - Sun's next version of their Application Server. Tom Daley presented this to about 40 people (there were two tracks running by this stage). Tom obviously knows the ins and outs of both the App server and the various databases to which he connects it. It was interesting to see how much effort Tom (and other speakers) put into not mentioning the word Microsoft, for example when listing members of TPC. I have to admit that a lot of this session went over my head, but I'm sure that'd be the same if someone like David Lean gave a similarly themed talk on tuning SQL Server. The bottom line that I took away from this presentation was that when you do tuning, consider the whole stack. the other useful tidbit I picked up was that Solaris has disk write caching turned off by default. Next up was Lee Chuck-Munn (LCM) on Interoperability using Advanced Web Services. This was also in track 2, but a heap of people came in from the other track to pretty much double the numbers from Tom's session. One of the big advances in JSE5 (and JEE5) is the addition of the concept of annotations. This means that instead of writing a huge amount of code to expose a class as a web service, one merely now needs to import a namespace, decorate the class with the annotation @WebService and the methods with the annotation @WebMethod. Both of these annotations can take parameters so you've got much more granular control over what's actually emitted. The compiler then adds the code to do the heavy lifting. Astute readers will recognise this pattern from elsewhere . It still seems like the tool support is not quite complete for this, there are a number of manual steps that need to be taken before the web service is deployed. @WebService @WebMethod Some cool things about this session were The final session of the day was a 90 minute marathon by Doris Chen on JavaServer Faces and Java Studio Creator. The theme for this session and the parallel one (on Windows Client Development) was "Code Camp", but I have to say it wasn't much like the CodeCamp I know. There wasn't even a demo for the first hour. Tough going at the end of the day. Having said that, there's some nice bits in JSF, and the Creator tool is very nice indeed. The basic premise of JSF is Model-View-Controller and it allows you to mark up a page - ASP.NET-style - and have server-side actions taken. This means that you can emit different markup based on things like browser capabilities etc. The IDE is very nice. Looks a lot like VS and has some of the same capabilities, including drag-n-drop data binding. All-in-all a good day. I've had a couple of polite enquiries from attendees about what I'm doing there, but I haven't yet had to ask myself the same thing. Looking forward to tomorrow's sessions.. Many more IDEs than this support MSSCCI for integrated source control operations. Brian's asking users of those IDEs to check it out and let us know that (or whether) your favourite IDE works.. I certainly think it's worth taking Brian up on his challenge.. My. Here's a list of the resources I showed at the end of my Security Summit sessions around the country. The first one is the most important as it will point you to the webcasts and all the resources from all of the sessions at the Summit. Security eForum site MSDN Security Development Centre Security Development Centre – Writing Secure Code Patterns and Practices: Security Guidelines What’s new in Security for v2.0 What’s new with Code Access Security in the .Net Framework 2.0 Security Enhancements in Visual Studio 2005 Repel Attacks on Your Code with Visual Studio 2005 Safe C and C++ Libraries SQL Server 2005 Security Visual Studio 2005 and SQL Server 2005 Webcast
http://blogs.msdn.com/b/acoat/archive/2006/03.aspx?PostSortBy=MostRecent&PageIndex=1
CC-MAIN-2014-23
refinedweb
707
70.33
Google Base Format Review I’ve started implementing Feed Validator support for the Google Base Bulk Upload formats, initial support is already online, more is committed and should go online overnight, and work will continue into next week, including better error messages. I sent an initial set of questions on Thursday night using the Contact Us form, but I’ve not heard back. So I made a number of assumptions, and have included some more questions below. Feedback on the Feed Validator can be sent to usual places: bugs, patches, and questions/comments. Feedback The documentation contains typos like “numerice”, and punctuation issues like Accepted values are “starting” or “negotiable;” The default is “starting at.” Listing_type has lowercase values defined, but the examples not only have a case mismatch, but the name of the element itself has changed. For location “Anytown, CA, 12345, USA” is listed as not acceptable, but many of the examples have even less: “Anytown, CA, USA” Is it event_date_range, event_dateTime or even eventdateTime? Dates in expiration_date and expiration_date_time are not formatted correctly. In products-atom.xml, you will find <g:service>Standard</g:service> <g:service>Overnight</g:service> ... but definition for service states: Acceptable values are ‘FedEx’, ‘UPS’, ‘DHL’, ‘Mail’, and ‘Other’ None of the feed examples contain a g:id element. Will the rss guid, rdf:about, and atom:id attributes be used if this element is not present? The gender and image_link examples don't contain a namespace prefix. Wellformedness errors can be found in age, delivery_radius, event_date_range, name_of_item_being_reviewed, and shipping None of the complex types are valid RDF/XML, and therefore can’t be used in RSS 1.0 — also personals and news are incomplete. None of the guids in the RSS 2.0 feeds are valid permalinks. Several of the Atom feeds — in addition to being in the Atom 0.3 format despite the prominent warning — contain a illegal issued element at the feed level, and the documentation refers to item elements in Atom feeds. Recommendations People who propose extensions should try to validate them first.
http://www.intertwingly.net/blog/2005/11/20/Google-Base-Format-Review
crawl-002
refinedweb
345
54.22
/* DDG - Data Dependence Graph - interface. Copyright (C) 2004 Free Software Foundation, Inc. Contributed by Ayal Zaks and Mustafa Hagog <zaks,mustafa_DDG_H #define GCC_DDG_H /* For sbitmap. */ #include "sbitmap.h" /* For basic_block. */ #include "basic-block.h" /* For struct df. */ #include "df.h" typedef struct ddg_node *ddg_node_ptr; typedef struct ddg_edge *ddg_edge_ptr; typedef struct ddg *ddg_ptr; typedef struct ddg_scc *ddg_scc_ptr; typedef struct ddg_all_sccs *ddg_all_sccs_ptr; typedef enum {TRUE_DEP, OUTPUT_DEP, ANTI_DEP} dep_type; typedef enum {REG_OR_MEM_DEP, REG_DEP, MEM_DEP, REG_AND_MEM_DEP} dep_data_type; /* The following two macros enables direct access to the successors and predecessors bitmaps held in each ddg_node. Do not make changes to these bitmaps, unless you want to change the DDG. */ #define NODE_SUCCESSORS(x) ((x)->successors) #define NODE_PREDECESSORS(x) ((x)->predecessors) /* A structure that represents a node in the DDG. */ struct ddg_node { /* Each node has a unique CUID index. These indices increase monotonically (according to the order of the corresponding INSN in the BB), starting from 0 with no gaps. */ int cuid; /* The insn represented by the node. */ rtx insn; /* A note preceding INSN (or INSN itself), such that all insns linked from FIRST_NOTE until INSN (inclusive of both) are moved together when reordering the insns. This takes care of notes that should continue to precede INSN. */ rtx first_note; /* Incoming and outgoing dependency edges. */ ddg_edge_ptr in; ddg_edge_ptr out; /* Each bit corresponds to a ddg_node according to its cuid, and is set iff the node is a successor/predecessor of "this" node. */ sbitmap successors; sbitmap predecessors; /* For general use by algorithms manipulating the ddg. */ union { int count; void *info; } aux; }; /* A structure that represents an edge in the DDG. */ struct ddg_edge { /* The source and destination nodes of the dependency edge. */ ddg_node_ptr src; ddg_node_ptr dest; /* TRUE, OUTPUT or ANTI dependency. */ dep_type type; /* REG or MEM dependency. */ dep_data_type data_type; /* Latency of the dependency. */ int latency; /* The distance: number of loop iterations the dependency crosses. */ int distance; /* The following two fields are used to form a linked list of the in/out going edges to/from each node. */ ddg_edge_ptr next_in; ddg_edge_ptr next_out; /* For general use by algorithms manipulating the ddg. */ union { int count; void *info; } aux; }; /* This structure holds the Data Dependence Graph for a basic block. */ struct ddg { /* The basic block for which this DDG is built. */ basic_block bb; /* Number of instructions in the basic block. */ int num_nodes; /* Number of load/store instructions in the BB - statistics. */ int num_loads; int num_stores; /* This array holds the nodes in the graph; it is indexed by the node cuid, which follows the order of the instructions in the BB. */ ddg_node_ptr nodes; /* The branch closing the loop. */ ddg_node_ptr closing_branch; /* Build dependence edges for closing_branch, when set. In certain cases, the closing branch can be dealt with separately from the insns of the loop, and then no such deps are needed. */ int closing_branch_deps; /* Array and number of backarcs (edges with distance > 0) in the DDG. */ ddg_edge_ptr *backarcs; int num_backarcs; }; /* Holds information on an SCC (Strongly Connected Component) of the DDG. */ struct ddg_scc { /* A bitmap that represents the nodes of the DDG that are in the SCC. */ sbitmap nodes; /* Array and number of backarcs (edges with distance > 0) in the SCC. */ ddg_edge_ptr *backarcs; int num_backarcs; /* The maximum of (total_latency/total_distance) over all cycles in SCC. */ int recurrence_length; }; /* This structure holds the SCCs of the DDG. */ struct ddg_all_sccs { /* Array that holds the SCCs in the DDG, and their number. */ ddg_scc_ptr *sccs; int num_sccs; ddg_ptr ddg; }; ddg_ptr create_ddg (basic_block, struct df *, int closing_branch_deps); void free_ddg (ddg_ptr); void print_ddg (FILE *, ddg_ptr); void vcg_print_ddg (FILE *, ddg_ptr); void print_ddg_edge (FILE *, ddg_edge_ptr); ddg_node_ptr get_node_of_insn (ddg_ptr, rtx); void find_successors (sbitmap result, ddg_ptr, sbitmap); void find_predecessors (sbitmap result, ddg_ptr, sbitmap); ddg_all_sccs_ptr create_ddg_all_sccs (ddg_ptr); void free_ddg_all_sccs (ddg_all_sccs_ptr); int find_nodes_on_paths (sbitmap result, ddg_ptr, sbitmap from, sbitmap to); int longest_simple_path (ddg_ptr, int from, int to, sbitmap via); #endif /* GCC_DDG_H */
http://opensource.apple.com//source/gcc/gcc-5465/gcc/ddg.h
CC-MAIN-2016-40
refinedweb
622
56.05
The OSC (Open Sound Control) library supports communication with OSC enabled devices (e.g., smartphones, tablets, other computers, etc.). OSC devices communicate via the Internet, so they do not have to be connected via cable. They could be anywhere – in the same room, in different buildings, or across the globe. To use the OSC library, you need following in your program: from osc import * The OSC library provides two types of objects, OscIn objects and OscOut objects: - OscIn objects receive incoming OSC messages from OSC devices (e.g., an OSC-enabled smartphone, or tablet). - OscOut objects send OSC messages to devices (e.g., computers) that listen for incoming OSC events. You could use a collection of OscIn and OscOut objects to synchronize (or share data between) two different programs on the same computer, or several computers used in an installation.
https://jythonmusic.me/osc-library/
CC-MAIN-2020-05
refinedweb
140
56.15
Fill the inside of a contour with 1. More... #include <mitkFillRegionTool.h> Fill the inside of a contour with 1. Finds the outer contour of a shape in 2D (possibly including holes) and sets all the inside pixels to 1, filling holes in a segmentation. $Author$ Definition at line 40 of file mitkFillRegionTool.h. Returns the path of a cursor icon. Reimplemented from mitk::Tool. Returns the tool button icon of the tool wrapped by a usModuleResource. Reimplemented from mitk::Tool. Returns the name of this tool. Make it short! This name has to fit into some kind of button in most applications, so take some time to think of a good name! Implements mitk::Tool. Returns an icon in the XPM format. This icon has to fit into some kind of button in most applications, so make it smaller than 25x25 pixels. XPM is e.g. supported by The Gimp. But if you open any XPM file in your text editor, you will see that you could also "draw" it with an editor. Implements mitk::Tool.
https://docs.mitk.org/nightly/classmitk_1_1FillRegionTool.html
CC-MAIN-2021-04
refinedweb
177
77.64
18 October 2013 18:00 [Source: ICIS news] HOUSTON (ICIS)--Here is Friday’s midday ?xml:namespace> CRUDE: Nov WTI: $101.03/bbl, up 36 cents; Dec Brent: $109.67/bbl, up 56 cents NYMEX WTI crude futures drifted higher on pre-weekend buying following Thursday’s sell-off. A weak dollar encouraged buying across various commodities. WTI topped out at $101.71/bbl before retreating. RBOB: Nov $2.6616/gal, up 1.37 cents Reformulated blendstock for oxygen blending (RBOB) gasoline futures fluctuated throughout the morning hours but stayed in positive territory by midday. Thursday’s three-day low brought renewed buying interest into the morning. NATURAL GAS: Nov: $3.699/MMBtu, down 5.8 cents NYMEX natural gas futures headed lower for a fourth consecutive day, losing value after revised weather forecasts for the near-term edged temperature predictions upwards, suggesting gas demand for heating purposes would be lower than initially anticipated. Longer-range forecasts predicting a warmer-than-average early winter across high gas consumption regions, such as the northeast and Midwest, has intensified the bearish sentiment. ETHANE: lower at 25.38 cents/gal Ethane spot prices were lower, tracking weaker natural gas futures. AROMATICS: benzene wider at $4.04-4.12/gal Prompt benzene spot prices were discussed within a wider range early in the day, sources said. The morning range was further apart from $4.07-4.11/gal FOB (free on board) the previous session. OLEFINS: ethylene bid higher at 46 cents/lb, RGP offered lower at 57 cents/lb US October ethylene bid levels rose to 46 cents/lb from 45 cents/lb the previous day against no fresh offers. US October refinery-grade propylene (RGP) offer levels fell to 57 cents/lb from 58 cents/lb, while bids were steady at 56
http://www.icis.com/Articles/2013/10/18/9716645/noon-snapshot---americas-markets-summary.html
CC-MAIN-2015-06
refinedweb
300
60.11
Created on 2014-07-06 14:39 by jason.coombs, last changed 2014-07-16 17:43 by eryksun. Consider this simple example in Powershell (Windows 8.1): C:\Users\jaraco> cat .\print-input.py import sys print(next(sys.stdin)) C:\Users\jaraco> echo foo | .\print-input.py foo The BOM (byte order mark) appears in the standard input stream. When using cmd.exe, the BOM is not present. This behavior occurs in CP1252 as well as CP65001. I suspect that Python should be detecting/stripping and possibly honoring the BOM when decoding input on stdin. This issue is present in Python 3.4.0 and Python 3.4.1. I have not tested other Python versions. I would argue that adding the BOM is a Powershell issue, and I'm not sure Python should do anything about it. There are probably cases where people expects the BOM to be received by python, so stripping it is probably not an option. As for detecting, it should happen automatically only if sys.stdin.encoding is set to 'utf-8-bom', but, by default, Python 3 uses 'UTF-8'. I'm not sure what you're suggesting. Are you suggesting that Powershell is wrong here and that Powershell's attempt here to provide more detail about content encoding is wrong? Or are you suggesting that every client that reads from stdin should detect that it's running in Powershell or otherwise handle the BOM individually? From my perspective, Powershell is innovating here and providing additional detail about the encoding of the content, but since Python is responsible for the content decoding (especially Python 3), it should honor that detail. I did some tests and determined that 'utf-8-sig' will honor the bom if present and ignore it if missing. Is there any reason Python shouldn't simply use that encoding for decoding stdin? I've tested it and setting PYTHONIOENCODING='utf-8-sig' starts to get there. It causes Python to consume the BOM on stdin, but it also causes stdout to print a spurious non-printable character in the output: C:\Users\jaraco> echo foo | ./print-input foo There is a non-printable character before foo. I've included it in this message. In Powershell, it's rendered with a square before foo: □foo Using PowerShell under ConEmu, it appears as a space: foo In cmd.exe, I see this: C:\Users\jaraco>python -c "print('foo')" ∩╗┐foo The space before the 'foo' apparently isn't a space at all. Indeed, the input is being processed as desired, but the output now is not. C:\Users\jaraco> python -c "print('bar')" bar (the non-printable character appears there too) If I copy that text to the clipboard, I find that character is actually a \ufeff (zero-width no-break space, aka byte order mark). So by setting the environment variable to use utf-8-sig for input, it simultaneously changes the output to also use utf-8-sig. So it appears as if setting the environment variable would work for my purposes except that I only want to alter the input encoding and not the output encoding. I think my goal is pretty basic - read text from standard input and write text to standard output on the primary shell included with the most popular operating system. I contend that goal should be easily achieved and straightforward on Python out of the box. What does everyone think of the proposal that Python should simply default to utf-8-sig instead of utf-8 for stdin encoding? > The BOM (byte order mark) appears in the standard input stream. When using cmd.exe, the BOM is not present. This behavior occurs in CP1252 as well as CP65001. How you do change the console encoding? Using the chcp command? I'm surprised that you get a UTF-8 BOM when the code page 1252 is used. Can you please check that sys.stdin.encoding is "cp1252"? I tested PowerShell with Python 3.5 on Windows 7 with an OEM code page 850 and ANSI code page 1252: - by default, the stdin encoding is cp850 (OEM code page) and os.device_encoding(0) returns "cp850". sys.stdin.readline() does not contain a BOM. -. If I change the console encoding using the command "chcp 65001": - by default, the stdin encoding = os.device_encoding(0) = "cp65001". sys.stdin.readline() does not contain a BOM. - when stdin is a pipe, stdin encoding = locale.getpreferredencoding(False) = "cp1252" and sys.stdin.readline() *contains* the UTF-8 BOM Note: The UTF-8 BOM is only written once, before the first character. So the UTF-8 BOM is only written in one case under these conditions: - Python is running in PowerShell (The UTF-8 BOM is not written in cmd.exe, even with chcp 65001) - sys.stdin is a pipe - the console encoding was set manually to cp65001 -- It looks like PowerShell decodes the output of the producer program (echo, type, ...) and then encodes the output to the consumer program (ex: python). It's possible to change the encoding of the encoder by setting $OutputEncoding variable. Example to encode to UTF-8 without the BOM: $OutputEncoding = New-Object System.Text.UTF8Encoding($False) Example to encode to UTF-8 without the BOM: $OutputEncoding = [System.Text.Encoding]::UTF8 Using [System.Text.Encoding]::UTF8, sys.stdin.readline() starts with a BOM even if the console encoding is cp850. If you set the console encoding to 65001 (chcp 65001) and $OutputEncoding to [System.Text.Encoding]::UTF8, you get... two UTF-8 BOMs... yeah! I tried different producer programs: [MS-DOS] echo "abc", [PowerShell] write-output "abc", [MS-DOS] type document.txt, [PowerShell] Get-Content document.txt, python -c "print('abc')". It doesn't like like using a different program changes anything. The UTF-8 BOM is added somewhere by PowerShell between by producer and the consumer programs. To show the console input and output encodings in PowerShell, type "[console]::InputEncoding" and "[console]::OutputEncoding". See also: See also issues #1602 (Windows console) and #16587 (stdin, _setmode() and wprintf). I tried msvcrt.setmode(0, 0x40000): set stdin mode to _O_U8TEXT. In this mode, echo "abc"|python -c "import sys; print(ascii(sys.stdin.read()))" displays "\xff\xfea\x00b\x00c\x00\n\x00" which is "abc" encoded to UTF-16 (little endian with the BOM), b'\xff\xfe' is the Unicode BOM U+FEFF (u'\uFEFF') encoded to UTF-16-LE. U+FEFF encoded to UTF-8 gives b'\xef\xbb\xbf'. So it looks like it's not an issue of the stdin mode. I tried all modes and I always get the Unicode BOM. I get different results that @haypo when testing Powershell on Windows 8.1 with Python 3.4.1: C:\Users\jaraco> chcp 1252 Active code page: 1252 C:\Users\jaraco> $env: How you do change the console encoding? Using the chcp command? Yes. I recently discovered that if I use chcp 65001 in my Powershell profile, I can finally see Unicode characters output from my Python programs! > I'm surprised that you get a UTF-8 BOM when the code page 1252 is used. Can you please check that sys.stdin.encoding is "cp1252"? C:\Users\jaraco> echo foo | python -c "import sys; print(sys.stdin.readline())" foo C:\Users\jaraco> python -c "import sys; print(sys.stdin.encoding)" cp1252 C:\Users\jaraco> chcp 65001 C:\Users\jaraco> echo foo | python -c "import locale, os; print(os.device_encoding(0), locale.getpreferredencoding(False))" None cp1252 It seems as if something may have changed in Powershell between Windows 7 and 8.1, because my results are inconsistent with your findings. There's a lot more to digest from your response, so I'll going to have to revisit this later. I find it amusing that the complaint is that Python isn't detecting the BOM and using the info when powershell produces it, but when python produces the BOM, it is powershell that isn't detecting it and using the information. So it looks like there's a bug here in powershell no matter how you look at it ;) I agree there appears to be an inconsistency in how Powershell handles pipes between child processes and between itself and child processes. I'm not complaining about Python, but rather trying to find the best practice here. I'm currently using PYTHONIOENCODING='utf-8-sig' and I've been mostly satisfied with the results. I get the spurious BOM appearing on output, but at least as you say that doesn't seem like a Python problem (at least that has been identified). > -. What if echo non-ascii characters? How they are encoded? Perhaps Python should detect when it is ran under PowerShell in a pipe and set stdin (and/or stdout and stderr) encoding to CP65001). Here I use the british pound symbol to attempt to answer that question. I've disabled the environment variable PYTHONIOENCODING and not set any code page or loaded any other Powershell profile settings. PS C:\Users\jaraco> echo £ £ PS C:\Users\jaraco> chcp Active code page: 437 PS C:\Users\jaraco> echo £ | py -3 -c "import sys; print(repr(sys.stdin.read()))" '?\n' PS C:\Users\jaraco> chcp 65001 Active code page: 65001 PS C:\Users\jaraco> echo £ | py -3 -c "import sys; print(repr(sys.stdin.read()))" '?\n' PS C:\Users\jaraco> echo £ | py -3 -c "import sys; print(repr(sys.stdin.buffer.read()))" b'?\r\n' Curiously, it appears as if powershell is actually receiving a question mark from the pipe. Please use ascii() instead of repr() in your test to identify who replaces characters with question marks. Bytes repr doesn't contains non-ascii characters, therefore Python is actually receiving a question mark from the pipe. What are results of following commands? py -3 -c "import sys; sys.stdout.buffer.write(bytes(range(128, 256)))" py -3 -c "import sys; sys.stdout.buffer.write(bytes(range(128, 256)))" | py -3 -c "import sys; b = sys.stdin.buffer.read(); print(len(b), b)" > PS C:\Users\jaraco> echo £ | py -3 -c "import sys; print(repr(sys.stdin.buffer.read()))" > b'?\r\n' > Curiously, it appears as if powershell is actually receiving > a question mark from the pipe. PowerShell calls ReadConsoleW to read the console input buffer, i.e. it reads "£" as a wide character from the command line. The default encoding when writing to the pipe should be ASCII [*]. If that's the case it explains the question mark that Python reads from stdin. It's the default replacement character (WC_DEFAULTCHAR) used by WideCharToMultiByte. [*] You can change PowerShell's output encoding to match the console: $OutputEncoding = [Console]::OutputEncoding If the console codepage is 65001, the above is equivalent to setting $OutputEncoding = [System.Text.Encoding]::UTF8 As Victor mentioned, this setting always writes a BOM, and under codepage 65001 it actually writes 2 BOMs (at least in PowerShell 2). Victor also mentioned that you can avoid the BOM by passing $False to the constructor: $OutputEncoding = New-Object System.Text.UTF8Encoding($False) There's still a BOM under codepage 65001, but maybe that's fixed in PowerShell 3. I avoid setting the console to codepage 65001 anyway. ReadFile/WriteFile incorrectly return the number of characters read/written instead of the number of bytes because the call is actually handled by ReadConsoleA/WriteConsoleA. Maybe that's finally fixed in Windows 8.
https://bugs.python.org/issue21927
CC-MAIN-2018-47
refinedweb
1,901
58.58
Scaling PostgreSQL Performance Using Table Partitioning Here’s a classic scenario You work on a project that stores transactional data in a database. The application gets deployed to production and early on the performance is great, selecting data from the database is snappy and insert latency goes unnoticed. Over a time period of days/weeks/months the database starts to get bigger and queries slow down. There are various approaches that can help you make your application and database run faster. A Database Administrator (DBA) will take a look and see that the database is tuned. They offer suggestions to add certain indexes, move logging to separate disk partitions, adjust database engine parameters and verify that the database is healthy. You can also add Provisioned iOPS on EBS volumes or obtain faster (not just separate) disk partitions. This will buy you more time and may resolve this issues to a degree. At a certain point you realize the data in the database is the bottleneck. In many application databases some of the data is historical information that becomes less important after a certain amount of time. If you figure out a way to get rid of this data your queries will run faster, backups run quicker and use less disk space. You can delete it but then the data is gone forever. You could run a slew of DELETE statements causing a ton of logging and consuming database engine resources. So how do we get rid of old data efficiently but not lose the data forever? Table Partitioning Table partitioning is a good solution to this very problem. You take one massive table and split it into many smaller tables - these smaller tables are called partitions or child tables. Operations such as backups, SELECTs, and DELETEs can be performed against individual partitions or against all of the partitions. Partitions can also be dropped or exported as a single transaction requiring minimal logging. Terminology Let’s start with some terminology that you will see in the remainder of this blog. Master Table Also referred to as a Master Partition Table, this table is the template child tables are created from. This is a normal table, but it doesn’t contain any data and requires a trigger (more on this later). There is a one-to-many relationship between a master table and child tables, that is to say that there is one master table and many child tables. Child Table These tables inherit their structure (in other words, their Data Definition Language__or __DDL__for short) from the master table and belong to a single master table. The child tables contain all of the data. These tables are also referred to as __Table Partitions. Partition Function A __partition function__is a Stored Procedure that determines which child table should accept a new record. The master table has a trigger which calls a partition function. There are two typical methodologies for routing records to child tables: - By Date Values- An example of this is purchase order date. As purchase orders are added to the master table, this function is called by the trigger. If you create partitions by day, each child partition will represent all the purchase orders entered for a particular day. This method is covered by this article. - By__Fixed Values__- An example of this is by geographic location such as states. In this case, you can have 50 child tables, one for each US state. As INSERTs are fired against the master the partition function sorts each new row into one of the child tables. This methodology isn’t covered by this article because it doesn’t help us remove older data. Let’s Try Configuring Table Partitions! The example solution demonstrates the following: - Automatically creating database table partitions based on date - Schedule the export of older table partitions to compressed flat files in the OS - Drop the old table partition without impacting performance - Reload older partitions so they are available to the master partition Take the time to let that last piece of the solution sink in. Most of the documentation on partitioning I’ve read through simply uses partitioning to keep the database lean and mean. If you needed older data, you’d have to keep an old database backup. I’ll show you how you can keep the database lean and mean through partitioning but also have the data available to you when you need it without db backups. Conventions Commands run in shell as the root user will be prefixed by: (root#) Commands run in a shell as a non-root user, eg. postgres will be prefixed by: postgres$ Commands run within the PostgreSQL database system will look as follows: my_database> What you’ll need The examples below use PostgreSQL 9.2 on Engine Yard. You will also need git for installing plsh. Summary of Steps Here’s a summary of what we are going to do: - Create a master table - Create a trigger function - Create a table trigger - Create partition maintenance function - Schedule the partition maintenance - Reload old partitions as needed Create a Master Table For this example we’ll be creating a table to store basic performance data (cpu, memory, disk) about a group of servers (server_id) every minute (time). CREATE TABLE myschema.server_master ( id BIGSERIAL NOT NULL, server_id BIGINT, cpu REAL, memory BIGINT, disk TEXT, "time" BIGINT, PRIMARY KEY (id) ); Notice that in the code above the column name time is in quotes. This is necessary because time is a keyword in PostgreSQL. For more information on Date/Time keywords and functions visit the PostgreSQL Manual. Create Trigger Function The trigger function below does the following - Creates child partition child tables with dynamically generated “CREATE TABLE” statements if the child table does not already exist. - Partitions (child tables) are determined by the values in the “time” column, creating one partition per calendar day. - Time is stored in epoch format which is an integer representation of the number of seconds since 1970-01-01 00:00:00+00. More information on Epoch can be found at - Each day has 86400 seconds, midnight for a particular day is an epoch date divisible by 86400 without a remainder. - The name of each child table will be in the format of myschema.server_YYYY-MM-DD. CREATE OR REPLACE FUNCTION myschema.server_partition_function() RETURNS TRIGGER AS $BODY$ DECLARE _new_time int; _tablename text; _startdate text; _enddate text; _result record; BEGIN --Takes the current inbound "time" value and determines when midnight is for the given date _new_time := ((NEW."time"/86400)::int)*86400; _startdate := to_char(to_timestamp(_new_time), 'YYYY-MM-DD'); _tablename := 'server_'||_startdate; -- Check if the partition needed for the current record exists PERFORM 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND c.relname = _tablename AND n.nspname = 'myschema'; -- If the partition needed does not yet exist, then we create it: -- Note that || is string concatenation (joining two strings to make one) IF NOT FOUND THEN _enddate:=_startdate::timestamp + INTERVAL '1 day'; EXECUTE 'CREATE TABLE myschema.' || quote_ident(_tablename) || ' ( CHECK ( "time" >= EXTRACT(EPOCH FROM DATE ' || quote_literal(_startdate) || ') AND "time" < EXTRACT(EPOCH FROM DATE ' || quote_literal(_enddate) || ') ) ) INHERITS (myschema.server_master)'; -- Table permissions are not inherited from the parent. -- If permissions change on the master be sure to change them on the child also. EXECUTE 'ALTER TABLE myschema.' || quote_ident(_tablename) || ' OWNER TO postgres'; EXECUTE 'GRANT ALL ON TABLE myschema.' || quote_ident(_tablename) || ' TO my_role'; -- Indexes are defined per child, so we assign a default index that uses the partition columns EXECUTE 'CREATE INDEX ' || quote_ident(_tablename||'_indx1') || ' ON myschema.' || quote_ident(_tablename) || ' (time, id)'; END IF; -- Insert the current record into the correct partition, which we are sure will now exist. EXECUTE 'INSERT INTO myschema.' || quote_ident(_tablename) || ' VALUES ($1.*)' USING NEW; RETURN NULL; END; $BODY$ LANGUAGE plpgsql; Create a Table Trigger Now that the Partition Function has been created an Insert Trigger needs to be added to the Master Table which will call the partition function when new records are inserted. CREATE TRIGGER server_master_trigger BEFORE INSERT ON myschema.server_master FOR EACH ROW EXECUTE PROCEDURE myschema.server_partition_function(); At this point you can start inserting rows against the Master Table and see the rows being inserted into the correct child table. Create Partition Maintenance Function Now let’s put the master table on a diet. The function below was built generically to handle the partition maintenance, which is why you won’t see any direct syntax for server. How it works - All of the child tables for a particular master table are scanned looking for any partitions where the name of the partition corresponds to a date older than 15 days ago. - Each “too old” partition is exported/dumped to the local file system by calling the db function myschema.export_partition(text, text). More on this is in the next section. - If and only if the export to the local filesystem was successful the child table is dropped. - This function assumes that the folder /db/partition_dumpexists on the local db server. More on this in the next section. If you are wondering where the partitions are exported to this is where you should look! CREATE OR REPLACE FUNCTION myschema.partition_maintenance(in_tablename_prefix text, in_master_tablename text, in_asof date) RETURNS text AS $BODY$ DECLARE _result record; _current_time_without_special_characters text; _out_filename text; _return_message text; return_message text; BEGIN -- Get the current date in YYYYMMDD_HHMMSS.ssssss format _current_time_without_special_characters := REPLACE(REPLACE(REPLACE(NOW()::TIMESTAMP WITHOUT TIME ZONE::TEXT, '-', ''), ':', ''), ' ', '_'); -- Initialize the return_message to empty to indicate no errors hit _return_message := ''; --Validate input to function IF in_tablename_prefix IS NULL THEN RETURN 'Child table name prefix must be provided'::text; ELSIF in_master_tablename IS NULL THEN RETURN 'Master table name must be provided'::text; ELSIF in_asof IS NULL THEN RETURN 'You must provide the as-of date, NOW() is the typical value'; END IF; FOR _result IN SELECT * FROM pg_tables WHERE schemaname='myschema' LOOP IF POSITION(in_tablename_prefix in _result.tablename) > 0 AND char_length(substring(_result.tablename from '[0-9-]*$')) <> 0 AND (in_asof - interval '15 days') > to_timestamp(substring(_result.tablename from '[0-9-]*$'),'YYYY-MM-DD') THEN _out_filename := '/db/partition_dump/' || _result.tablename || '_' || _current_time_without_special_characters || '.sql.gz'; BEGIN -- Call function export_partition(child_table text) to export the file PERFORM myschema.export_partition(_result.tablename::text, _out_filename::text); -- If the export was successful drop the child partition EXECUTE 'DROP TABLE myschema.' || quote_ident(_result.tablename); _return_message := return_message || 'Dumped table: ' || _result.tablename::text || ', '; RAISE NOTICE 'Dumped table %', _result.tablename::text; EXCEPTION WHEN OTHERS THEN _return_message := return_message || 'ERROR dumping table: ' || _result.tablename::text || ', '; RAISE NOTICE 'ERROR DUMPING %', _result.tablename::text; END; END IF; END LOOP; RETURN _return_message || 'Done'::text; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100; ALTER FUNCTION myschema.partition_maintenance(text, text, date) OWNER TO postgres; GRANT EXECUTE ON FUNCTION myschema.partition_maintenance(text, text, date) TO postgres; GRANT EXECUTE ON FUNCTION myschema.partition_maintenance(text, text, date) TO my_role; The function below is again generic and allows you to pass in the table name of the file you would like to export to the operating system and the name of the compressed file that will contain the exported table. -- Helper Function for partition maintenance CREATE OR REPLACE FUNCTION myschema.export_partition(text, text) RETURNS text AS $BASH$ #!/bin/bash tablename=${1} filename=${2} # NOTE: pg_dump must be available in the path. pg_dump -U postgres -t myschema."${tablename}" my_database| gzip -c > ${filename} ; $BASH$ LANGUAGE plsh; ALTER FUNCTION myschema.export_partition(text, text) OWNER TO postgres; GRANT EXECUTE ON FUNCTION myschema.export_partition(text, text) TO postgres; GRANT EXECUTE ON FUNCTION myschema.export_partition(text, text) TO my_role; Note that the code above uses the plsh language extension which is explained below. Also note that on our systems bash is located at /bin/bash, this may vary. That Was Fun, Where are we? Almost there. So far we’ve made all the necessary changes within the database to accommodate table partitions: - Created a new master table - Created the trigger and trigger function for the master table - Created partition maintenance functions to export older partitions to the os and drop the old partitions You could stop here if you’d like and proceed to the section “Now Let’s See it in Action” but sure to continue below to configure automated maintenance. What we have left to do for automated maintenance is: - Install the plsh extension - Setup the os to store partition dumps - Create a cron job to automate the calling of the maintenance partition function Configure PostgreSQL and OS Enabling PLSH in PostgreSQL The PLSH extension is needed for PostgreSQL to execute shell commands. This is used by myschema.export_partition(text,text) to dynamically create a shell string to execute pg_dump. Starting as root, execute the following commands, root# cd /usr/local/src # Build the extension .so files for postgresql root# curl -L -o plsh.tar.gz root# tar zxf plsh.tar.gz root# cd plsh-*/ root# make all install # Note that the postgres header files must be available root# su - postgres # Or whatever account postgresql is running under postgres$ psql my_database # Substitute the name of your database with the partitioned tables my_database> CREATE EXTENSION plsh; # NOTE: This must be done once for each database Create the directory, root# mkdir -p /db/partition_dump Ensure that the postgres user owns the directory, and your deployment user’s group has permissions as well so that it can read the files. The default deploy user is ‘deploy’ on Engine Yard Cloud. root# chown postgres:deploy /db/partition_dump Even further information on PL/SH can be found in the plsh project’s README. Schedule Partition Maintenance The commands below will schedule the partition_maintenance job to run at midnight every day root# su - postgres ## This is the OS user that will run the cron job postgres$ mkdir -p $HOME/bin/pg_jobs ## This is the folder that will contain the script below postgres$ cat > $HOME/bin/pg_jobs/myschema_partition_maintenance #!/bin/bash # NOTE: psql must be available in the path. psql -U postgres glimpse <<SQL SELECT myschema.partition_maintenance('server'::text, 'server_master'::text, now()::date ); SQL ## Now press the <ctrl+d> keys to terminate the “cat” commands input mode postgres$ exit ## Exit the postgres os user and execute as root: root# chmod +x /home/postgres/bin/pg_jobs/myschema_partition_maintenance # Make script executable< root# crontab -u postgres -e ## Add the line: 0 0 * * * /home/postgres/bin/pg_jobs/myschema_partition_maintenance View the cron jobs for the postgres user to ensure the crontab line is correct: root# crontab -u postgres -l 0 0 * * * /home/postgres/bin/pg_jobs/myschema_partition_maintenance Make sure your /db/partition_dump folder is backed up if you are not using an Engine Yard Cloud instance. If you ever need the data again you’ll need these files to restore the old partitions. This may be as simple as rsyncing (copying) these files to another server just to be sure. We find that sending these to S3 works well for archival purposes. Now your master tables are scheduled for partition maintenance and you can rest knowing that you’ve create something special; a nimble database that will keep itself on a weight loss program! Reload Old Partitions If you have separation anxiety from your old data or maybe a dull compliance request landed on your desk then you can reload the old partitions from the file system. To reload a partition first we navigate to /db/partition_dump on the local db server and identify the file and then as the postgres user we import the file back into the database. postgres$ cd /db/partition_dump postgres$ ls # find the filename of the partition dump you need postgres$ psql my_database < name_of_partition_dump_file After the partition file is loaded it will be queryable from the master table. Be aware that when the next time the partition maintenance job runs the newly imported partition will be exported again. Now Let’s See it in Action Create Child Tables Let’s insert two rows of data to see creation of new child partitions in action. Open a psql session and execute the following: postgres$ psql my_database my_database> INSERT INTO myschema.server_master (server_id, cpu, memory, disk, time) VALUES (123, 20.14, 4086000, '{sda1:510000}', 1359457620); --Will create "myschema"."servers_2013-01-29" my_database> INSERT INTO myschema.server_master (server_id, cpu, memory, disk, time) VALUES (123, 50.25, 4086000, '{sda1:500000}', 1359547500); --Will create "myschema"."servers_2013-01-30" So what happened? Assuming this is the first time you’ve run this two new child tables were created, see the comments inline with the sql statement on the child tables that were created. The first insert can be seen by selecting against either the parent or child: SELECT * FROM myschema.server_master; --Both records seen SELECT * FROM myschema."server_2013-01-29"; --Only the first insert is seen Note the use of double quotes around the child partition table name, they aren’t there because the table is inherited, they are there because of hyphen used between the year-month-day. Perform Partition Maintenance The two rows we inserted are more than 15 days old. Manually running the partition maintenance job (same job as would be run by cron) will export these two partitions to the os and drop the partitions. postgres$ /home/postgres/bin/pg_jobs/myschema_partition_maintenance When the job is done you can see the two exported files: postgres$ cd /db/partition_dump postgres$ ls -alh … -rw------- 1 postgres postgres 1.0K Feb 16 00:00 servers_2013-01-29_20130216_000000.000000.sql.gz -rw------- 1 postgres postgres 1.0K Feb 16 00:00 servers_2013-01-30_20130216_000000.000000.sql.gz Selecting against the master table should yield 0 rows, the two child tables will also no longer exist. Reload Exported Partitions If you want to reload the first child partition from the exported file, gunzip it then reload it using psql: postgres$ cd /db/partition_dump postgres$ gunzip servers_2013-01-29_20130216_000000.000000.sql.gz postgres$ psql my_database < servers_2013-01-29_20130216_000000.000000.sql Selecting against the master table will yield 1 row, the first child table will now exist as well. Notes Our database files reside on a partition mounted at /db which is separate from our root (‘/’) partition. For more information on PostgreSQL extensions visit the extensions documentation. The database engine doesn’t return the number of rows affected correctly (always 0 rows affected) when performing INSERTs and UPDATEs against the master table. If you use Ruby, be sure to adjust your code for the fact that the pg gem won’t have the correct value when reporting cmd_tuples. If you are using an ORM then hopefully they adjust for this accordingly. Make sure you are backing up the exported partition files in /db/partition_dump, these files lie outside of the database backup path. The database user that is performing the INSERT against the master table needs to also have DDL permissions to create the child tables. There is a small performance impact when performing an INSERT against a master table since the trigger function will be executed. Ensure that you are running the absolute latest point release for your version of PostgreSQL, this ensures you are running the most stable and secure version available. This solution works for my situation, your requirements may vary so feel free to modify, extend, mutilate, laugh hysterically or copy this for your own use. Next Steps One of the original assumptions was the creation of partitions for each 24 hour period, but this can be any interval of time (1 hour, 1 day, 1 week, every 435 seconds) with a few modifications. Part II of this blog post will discuss the necessary changes needed to the partition_maintenance function and table trigger. I’ll also explore how to create a second “archive” database that you can use to automatically load old partition data, keeping the primary database lean and mean for everyday use. Share your thoughts with @engineyard on Twitter
http://blog.engineyard.com/2013/scaling-postgresql-performance-table-partitioning
CC-MAIN-2017-13
refinedweb
3,278
53.31
VMD 1.8.7 Development VMD Development Status - Working towards final release - gamessplugin: Improve function that parses SCF iterations. - Add functions to determine if a wavefunction with a given signature exists. - Add function QMData::get_avail_orbitals() to get the occupancies for all available orbitals for a given wavefunction signature. - moved text label that was getting cut off by Tk (discovered when making screen shots) - Removed unused functions. Made order of functions in QMData.C roughly match QMData.h. - Added test code to regenerate the orbital list any time the wavefunction type, spin, or excitation selections change - Handle more cases in the orbital GUI logic, reactivate controls after updates, regardless whether or not there are orbitals in the new list - Ordered the plethora of functions in QMData.h and titles for groups of functions. Deleted unused functions from QMData. Renamed a function. - Correct orbital list regeneration behavior when a nonexistent wavefunction parameter combination is selected in the GUI - Refer to the index of the wavefunction signature in QMData as iwavesig to distinguish it from iwave which refers to the index of the wavefunction in QMTimestep. The wavefunction signature is the timestep independent wavefunction ID. - Added function to retrieve the list of available orbitals for a given wavefunction. - Catch cases where the qm_data member of a Molecule is still NULL but the rep is set to Orbital, e.g. when loading a saved state. - Added new routines for dynamically regenerating the list of available orbitals in the GUI, based on the currently selected wavefunction type, spin, and excitation parameters. - migrated callback data structures into GraphicsFltkReps.h since that's where they're primarily used. This will enable referencing the callback handle pointers within the orbital representation. - fix incorrect callback handle on Orbital representation - gamessplugin: Made reading the GUESS section optional since it is not always printed in the output. Read in point group symmetry, even though we don't use it yet. - gamessplugin: Improve version string parsing. - gamessplugin: Return gracefully when there are no atom coordinates found as it is the case with FMO calculations. - gamessplugin: Read wavefunctions for CI GUGA and CIS calculations. - gamessplugin: Made wavefunction keyword parsing scheme more robust. We can now read Ruedenberg localized orbitals. - apbsrun bugfix: gracefully handle the situation of a top molecule without a representation. - contactmap bugfix: avoid division by zero in a couple of places. - gamessplugin: Enable reading gradients. - readcharmmpar: bugfix: add missing expr that makes paratool run into errors otherwise. - gamessplugin: Enable correct readding of orbital occupancies and energies for MCSCF calculations. - Better handling of orbital occupancies and energies. - gamessplugin: Handle orbital energies and occcupancies properly. Enable to read occupancies for CI natural orbitals. - Add flags for orbital energies and occupancies per wavefunction. - namdgui: Withdraw window instead of destroying it when user closes it. Withdraw children with parent. When user iconifies main window, unmap children. - Added code (still commented out) to get the right orbital from the orbital index used in the gui. Improved comments. - namdgui: Rolled back Axel's recently commited GUI fixes since they didn't work. The scrollbar didn't scroll down to reveal the rest of the frame. Fixed the problem of the too large window by putting two frames into separate widgets accessible from the Edit menu. - Add comments for the functions for getting the wavefunction indexes and labels. - cpmdlogplugin, gaussianplugin: follow molfile plugin API changes to keep cpmdlogplugin and gaussianplugin compileable. - Changed variable names runtyp->runtype and scftyp->scftype. - gamessplugin: Get rid of unused variables. Reorganize qm data structure (reorder only). Use new variable names. - gamessplugin: Defortranized variable names scftyp and runtyp. - gamessplugin: Handle the case when SCF does not converge for single point runs. - Add safety and range checks for some query functions. - Add MOLFILE_MAXWAVEPERTS macro for the maximum number of wavefunctions allowed per timestep. - libbiokit: minor text change to an error message to help identify reason - atomids in lammps data files can be anything for as long as they are unique. support this case upon reading through an index map. - if we advertise using CODATA 2006 for unit conversion, we should use that and not something else for AU to eV definition. - hbonds: added a clarification to hbonds webpage - timeline: Data collection interface, data file format to ver 1.3 now with .tml extension, 2D zooming working properly, lots of GUI fixes and GUI improvements - ilstools: bug fixes. - Cranked VASP plugin version to match latest code. - Added Sung Sukong's VASP parchg plugin - topotools: plug memory leak. - ILS: Allow, but ignore specifying orientations for monoatomic probes. This makes it easier to write a reusable input script. - Applied Sung Sukong's VASP plugin update to workaround input files with minor errors in them. - Added conversion factor from Hartree into eV - cranked vasp plugin version numbers, and tagged all of the ones that use strtok() as thread-unsafe. - Updated versions of Sung Sakong's VASP plugins, in support of the new VASP 5.2 package, which has some new/updated file formatting. - multiseq: Fixed a bug that was occuring with the multiseq window was zoomed out to the point that the text was replaced with just colored pixels (found it on Windows). Introduced this bug back when we set the text color to be the "opposite" of the background color. - paratool: Improved text of a menu item. - resptool: Updated version that fixes several bugs and shortcomings. - readcharmmpar: Recognize lines beginning with '*' as comments. Fix indentation. - molfile_plugin.h: Removed unused fields from the qm interface. Aligned some comments. - readcharmmtop: hybrid topology now includes CMAP terms (from C. Chipot) - signalproc: add rudimentary documentation for most of the additional functionality. - signalproc: place code in namespace to avoid polluting the global namespace. - Added functions to translate between orbital ids and indexes. Add function to query the maximum number of available orbitals over all frames for the given wavefunction. - Have autoionize write the box information if it was there in the input pdb - Fixed QMTimestep copy constructor. - Add get_max_avail_orbitals() function that returns the total number of different orbitals present over all frames for the specified wavefunction. - hbonds: Don't attempt to call multiplot when running in text mode. - Store the orbital IDs in the wavefunction. - Change orbital_indices ot orbital_ids to reflect the fact that they are 1-based and don't have to start with 1 either. - Added orbital index numbers lists for each wavefunction to qm_timestep. Removed unused fields. - cpmdlogplugin, gaussianplugin, gamessplugin: Following Axel's suggestion, added num_occupied_A and num_occupied_B to the interface since the wavefunction may have only a subset of orbitals, and we want to know where the frontier orbitals are located. with the similarity reordering in VMD this information will be essential, if somebody compares the .log file and the orbital rep. - multiseq: based on what I discovered when using VMware, revised the size of a dialog box so that it fits on the screen better. - topotools: need to export selections2mol. - Switched on the new Orbital Rep code. Now one can choose between several wavefunctions per timestep. - added test code for menu item activation/deactivation. Used volumetric data reps and coloring as the first test case. - Change numerical values for spin alpha and beta. - provide a function that gets the wavefunction index from the IDtag. This is necessary since some timestep might not contain a certain wavefunction thus changing the indexes of the follwing wavefunctions. - gamessplugin: Remove the idtag field from the wavefunction since it will be set by VMD based on the other wavefunction descriptors. - Assign a wavefunction identifier based on type, spin, excitation and info string. - removed MOLFILE_WAVE_OTHER from list of wavefunction types since we have UNKNOWN which takes care of all other than the specified cases. - gamessplugin: Populate the wavefunction info string. - migrate loop control params out toward script interface - Add support for test looping to prevent host thread launch overhead from interrupting kernel execution when doing power consumption tests. - increase benchmark loops for madd kernel - increase arithmetic intensity of MADD benchmark inner loop - Set default orbital min/max range values to -0.1 and 0.1 respectively - solvate: Write a new pdb with bounding box information, as per justin's suggestion - Added new GUI controls for wavefunction selection, though they remain disabled until matching code is added to DrawMolItemOrbital to draw orbitals for the selected wavefunction. - Updated orbital rendering code with new parameters and state tracking to allow selection of wavefunctions by type, spin, and excitation - Increased maximum atom representation storage to accomodate new orbitals representation - gamessplugin: Removed old debugging output. - Added function to translate betrween the wavefunction type flags from the GUI and the wavefunctions actually stored. Removed debugging printf. - changed order of #define GUI_WAVEF_TYPE_* - prepare orbital gui for new wavefunction choosers - provide a list of #define GUI_WAVEF_TYPE_* that enumerate the options in the dropdown list for selecting the wavefunction type in the Representation window. - Removed debugging output. - Enable VMD to store multiple wavefunctions per timestep. Fix wrong behaviour of QM related molinfo get commands. Before they would override the Tcl result object instead of appending to it. - gamessplugin: Populate spin, orbital type, and excitation fields when sending QM timestep data. - hoomdplugin: some comment corrections. support minimal hoomd xml files that don't have a type section. - Prevent "within 0 of XXX" from causing a memory exhaustion and a subsequent crash. - rnaview: Close file that was not being closed. - rnaview: Removed conflicting parsing code for -debug option. - Revised multiseq tcl package number from 2.1 to 3.0 to match what Elijah et al are calling it externally. - Removed cpmdlogplugin from the release builds since it requires a non-standard build of CPMD and we don't want to "tease" users with this until all of the matching pieces are available both in the standard CPMD code and in VMD. - prepare for making final VMD release builds, no more beta tags - Cranked version number - VMD 1.8.7 beta 6 (June 16, 2009) - Fixed bad latex in python docs caused by a patch insertion/paste problem of some sort. - need to quote string when using square brackets in glob pattern. fixes spurious "0-9: command not found" error with 'atomselect list'. - fix macish no-line-break measure surface latex source - Added docs for measure surface - reworked vmdhttpcopy to first do a HEAD check on the URL to see if it exists (and is readable, accessible on the network, etc) and then do a request to get the actual file. This should help a lot on machines that have been firewalled off from the remote file. - multiseqdialog: reworked some of the initialization code that executes when a user is starting multiseq for the first time. Tells them that they need a good network connection, and handles results from vmdhttpcopy in a more sane fashion (checking for a few common errors, etc) - inorganicbuilder: Added waitfor all to mol new and mol addfile commands, to possibly fix file deletion race condition problems on Windows. - Fixed bug that crashed vmd when tying volmap ils without options. - Warn users about potential buggy rendering when the X11 'Composite' extension is enabled. - molfile_plugin.h: Added new wavefunction type. Changed wavefunction type name. Added documentation. - gamessplugin: Made wavefunction parser even more robust. - basissetplugin: Removed unused helper functions. - plugin docs: Update docs to match current plugin version number. - edmplugin: Added code to write X-PLOR maps (only orthogonal cells for now). The X-PLOR format requires that the edges of the cell be integer multiples of the grid spacing. To overcome this limitation, we pad the box accordingly and resample the map, keeping the original grid spacing. - Added comments on two MolAtom members that should probably become unsigned bit fields to save memory. - Changed constant memory layout for CUDA ILS: permit up to 160 atom types, up to 8 probe atoms (for ethane), reduce maximum number of bin offsets to fit into first 8K page, reduce maximum number of conformers for increased probe size, and leave the highest 1K unused. - if CUDA ILS fails, fall back on CPU calculation - small GUI tweaks and cleanups. Update documentation to mention some possible optimizations for certain g(r) calculations. Step version number to 1.1. - contactmap: Fixed bugs in initial data field filling, which were obvious when loaded contactmap without any molecules present. Also, can now compare different-length molecules. - gamessplugin: Enable reading CI runs. - fix c++isms in gamessplugin - vmdmovie: Added a new "dry run" movie mode that doesn't do any image generation or encoding, to let users test their movie segments much more conveniently. - vmdmovie: All of the supported movie renderers support both bmp and ppm image output - vmdmovie: All of the VMD versions now incorporate the same list of renderers. - vmdmovie: updated documentation version number to match the latest vmdmovie plugin - Updated the behavior of the shared library compiles to link with g++ so that the shared library builds can use CUDA etc. - molfile_plugin: Added two new QM wave function types. - gamessplugin: Enable reading GVB ROHF calculations. They have an extra set of so called geminal orbitals which can be loaded now. - gamessplugin: Made parser more robust. Simplified parsing structure. Fixed memory leaks. - Added CUDA source files to make_distrib source distributions - Removed outdated SWIG interface - Updated python docs per Axel's patch. - namdplot: close input file at the end of the namdparse proc - reduced solvate GUI picture to 60% of the original size to improve the layout of the docs page. - avsplugin: Update URL with the CVS Field file format description. Updated version number to match latest revision. - mapplugin: Update URL with the AutoDock file format description. - Added ssrestraints and rnaview plugins to the main plugin docs page. - ssrestraints: fix a memory leak - gamessplugin: Fix some problems with reading older file formats. - Added prototype detection code for X11 "Composite" extension - gamessplugin: Enable reading older versions of GAMESS output (the format changed 2005). - Bugfix: Allow loading of QM logfiles that contain no explicit basis set (such as calculations with semiempirical methods in GAMESS). This takes care of Rui Rodriguez's bug. - make the generation of a list of atom selections a bit smarter. - Changed FileRenderer::nearest_index() to search the entire color table and not just the first 33 colors. This was causing problems for sphere and point arrays colored by one of the attribute-based color scales. - Try pale green selection highlight color and get user feedback - Fix bug in volmap command parser that could result in a crash if the selection parameter was missing. - Silence console output from performance measurement code in the orbitals rep - Recompute the orbital grid if the user changes the step size parameter - Cache molecular orbital grids and only recompute them when the selection changes, the timestep changes, or the orbital index changes. Other representation parameters should only affect the rendering and not the computed orbital grid itself. - prevent double inclusion of volumetric data header from causing troubles - signalproc: added support for regular sliding window average for sake of completeness. - signalproc: First part of signalproc documentation overhaul. Added overview for all packages and sgsmooth results example. - signalproc: fix non-portable use of find, so that fftcmds.so does get installed. - Add documention for the 'evaltcl' command in the Python section of the User's Guide. - try harder to make the VMD module work when imported into a Python interpreter and give a hint to the user in case it ultimately fails. turn 'evaltcl' into a regular method forwarding calls to VMDevaltcl, but only if the latter is actually available. add embedded documentation for 'evaltcl'. - some minor tweaks and changes to make the VMD python module behave consistently and without errors when using it from a python interpreter. make the tcl evaluation command directly available as 'evaltcl'. - topotools: expand topotools documentation to add some explanations on usage and scope. - topotools: implement a "selections2mol" utility method for use in "trunctraj" and otherwise. - topotools: fixed bug in sorting of residue numbers - one more update for CG-CMM topology and parameter input generation. - cranked mutator plugin version due to bug fix provided by Grischa Meyer. - Applied Grischa Meyer's fix for a scenario where mutator would fail when one tried to mutate one residue in one segment in a file which has many segments and the resid of the mutation is higher than the number of residues in the smallest segment. The problem was caused by an empty "oldres" variable, and is fixed by moving the offending code into the safety of an appropriate if/then block. - improve support for reading LAMMPS topology files for CMM coarse grain systems. - topotools: remove redundant function definition. write a Masses section, if reasonable data is present. - topotools: minor cleanup and documentation fixes. - Cranked version number - VMD 1.8.7 beta 5 (June 1, 2009) - vmd.sh: correct variable name broken in two by a newline char. - Tweaked the color of browser selections to be a lighter shade of gray than the default window background color. - Reduced maximum ray recursion depth from 30 down to 8, since there's really no sane reason one would ever need this for a normal VMD scene - Added code to detect and report mismatches between the CUDA runtime and the installed CUDA driver. - Teach the CUDA management code how to deal with devices that are in computeModeProhibited state. - disable trunctraj until it's ready for prime-time - Added hbonds plugin to the docs page - reduced the size of the screen shot for the hbonds plugin docs - fixed name of multitext plugin on the docs page - Added mergestructs to the docs page - Added ilstools, reordered the "other" grouping - added signalproc plugin to the docs page - Added topotools to the docs page - Added nanotube builder docs to the plugin docs page - added credits and documentation for nanotube plugin. - Added CUDA support to win32 vs2005 builds, runs well so far. - Fixed a bad fopen() file mode that was causing a crash when compiled with MSVS 2005. - Added libtachyon to vs2005 win32 builds - Updated vs2005 project for recent changes - nanotube: use "mol new atoms XXX" instead of a temporary file. convert to vmdcon. - topotools: make adddefaultrep independent from namespace variables, so it can be used in other plugins. - qmtool, paratool: changing the palette at this point triggers initialization failures, if the GUI is enabled from a script. Commented out the call for the time being. - ilstools: make the GUI handle the situation of having no molecule or no usable top molecule gracefully and without error that are silently ignored. - use correct callback name for cggui plugin. - use correct callback name in hbonds plugin registration. - only enable the use of rlwrap on Linux platforms for the time being, as the tests for its existence encounter problems on platforms like AIX that use ksh rather than bash, and for which rlwrap is most likely not installed anyway. - Added AIX6_64 target to make_distrib - fix Blue Print plugins build config - updated build configuration for NCSA Blue Print now that it's running AIX 6.x - Added AIX6_64 target for Blue Waters - ilstools: some more GUI tweaks to make it look more regular and keep room for large sampling molecule names. convert to use vmdcon for log messages. - ilstools: replaced inserted scrolled frame between GUI and toplevel. cleaned up the confusing use of $frame and removed all explicit references to .ilstools except when initializing the toplevel window. - Added macosx.x86.opengl.nocuda target for MacOS X 10.4.x builds that cannot support CUDA - convert sequence viewer to use vmdcon. step version number to 1.1. - namdgui: make the GUI a little bit wider for safety and center the scrolledframe. - rewrite of the code for the left side panel of the sequence viewer to use grid as layout manager and make the zoomslider fill the panel. - rewrote and simplified the menubar handling to match other plugins. removed some dead and non-working code. - solvate: convert solvate to use vmdcon. - solvate: Fix a bug that occurs for very small water boxes Compress the gui to get rid of some wasted space Remove the scrollbar (can be added in again very easily be changing what it is set to - autopsf: Shorten the autopsf gui - molefacture: Slim down the molefacture gui - autopsf: Make the checkbuttons for the fragments into radiobuttons - inorganicbuilder: Shrunk GUI - zoomseq: comment out "Close Window" function for style consistency. - untabify zoomseq. - reduce namespace pollution by importing the scrolledframe proc into the individual namespaces and not into the global one. - make solvate GUI resizable in y direction by inserting a scrolled frame, similar to namdgui. - convert namdgui to use vmdcon. - namdgui: resizable by inserting a scrolledframe between toplevel window and the existing gui elements. width is still fixed at 550px, but height can be changed. defaults to 400px showing the file i/o widgets. - fix off-by-one buffer overflow detected by gcc-4.3 - Tweaked MSM coulomb button - Updated the volmapgui plugin to indicate the relative performance of the "coulomb" and "coulombmsm" map types - Corrected order of x/y/z lattice dimension parameters for the multilevel summation-based coulomb potential calculation. - Updated volmapgui plugin adding support for the new multilevel summation based Coulomb potential map type ("coulombmsm"). - Moved the multilevel summation based electrostatic algorithm from the old "coulomb" map type, into a new "coulombmsm" map type. - Scaled down the ilstools GUI snapshot in the docs so it doesn't take up the whole web page. - Set default contact map window size to be more netbook-friendly - Changed the window title from "VMD Seq Compare" to "VMD Contact Map" since that's the name of the plugin and that's really the only calculation it can do presently. - Resized rep browser column widths to accomodate longer representation and coloring method names, e.g. "DynamicBonds", and "PhysicalTime". - Further fine tuning of color menu browser widths and positioning. Increased the width of the color scale image to take up the entire window. - Increased the width of the color window by 40 pixels to accomodate longer color category item names and color names - Added a text label for the shadowing and ambient occlusion controls to indicate they are (currently) only for external renderers and have no effect on the OpenGL rendering - Added new macros for colors used for text in browsers to signify active/inactive or displayed/hidden states, updated the color scheme for the browsers to be slightly off-white to differentiate them visually from the text input fields, and changed the default "inactive" text color to red rather than magenta. - Started adding macros to allow redefinition of the main window colors - enable alternate color scheme, time to collect feedback from users.. - checked in alternate color scheme, though not enabled - Updated more FLTK GUI source files to use the new color macros - merge the text/selection macros for choosers since they are really the same thing in FLTK's view - Made color macro names more consistent with FLTK's coloring terminology - Replaced hard-coded VMD FLTK color scheme with macros that are much easier to modify. This will make it much easier to devise an interface that improves on the old cyan/black/yellow scheme used in the past. - Fixed Tachyon triangle strip generation code so that per-vertex colors aren't exported when volumetric texturing is active. - Applied Justin's patch adding VMDevaltcl to the Python interface and changing the behavior when loading in standalone vs. module mode - Cranked version number - VMD 1.8.7 beta 4 (May 27, 2009) - Added a progress callback to the internal Tachyon renderer calls so that long-running ambient occlusion renderings don't leave the user mystified as to how long things are likely to take... - Added several new materials optimized for ambient occlusion renderings - Updated the "diffuse" material so it looks closer to the same whether rendered in GLSL, normal OpenGL, or in Tachyon - Corrected material state handling for file renderers, so that the volume slice representation looks right when rendered with ray tracers - require latest version of Tachyon for volumetric coloring/texturing features - corrected export of scenes containing triangle meshes or vertex arrays with volumetric texturing in effect. - Enabled volumetric coloring now that it's working correctly for the VolumeSlice representation. Need to add missing code for the other cases still. - Added 3-D texturing to the built-in Tachyon renderer - Cleanup of 3-D texturing implementation for external Tachyon renderings. Added comments to clarify the steps in transforming the texture plane equations from molecule coordinates into the renderer's world coordinates. - corrected handling of objects drawn with lighting disabled. - Call virtual method to enable volume texturing once a volume texture is defined. - enable volume texturing by default for tachyon renderer - autopsf: Fix an indexing problem when using osel in some cases - Fixed Z offset bug and handedness of 3-D texture plane equation vectors passed to Tachyon. Translation and scaling of 3-D volumetric textures both appear to work correctly now. Rotations give incorrect renderings, so more bugs remain. - gaussianplugin: recover ability to parse wavefunctions and store them appropriately. currently only cartesian basis sets are supported. orbital display for some simple cases recovered. - cpmdlogplugin, gaussianplugin: next step in fixing the gaussian plugin for orbital display. needed to add a parser for counting total atomic basis functions, total primitives and total shells, so that we can allocate arrays in the correct sizes before parsing the basis set and the wavefunction(s). currently handles only inline basis sets but not external ones. all basis functions are assumed to be cartesian; pure basis functions will need to be converted. - cgtools: Use better default md parameters - timeline: many GUI, feature, and stability fixes. (Hopefully have at last solved non-atom molecule problems) - eliminated old (now unused) macros that were previously used for sizing internal data structures in the GAMESS plugin. - fixed a bug that was occuring when you used the mouse to select an element in a sequence that was "past the end" of the sequence. Basically something that makes the plugin more robust - cubeplugin: convert cubeplugin to vmdcon. - cubeplugin: added support to read charge field from atom specification on suggestion by xavier cartoixa soler. - ILS: Removed outdated citation message. - Cranked version number - VMD 1.8.7 beta 3 (May 18, 2009) - Updated the vmdmovie plugin to allow use of TachyonInternal on Windows, since Windows versions of VMD now include a built-in "TachyonInternal" renderer just like the Unix versions do. - Prevent snprintf() from tripping up msvc compiles - dtrplugin: Updated version from DESRES, fixes a number of bugs and improves interoperability with Schrodinger's maestro tool. - maeffplugin: Updated version from DESRES, improved interoperability with Schrodinger's maestro tool - vmdmovie: Fix an unprotected 'molinfo top get numframes' call that could cause an error when no molecule was loaded. - Updated documentation build to use ps2pdf rather than distiller, since ps2pdf is free and widely available whereas distiller is no longer available - Added documentation for new "render" subcommands to control antialiasing and ambient occlusion lighting parameters, and image output formats - Added docs for new ambient occlusion and shadow control display commands - Added shadow control to display command built-in help - added ambientocclusion to built-in help query list - updated readme info with new rendering features - vmdmovie: removed hard-coded Tachyon shader mode flags from the command line arguments since these are now contained in the scene files emitted by VMD - vmdmovie: removed hard-coded antialiasing sample flags and rendering mode flags from Tachyon execution strings, since VMD now exports this information in the emitted scene file itself. - Added ilstools to the Analysis extensions menu - Applied Olaf's updates to the plugin test main to allow multi-file tests and exercising more of the new plugin APIs. - Updated AA sample count in default Tachyon run command string - make psfgen compilable again when using molfile plugin interface. - vtfplugin: fix C++isms - Updated the external Tachyon renderer code to emit all of the key parameters in the scene file rather than depending on command line options. The new code uses the "shader_mode" block to enable the VMD-specific transparency and fog rendering modes, as well as setting the appropriate rendering quality mode, and optionally enabling ambient occlusion lighting if needed. Changed both the internal and external Tachyon renderers to use a default of 12 AA samples per pixel, and 12 AO samples per AA sample. - A bunch of minor bugfixes and changes in order to work with the new format of CHARMM toppar files that allow more than 4 Characters for resnames, atom names and types. - added new 'ilstools' plugin - Minimum reasonable AO samples is about 16 samples per AA sample, with a default of 8 AA samples, we get a nice total of 128 AO samples per pixel. - Added shadowing and ambient occlusion controls to the display menu - Added display commands to enable/disable rendering with shadows and ambient occlusion lighting, AO ambient value and direct light rescaling factor, and FileRenderer commands to control the number of AO samples taken. Currently implemented only for TachyonInternal. - minor cleanup/reorg for readability - pretty up display settings window - Added several new materials using the outline shader - doc: Add little segment in tutorial about "logfile" and the new GUI controls for it. - Bumped up required Tachyon version number now that larger-than-unity texture outline factors are allowed (requires range clamping on output). - corrected a typo in the Tachyon texture output for outline rendered objects - Cranked up outline factor for goodsell material to leave dark outlines - Allow the outline factor to go beyond unity so that users can make dark halos around objects if they like. - improve readability of outline shading section of the GLSL fragment shaders - vtfplugin: Updated with Olaf's latest version - Fixed up the File menu command logging feature and corrected missing behavior entries for the newly-added command logging items. - hide "render imagesize" from built-in help until at least one external renderer implements it. - renamed old "aalevel" parameter to file renderers to "aasamples" which is more correct. - Misc cleanup and improvement of handling of previously undocumented renderer antialiasing controls and image format options - Added missing render subcommands to built-in help - updated default material list, added "Goodsell" shader to the built-in materials - solvate: pretty up I/O calls - improved order of material parameters written to saved state files - Increase default antialiasing for Tachyon renderings to 8 samples per pixel - Updated docs with note on outline shader - Applied AK's patch to add text command logging to the GUI - Updated FileRenderer and Tachyon renderers to support the new outline shader modes as well. - ssrestraings: Fix selection logic when deciding if STRIDE should be run on each segment separately. - Added two new material parameters "outline" and "outlinewidth" for use with the GLSL shading mode. These cannot currently be rendered by any of the external renderers, but the improved convenience of having them built-into VMD rather than having users hack the shader files externally is well worth it. It should be straightforward to add matching rendering support into Tachyon. - Added outline rendering to both VMD GLSL fragment shaders - ssrestraints: Only run STRIDE on each segment if the given selection contains protein. - Added a query for zero-copy mapped host memory - Add helper package to run STRIDE on each segname separately, which is more robust than running STRIDE on the whole structure at once. Using this approach, secondary structure is correctly calculated for the ribosome structures. - solvate: Added "waitfor all" flags to all file loading commands to prevent open file handles from lingering by the time we get to the point where the file delete calls are made. - topotools: make all procs that create a new molecule behave more like "mol new" and have them create a representation and reset the display view. The package internal variable "newaddsrep" controls this behavior. - lammpsplugin: let atoms have a radius when reading lammps data files. we use 1.5 by default, same as the molfile plugin. fixes problems with VDW rep reported by Lutz Maibaum. - fix help message for "mol" command. - fix cut-n-paste error in vecmul documentation. - topotools: fix undefined variable bug in replicatemol error message. - prevent string buffer overflow when renaming molecules with huge name strings. - Eliminated standalone build ifdefs from ILS code again - ILS: add option to ignore exclusion checks - Cranked version number - VMD 1.8.7 beta 2 (May 13, 2009) - Updated msvc6 project for recent thread pool changes. - hoomdplugin: finalized support for velocities by adding timestep metadata reader function. - Updated to Tom Bishop's latest version 2.0 of the VDNA plugin - seqdata: fixed a bug that was occuring when a list item that contained spaces was passed in. - Assume the MAP[CRS] fields apply also to the ORIGIN coordinates as they do for N*START - pbctools updated to Olaf's latest version 2.5 - ccp4plugin: Added support for MRC2000 format headers with floating point ORIGIN records - fixed device minor version check logic to accept G80 hardware - Switch default VMD builds to use CUDA 2.2 - ILS: Fix bug in rotamer generation code that prevented correct processing of nonsymmetric probes. - export vmdconio.h header with VMD alongside vmdplugin.h and molfile_plugin.h so that plugins can again be built against the VMD installation only, including those that have been converted to use the vmd console interface. - ssrestraints: Require input psf/pdb files, as opposed to acting on a previously loaded molecule. The RNA restraints code relies on the 'residue' definition, and requiring psf/pdb files prevents us from relying on "guessing" from VMD. - Allow the use of the environment variable VMDCUDANODISPLAYGPUS to prevent GPUs used for display from being used for computation. This is helpful in cases where only one GPU is installed and it gets overwhelmed by work, making the host windowing system unresponsive. - Changed threadpool manipulation routines to check for NULL parameter values and return error codes as appropriate. - Enabled automatic worker scheduler tile size scaling using predictive relative performance heuristics. - Use GTX 280 and Tesla C1060 as the "1.0" speed reference for the dynamic scheduler - Added device pool initialization code to compute and set speed scaling factors for each GPU device. - Added APIs for setting and querying relative device performance scaling factors, and for automatically scaling peak requested scheduler tile sizes by device performance index. - Changed all thread APIs to use the same symbolic constant return codes to indicate when the work schedulers/iterators have no more work units left - Fixed missing mutex unlock call prior to returning an empty status for an empty error stack - updated conditional compilation thread library selection tests - ILS: Put the energy threshold clamping back into the CPU kernels. Otherwise the algorithm is incorrect (and slower for mono-atom case). - ILS: Removed the heuristic that puts a restrictive bound on the number of "extra atoms" permitted for a given number of atoms. Instead we allow the maximum number of extra atoms that the CUDA kernels can handle. - Line up columns when printing the number of SMs in each GPU device found - ILS: Remove clamping of the occcupancy value in the different kernels. Clamping during the computration doesn't give any speedup but it decreases accuracy in some cases where the downsampling over gridpoints gived a different final result when the individual points were clamped already. Now the energy cutoff is only applied during the energy exclusion to identify points that would always be excluded and after the final downsampling. - Updated documentation for mergemols and replicatemol. - Merged in external tools to merge molecules and replicate unitcells. Some refactoring of the sources into more logical pieces. Place the "topo" frontend command into the TopoTools namespace and 'export' it to the outside via an alias. The source is more readable now, due to removal of most namespace qualifiers. - volmap compare: Added RMSD per bin to the histogram. Added command option -interval and -numbins. - ssrestraints: Update docs with new -hbonds option. - ssrestraints: H-bond restraints based on a script by Peter Freddolino. - topotools: properly skip over pair, angle, dihedral and improper coefficients in the topology file, handling empty and comment lines, too. - Changed histogram bin interval to 2.5 for volmap compare. - Fix the weighted RMSD computation in volmap compare. Fixed bad histogram bin assignment. - ILS: Changed the -conf option to -orient in "volmap ils" because that's a more accurate name. The old syntax still works, though. - Added note about GPUs for ILS. - Updated ILS documentation. - removed @myselection example since this was eliminated in rev 1.74 of AtomSel.C many years ago. - remove '$' from the list of recognized "break characters" to rlwrap as this breaks with certain versions of /bin/csh. removed it in /bin/sh version, too, to have the identical behavior in both scripts. - Started process of merging the CUDA device pool feature into the lower level thread pool APIs for better performance and reduction in code to maintain - topolammps: velocities list has to be initialized outside the loop. - fix a typo in the color clamping routine - collapse platform macro tests where possible. - volmap compare now also returns the average error per bin as well as the maximum error per bin (and the histogram printing includes the values as well) - eliminated unnecessary include on MacOS X - Collapsed many instances of ARCH_LINUXxxx down to a single test for definition of the __linux macro. Only if we have a specific reason to differentiate the flavors will we need to check for the VMD compilation macros. - Replaced VMD-specific hp-ux macro tests with general ones - collapsed AIX macro tests down to a single check for _AIX - collapsed separate IRIX macro tests down to single __irix test - Collapsed a large number of conditional compilations for Linux down to a single test for __linux. There were historical issues with __linux not being defined in c99 mode in older revs of GCC, but it appears to be fixed now. I've also checked that Intel C/C++ both do the right thing as of version 9.x at least. - Correct ABI compilation mode for text mode 64-bit AIX5 builds - Fixed a bug in handling of accession codes and database info that was introduced in rev 1.439 with AK's patch to allow creation of empty molecules. The accession info was being appended out-of-sync with the file lists being updated, breaking the correct behavior in the normal use case. In the special case where a molecule is generated internally via scripting commands, nothing should be recorded since the file records aren't being updated either. - Fix unprotected use of strcasecmp() in psfcheck. Win32 doesn't provide this routine by default. - Added AIX5 text build configurations for anlaysis-only use - Fix namespace collision with AIX system-defined "hz" macro. - Changed tilestack initializer to assume caller-allocated memory to improve cache use when inserted into the thread pool object. - Use correct frame count when reporting time/frame. - eliminate unnecessary padding bytes. Since the tile stack will only be access at the same time as the shared iterator, any shared cache lines are harmless, the sharing is thus real and would not create any performance loss. - ILS: added return of histogram information from volmap compare - ILS: Silenced excessive debugging output with check for VMDILSVERBOSE environment variable - ILS: Added comment about deficiencies in generating tetrahedral probe distributions at higher frequencies. - ILS: Fix bug in tetrahedral probe conformer generation. Remove unnecessary code. - ILS: Support of higher numbers (over 32) of probe orientations by geodesic triangulation of an icosahedron. In most practical cases we hopefully don't need more than 32 orientations but we need at least one reference calculation with a ridiculously large number. - Updated CUDA orbital code in prep for dynamic tile size selection by thread pool workers at runtime. - Added option to ignore probe symmetry through env variable VMDILSNOSYMM. Improved log messages and comments. - ILS: Generation of uniformly distributed probe orientations based on vertices and faces of platonic solids. Various minor other improvements. Still needs some cleanup. - rename APIs for dynamic work scheduler to be more developer-friendly - Misc cleanup and commenting on CPU affinity routines - Call sched_yield() after setting new thread CPU affinity mask to cause the new mask to take effect immediately. - correct a buglet in the CPU affinity code - psfcheck: Ignore "end" lines just like "END" lines - Added matching calls for device pool. - Added iterators into the threadpool construct for caller convenience - reorganized the header to facilitate adding new structs to the threadpool primitive. - Added a tasktile stack for use in handling errors and exceptions. - Revised the threading primitives to accept a new tile structure that describes the half-open interval of tasks, instead of individual integer parameters. Eliminated the single task work request routines in favor of using the variable size tile request version in all cases. - updated dependencies for lammpsplugin. add hash files, remove periodic table. - updated plugin for native lammps text mode trajectories. added a completely new parser for the data section that can now also handle many forms of "custom" dumps in addition for the simpler "atom" format. due to additional information in the plugin about the contents of the data (=ATOMS) section, optional data can be read in as soon as it is supported by VMD. support for molid, charge, and velocities is already in. more to come when VMD is ready for it. - added integer hashing functions from main VMD trunk with slight modifications, so that it can be included together with the string hash. will be used by improved LAMMPS plugin. - topolammps: add support for numbers in exponential representation that have a capital 'E' instead of a small 'e' to indicate the exponent. fixes reading the micelle data file. - Enable multiple planes per kernel call. Use heuristics based on timings for testcases on GT200 to determine the number of planes to process per kernel call. - removed commented out code in create_unique_paramlist() - Cranked version number - VMD 1.8.7 beta 1 (April 29, 2009) - Prevent machines without CUDA from creating an empty device pool. - Prevent MacOS X systems with no CUDA drivers/devices from catching the emulation device - updated list of authors - Added display of third line of authors that have made significant contributions to the code in the main VMD executable. (contributors of plugins aren't listed, as they get their credits elsewhere) - ILS: Check for errors from create_unique_paramlist(). Set upper bound on unique atom types to 200 so that our naive search never devolves into a quadratic algorithm. Allocate less memory for temp storage, perform fewer sqrtf()s. Typecast float* arrays to flint* so that we can perform equality comparison between ints rather than floats. Check validity of VDW parameter types. Left old version of create_unique_paramlist() commented out, just in case. - seqedit: removed debug line that had slipped through - Disabled 3dconnexion driver code for MacOS X builds until it has been completed and fully tested. Enabled CUDA by default for MacOS X 10.5.x builds. - MSM: Corrected non-portable use of "uint" type that was preventing compilation of the CUDA kernels on MacOS X 10.5.x. - Silence CUDA error/warning messages that can occur with mismatched driver versions, as this is apparently common with machines running linux distributions that install NVIDIA drivers (and thus libcuda.so) despite lacking an actual NVIDIA GPU. - Updated plugin build script for change of NCSA cobalt login node name - Changed AIX5 builds to tune for Power5 processors by default - changed version to be more verbosely a beta version, to prevent people from continuing to run the beta revs for months on end. - ILS CUDA: Better error reporting, does one plane, limit slabs to two planes - volmap compare: Histogram of error in map 1 relative to map 2 - Added code to handle newer style LAMMPS native trajectory files based on suggestion from Lutz Maibaum. The change in LAMMPS will finally allow to detect the content of the trajectory file, so support for custom style trajectory files can be implemented and will follow soon. Fix incorrect variable declaration for write file descriptor. - enhanced error messages for psipred. Still not good... but better.. - ILS: Moved sync threads to after early exit of entire thread block. Improved performance for exclusion optimizations by reducing shared memory use to within 4K, by decreasing number of conformers per loop from 8 to 5. - revved required Tachyon version number for new fog features. - ILS: Change exclusion logic for (commented out) warp vote. Add test for thread block early exit to monoatom kernel. Using distance-based exclusion testing is too slow (for slices). Is the exclusion distance too large (at least for xenon example)? Disabled distance-based exclusion check. - ILS: Changed logic from 'inclusion' back to 'exclusion' - fixed typo in fog rendering mode - Enable built-in "TachyonInternal" rendering for Windows builds, using multi-core enabled Tachyon. - Cause Tachyon renderings to use planar Z-depth based fog coordinates rather than the more physically correct radial fog, since this will much more closely match what users see in the VMD OpenGL display. - eliminated old VolMap.C file from Win32 builds - ILS CUDA: Enabled thread work compaction for exclusions. Fixed by adding missing sync threads. - Various updates to please GCC 4.1.x. - Rewrote color scale function to avoid undefined compiler behavior. - Added default case for eye position switch block to please GCC 4.1.x - ILS CUDA: Have early exit optimization for thread block enabled. Have thread work compaction in thread block disabled (gives wrong results). - Enabled thread pools for Win32 builds, since the condition variable implementation adapted from Tachyon has been working fine so far. - Added conditional compilation ifdefs for BUILD_STANDALONE to allow compilation of the ILS module outside of VMD. At present, there are many dependencies on other VMD data structures, but the intent is to gradually address these one at a time until it's runnable. - eliminated old dependency on config.h for DEF_VMDTMPDIR, as this was only really used as a method of last resort. - Added method for specifying optional probe symmetry. - Platform-specific temporary directories are now dealt with purely in the hard-coded utility routines, since it was already the case that the configured directory was only used as a method of last resort. - more work towards standalone builds - Added include of stdlib.h for standlone ILS builds that need RAND_MAX - Added CUDA kernels to find distance- and energy-based exclusions. Note that the performance is lower because the multiatom occupancy code doesn't yet take real advantage of having the exclusions. - removed bogus "color rgb" command listed built-in help, leftover from some incomplete cleanup from one of Jordi's previous revs. - ILS: Allow probes with more than 2 atoms. - removed some commented out lines - commented out a couple of debug statements that had slipped through. - Optimized monoatom kernel using techniques from multiatom kernel - Changed 3D bin offset index into "flattened" offset for 1D atom bin array. This reduces register counts of both kernels, aligns constant memory access to int, and removes 2 int multiplies from loop over atom bins. - Removed USE_FLAT_OFFSET macro and alternative code paths, all code paths use this optimization now. Startup code in multiatom kernel replaces as many int mults as possible with bit shifts and __umul24() calls. Fixed host code to process thick slabs whenever DO_ONE_PLANE macro is "off.' - Added a couple of comments about decreasing register use in multiatom kernel - ILS: Optimized multiatom CUDA kernel. Eliminated as many int multiplies inside loops as possible. Loop over fixed number of conformers and correctly sum results of padded list of conformers when calculating occupancy. Much better performance now. - gaussian/cpmdlogplugin: Step one in adapting gaussian and cpmdlog file plugins to the updated molfile QM infrastructure: adjusted internal data structures and implemented reader test routines. wavefunction parser still incomplete, but no more segfaults on the simple tests. - Removed old multiatom kernels. Renamed kernel cuda_occupancy_multiatom_final to cuda_occupancy_multiatom. - Fixed a loop range bug and made the memory clearing code run faster by reducing the maximum number of iterations taken in the allocator. - Changed CUDA device pool function names to be more palatable in reusable code. - ILS: removed ATOMTRANS code, calculate all interactions on untranslated positions - Enable clearing of all CUDA device memories (global and constant memory) on program start. - Optimized inner loops of multiatom_final() for better performance. - Added new source file with CUDA memory clearing code - Added a new CUDA utility routine to allocate and clear all accessible device memory (both constant memory and global memory) to aid in debugging. - multiseq: added in an error box if you choose to predict secondary structures and things haven't been set up. You are now notified of what is wrong. - ILS: Added cuda_occupancy_multiatom_final() CUDA kernel. This version has shared memory summing of conformer potentials. The loop unrolling of "_clean()" have been removed along with all of the related macros. This "final()" will be our new base version for optimizing the inner loops over the probe atoms. - ILS: Added shared memory accumulation of conformer potentials. Unfortunately, this is not working with loop unrolling, so it's disabled. Also renamed conditional macro USUM to more descriptive SHMEM_SUM_CONFORMERS. - multiseq: removed a debug line that had slipped in - topotools: added checks for supported atom styles and writing out atom types and residue names to lammps data files as comments, if available. - topotools: added a special case for adding bonds to an "all" selection resulting in massive speedups. - added some code that sets the text color in the boxes in the main MS window to hopefully be of a higher contrast than what we had before. Right now, the code is doing an ^, but I played around with adding and modding, but got the same values. - avoid parameter name collisions with AIX5 "hz" macro - stamp: removed completely bogus use of strcat in a function - Updated plugin build scripts for IBM AIX on the "Blue Print" test machine. - Beginning of beta builds. Still have a several nagging known buglets to fix, but we're getting close. - timeline: Version bump to 2.0 - Added code for use of pinned memory (but disabled currently) for orbital kernels - multiseq: fixed a couple of slider bars that were allowing 0% to be returned, which didn't make any sense - Fixed indentation for measure symmetry. - multiseq: added in some error checking for the user when they import data. Now tells them if they chose file with files listed, and if they choose BLAST without a database being given. - Added an explicit synchronization at the end of each work block so that asynchronous kernel launches and I/O's don't allow one GPU to grab more work than it should resulting in load imbalance. - Optimized the orbital kernel memory copies to reduce overhead - Changed the CUDA molecular orbital kernels to use the blocked work distribution mechanism for improved performance. - Added blocked work request routines to the on-demand thread launch mechanism as well, to ease migration between use of the thread pool and use of on-demand spawned threads. - Eliminated outdated Tcl command options. Added arguments to specify probe completely without atom selections using just Tcl lists. - Eliminate unnecessary dependencies in pbc measure routines - Peel away unnecessary dependencies in timestep class - added documentation for "order" flag to "measure fit". - Started working on standalone build of top level ILS driver routines - Improve performance in multiatom by unrolling inner loops over probe atoms. For now, restrict CUDA grid from slabs to slices. - Fix memory leak when using "measure fit" with "order" as reported by chris macdermaid. - ILS: Removed user specified selection and all its dependencies. - Started making ILS independent of AtomSel. - volmap: Fixed bug calculating "meanrange". Report elements producing max difference - gamessplugin: Protected printing of atomic numbers and other info with debugging macro - silence debugging output in GAMESS plugin by default - silence various debugging messages in the QM code, except when the macro DEBUGGING is defined - ILS: removed various debugging code that's been turned off for a while. - Removed more unnecessary dependencies in ILS code - Started trimming unnecessary dependencies out of the ILS code to make it easier to form a standalone app from the same source code. - bugfixes and some cleanup. - Added shared iterator block request routines for use by CUDA codes that may want multiple work units at a time for improved overlapping of communication and computation, and for use in scheduling work across both CPUs and GPUs, or GPUs with a large variation in the SM count where different work scheduling chunk sizes are appropriate. - corrected shared iterator increment logic - Rewrote shared iterator routines in prep for caller-requested increment (e.g. block size for work distribution). - Changed CUDA device pool initialization code to limit max number of device worker threads to the maximum CPU core count we're allowed to use. - Started redesigning the dynamic load balancing routines so that they can be used to schedule work not only round-robin, but with blocks, and to allow the worker threads to request an efficient block size based on the attributes of their associated CPU and/or GPU accelerator. - ILS: Removed outdated argument to the volmap ils command. - ILS: Use the molfile_plugin interface to write the DX file instead of Jordi's copy of the dx writer in VolmapCreate. - Replaced SAFESTRNCPY() macro in write_volumetric(). It was designed to work with two statically allocated arrays but SAFESTRNCPY fails here because sizeof(name) is just the size of the pointer and not the size of the allocated memory. - ILS: debugging code, clean version of multiatom, calculate cuda expf() - ILS: fixed max_energy parameter to compute_allatoms(), plus some disabled printfs - ILS: Removed unnecessary -margin argument. - ILS: Get rid of too much debuggihg output. Change Max. energy default to 87 which is the machine limit on the GPU. Simplify the class interface. - ILS: Fixed code for combining frames and for downsampling the final map. Added safety checck, preventig to run ILS with a num_conf larger than 1 for monoatomic probes. - cleaned up some error messages to make them more obvious - cleaned up some error messages to make them more obvious, and removed a puts that had slipped through - fixed a bug that was occuring if you did a select, shift-select, control-select, control-shift-select - had an proc call that wasn't doing anything. Got rid of it - decreased DEFAULT_EXCL_DIST for CPU multi-atom to agree with all atom check - removed VolMap.[Ch] from the build since they are no longer used - Fixed noop in volmap compare. - changed conditional expression to please GCC 4.3.x - Added parens around conditional evaluations to please GCC 4.3.x - multitext: updated docs to show example calls - removed the old "textview" plugin from the build/distribution since it has been superceded by the new "multitext" plugin. - Updated all of the package version numbers for the new MultiSeq plugins. - removed outdated/unneeded MultiSeq plugins from the top level Makefile: colorbar, plotter, and simpleedit - ILS: Reorganized constant memory so that everything is stored in first 8K page except for arbitrarily long array of conformers that follow. Load parts of conformers array from constant memory into shared memory, based on NCONFPERLOOP (looks like optimal value is 8). Enabled code path in which first warp cooperatively performs the loading, making sure that we no longer access first 8K constant memory block as we load the conformers. Performance is only a mildly better, not approaching the factor of 2 improvement that earlier tests showed might be possible. - import new version of MultiSeq code from ZLS and all attendant plugins. - psfgen, autoimd: Set CVS to ignore files created during latex compilation - Cranked version - VMD 1.8.7a63 (March 31, 2009) - Updated the MSVC6 build settings to enable multithreading now that the Win32 threading primitives have caught up with the POSIX threads implementation. - Fixed a bug in alchemical system handling in the maeff plugin. - Molecule writes should set molfile_timestep::physical_time - ILS: corrected missing conditional compilation logic for CUDA vs. non-CUDA builds. - ILS: Migrated the function prototype for vmd_cuda_evaluate_occupancy_map() to the CUDAKernels.h header with all of the others. - ILS: Test use of constant memory. (Test is disabled.) Shows that performance significantly impacted by not restricting constant memory reads to a single 8K page. - ILS: Added to multiatom inner loop to accumulate energies for 8 conformers to shared memory, reducing number of bin neighborhood loads by a factor of 1/8. Unfortunately this does not improve performance for "gpu_small" test case, and slows performance if this number of conformers is increased or decreased. - ILS: Sync CUDA API calls to gaurantee timing values for kernel execution are correct. - switched plugin builds from asuncion to sundemo until asuncion is reinstalled - ILS: Added CUDA kernel for multi-atom case - ILS: CUDA on single GPU is working for ILS monoatom case. Fixed bug calculating num_unique_types. Fixed several bugs in original CUDA routine. - Restrain secondary structure of selction 'extended_beta' instead of 'sheet' to prevent restraining beta bridges. - namdgui bug fix, wouldn't run simulations due to an apparently missing "variable fixedatoms" line while writing temporary files... this line has been added - misc cleanup in Win32 condition variable implementation - Added condition variable routines for pthreads and Win32 builds, and rewrote the run_barrier primitive to use them. The Win32 condition variable implementation is based off of one of three basic approaches. The best approach is to use the new native condition variable primitves in MS WS2008. The other two implementations are my own variation of Doug Schmidt's approach as described in his white paper. One of these uses mutexes as in Schmidt's paper. The other implementation instead uses the Win32 Interlocked[Inc/Dec]rement() APIs for (hopefully) better performance and scalability. Neither Win32 implementation is fully tested yet, but this is a start. - Changed bin offsets array from int to char to reduce memory use - Added Win32 code to delete the critical section - Enabled multithreaded Windows builds for MSVS2005. - Renamed the atom parser WORD, INT, FLOAT, and ERROR macros/enums to avoid conflicts with Windows system headers - Added mutexes for Win32 thread-enabled builds - Protected CUDA device barrier code so it's only used in a CUDA build and not in non-CUDA builds. - renamed "rad1" and "rad2" to avoid namespace conflict with Windows headers needed for multithreading stuff. - renamed parameter "rad2" to avoid namespace conflict with Windows headers needed for multithreading stuff. - ILS: remove atom translation in the CUDA version for now - ILS: Add CUDAVolMapCreateILS.cu to CUDA enabled builds - Cranked version - VMD 1.8.7a62 (March 18, 2009) - Added all of the orbital classes to the MSVC 6.x builds and enabled the orbital representation in the GUI. - Fixed missing include for QMTimestep.h which was upsetting MSVC 6.x - Added a workaround for lameness in the Windows version of Tcl 8.5.x where it is unable to find it's library directory. - Enabled the orbital representation in the MSVS2005 builds - Added and enabled the molecular orbital code to the MSVS2005 project - Commented out wavefunction printing since MS Windows lacks both the log2f() and log2() math functions. - improved floating point consistency in the CPU orbital code - Changes to Tcl 8.5.x require (on MS Windows at least) that console output be done using the new Tcl_WriteChars() routines, and not with Tcl_Write() as had been done in the past. Calling Tcl_Write() with character strings in the new 8.5.x versions for Windows results in gibberish output otherwise. - Added carbohydrate related source files, and enabled various of the option build flags that hadn't been turned on yet in MSVS2005. - Updated MSVS2005 project with recently added source files - volmap: Corrected missing include of Inform.h - Corrected missing ifdefs for carbohydrate analysis code - Added CUDA device pool code to the Win32 builds - Only destroy the CUDA device thread pool in threaded builds - corrected inconsistent use of floating point types - Silence debugging output from CUDA device thread pool initialization. Only initialize the thread pool when building a threaded version. - Added support for the python version of Axel's "mol new atoms" structure building feature. - Added a linux sharedlib build target - corrected a comment - Applied AK's fix for the csh startup script invocation of the 'rlwrap' tool. - AK's bugfixes/cleanup in topotools and support for reading velocities from lammps data. - Removed all of Jordi's original implementation. - Translate atoms by origin when hashing into bins. - Disabled the "workaround" for the supposedly wrong cell dimensions. Some cleanup. - ILS: Use "max_energy" to set energy threshold. The exclusion distance given by "clashcutoff" is too large! - ILS: Removed original implementation, now superseded by ComputeOccupancyMap. Updated atom_bin_stats() and write_bin_histogram_map(). - ILS: Cleaned up the rest of ComputeOccupancyMap. Correctness has been validated and the code path is enabled. - ILS: Improved profiling of new code for computing a frame. Cleaning the new ComputeOccupancyMap codes. - ILS: Fix grid cell spacing and offset problem. - ILS: Fixed bug in averaging occupancy for multi-atom conformers. Patched all atom algorithm to work for the mono-atom case. Reduced default exclusion distance. - ILS: driver code to invoke slow quadratic complexity algorithm to check correctness - ILS: finished computation routines for ComputeOccupancyMap - Allow a new molecule to be constructed containing N "empty" atoms. This makes it much easier to build molecules from scratch (avoiding reading dummy files or the like) in structure building plugins. This adds a new "mol new atoms N" command that will create a molecule containing N atoms, but with no data set for the atoms initially. - clamp PDB residue name length output to the fixed field width. - ILS: compute_allatoms() quadratic complexity algorithm for checking correctness - Don't automatically recalc secondary structure when the molecule is reanalyzed, instead, merely invalidate it and let the rest of the code act appropriately. - Changed the bond search code so that in the case when we're asked to use the atom radii to compute the distance cutoff, we use an effective minimum radius of 0.833 A, which leaves the bond search code in a comfortable parameter range, otherwise we could get fed atom radii of 0.0 which would cause hanging behavior in the case of a molecule with explicit radii set to zero. - change hydrogen atom type logic to deal with atoms with NULL names. - AK's topotools typo fix. - Changed the molecular orbital kernel to use the VMD CUDA device pool rather than spawning new child threads for each device on every invocation. - Added code to manage pools of host threads that are already attached to GPUs and can be woken from sleep and launched with much lower latency than newly created threads that aren't yet attached to a GPU. - Added support for both blocking and non-blocking variants of the threadpool launch call and a matching wait call. - Save the device index with the property list - made threadpool preprocessor checks deal with Win32 builds that may have threads enabled, but where we currently lack an implementation of the run barrier code. - minimally functional thread pool - added find energy exclusions to ComputeOccupancyMap - make threadpool launch routines in non-threaded builds, so we can use a single code path in the calling code. - make new threadpool routine compile on non-threaded builds - tweak handling of thread parms in the run barrier construct - Applied Axel's updates for topotools - AK's patch: another round of bashism removal in bourne shell launch script. - ILS: added find distance exclusions to ComputeOccupancyMap - partial thread pool implementation - Added draft version of a run barrier for use in implementing a thread pool construct. Misc cleanup elsewhere. - ILS: finished setup for ComputeOccupancyMap - ILS: code (commented out) in compute_frame that will use ComputeOccupancyMap - ILS: algorithm to choose bin size based on map spacings - ILS: bundling occupancy map computation data as a struct - here are the definitions - ILS: Remove some debugging output. Add routine to print the binning histogram to a dx file. Fix unwanted behaviour when selecting atoms for ils. - Differentiated the process-shared version of the symmetric counting barrier from the process-local version, since we may want to use these as a component of a thread pool abstraction, the difference in performance is substantial. - ILS: fix inconsistent preprocessor defines for static routine for histogramming the atom bins. - changed the FreeVR code to use its own env variable for hard-setting the number of draw processes (for debugging) - corrected a bug in the thread barrier destroy call for the version used in VMD - ILS: for debugging: print out before and after min/max values - ILS: changed floor to floorf. - Removed the old code supporting Unix International threads, since we've been building solely with POSIX threads now for several years. If we want it back, we can just pick it up from CVS or by re-importing that from Tachyon again. - moved bin histogram diagnostics into separate function - Fixed bug in binning code. (origin[0] was used for all dimensions) - applied Axel's fix correcting a typo in the Bourne shell version of the startup script. - eliminated inconsistent use of floating point types for constant periodic table entries. - Applied Michelle's ring coloring changes - more polygon winding order corrections for the Twister representation - corrected polygon winding order for main body of Twister ribbons - another update to the cremer-pople ring coloring scheme - Added a lerp-based version of the color gradient logic for ring pucker. - ILS: Handle extra atoms with an array, like an additional extended bin. Have the exclusion and computation routines process extra atoms. Early exit from inner loops on distance-based exclusion check. Clamp occupancy to zero for excluded lattice points. - altered the pucker coloring scale per Michelle's changes - Remove limits on ring sizes for pucker calculations since the Cremer-Pople scheme works for rings of arbitrary size. - Added helper routines to check/eat Fortran unformatted I/O record markers - computation routines skip over excluded lattice points - ILS: find energy-based exclusions - Cranked version - VMD 1.8.7a61 (March 10, 2009) - minor fixes for changeover to pucker based solely on cremer-pople - Applied Michelle's change to use the Cremer-Pople puckering algorithm in place of Hill-Reilly in all cases. The methods are still called hill_reilly_ring_pucker and hill_reilly_ring_color, but that can be fixed later. - Cranked version - VMD 1.8.7a60 (March 10, 2009) - Updated the ring puckering calculations with Michelle's fix, which now uses the Cremer-Pople technique for 5-member rings, but uses Hill-Reilly for 6-member rings. The Hill-Reilly algorithm yields a different pucker value depending on which atom it starts with, and since we don't want to have to deal with that problem we will use the Cremer-Pople algorithm since it's invariant with respect to the starting atom selected. - Eliminated extra line feeds from the wavefront obj output for paranoia's sake - eliminated leading spaces for Wavefront OBJ files since a user reported trouble importing the file into Blender. - ILS: find distance-based exclusions - Updated rendering mode lists in the docs - Removed the old Sun-specific "AlphaBlend" rendering mode that was dependent on the Sun global alpha OpenGL extension. Our GLSL code now does the same thing, but works with any modern GPU, so there's no need to carry around this hardware-specific code any longer. - Removed the now-unused OpenGL extension handling code that was specifically tied to the Sun XVR-1000/XVR-4000 graphics accelerator hardware. - ILS: Allow switching between old code that stores intermediate results as pmf instead of occupancies. Switch old code on by setting env(VMDOLDILSUSEPMF). - ILS: Use bin index offsets to tighten bin neighborhood for calculation. - ILS: No longer need list of conformers passed to atom bin create. - ILS: Remove code to determine probe radius and extend cutoff. - ILS: Generate binoffset list, use provided extended cutoff. - ILS: Pass extended cutoff that takes probe radius into account into atom binning function. - ILS: Eliminated inconsistent use of floating point types - ILS: Added destroy routine to free memory from creating atom bins. Renamed routines to create and destroy atom bins. Changed function parameters to include bin offset list. - ILS: Add code path for computing monoatom occupancy. - ILS: Added + removed comments. Clamp subres greater than or equal to 1 - ILS: Added monoatomic occupancy calculation. Free temp buffer storage for calculating conformer energies. - volmap: Avoid nan for identical maps in volmap compare. - Added function prototype for monoatomic occupancy calculation. - Eliminated inconsistent use of floating point types - Add support for "all" as a valid dataset flag for the "mol dataflag" command - Added "mol dataflag [set | unset] flagname" command to allow users/scripts to override which fields are output when a molecule is written to a new file. This makes it easy for one to cause the autogenerated bonds to be stored, or alternately to prevent fields (e.g. beta, occupancy, etc) from being stored. This is particularly useful when working with very large structures (e.g. 100M atom NSF benchmark case for Blue Waters), since one can significantly reduce file sizes by limiting what fields are output. - topotools: Added topolammps.tcl to CVS - Fixed compute_ils() to correctly combine VDW params. Extended compute_ils() to calculate energies averaged over conformers. - fixed ILS binning to account for radius of conformers - Major cleanup of TclMolInfo - Added a method to unset dataset flags so that users can prevent certain fields from being written to disk when a molecule is saved. Unsetting the flag essentially marks them as unimportant. - Cranked version - VMD 1.8.7a59 (March 5, 2009) - Continued revisions to AMBER parm7 plugin to deal with minor variations in file contents vs. what the main AMBER tools generate. - parm7plugin: Eliminated tabs and misc formatting cleanup in prep for some more bug fix work - More topotools improvements from Axel. Bugfixes and new features (can now read and write some LAMMPS topologies). The LAMMPS support is incomplete and probably will never be perfect due to incompatible atom kinds (granular, dipole, peridynamics) Its getting better all the time. Now it works for Axel's minimal requirements (interchange between lammps and hoomd). - Add probe_vdw to the ILS parameter list. - Pass # probe atoms and # conformers into ILS function. - Fixed rotamer generation. - Finished basic compute_ils routine - Fix bug in ILS probe coordinate setup. - Passing array of conformers (rotamers) into the new ILS function. - Cranked version - VMD 1.8.7a58 (March 5, 2009) - Added new "withinbonds" atom selection keyword - Updated MSVC6 project with newly added multilevel summation source files - volmap ILS: Cleaned up the initialization process. - Eliminated compiler warnings from floating point type conversions - Fixed the "ringsize" and "maxringsize" atom selections so that they will only accept integer values. - Applied Michelle's patch updating the Hill-Reilly ring puckering calculation for 5-membered rings. - Corrected the vdwtype array. - Update angle/dihedral/improper data flags when they have been written to by the user, so that they get saved when a molecule is written out. - Fixed ILS binning function to return amount of bin padding. Fixed parameters for compute function. - Improved interface to the new ILS functions. - Fixed ILS binning, pad lattice dimensions by cutoff - Included vdwparams into compute_ils() stub. - Moved the ILS driving function towards the end, just before the new kernels. - Add stub for ILS calculation function using the binned atoms. - Eliminated cached molecule pointer in CoorData and MolFilePlugin by explicitly passing in the molecule pointer when the next()/skip() methods are called in VMDApp/CoorData/MolFilePlugin. - More FreeVR configuration fixes - Fixed FreeVR linkage flags for Linux builds - topotools: AK's patch to make the topo command print a proper help message in more cases (e.g. no molecule loaded) - Applied Justin's patch adding a new "NOSTATICPLUGINS" compile time configuration option, to disable static linkage of molfile plugins. - cranked version - VMD 1.8.7a57 (March 3, 2009) - AK's update for hoomdplugin to comply to recent changes in hoomd format. newly added attributes are supported now. hoomd expects all atoms to be contained in the box centered about the origin and then use the image section for "unwrapped" coordinates. this is now implmented. for systems without box dimensions, we stick with unwrapped coordinates. - Applied Axel's patch to fix a couple of typos in the topotools plugin. - Accept rings of size 5 or 6 for the "pucker" selection. We may wish to allow even larger rings, but this matches our carbohydrate coloring code which is well tested for rings of these sizes. - Fixed some non-portable constructs in the ring puckering analysis code - Cleanup and compartmentalization of ILS. Added volmap compare command. - Made gridsize() const. - Added a "pucker" atom selection keyword that uses the same sum of the Hill-Reilly pucker parameters used in the rendering code. One caveat with the current code is that it will assign only one pucker value to a given atom, the value corresponding to the final ring processed. If an atom is a member of multiple rings, it will return the final value. We may need to use a completely different approach to make this query more usable given the multiplicity of rings an atom may be a member of. - volmap: Added function to ste the probe parameters, which eliminates a bunch of public variables. Also allow to specify the probe in form of a selection. - dtrplugin: cranked minor version subsequent to applying Justin's patch - dtrplugin: Applied DESRES patch for dtrplugin to support certain Desmond 2.0 trajectories - Revised the CUDA device detection and startup info messages to detect systems that have an out-of-date or otherwise incompatible device driver, and differentiate that from the case where no devices exist, or only an emulation device is detected. - timeline: More improvements for file I/O. GUI improvements for larger data sets. Right-click marquee zoom-in (click zoom out) is working acceptably. - Updated docs for new molinfo commands (bondsrecalc, angle/dihedral/improper/etc) - Added Axel's patch completing basic functionality for topotools. sort/unique added. sort uses tcl internal lsort (O(N log(n)). - cranked version - VMD 1.8.7a56 (February 27, 2009) - Applied Michelle's patch fixing the Hill-Reilly pucker sum calculation - volmap: Fixed ILS memory leak. - added topotools docs to CVS - molefacture: Make the FEP interface better organized and more usable. Add documentation for the FEP gui - Applied Justin's patch to correct maeffplugins's handling of NULL bond orders. - rmsfit.c: Fix bug that was causing weights to get squared in the correlation matrix while the translation vector uses unsquared weights, resulting in a bad fit - continued volmp ILS cleanup - misc cleanup and completion of infrastructure to allow standalone runs - Removed old d_num_shell_per_atom and d_atom_basis arrays which are no longer used by the tiled shared memory CUDA orbital algorithm - Added ifdefs to allow standalone compilation of the CUDA orbital kernel - Reduced external dependencies in CUDA orbital kernel to make it easier to supply standalone benchmark code to NVIDIA - cranked version - VMD 1.8.7a55 (February 25, 2009) - Applied Simon's patches to fix the pucker sum for Hill-Reilly and a fix for ring orientation computations adding recognition of "C_1" to the list of atoms it looks for. - volmap: Deleted long-range electrostatics since it never really worked and we will replace it by multilevel summation anyway. - Added parser implementation for new 'ringsize' and 'maxringsize' selection keywords. May still want to alter the syntax somewhat. - Improved the implementation of the "maxringsize" and "ringsize" selections. Need to see if we can do size ranges in an efficient way by adding some new variant of this selection syntax. - basemolecule: silence ring finding debugging output by default - Added crude first cut implementation of "ringsize X from FOO" selection. - volmap: Added function to retrieve gridsize to VolumetricData. Cleanup and compartmentalization of ILS VI - Updated build script for recent changes to the compile farm - cranked version - VMD 1.8.7a54 (February 24, 2009) - Enable the multilevel summation code, but only used when VMDUSEMSMPOT environment is defined, to enable testing whlie we decide on new Tcl bindings for the MSM code. - Added the multilevel summation code to the VMD build. - Added multilevel summation code to VMD CVS tree. - volmapcreateils: Cleanup and compartmentalization V - vtfplugin: Added another macro to enable zlib features in vtfplugin per Axel's patch - vaspchgcarplugin: Updated thread safety flag, cranked version - Eliminated angle duplicate checking as it had O(N^2) behavior in the previous implementation. We'll want a single-pass sorting based scheme to eliminate duplicates, but that can come later. - autoionizegui: Made the segname used by ::Autoi::sod2pot user defined Removed some memory leaks due to undeleted atom selections Replaced 'mol load' with 'mol new/add' Replaced 'exec cp' with 'file copy' Added comments about code that should be moved to autoionize.tcl - volmap: Cleanup and compartmentalization IV - Updated HOOMD plugin with Axel's updates for angle type info etc. - cranked version - VMD 1.8.7a53 (February 23, 2009) - Updated Axel's topotools plugin per reorganization of the bondtype/angletype functionality in VMD. - cranked plugin ABI version now that things are working with the updated angles APIs etc. - cranked LAMMPS plugin version since Axel's patch added limited write support. - Added Axel's latest patch adding vmdcon support to LAMMPS plugin - Continued cleanup of bondtypes, angletypes, and associated interface routines. - Updated to newly added angle types/strings to molfile plugin APIs - added angle types/strings to molfile plugin APIs - Fixed some orbital sorting code that is still commented out. - Cleanup and compartmentalization I - Added angle type storage akin to the recently added bond type storage, along with matching updates for the molfile plugin APIs. Several more steps upcoming... - gamessplugin: Fixed an improper use of free(). - Second half of multi-wavefunction bugfixes. Changed occupancy type from int to float (bugfix) - A few bugfixes for the new multiple wavefunction support. - Added prototype of MSM-based electrostatic potential code to the volmap coulomb command. Likely the best way to do this will be to add a parameter to allow the user to specify the computation method. We'll also need to add parameters to specify periodic/nonperiodic systems, etc. - Added partial support for multiple wavefunctions per timestep. Allow loading basis sets that don't have data defined for every atom in the system but rather for every atom type. - gamessplugin: Fixed C++isms. - Fixed typo (an additional comma) that caused a warning. - Updated to Axel's newest HOOMD plugin - Added Axel's topotools plugin - Added support for multiple wavefunctions. - eliminate warnings on Solaris - Added basissetplugin for reading basis sets into existing molecules. - Added support for multiple wavefunctions. Added support for basis sets with less atoms than atoms in molecules (e.g. in symmetric molecules.) - Updated psfgen plugin I/O for the new read_bonds() and write_bonds() APIs - Added basissetplugin for reading basis sets into existing molecules. - Updated plugin ABI version number to 15 - Updated plugins for the new read_bonds()/write_bonds() API with bondtype info. - Added bondtype info to the molfile plugin API for ABI version 15 or greater - fix typo in macro test - Added data storage, logic, and new text commands for manipulating bond type information akin to the way we've previously stored/manipulated bond orders. This will allow VMD to be used to build and translate topology files for HOOMD, LAMMPS, and other codes that cannot use PSF files. This adds new "getbondtypes" and "setbondtypes" subcommands for atom selections, and new moinfo "bondsretype" subcommand. We'll likely follow this scheme for adding similar commands to query/manipulate angles/dihedrals/impropers/cterms, etc. - Added dynamically allocated integer blocks to be used akin to how the existing floating point extra data blocks have been stored. - Clear device property arrays to zero at initialization just for paranoia's sake. - Initialize the kernel timeout flag to zero when using CUDA revs earlier than 2.1. - renamed the per-atom "extra" field to "extraflt" to differentiate from a soon-to-be-added collection of optional per-atom integer fields - Added code to detect and report which GPUs have kernel execution watchdog timers active. VMD will try to avoid using these for long running calculations. - check CUDA runtime API version macro rather than driver API version - Converted the CPU Coulomb potential kernel to use the new threadlaunch apis already in use for the CUDA GPU version. - Converted the CPU orbital kernel to use the new threadlaunch apis already in use for the CUDA GPU version. - Converted the orbital kernel to use the new threadlaunch apis already in use for the coulomb potential kernel. Getting comparable performance for the orbital kernel required adding a special 1-thread fast path to the threading routines as there's a significant amount of overhead associated with binding a CUDA device to a newly created thread with the current version of CUDA, enough to reduce performance by up to 30% in the case of the 8800GTX. - Added a performance optimization for the case of only running a single thread. This allows the abstraction to be used for things like the CUDA orbital kernel where the whole calculation takes less than a second and launching a new child thread may not be strictly necessary if there's only a single GPU device. We'll need to implement a GPU thread pool to avoid thread launch overhead in the longer term. - Updated the CUDA potential kernel to deal with fatal errors occuring after GPU worker threads have already been launched. - Added routines to set/query fatal errors on shared iterators so that worker threads can cause cancellation of an entire calculation if an unrecoverable error occurs during the calculation. This can be used to cause CPU fallback in cases where a GPU starts failing, runs out of memory, or something similar at a point too deep within a calculation to be able to recover. In the case of a purely CPU-based code this can be used to handle things like fatal memory allocation errors occuring within worker threads after a computation has already launched. - Added thread safe shared flag functions and used them to implement a global error feature for the threadlaunch routines as a means of handling GPU kernel execution errors since their host threads have already been launched. - Replaced the hand-coded thread launching code in the top level CUDA Coulomb potential routines with the new encapsulted thread launcher, using the shared iterator for dynamic work distribution. - Added a completely encapsulated mechanism for launching a group of threads with a pointer to client data, and a work distribution iterator configuration. Three helper routines can be called within a worker thread to query their ID, and get the next work unit from the iterator. This will be easy to adapt to a more sophisticated work distribution scheme at a later time. - Fix bugs in new volmap command parser. The command parser was completely ignoring the -minmax flags due to untested changes in the structure of the parsing logic. - fix bad string logic. All of this VolMap command parsing code is going to be rewritten, it's absolutely hideous. - Rewrote the CUDA Coulomb potential kernel to use a shared iterator rather than a simple static for loop-based round-robin slice scheduler. The shared iterator still can't deal with things like exceptions, but it will dynamically load balance among a pool of wildly dissimilar GPUs with great effectiveness. - Added a thread-safe shared iterator for use in dynamically load balancing multiple GPUs of wildly different performance levels. For very simple workloads where it's all-or-nothing, one can use this in place of a hard-coded for loop based round-robin static decomposition with just a few lines of source changes. The iterator has an adjustable step size so you can count up or down in any step size. This is not a substitute for a more sophsticated data structure like a double-ended queue, as there's no way for a worker thread that encounters an exception/error of some kind to "put back" an iteration that it has consumed, so such an event would be fatal to codes that use this simple iterator. This iterator makes the most sense in cases where the whole calculation is likely to be over very quickly. - molefacture: Fix a variety of bugs pointed out by Chris Chipot - molefacture: Fix the fragment documentation to properly describe SHORTNAME - molefacture: Fix the fragment names of a couple new base fragments - cranked version - VMD 1.8.7a52 (February 18, 2009) - molefacture: Make editing atom properties more intuitive - molefacture: Fix the thiophene and furan fragments - Updated linux targets using Intel C/C++ to enable CUDA support by default, and added a 64-bit target as well. - Updated the Intel C/C++ compilation support in the configure script. Needs more testing yet, but the new builds can mix Intel C/C++ and CUDA in the same binary with success. - Applied Chuck Rendleman's patch to fix uninitialized variable warnings from GCC 4.2.x - molefacture: Add script for generating custom fragments - molefacture: Add documentation on custom fragments - molefacture: Add documentation of some new features - tweaks to distrib script - Atom selections are now properly applied to bonds, angles, dihedrals, impropers, and cross-terms when writing to file formats that support them. Only bonds, angles, dihedrals, impropers, and cross-terms that have no missing atoms are remapped and emitted to the output file. - warn the user if we aren't going to write angles/dihedrals/impropers/cterms for a selection - Made the CUDA orbital kernel source much more printable for meeting discussions. - Updated the HOOMD plugin with Axel's latest code. - Removed the conditionally compiled approximation variants of the GPU orbital kernels, since they were only needed for performance tests for the paper. If we use an approximation-based kernel in the future, we'll have a different formulation that's oriented towards a cutoff-based kernel for some formulation of linear-time algorithm. - Applied Justin's update to dtrplugin to enable correct behavior of the "clickme.dtr" method of loading a dtr frameset, since they are actually organized as a directory. - eliminated unnecessary 'extern "C"' blocks on the VMDPLUGIN_init/register/fini routines, as they should be fully prototypes in vmdplugin.h already. If the prototype in vmdplugin.h is insufficient for a particular compiler or in some build environment, we'll just revise the vmdplugin.h prototypes to set VMDPLUGIN_API the same way VMDPLUGIN_EXTERN is set currently. - Added test code to test the concept of JIT code generation for CUDA molecular orbital calculations. The current test case is only setup to generate code for the C60 test case (one atom type), but it should be trivial to extend this for an arbitrarily complex system. - Updated CUDA code to work correctly if compiled with CUDA 2.0 but run on a system with a bleeding edge driver, avoiding errors on a multiplicity of calls to cudaSetDevice() in certain cases. - cranked version - VMD 1.8.7a51 (February 10, 2009) - multiplot: integrated Nadja Lederer's undraw subcommand, updated documentation and version number. - Added escapes for wildcards in the 'find' expressions for the 'clean' target of the main plugin tree makefile. - Eliminated a DESRES workaround for the older VMD plugin header that was setting the declspecs incorrectly for statically compiled dtrplugin/maeffplugin builds on Win32. - Changed the parm7 plugin to accept files that have mixed case in the format specifiers for each flags block. - Made parm7 reader more flexible based on feedback from Ross Walker. - Fixed inadequate internal buffer size in parm7 plugin. This was inherited from older code, and is the reason that Ross Walker had been encountering problems when loading files from deeply nested paths. - Updated make_distrib to copy the completion.dat file for rlwrap - Updated make_distrib for the changes to support both vmd.csh and vmd.sh startup scripts in the distribution. - Added tests and actions to install either the vmd.csh or vmd.sh startup script depending on what command shells the host system has available. The current default is still to use the c shell based startup script, and install the Bourne shell script only if the /bin/csh interpreter is missing. Once the Bourne shell scripte reaches more maturity and has been tested thoroughly, we may consider using it by default since it's typically available even on very limited linux distributions. - renamed 'vmd' startup script to 'vmd.csh' to differtiate now that we have versions for both bourne shell and c shell. - added Axel's bourne shell version of the VMD startup script for use on deficient linux distributions. - Added the rlwrap completion.dat file to the installer - Updated the startup script with Axel's latest patch for 'rlwrap' usage. - Added a memset() call to the texture map allocation to force initialization of all border voxels/pixels to zero, yielding cleaner valgrind runs and eliminating speckles when viewing un-clamped texture maps (since the code does not presume the ability to display NPOT textures). - disable generation of Tachyon embedded texture maps until we make further changes to the display commands and texture storage to make it possible to completely eliminate padding bytes from the generated scene files. - Added incomplete but partially functional implementation of 3-D texture export for the Tachyon renderer. This code still needs work as it only works for orthogonal volume data basis vectors and has some scaling issues, but it has been tested and now gives correct renderings in a subset of cases. The code is still disabled by default, but will be enabled when the remaining bugs are fixed. - Matrix4: Added a first implementation of a transform method designed to operate on the VMD texture plane equation coefficients, used in exporting 3-D textures to external renderers like Tachyon. This will likely need rewriting as the display command is revised and improved and we learn more about interchanging the plane equations or volume data basis vectors and scaling coefficients between VMD and various external renderers. - Added missing macro to map snprintf() to _snprintf() on Windows builds of psfgen when plugin-I/O is enabled. - Updated all instances of the cudaSetDevice() calls in VMD to recover if they get a cudaErrorSetOnActiveProcess return value. If this occurs, they attempt to soldier on using whatever GPU the main process is already attached to. Older revs of CUDA didn't yield an error and merely treated it as a no-op of sorts. Starting with CUDA 2.1, this yields and error which caused the safety checks in the various CUDA kernels in VMD to abort entirely, even though this is not a critical error. It's mainly an issue when building without the PTHREADS option set, since all of the CUDA kernels launch from the main thread in that case. - Allow compilation of non-QM plugins for the old plugin ABIs (e.g. VMD 1.8.6) - Eliminate dllimport/dllexport declarations for static plugin builds on Windows. - Switch to CUDA 2.1 for current builds - cranked version - VMD 1.8.7a50 (February 6, 2009) - Free the name string returned by the XGetWMName() query used in the SpaceNavigator/3DxWare X client driver code. - fixed a small memory leak orbital callback struct used in the GUI - cionize: corrected dx output routine by comparing against the independent dxplugin code. - Fix another buglet in command processing when compiled with Tcl 8.5.x. Since the command objects can't be set to zero length without duplication or recreation, due to sharing, we simply delete them and allocate new ones. - cionize: fixed compiler warnings - cionize: fixed compiler warning - cionize: destroy timers when finished - fixed a couple of memory leaks in the QMData class. - gamessplugin: Eliminated calloc(0, xxx) calls. - Fix a tiny memory leak of the list returned by the XInput device query - Fix two GLSL shader path string memory leaks - Fix to tiny memory leaks for temporary GLSL shader path strings - Correct an error in the indexing of the pre-generated display lists OpenGL display lists in the destructor calls. - Changed precision from double to float for QM frequencies, intensities and normalmodes. - Changed molfile plugin orbital occupancies from int to float. - Don't attempt vertex fusion if we get an empty list. The vertex fusion code requires non-empty arrays. - cranked version - VMD 1.8.7a49 (February 5, 2009) - pulled in first full-fledged test of multiseq plugin version 2.1 - changed commenting to document window handle call. No code change. - cranked version - VMD 1.8.7a48 (February 4, 2009) - Added Axel Kohlmeyer's plugin for reading output files from HOOMD This plugin currently depends on the 'expat' XML parser library. - Applied AK's latest update to cpmdlogplugin and gaussianplugin - Added significant extra logic within the water box replica loop to avoid having to perform costly solvent/solute atom overlap tests with "within" atom selections except in cases where it's known that their bounding boxes actually overlap. In the cases where they do not overlap, the atoms only have to be checked against the bounding box for the resulting solvated system. This gives over a factor of two speed boost when solvating large systems like the NSF BAR domain test case for Blue Waters. - Added progress status messages for long running solvate jobs - Added some profiling data to the core of the solvent box replication code to guide further tuning efforts. - Implemented a special-case version of the code that matches unique residue IDs to residue names to avoid quadratic time complexity which severely slowed down generation of large solvent boxes (e.g. 100M atom NSF BAR domain test case for Blue Waters). - reorganized the solvate internals to improve readability and added comments on a few algorithms that need some work to improve performance on large systems. - solvate: updated comments, prettied up the code - Updated minor version number of solvate due to recent changes - psfgen: Added code to load the bonds, angles, dihedrals, impropers, and cross-term maps into the psfgen data structures when the "readmol" command is called for a file that contains all info and not merely for reading coords. - psfgen: Added explicit initialization of various array pointers to NULL. - psfgen: Initialize the atomcoords pointer to NULL to handle cases where we load a structure but no coords. Updated source file comments. - solvate: Modified the solvate plugin to accept .js format input files, using the new psfgen commands. The new code doesn't handle rotated systems yet, and much cleanup remains to be done, but this is a necessary step to building the complete chromatophore or the NSF Blue Waters bar domain tests since they greatly exceed the capacity of existing file formats. This feature requires the use of one of the plugin-enabled psfgen builds. - Added code to the topo_mol_pluginio to enable plugin-based "readmol" version of "readpsf" for fully populated structure files, e.g. replacing the pair of commands readpsf+coordpdb. - psfgen: If an error occurs, we exit out prior to attempting to parse any further data from the psf file. (previous rev was continuing to parse header info used by autopsf before checking for errors) - namdgui: Ensure proper scaling when using AMBER parameters. - AK's updates to gaussianplugin and cpmdlogplugin: cleanup of gaussian and cpmdlog plugins This change removes all code that had remained from the precursors and makes the plugins by default less chatty. It re-instates the wavefunction read functionality for older CPMD versions, and suggests a workaround for coordinates on load. - Updated VASP CHGCAR plugin from Sung Sakong fixes a bug. - Added perfstat configure flag options for AIX5 - updated AIX5 perfstat code - Added physical memory query code based on the AIX perfstat interface found on recent machines - Updated the physmem queries for newer revs of AIX5 - improved the free memory determination routine so it doesn't yield bogus numbers on AIX. Still need to catch these a bit more gracefully. - Updated AIX5 info for builds on NCSA "Blue Print" - Fix dtrplugin for AIX5 - fixed problems with the 'distrib' make target for the signalproc plugin - Updated signalproc makefile with Axel's latest rev - Added missing signalproc makefile to CVS - Updated sgsmooth code per Axel's fixes for MSVC and eliminating iostream - Updated MSVC builds for Tcl 8.5 and added the new ILS source files to the build - Removed irspecgui src in favor of new signalproc plugin - Updated the Inform class with recent vmdcon log level updates - Added Axel's 'signalproc' signal processing plugin - revised VMD init to textview to point to the new multitext plugin instead. - Added new 'multitext' plugin to replace the old 'textview' plugin. Revision of the old textview plugin that is multiple instance aware. You can create instances, get handles back, and have multiple copies of the code going at once without trouncing on each other. - fixed dipwatch makefile version - pbctools: added Olaf's doc .tex file - gofrgui: updated doc links - gaussianplugin: eliminated non-portable __FUNCTION__ preprocessor macro - AK's tweak to clonerep - cionize: eliminated C++isms - irspecgui: changed tk_getOpenFile calls to avoid annoying defaultextension behavior - Fix a crashing bug when picking atoms with the mouse mode "Pick" and python as the active text interpreter. Also unconditionally initializes the vmd module, which is helpful for running VMD as a Python module. - Cranked the minor version of the maeffplugin, given the largish number of changes that were recently made for portability reasons. - Work around a C++ loop variable scoping problem in maeffplugin - maeffplugin: applied Justin's patch to eliminate template issues on MSVC6 - convert remaining Tcl link dependencies to 8.5 - Added the truncate_trajectory plugin (trunctraj) - Switched to framework linkage flag, and use Tcl 8.5 - Various minor revisions to dtrplugin and maeffplugin to allow compilation on MSVC6. Still have to workaround a remaining problem with the template code in maeffplugin on MSVC6. - cranked version - VMD 1.8.7a47 (January 30, 2009) - Added truncate_trajectory plugin to the startup scripts - Updated truntraj Makefile to copy parameter/topology files etc. - Added vmdcon log level comments etc. - AK's patch cleaning up the vmdcon log level features and adding comments to the code. - Prettied up debugging output from cpmdlogplugin - Second try for the arbitrary shape patch to dxplugin. This version also updates the console I/O code to use the vmdcon feature when available. - added truncate_trajectory plugin by Thomas Evangelidis - Reverted the dxplugin code until we solve bugs resulting from the update for arbitrary shape support. Kept the comment updates and other changes not related to the bug. - dtrplugin/maeffplugin: Workarounds for compilation problems on Linux systems using GCC 4.3.x. - cpmdlogplugin: eliminate non-portable preprocessor macro usage - Applied Axel's update to allow the cpmdlogplugin to read trajectories from a specially modified CPMD version that projects wavefunctions onto atomic orbitals during an MD run. The support for the old static output is currently broken, but will be addressed subsequently once things are cleaned up. - Updated cubeplugin Makefile dependency for new unit conversion header - Updated basis set handling code in gaussianplugin - Marked VASP plugins thread-unsafe due to use of strtok() - avsplugin marked thread-unsafe due to use of strtok() - Updated to use unit conversion header - dtrplugin/maeffplugin: synced header comments with DESRES repository version - Added required copyright/license/redistribution info for dtrplugin and maeffplugin by D. E. Shaw Research. - dtrplugin/maeffplugin: Updated the formatting of the license block as per request from Chuck Rendleman at D. E. Shaw Research. - Enable static linkage compilation of dtrplugin and maeffplugin - Added conditional compilation of the default main() routines in dtrplugin and maeffplugin. - Enable compilation of dtrplugin and maeffplugin by D. E. Shaw Research - Added preprocessor tests to allow compilation of dtrplugin on Solaris sparc/x86 - Added VMD CVS version tag macro to top of dtrplugin/maeffplugin source files - Added perforce version tags from DESRES source tree to the top of the dtrplugin and maeffplugin source files for future reference. Whenever we have 100% sync against their tree, we can manually update these strings. - Added new "dtrplugin": Frameset plugin for reading/writing Desmond and Anton trajectories, written by D. E. Shaw Research. Framesets are stored as a directory of files as opposed to a single large file. This file was originally named frameset.cxx, but has been renamed dtrplugin.cxx for use in the VMD plugin tree. - Added new "maeffplugin": Maestro file reader/writer plugin written by D. E. Shaw Research. Reads .mae, .maeff, and .cms files. - Added connected() method for the python IMD module - Made python molecule.write use waitfor=1 by default. - get_vmdapp() now correctly handles null modules, dictionaries, and objects returned via the python interfaces. - Fixed handling of "vmdcon" command with no arguments for binaries not compiled with the VMDTKCON option - cranked version - VMD 1.8.7a46 (January 28, 2009) - Added cpmdplugin dependency for unit_conversion.h - cpmdplugin: updated to use the unit conversion header/macros - cpmdlogplugin: now uses the internal VSTO-6G basis set unless overridden by an environment variable. - cpmdlogplugin: Prevent crashes when basis set file can't be loaded. - Fixed bogus sizeof arithmetic in scftyp and runtype string table lookups, added new SCFTYP_TOTAL and RUNTYP_TOTAL enums for this purpose. - Eliminated compiler warnings about hidden class member variables. - changed IMDSimThread class to use an extern "C" thread proc routine which calls into the IMDSimThread::reader() routine rather than tricks with a static method. - IMDSimThread: make the reader() method public so it is legal to call it from an extern "C" thread wrapper routine. - Changed the Tcl asynchronous handler and the signal handler procs to explicitly use extern "C" linkage to please the compiler - Changed the vmd_alloc(), vmd_dealloc(), vmd_realloc(), and vmd_resize_alloc() shared memory allocation routines to use extern "C" linkage for consistency of function pointer types, to please various compilers. - Fix portability nits in recent patches/updates. - renamed loop variables to eliminate warnings about hiding Fl_Window::i - Renamed parameter to eliminate compiler warnings about hiding member variable 'pos' - Updated various multithreading thread-worker routines to use extern "C" linkage to please the compilers. - Applied AK's patch to allow the dxplugin to deal with other shapes, and to correct a string handling bug. - Updated runtype scftype enumeration string tables and methods - AK's patch to adjust strings returned when using internal basis set - Enable compilation of the new cpmdlog QM plugin - Updated cpmdlogplugin for updated console redirection api - Axel Kohlmeyer's CPMD logfile reader plugin - Added header containing unit conversion macros to be used within molfile plugins. - Updated vmdinit.tcl for vmdcon console redirection feature updates - Revised QM portions of the plugin API, replacing various strings with integer enumerations and updating the comments to be Doxygen-usable. Cranked the ABI version number, enabling the new cons_fputs() entrypoint. - Updated the GAMESS and Gaussian log file reader plugins according to recent plugin QM API changes, replacing strings with enumerations and updating comments to be more Doxygen friendly. - Applied Axel's patch to make tkcon do the right thing with common commands like vim/pico/etc. Also catches calls to "gopython" which really don't work if done from inside of tkcon presently. - Applied Axel's patch to improve qm-related Tcl output format strings - Applied AK's patch updating the VMD QM data structures to use enumerations rather than strings to indicate the SCF type, run type, and so on. Various headers updated for improved Doxygen documentation, and readability. - increase number of fractional digits for orbital energy in GUI - Applied Axel's updates to the VMD console redirection feature, enabling message buffering, priorities, masks, and new text commands to control the console redirection feature. - applied Axel's latest updates to his gaussian plugin - Added cons_fputs() entry point for console I/O managed by the calling application. This should really be provided by the caller in a block of read-only function pointers, but for the time being we'll start out with it here and revise further. - Added an updated version of Axel's console I/O routine for use in plugins. When compiled against a plugin ABI that supports the use of cons_fputs() it will check the cons_fputs() function pointer and if not NULL, will call the application-provided routine for console I/O. If compiled against and older plugin ABI, it will simply direct output to stdout as would have been done via normal printf() calls. - gamessplugin: fixed C++isms, marked as thread-unsafe, and cranked version - Fix string termination arithmetic in netcdfplugin - Fix a C++ism in psfgen - Disable exception handling in the hesstrans plugin since unhandled exceptions can't cross the C-based plugin interface back to VMD - Corrected C++isms in cionize code - corrected comment blocks in STAMP - Replaced printf() by msgInfo. - Improved precision/correctness of measure dipole constants - Increased the precision of the VMD_ANGS_TO_BOHR constant - Applied Axel's patch to prevent throwing an unhandled exception in the MeasureSurface code. - Added ifdefs to auto-select the most appropriate orbital kernel by predefined compiler macros - Fixed QMTimestep to allow 'animate dup' to operate correctly. - cranked version - VMD 1.8.7a45 (January 22, 2009) - Check which QM arrays exist during destructor calls to properly handle situations where log files don't contain all data. - Applied Axel's patch adding multiplicity to the set_occupancies() method for QMTimestep. - Use 1-based indexing for QM orbitals in the GUI - volmap: Add ILS -maskonly mode that computes a mask map containing 0 for gridpoints that don't have contributions from each frame (due to drift of the structure). - renamed QMDATA_RUNTITLESZ to QMDATA_BIGBUFSZ, and increased the size to match that found in the plugin API - Use the safe strncpy macro for the volumetric data strings as well. - Replaced raw strncpy() calls with size-checked macro that will use a max length of the minimum of the source/target array lengths - gaussianplugin: Added return values for newly-non-void get_basis() routine. - Enable compilation of the new gaussian plugin - gaussianplugin: fix return type for get_basis() routine - Added field for occupancies to qm_timestep. - Added makefile dependencies for Gromacs.h and gamessplugin.h as they had not been listed previously - Updated gamessplugin to match the new QM plugin APIs that were revised to better accomodate Gaussian - revised the QM related sections of the plugin API to better accomodate Gaussian, based on early experience with Axel's gaussian plugin. - Minor bugfix. Cleanup. Improved warning output. - misc cleanup and doxygenation of QM data structures - plugins: discard numbers in atom labels in periodic table element idenfication routine - Updated the QMData class with additional shell type constants, and adjusted the storage space for the run title to accomodate Gaussian log files. - use a sentinel value to indicate undefined occupancy field - Added Axel's Glass3 material for molecular orbital renderings - Added Axel's first revs of a Gaussian reader plugin that works with the new molecular orbital rendering code. - Added option -com to "pbc wrap" which allows to set the center of the wrapping cell to the center of mass of the given selection. - Add some safety checks for the QMData/QMTimestep get_xxx() functions. - situsplugin: Decrease tolerance for determining if a cell is orthogonal or uniform. - Improved user ILS interface. - Finally separated ILS from the VolMapCreate baseclass. - Use new version of compute_pbcminmax(). Improve indentation. - Allow to specify frame in compute_pbcminmax(). - Cleanup and further preparation for separating volmap and ILS. - Check for tcsh prior to checking for and/or enabling 'rlwrap' - Swap left/right eye mappings for Anaglyph stereo as suggested by Christopher Bruns, since left-eye-red convention seems to have won the "format war" some time ago and most anaglyph glasses follow this scheme. - volmap: cleanup - autoionize: Change the error to a warning for non-integer total charges; in some cases this is desired by the user - autoionize: Display an error message if the system has a non-integer total charge - Added Axel's patch to enable user-configured trajectory step size for the movie maker plugin - readcharmmtop: Changed the charges on the CYSD patch to yield an integer overall charge (those charges are still made up though; their origin is unclear, as they were in the file in jordi's original commit) - cranked version - VMD 1.8.7a44 (January 16, 2009) - multiseq: revised font selection to use [font actual... ] and not an lindex into what the default font used to be - tkcon: removed the -exact flag from the package require, since this fails on Tcl 8.5.x - cranked version - VMD 1.8.7a43 (January 16, 2009) - volmap: Further simplification of argument parsing. - Further changes toward separating ILS from volmap. - corrected vdna package version in pkgIndex.tcl script - updates to some debug messages to give version numbers, and updated pkgIndex to properly match version numbers - Some changes in preparation of separating ILS from volmap. - Added Axel's placeholder vmdcon stub command for VMD binaries that have been built without it. - Fix floating point type inconsistencies in ILS code that yielded function overloading ambiguities on Solaris. - Force extern "C" linkage for all of the threading routines in VMDThreads - Applied Axel's patch to update the multiplot version and to fix reset behavior. - doc: Removed another stray bracket. - Applied Axel's initial patch to make it possible to get tkcon to interoperate somewhat with the vmdcon interface. - Added Axel's command completion rule set for use with the 'rlwrap' readline wrapper tool. - Applied Axel's updates to the optional "vmdcon" console interface - gamessplugin: Moved static function declarations from *.h to *.c. - Use C linkage for all of the low level threading routines. - Updated gofrgui docs with additional web links, and an updated multiplot package version requirement - Updated the dipwatch plugin with the latest version from Axel. - renamed measure diple "-nocenter" option to "-origincenter" - updated multiplot version and docs for Axel's patch - Applied Axel's patches to enable embedding of multiplot within another window. - Applied Axel's doc update for measure dipole - Applied Axel's patch to allow measure dipole to use geometric center, center of mass, or the origin as the center. - doc: Removed unmatched bracket that prevented correct building. - cgtools: There was a minor revision of the RBCG parameter file, rbcg-2007.par. Thanks to trial runs by some external users, we realized that there were a couple lines missing in the file. it worked for our simulations, but because of those missing lines some simulations with very specific order of amino acids in a protein could not be performed. - Use better names for the ILS related classes. - Put ILS code into separate file. Some cache optimizations. - Workaround (fix maybe?) for a problem with Tcl 8.5's behavior with regard to Tcl_SetObjLength() resulting in an abort() call while parsing console or script input in our line-by-line parsing modes (e.g. the 'play' command, reading .vmdrc, or console input). The old code was efficient and reused the same object over and over, but with Tcl 8.5 this results in an abort() call from within the Tcl library. The new alternate code deletes the old object and makes a new one for every command, which is less efficient, but doesn't trigger problems with Tcl's internals. - solvate: Prettied up the atom selection for the extra overlap check - nanotube: Applied Bob's update for the nanotube builder that adds more parameter checking. - solvate: Avoid an unnecessary duplicate structure load after the overlap check, deleted the associated atom selection, and changed the code so that the extra safety check looking for overlaps is only done for structures containing fewer than 4 million atoms. - solvate: First round of revisions to solvate to take advantage of plugin-based file I/O in psfgen. The code checks the output name for a .js filename extension, and if found it does all intermediate file I/O and final output using the .js format. This is just a stopgap revision until the solvate interface is redesigned to handle these new features more gracefully. - solvate: eliminated deprecated file loading syntax from solvate plugin - volmap: Generation of the path for the checkpoint file was not Windows compatible because it used forward slashes. This is fixed now. - Cleanup of plugin build script prior to revisions for new Tcl/Tk versions - volmap: Corrected manual entry for volmap command - volmap: Made ILS substantially faster for diatomic probes: Check if a single sphere can be placed at the subgrid points before testing the rotamers. If we cannot fit a monoatomic probe then there is no way we can place a diatomic one and we can skip the whole gridpoint. Made the max energy cutoff a user controlled parameter. Lowering the energy cutoff gives a big speedup but the optimal choice depends on the application. - volmap: Added timers for the different steps of ILS computation. - volmap: Improved comments. Replace double quotes with single quotes when writing data name string to file. - dxplugin: Added comment about transposing the order of grid data. - Added conversion factor from Angstroms to Bohr for use by QM related routines - namdgui: Improved AMBER support. - namdgui: Added some support for AMBER files. - nanotube: Added Bob Johnson's nanotube builder plugin - Not doing 32-bit builds for Solaris/sparc anymore, since nobody has such old machines anymore. - cgnetworking: fixed a problem that C�ar had run across with floating poin numbers being out of range. Anton had put in number test before doing an exponential and this was very system dependent. I had flagged it as something that needed fixed, and finally got around to doing it. Now we do the calculation and set the result appropriately if the system can't handle the calculation - cranked version number, enable CUDA register count output during compilation - VMD 1.8.7a43 (December 22, 2008) - updated webpage for the hbonds plugin - correct floating point consistency - pass origin coordinates as parameters rather than as a global memory reference. - eliminated unused parameters from tiled shared kernel - Padded the GPU shellinfo arrays elements out to coalesced block sizes - Added compile time macro to enable/disable use of Dave's approximation - Merged the shell symmetry type and count of primitives per shell into a single array in GPU global memory to reduce the number of global memory read transactions. Added Dave's aexpfnx() approximation to the GPU code, and cleaned things up in a few places. - misc cleanup of CUDA orbital routines - use shift rather than multiply to pick up a few clock cycles - Reorganized the global memory storage of per atom coordinates, basis set index, and shell counters, and forced coalesced memory alignment. - misc cleanup, changed environment variable name for test runs - rename CUDA kernels to match the text in the paper - Correct floating point constant type for ANGS_TO_BOHR - Corrected the summary of individual MO runtime components - Removed the older versions of Dave's exponential/gaussian approximation routine, since the newest version now outruns all of the prior versions. - Updated Dave's SSE loop with the _mm_movemask_ps() intrinsic replacing the slower ORing of individual condition codes. - prettied up Dave's SSE approximation - eliminated conflicting type redefinition for new exp approx code - disable the SSE in the default build for now - Added Dave's new aexpfnx() and aexpfnxsse() routines for approximating exp(x). - Fixed various crash-causing bugs in xbgf, bgf, and mol2 plugins - Fixed missing copy of the contraction coefficient parameters in the log2e fixup code. - pre-factored log2(e) into the exponent terms send to the GPU so that we can call the exp2f() routine rather than __expf(), giving us an improved maximum error bound of 2 ulps over the full range. - Added Dave's expn2sse() implementation - Fixed an xdist coordinate scaling bug in the SSE loop and added an SSE version of the Cephes exp() routine, adapted from the open source exp_ps() variant by Julien Pommier. - Added skeletal SSE implementation of the orbital calculation code. Still needs a 4-way SSE-ized expf() to be runnable. - prettied up formatting on timing info - print gridpoints/sec rate for orbital calculations - Enabled info messages for GPU kernels. - Display the orbital occupancies in the menu - Added Dave's new expn2() approximation, which gives a nice performance boost, particularly for GCC. - Updated and cleaned up the formatting on the shared memory tiling comments - simplified shared memory block addressing arithmetic - fix typo in include - Increased the shared memory buffer sizes and added a bit of short-circuit code to prevent the basis set shared memory block from being loaded except when necessary when beginning a new atom. - Updated the shared memory loader for the basis array to reload only when strictly necessary. This yielded a 20% performance boost. - Added code to use Dave's spline approximation rather than the real expf() routine, albeit with the requirement that the input is always a value less than or equal to zero. This code runs about four times faster than expf() for molecular orbital computation in early testing. - cranked version - VMD 1.8.7a42 (December 4, 2008) - Added new routines to check the maximum shell type and maximum number of primitives per basis function. Added new checks to ensure compatibility with the limits inherent in the CUDA implementation prior to attempting to launch a GPU kernel. - Enable the molecular orbital code for testing for the time being. - Turned off excess performance and debugging output generated by the CUDA orbital code. - Now that the global+shared mem kernel works, there is no longer any need for the old intermediate "cuorbital()" kernel at the present time. - First working shared kernel entirely based on the use of shared memory based tiling for bandwidth amplification by sharing various wavefunction and GTO primitive coefficient data among all threads in a block. - Eliminated the catch-all loop for shell types higher than those handled in the hand-written cases, since we can only test with systems containing shell types up to "G" at present. Implemented a program-managed cache in shared memory for storing the wavefunction coefficients. The current shared memory tiling also assumes a maximum shell type of "G" at present, though higher shell types could easily be supported. - changed kernel override processing order so that constant memory is always initialized before we override, to simplify various speed testing modifications - Reorganized the order of memory references for loop control variables so that loads from arrays that are indexed the same occur right next to each other. CPU and GPU cache utilization can be improved by storing these matched-indexing arrays together as even/odd elements. - Fixed the console printf calls in gamessplugin so they identify themselves correctly in all but the few cases that are intended only for debugging. Changed the format to match all of the other plugins. - Added padding for all CUDA device arrays to simplify memory coalescing for the global-memory-only kernel versions - silence QM debugging output for now - Added a routine to compute the maximum number of wave_f references in a single shell, to help the CUDA kernel determine what strategy to use. - Corrected the CUDA global-mem-only kernel so it wasn't using any of the constant memory data. It got broken at some point via cut/paste. - Migrated the computation strategy logic to the earliest part of the top level CUDA orbital routine and added environment variable checks to allow forced use of the fallback code paths for testing correctness and performance. - Generate an index array that sorts atoms by atomic basis set type. Pass pointer to this array *atom_sort into the Orbital upon construction. Here it can be used to sort the wavefunction table and the offset arrays accordingly. Minor cleanup - Added additional timers into the MO rep code so that we can profile the MO kernels in the context of the full rep, and tune the graphics pieces as necessary. - Updated the CUDA orbital kernel for the new unique-basis-set and sorted atom implementation. Simplified the regular C version slightly. - Use offset instead of pointer into basis_array to get entry for an atom. - Use unique basis sets, i.e one entry per atom type. - Removed any dependency on the individual atom from the basis set so that we can create a unique basis set (i.e. one entry per atoom type). Added functions to compare and copy atomic basis entries. Cleaned up along the way. - cgtools: Fix POPC's topology, which was identical to DPPC - Separated basis set normalization from setting up the hierarchical basis set structures. This is a condition for efficient collapsing into a unique basis set. - Made two variables in QMTimestep private and added access functions. Removed inline statements that shouldn't be there. Added function to compute MO occupancies. - molefacture: Get a fully working fep gui. Add AM1 minimization option. Squash various bugs. - runante: Add compatibility with the new version of molefacture, and ability to use divcon for charges - Factored out multiplication by contracted_gto from each of the shell cases, in particular tweaked the catch-all loop implementation. - Factored out multiplication by contracted_gto from each of the shell cases, and improved efficiency of a few of the hand-coded angular momenta calculations. - Fixed frame selection bug in VolMapCreate. Previously, VolMapCreate would override which_frame of the given selection with TS_NOW. - Fix return codes in init_basis(). - Added some error checking for QM data. - Removed QM access functions that are now unused. - Renamed molfile_qm_orbital_t to molfile_qm_basis_t because that's what it really is. - Simplified QMData setup. - Removed unnecessary vmdplugin_ABIVERSION tests from the QM interface since it has been in use only in version 12. - eliminate redundant memset() calls to clear sub structs.. - Removed a bunch of unneeded variables from the QM interface. We compute stuff on the fly instead. - Only use basis_string to send info about standard basis sets and eliminated data fields for Pople style basis sets. This can be parsed from the string in VMD if needed at all. - cgtools: added the reverse coarse grain parameter and topology files. Revised the docs to mention the two files. - cgtools: added the reverse coarse grain parameter and topology files. Revised the docs to mention the two files. - cgtools: spelled out RBCG a few times to make it more clear - Determine the highest shell that occurs in the basis set in order to allocate **norm_factors correctly. - gamessplugin: Change shell_symmetry from char* to int* Remove unused code Add preliminary code for reading potential suface scans. - molfile plugins: Change shell_symmetry from char* to int* - Added a function to the QMData that creates an orbital and returns a pointer to it. Eliminated compiler warnings. - Fixed problem with the shell symmetry (int vs. string representation). - Enabled the carbohydrate reps in the Windows builds now that we're free of various STL templates that MSVC can't deal with. - Applied JG's patch reversing polygon winding order for the background gradient polygon so that it doesn't get culled when backface culling is enabled. - improved floating point consistency to please msvc - typecast to please msvc - molefacture: added a delete for an atomselect - Removed the experimental "mol orbital" command since we have a built-in orbital representation now. - Applied JG's patch to deal with FP imprecision in bin assignment for the spatial search routine. - Cleaned up const char return types and parameters to QMData::get_shell_type_str(). - pbctools: reverted the documentation change, but added the link to Olaf's page back in - Updated pbctools plugin with version 2.4 from Olaf Lenz - Corrected the coordinate unit conversions in all three CUDA kernels as per the previous bug fixes. The previous patch only fixed one of the three CUDA kernels. - Fixed computation of the gridsize so that orbitals are really centered on the atoms. - Added safety chacks in QMTimestep thereby fixing the bug that would crash trajectories with empty wavefunctions. Fixed small bug in yet unused code in Orbital class. - timeline: file load/read for both: per-residue and free-selection groups are working other debugs/improvements, including crude velocity functions some hoped-for functions will have to wait for after imminent VMD release to be reliable/present, so do not appear here ... - Force use of a single GPU with a single thread for now, as this gives us a 20% speed boost due to the initial 0.1s GPU attach time for the newly generated thread. By using the main VMD thread for computing the Orbital kernel, we eliminate this 0.1s launch overhead, and the peak framerate for animating orbitals will be much faster. To solve this in the longer term, we'll want to keep a thread pool within DrawMolItem, and avoid re-launching/joining the threads except when necessary. - greatly increased default orbital grid resolution for the purposes of SC2008 demos and testing of the CUDA kernel. - Simplified constructor for the orbital class. - Made a bunch of functions that return const pointers const. - Fixed the units and the access of the atomic coordinates. - Reduced amount of debugging output. Cleanup - Changed the sorting of the wave function coefficients from lexicographical order of the corresponding angular momenta to an order determined by the power of the y and z component. This matches the order in the orbital computation loop. - Added function to retrieve the string representation of the angular momentum. - Corrected the order in which the normalization factor table was populated. Changed the type of shell.symmetry variable from char to int and added function to retrieve the string representation. - Improved some comments. Removed unused variable. Misc. cleanup. - Fixed debugging artifact (the angular momentum dependent normalization factors were omitted). This fixes the problem with the orbitals looking too big. Some cleanup. - Changed order of the explicitly given functions for angular momenta to match the order generated by the fallback loop. - Converted distance between grid point and atoms from Angstrom to Bohr since that seems to be the unit implied by the basis set. Fixed bug that prevented getting the correct atom coordinates. - disabled the orbital grid optimization pass for the time being until we make it more robust and prevent it from slowing down the CUDA accelerated code. - Only print the wavefunction data when debugging - Updated the molecular orbital representation GUI such that it lists only 20 orbitals beyond the highest occupied molecular orbital (HOMO). Also updated chooser text to include the orbital energy, and a slot for occupancy, although the occupancy is currently listed as N/A since we don't have that data available yet. - Fixed the neighborlist code. It has been verified on the chromatophore by also computing using a larger neighborhood. - cionize: Using generalized neighborlist code. It is correct, as verified using virus, but suboptimal because the neighborlist is not as tight as it can be for our common parameter choices. - cionize: fixed return from write_grid_dx that always failed - Fixed QMData memory access bug - Changed a number of direct accesses to QMData and QMTimestep variables to use access functions instead. Made these variables private. - cionize: Implemented factored interpolation. This algorithm generally reduces the number of multiplies for cubic interpolation from 64 down to 12. Performance is faster when there aren't too many exclusions, e.g., on the virus with 30% excluded map points. It is slower when there are a significant number of exclusions, e.g., on the 1.5 M atom water test system with 80% excluded map points. The original algorithm can completely skip excluded map points, whereas the new algorithm still has to do most of its work per point. The new implementation has been verified to be correct (it agrees with original implementation up to roundoff error). It is currently disabled (commenting out the preprocessor macro definition MGPOT_FACTOR_INTERP). The plan is to improve performance before enabling. We will use a heuristic based on the exclusion ratio to dynamically choose the fastest interpolation method. - Replaced unsigned ints in QM interface by ints. - Added sorting of the wavefunction coefficients for each shell by the angular momentum. This assures that the traversing order is always the same as assumed by the orbital calculation loops independent of the order in which they were read in from file. Started replaceing direct access to QMData member variables by access functions. - gamessplugin: Changed the wave function parser to read blocks rather than words so that it correctly reads G-shells where the angularmomentum field is fused with the atom number. Eliminated unused variable. - Added various comments about code that needs to be corrected in the MolFilePlugin system. - Timestep has no business including vmdplugin.h under any circumstances - Changed to single-precision floating point constants to please msvc - Corrected a typo in the Spaceball dominant axis assignment logic - Applied Simon's patch to replace the use of STL vector with ResizeArray, allowing the carbohydrate code to work on Windows MSVC, and eliminating the dependency on the STL. - Use double precision for memory allocation arithmetic since large potential maps (e.g. chromatophore) can easily contain many billions of voxels, thus overflowing a 32-bit integer if the math was done using a normal integer type. - Updated the MSMS plugin to deal with newer revs of MSMS that emit comment lines at the top of the .vert and .face files. - Fixed hbonds plugin makefile - Added a new OpenDX output routine adapted from the VMD dxplugin, with support for binary DX file output, used in place of the binary I/O test harness that David had previously been using. - Fixed file open mode for writing so that writing binary DX files will work correctly on Windows. - Doxygenized the comments for the recently added QM data structures - The QMData class has now an array of flags which determine which cartesian component of the angularmomentum each wavefunction coefficient corresponds to. The array has a length of 3*num_wave_f and each triplet represents the exponents of the x, y, and z components. I.e. (1, 0, 2) means xzz for an F shell. Next the QMData class must provide a routine to sort the wavefunction coefficients of each shell according to that scheme. - Added support for angular momentum flags. - Added support for sortable agular momentum flags for the wavefunction array. - molfile_plugin: Got rid of the homo_index variable for orbitals. We will compute that on the fly in VMD. - gamessplugin: all-new file parser that reads the file in a logical order and is very robust wrt different kinds of logfiles containing various amounts of data. also handles truncated files which is very useful if you want to analyze a run that you broke off because something was wrong. Or even better, you can analyze your simulation while it's still running. - Removed the hand-coded G shell code, thereby saving registers and allowing the G80-based cards to run about 25% faster for most cases. - Updated the cufastorbital() kernel so that _all_ of the orbital data is now stored in constant memory. Removed the old unused global memory kernel parameters, and streamlined the routine further. - Updated the fast orbital kernel to store the atom coordinates in constant memory along with the wavefunction and basis set tables. Also changed the code to use the __expf() intrinsic which only takes 32 clock cycles per call. - Increased the default orbital grid resolution slightly, and improved the grid volume optimization parameters for better performance with the GPU-accelerated kernels. - Adjusted the sizes of the CUDA constant memory arrays to better fit the sizes that occur in the test runs I've been doing for the new orbital code. - Added two new CUDA orbital kernels that store as much of the wavefunction data and basis arrays in constant memory as will fit. The code determines which of the three kernels to use depending on how much of the data was loaded into constant memory. - Added environment variable check to make it easy to enable/disable the CUDA based orbital code for demos/testing in the next several weeks. - dowser: Clamp the beta values in case the energies calculated by Dowser don't fit in a valid PDB file, avoiding very rare cases where writepdb will fail attempting to write a beta value that doesn't fit in the PDB file. - Pull array references out of the loop tests to improve performance - Added code to unpack the padded GPU orbital grid - Fixed initialization of one of the GPU arrays for the CUDA orbital code, which now appears to run correctly. - More bug fixes for the CUDA orbital kernel - Updated cuda code, closer to functional now - Signedness correction until we revise the API - Added necessary array size info to the CUDA kernel parameters so that the CUDA code can download all of the orbital arrays onto the GPU, etc. - Added new get_orbital_occ_energy() method for use by the GUI code - gamessplugin: Changed order of some function so that they appear in the file more or less in ther order they are being used during the parsing process. - gamessplugin: Got rid of read_next_timestep(). Read angular momentum identifiers for wavefunction coefficients from file (not yet passed on to VMD). - Made QM plugins independent of the outdated read_next_timestep() function. It was only used by can_read_timesteps() but for QM files we want to use can_read_qm_timestep() querying the existence of read_timestep() in the plugin which is the function that actually provides the timestep data. Tested using ABI versions 10, 11 and 12. - Use new angular momentum ordering scheme in print_wavefunction(). - Added routine to print the wavefunction for debugging. Fixed small bug. - Reorganized the wavefunction loops to process the angular momentums in successive px, py, pz order which is what we're planning to use as the canonical wavefunction ordering within VMD. - gamessplugin: Silenced most of the debugging output. - Made QMData initialization less chatty. - Added command to get the basis set in form of nested lists. - Fixed small bug: symmetry was filled with an int rather than a char. - Added functions to allocate and set data in the QMData class. - ssrestratins: Update usage info. - ssrestraints: Add ideal values for 3-10 helix. - ssrestraints: Fix ideal phi and psi angles for helices. Re-set the internal state after running with the -ideal option. - Leave the cell lengths at zero by default, indicating a non-periodic system - Added a comment about Jan's idea to replace the primitive loop with the actual gaussian that the primitives are attempting to model. - Compacted the cephes fast expf() routine a bit more - Added a variation of the single precision expf() routine from the free cephes math library for use in the orbital grid code. This gives a 2x speed increase over using the standard GNU libc implementations. - The Situs format requires an orthogonal, uniform cell (same grid spacing in all directions). When asked to write an orthogonal, non-uniform cell, instead of returning an error, we now return a warning and re-sample the map. - prettied up the GFLOPS counting code, and profiled the runtime due to calling exp(). - fixed straggling reference to one of the old QMData member variables - cionize: support big data sets in latcut04, choose which device to run long-range part - changed QM related variable names - Added the size of the wave_f array to the Orbital class. Also renamed a bunch of variables. - updated the flop counter to account for the hand-optimized cases - remove CPU count mesg during multithreaded orbital run on the CPU - Added a new routine to compute the exact number of FLOPS executed for a single molecular orbital gridpoint for the loop-based routine - closer to a runnable cuda orbital kernel.. - fleshed out more of the cuda orbital kernel setup code - removed the less optimized loops for high orbital calcs - re-enabled CPU/GPU processor count matching - further updates to the cuda kernels for molecular orbital calculation - Updated class member variable names to match recent updates in the other QM data structures. - Added CUDA molecular orbital code to the build - Added multithreading to the molecular orbital grid computation code and implemented the skeletal portions of a CUDA implementation. - Added routines to determine the HOMO and LUMO. - Renamed variables in the QM interface. - gamessplugin: Fixed broken build by adding function declarations before registering them with the plugin API. Renamed a bunch of variables to be consistent with the names in VMD's QMData class. - gamessplugin: Reorderd functions in a more logical way. Improved a feww comments. - Further reorganization of the molecular orbital grid computation code - continued reorganization of the grid computation routines - Split molecular orbital code into two routines, evaluate_at_grid_xyz() will now be used for general purpose calculations and for grid size optimization, and a new single-purpose highly optimized evaluate_grid() routine will be used to compute the whole grid, optionally with multiple CPU cores, GPUs, etc. - rewrote the molecular orbital grid loop for fastest memory traversal order, hoisted some work out of the innermost loop, and did a bit of cleanup in preparation for further code specialization and work with CUDA. - Eliminated unnecssary passing around of internal variables. - Corrected the initialization and loading of the qm timestep metadata using the new plugin API. - Updated the plugin API to separate the QM timestep metadata entry point and data structures from the non-QM timestep metadata routines/structs. Updated the logic in MolFilePlugin to deal with the change. - gamessplugin: Added QM timestep metadata entry point - separated the QM trajectory metadata from non-QM trajectory metadata API, adding a new plugin entry point for the QM case. - Changed the DX plugin to return a non-zero thickness for planar maps where the xdelta/ydelta/zdelta values are non-zero. - Changed volume texturing allocators to work with planar volumes - Updated cell length/axis routines to deal with planar volumes - added new position coloring modes to volume texturing switch statement. - situsplugin: Don't attempt to write a Situs file if the cell is not orthogonal. Ideally, we should resample the map when the cell is either not orthogonal or not uniform, printing a warning. - Further optimized the catch-all molecular orbital evaluation loop to minimize branching and eliminate unnecessary use of pow(). - Added molecular orbital loop that avoids the use of pow() - Fixed incorrect loop control conditions in the catch-all molecular orbital evaluation code. - Misc cleanup and commenting on the orbital rendering code - gamessplugin: Got rid of now unused variables and functions. - gamessplugin: Removed the old/buggy molecular orbital code - Prettied up the chooser control for the Orbital representation. We probably want to replace the chooser with a text input field that allows the user to select a list or range of orbitals, much like we do for the draw multiple frames feature - Add more orbital entries in the chooser and added more safety checking to the representation rendering code. - Set better defaults for the new Orbital representation - Silence all unnecessary console debugging messages in the orbital related code since it gets invoked on every change to the new Orbital rep. - Added the new orbital representation code to the configure script - Added brand new "Orbital" representation, that computes the requested molecular orbital, extracts an isosurface, and renders it, all entirely on-the-fly. The GUI needs a lot of work, but the basics are there, and it currently reuses all but a tiny part of the Isosurface representation GUI controls, and all of the rendering code. - Added ifdefs to prevent problems when compiling with the new plugin ABI, but with orbitals disabled in the VMD data structures. - gamessplugin: Only populate the orbital data structures when using the latest ABI, to prevent crashing due to older revs not allocating memory properly etc. - Added comment about opportunity to improve performance by using exp2f() rather than exp(), which would require some premultiplication of exponent coefficients etc. Rewrote the exceptional orbital handler to avoid the use of pow() instead calculating the distance factor powers as the intraorbital loops execute. - misc cleanup of orbital variable scoping etc. - no need for shell_type to be a character type anymore. - Made orbital symmetry dependent on the shell rather than on the primitive. This greatly simplifies the inner loop for orbital calculation. Currently something is still wrong with the normalization factors and the orbitals are not exactly centered on the atoms but fixing these bugs will most likely not affect the structure of the inner loops. - jsplugin: Updated endianism detection message - cionize: data-parallel multi-GPU support for MSM short-range part - Added comment documenting VolMapCreateInterp function. - docs: Added documentation for volmap interp. - rmsdtt: Set menubutton width to avoid truncation in OS X. - Initialize new basis set data structures after reading all data from file. - Changed variable name in QMData class from basis to basis_array to emphasize that this is the flat array we are using for the GPU computation of the orbital. I also added a simple hierarchical data structure to store the basis set data (counters and pointers into basis_array). This will make it a lot easier to retrieve info about certain basis functions and to compute things like GTOs or even primitives. - Fixed a problem with the orbital grid dimesion optimizer. - Changed the char based storage of the shell type to an integer representation and changed the variable name from orbital_symmetry to shell_symmetry. This is better for lookup tables. - Eliminated redundant variables. Added support for g-orbitals. - Renamed variable atomic_shells to num_shells_per_atom. - Renamed variables for clarity. Changed optimal boundary finding algorithm in the Orbital class: Based on the idea that the wave function trails off in a distance of a few Angstroms from the molecule. We start from the current grid size (which could be for instance the molecular bounding box plus a padding region) and test the values on each of the six boundary planes. If there is no value larger than the given threshold in a plane then we shrink the system along the plane normal. In the distance the wave function tends to be smoother so we start the testing on a coarser grid. When we find the first value above the threshold we jump back one step and continue with half of the previous stepsize. When stepsize has reached minstepsize then we consider the corresponding boundary plane optimal. Note that starting out with a too coarse grid one might miss some features of the wave function. - cgtools: Initialize some vars that were slipping through a boundary condition. Fixed some strange formatting bug that had messed up the linebreaks in the tcl - Fixed bug in the orbital calculation code that was introduced during the previous cleanup. - Added support for CUDA 2.0 (64-bit only) on Solaris x86 - removed plugin ABI ifdefs in QMData. The VMD data structures should not depend on the plugin ABI. - gamessplugin: Removed some of the unused animated normalmode code. - gamessplugin: Fixed bug that ocurred sometimes when loading geometry optimization runs. Fixed memory hole that ocurred when loading Hessian runs. Reorganized gamessplugin.h: Moves main datastruct to the beginning of the file. - psfgen: Added a special makefile that enables plugin-based I/O and includes the appropriate linkage against the static plugin library. This is only intended as a short-term solution for testing, as it doesn't work for Win32 or MacOS X builds. - added a timer to calculate_mo() - misc cleanup and optimization of the QM orbital code - cionize: Added comment about adding timing for the MSM long+short range summation step - massive cleanup of the orbital calculation class replaced tabs with spaces replaced if/else chain with switch statement - mol2plugin: Fix handling of optional bond order data in mol2plugin - gamessplugin: A few more changes for next-gen gamess reader. Enhanced code readability. - gamessplugin: New read_timestep() and read_timestep_metadata() functions for next-gen file reader. Removed C++-isms - psfgen: fix typo in psfgen error string - gamessplugin: Improvement of file parser so that it reads trajectory data. - gamessplugin: Compacted orbital related code and moved it to the end of the file. It will eventually be deleted because this functionality will be performed by VMD itself. - gamessplugin: Merging accumulated improvements of the file reader into the cvs tree: This first step is characterized mainly by renaming variables and reordering some code. - Added the new QM related source files to the default builds, though they are not enabled without the VMDWITHORBITALS define and the plugin ABI is set to version 12 or greater. - psfgen: warn on pdb and fail on psf output if segid is more than 4 characters long - Updated comments regarding bond order information. - Updated molfile_plugin.h comments regarding bond order information - Fix handling of optional bond order data in bgfplugin and xbgfplugin - psfgen: allow segid up to 7 chars - multiplot: Jan's changes to make multiplot more Mac friendly - cgtools: commented out a print statement that didn't need to be there - Added experimental Tcl commands to query QM data - Added more qm data initialization code - cionize: have to precede __constant__ with static - cionize: added cuda version macros - Applied Jan's patches adding QM orbital data based on new plugin APIs. - Added missing method for testing availability of timestep metadata - Applied Jan's patches for orbital calculations to the main VMDApp code. - Applied Jan's changes to the QM data structures used by the next-gen plugin APIs. - Fixed C++isms in the gamess plugin - Applied AK's patch replacing the ::autopsf::lreverse proc with the use of the global namespace 'lreverse' provided by Tcl 8.5, or emulated by the conditionally defined proc in vmdinit.tcl - Applied AK's patch conditionally defining an 'lreverse' proc for use in Tcl versions older than 8.5 so that 'lreverse' can safely be used in other plugins even when VMD is compiled against an older Tcl. - Applied AK's patch correcting comment text for measure gofr - Corrected improper use of C++ style comments - gromacsplugin: Applied AK's patch to add support for comment lines in g96 files - cionize: Added AK's patch for strict ANSI gettimeofday() params. - gamessplugin: Renamed variables for clarity Corrected bad comments Fixed a bug in the f-shell code - VMD 1.8.7a38 (October 15, 2008) - psfgen: Added new code to support coordinates-only and residues-only read modes. - psfgen: Expanded argument parsing for the new 'readmol' command to allow it to eventually duplicate all of the capabilities provided by the existing "readpsf" "coordpdb" and similar commands. The parser needs to support modes for reading just coordinates, just residues, full structure data, and various other optional flags beyond that. - psfgen: Added code to remove whitespace and match the atom name format expected by psfgen. Enabled some of the alternate atom name matching code. Still need to enable chain and element matching. - psfgen: Added atom alias checking and other missing pieces to the plugin-based structure loading code - psfgen: added coordinate reading to readmol implementation - psfgen: added segid-specific coordinate loading to the readmol implementation - psfgen: cranked psfgen subminor version number to indicate that this build has the new plugin-based structure reader code. - psfgen: added new 'readmol' command that calls plugin API to load structure or coordinate files - psfgen: Added plugin structure loading framework. Still need to copy the data loaded by the selected plugin into the internal psfgen data structures. - psfgen: fix typo - psfgen: Added skeletal routines for loading structure and/or coordinate data through the plugin interface. - docs: correct categorization of Intersurf - Fixed some bugs in the orbital rendering code Added some comments about other possible existing bugs Renamed a bunch of variables for clarity. - cranked version - VMD 1.8.7a37 (October 9, 2008) - psfgen: Added check to make sure that a given plugin supports write_timestep() before attempting to write atom coordinate data. - psfgen: Fix psfgen plugin-based coordinate output code - psfgen: Changed psfgen "writeplugin" to "writemol" which is less obtuse sounding - Reorganized the top level plugin makefile to gaurantee that the static library version of the molfile plugins is always completely built and linked prior to compiling and linking any of the other plugins. This became a particularly tricky issue with the addition of plugin-based I/O within psfgen, but was already required by catdcd as well. The new makefile structure explicitly builds all versions of the molfile plugins prior to beginning any of the others. - jsplugin: Added support for cross-term maps - psfgen: corrected struct member references for cmaps - psfgen: Added support for writing cross-term maps - psfgen: Added code to emit angles/dihedrals/impropers using the plugin API. Still need to implement cross-terms and logging/remarks. - psfgen: Added skeletal code for emitting bonds/angles/dihedrals/impropers/cterms via the plugin interface, reusing much of the logic from the native PSF output code. - psfgen: Fixed a few typos, and got first successful test run invoking a real plugin - vtfplugin: initialize parsed line pointer in all cases - psfplugin: fix linkage scope for start_psf_block() - psfgen: Added the primary plugin-based structure file writing infrastructure to psfgen. The implementation presently includes all of the data normally emmitted to a PDB file via "writepdb". The next step will be to add in the necessary code blocks to emit bonds, angles, dihedrals, impropers, and cross-terms. Finally, in order to support autopsf some effort will have to be put into dealing with handling of remark lines, which may be somewhat tricky due to formatting and line length limitations inherent in the various file formats supported by the plugin API. - psfgen: Added plugin enumeration and registration routines to psfgen - psfgen: Added plugin header paths to compilation directives - psfgen: Use compile-time macros to enable/disable the new psfgen "writeplugin" command. - psfgen: cranked version number due to updated PSF input/output code, and the new experimental 'writeplugin' command - corrected the ordering of the cross-term output vs. the acceptor/donor and NNB stuff that is presently unused and unsupported by psfplugin. - Added new routines for doing file I/O via the VMD plugins rather than hard-coded routines. This implementation is purely skeletal at this moment, and much needs to be added before it will be usable. - revised psfplugin docs for current version of the plugin - psfgen: compact output code - psfgen: Eliminated entirely redundant functions for parsing the leading header portion of each block of the PSF file, replacing the separate routines for bonds, angles, dihedrals, impropers, and cross-terms with a single psf_start_block() routine that accepts the block string you're looking for. - moved Solaris plugin builds to asuncion - Added notes about plugin build ordering - fix cut/paste error in array reference for cterms - Fixed cross-term indexing on output, and misc cleanup - Fix bug in add_cterms() - psfplugin: cranked minor plugin version now that cross-term code is enabled - Added write support for cross-terms to psfplugin - Added code to MolFilePlugin to enable loading and saving cross-term info - Added cross-term read support to psfplugin - psfplugin: Fix cross-term rows/column init - Added support for storage of cross-terms - Minor tweaks to please MSVC - Updated pbctools with Olaf's new version 2.3. - Minor cleanup on the nucleic backbone identification code. - cranked version - VMD 1.8.7a36 (October 3, 2008) - Migrated angle/dihedral/improper informational output to BaseMolecule where it more rightly belongs. - jsplugin: corrected a bug in endian swapping and memory allocation - jsplugin: Added more diagnostic output for testing purposes - jsplugin: Added angle/dihedral/improper reading/writing code and wired up the new routines via the callback registration interface. - jsplugin: Added partial implementation of angle/dihedral/improper handling to the jsplugin code. - psfplugin: removed angle/dihedral/improper force related code bits since PSF files can't actually read/store such information at present. - psfplugin: cranked major version of PSF plugin now that it handles reading and writing angles/dihedrals/impropers. Still need to add support for cross-terms. - molefacture: Modify opls type definitions - molefacture: Add extra features for use with antechamber - molefacture: Fix usage of runante with molefacture - Added storage for angles/dihedrals/impropers in BaseMolecule, and matching code to load/save them in MolFilePlugin. - Added angle/dihedral/improper reading and writing code to psfplugin - If the user alters bond info with the mouse, we flag it has having been modified by the user, and thus it becomes "valid" and will be saved if the molecule is written to a format that can store bond info. - cranked version - VMD 1.8.7a35 (September 24, 2008) - Renamed all of the internal functions of the xbgfplugin to avoid confusion with the original non-extended bgfplugin source code/symbols/etc. - revised JS plugin format forward to the new form - Fixed missing static linkage scope declator - Fix cut/paste typo in occupancy/bfactor flag code in the molfile writing code. Pulled flag manipulation code outside of atom data field scatter/gather loops. - Enabled angle reading calls and matching flag setting logic - Added angle reader driver code into the MolFilePlugin interface in VMD. Still need to add matching data structures in BaseMolecule. - Added major version checking in the JS plugin reader. - psfplugin: More updates to psf angle reader code - psfplugin: Added basic code for the read_angles() and write_angles() APIs. - psfgen: correct bogus comments resulting from cut/paste - molfile plugins: fix types on read_angles() API - cranked version - VMD 1.8.7a33 (September 23, 2008) - Added a set of "data validity" flags to BaseMolecule which are used when structures are loaded, modified, and saved, to track what data fields VMD should be concerned with saving when writing to file formats that support "everything". It's wasteful for VMD to always pass on all data fields for writing by default since some of them are all zeros, or contain "guessed" data or properties that VMD is perfectly capable of guessing again at a later time. If the user modifies fields that were guessed, then VMD assumes that the whole field is now "valid" and that will cause it to be saved just as if it had been loaded from another file originally. This allows one to write structure building/verification plugins and have them capable of saving their results. - Fixed use of jsplugin version numbering macros - don't bother building the 32-bit Solaris x86 versions - Changed the carbohydrate ring finding code to use the NameList::typecode() routine to find atom name codes rather than the incorrect method that had been used previously. - applied Simon's patch to correct the lookups of atom names for the carbohydrate ring finding routines - molefacture: Fix a litany of annoyances with the protein builder - autopsf: Make better guesses about disulfide bonds in some cases - cgtools: doc changes wording tweaks suggested by anton - cggui: wording tweaks suggested by anton - cggui: revised some prompts per Anton's request - cggui: added a module to scale bond/angle constants in a CG parameter file that has been created. Taken from anton and optimized. - cggui: added documentation for a module to scale bond/angle constants in a CG parameter file that has been created. Changed all needed pictures to make it accurate. - correct a string concatenation bug - updated configure script to use CUDA 2.0 toolchain - jsplugin: Use major version number to control structure read/write feature - jsplugin: Fixed up more of the structure reading/writing code. The new code now seems to correctly read what it writes. - jsplugin: finished the structure writing block - jsplugin: Fixed a few bugs in the new structure writing routines, and added debugging output for the time being. - jsplugin: crank version when structure info is enabled - jsplugin: Added bond and bond order storage - jsplugin: Finished the structure writing block - Added SymmetryTool files. - Final version of measure symmetry. All printfs removed. Bugfixes. - jsplugin: Added code to compress the atomic data structure on-the-fly using hash tables to make unique name string lists, which are then indexed into by the data that's actually stored for each atom field. This closely mirrors what VMD does internally already. Ideally we'd go a few steps further storing a unique atom ID key for a unique combination of multiple fields, further reducing file size. We'll eventually want to provide the means to special-case things like bulk solvent atoms which will reduce storage even further. - jsplugin: fix typo, began adding structure data to the handle - modernized jsplugin initialization code. - jsplugin: normalized the console I/O - AK's patch for the case where the bonds variable is unset. - MeasureSymmetry: Improved generation of GAMESS standard orientation. Some cleanup - MeasureSymmetry: Made unique coordinate finding more robust. It is especially better now in finding connected sets of unique atoms. Smaller bugfixes. - Added new code to allow the paperchain representation to use the normal VMD color scale rather than the hard-coded gradient table. - Silence spurious output from the ring finding code. - refactored pucker coloring routines for carbohydrate structures - Updated comments about STL vector issue in the ring finding code - misc cleanup, and eliminated some non-portable C++ idioms - Cleanup of carbohydrate rendering code - MeasureSymmetry: Added determination of unique atoms. Added support for reorienting molecule according to standard GAMESS coordinate frame. Fixed a problem that occurs when two eigenvalues of the moments of inertia tensor are incitendally identical (or very similar). This leads to wrong assumptions about the symmetry of the molecule. However one can prevent this by checking the existence of rotary symmetry axes corresponding to the principles axes of inertia. If two eigenvalues are the really the same because of underlying molecular symmetry then there must be a Cn axis orthogonal to the two corresponding principles axes. A few smaller bugfixes - improved comments in volmap code - cranked version - VMD 1.8.7a33 (August 13, 2008) - Added the new spaceball source files to the MSVC builds - Get around the problem of MSVC 6.x not having any of the erfc() variants. - Enabled new polyhedra and carbohydrate representations in the MSVC builds - Added comment about the use of std::vector in the ring finding code - Migrated inclusion of the vector template into BaseMolecule.C rather than the headers, which was causing problems on MSVC. - Corrected missing include - eliminated MSVC warning - Added typecast to please msvc - Unpacked the coloring method menu by one level. Still much shorter than a flat menu, but easier to use than the fully hierarchical menu. More sorting is in order, but this is a first step in that direction. - Enable the new "polyhedra" representation in the default build. - Added a new "Polyhedra" representation which can be used to generate tetrahedral representations commonly used for inorganic structures. The code is a derivative of a short patch provided by Francois-Xavier Coudert. The algorithm finds all atom pairs within a user-supplied cutoff distance, and for the subset originating with selected atoms, draws polyhedra using all of the neighboring atoms as vertices. This initial (simple) implementation makes no attempt to avoid replication of vertex coordinates, and emits triangles independently of each other which can result in a significant amount of memory use when the cutoff distance is large. It would be a tremendous improvement to rewrite the rendering code to build non-redundant vertex arrays, and emit groups of rendering commands for each of the colors to be drawn. Elimination of redundant vertex data would decrease the size of display list data by factors of hundreds for cases with large cutoff radii and very densely packed silicon structures. - cranked version of the vmdtkcon package - Added AK's patch to prevent TkCon from getting caught in an endless loop if the current directory is deleted/unmounted out from under it. - cranked version - VMD 1.8.7a32 (August 7, 2008) - Changed the behavior of VMDApp::molecule_savetrajectory() so that when writing files with "waitfor all" specified rather than adding the I/O transaction to the molecule's I/O queue for the final completion step, the completion, file closure, and memory freeing occur synchronously as well. This prevents problems from occuring with analysis scripts that do significant amounts of file I/O within loops that never return control to the main VMD loop, where the I/O queue processing is normally handled. With the old code, it was possible for a massive number of outstanding I/O queue entries to accumulate, waiting only for their final close operations command and callback triggering, etc. The new implementation creates a new Molecule::close_coor_file() routine that's used both within the I/O queue handling logic as well as for the synchronous case in VMDApp::molecule_savetrajectory(). This eliminates the need for script developers to insert explicit calls to "display update" in tight loops that do lots of molecule file or trajectory output. - Added comments to the filespec setup in the selection writeXXX processing code. - Only emit timing stats if the I/O took longer than 3 seconds. - Added check for the atom name "OXT" in the structure analyzer. - cranked version - VMD 1.8.7a31 (August 6, 2008) - Added AK's irspec patch for OpenMP - Added AK's patches for irspecgui src/docs - gofrgui: updated docs - Fixed various C++isms in C source files - crdplugin: cranked minor version number - Applied Axel's patch to multithread the gofr/rdf all pairs histogram calculation. - inorganicbuilder: Made the wireframe for the device box thicker so its easier to see - Fixed animation behavior so that single-step commands don't wrap around when the animation mode is set to "once". This affects the behavior of the GUI, the text UI, and Spaceball devices. - namdenergy: Add amber defaults when a parm file is loaded - namdenergy: Fix docs about using amber with namdenergy - Applied Axel's patch to correct integer truncation that could create bad results for measure gofr. - Applied Simon's patch to alter the maximum pucker sum in relation to 0.6154 radians which has significance for perfect tetrahedral bond geometry (see Hill paper). - Fixed another C++ism in gamessplugin. - gamessplugin: Fixed illegal use of C++ syntax in a C source file - Fixed bug in crdplugin where trajectories without box information were lacking line feeds between timesteps. - Added movie maker return codes for use by text interface callers Added placeholder safety check to prevent "snapshot" renderer from being used when VMD is running in pure text mode with no windowing system. - vmdmovie: improved the performance of the cleanframes proc across the board - vmdmovie: Cranked version number, added parameter to text mode interface to select movie type, and did some misc cleanup here and there. - namdgui: Better defaults for some variables. - molefacture: Fix masses written by topology file generator - Added a comment for the "hydrophobic" selection. Andrew chose the residues from Branden and Tooze (pp6-7) - Fixed unprotected modification to the plugin ABI - Added parameter scfiter to struct molfile_qm_timestep_t. In a QM simulation for each trajectory point (i.e. optimization step) a number of SCF iterations is performed until the energy converges for this geometry. If we want to make use of the stored scfenergies for a given timestep we also have to store the number of iteration for the timestep. - inorganicbuilder: Fixed some problem in the addMaterial interface - cgtools: added a script that i've tweaked from anton that extracts values for bond and angle parameters of a CG molecule from an all-atom simulation of the same molecule. - cgtools: cleaned up some code that wasn't deleting selections, and code that was unnecessarily creation atomselect macros. - resptool: Correct the ESP intermediate file format. Fix the autodetection of RESP binary. - paratool: Fix bug that would pick the wrong element from a the parameter list after selecting it with the mouse. - cranked version - VMD 1.8.7a30 (June 20, 2008) - Changed Spaceball behavior when the display projection is in orthographic mode, so that rather than translating in Z, we scale the molecule. This seems to match user preference for most people. We'll make this a user-selectable mode toggle eventually. - updated comments in the Spaceball code. - MeasureSymmetry: fix compiler warning. - Further improvements for animate mode with regard to varying rendering load. Still needs a timer to normalize the input by frame rendering time. - Capped the maximum allowable Spaceball trajectory animation stride to 20 by default. This needs to be a user-defined parameter. - Added some notes to the current Spaceball code documenting things that need adjustment. - Applied Olaf's pbctools bug fixes to correct for 'segid' rather than 'segment'. - Added a help button and text and image for docs - inorganicbuilder: Added docs and image files for docs - mergestructs: Added a help button and text and image for docs - Added "TDCONNEXION" configure option used to enable support for the 3DConnexion MacOS X device API. - Enabled the 3DConnexion SpaceNavigator API in the MacOS X builds by default. - Notes on MacOS X single-threaded event handling issues for the SpaceNavigator - Added support for 3DConnexion SpaceNavigator on MacOS X - gamessplugin: Making all functions static since they are not supposed to be used elsewhere. - gamessplugin: Fixed bug that would prevent proper reading of # of processors and memory for some versions of GAMESS. Added a debugging output function that makes it easy to compare what's in the file and what was read. The basis set info is now read by default, before it was only read for single point runs. - cionize: Open the GPU device prior to starting timers, as there can be an artificial delay during the first open call depending on whether or not X-windows is running. - cionize: Added a 64-bit build with Intel C/C++, CUDA, etc. - cionize: added BENCH statements for profiling - cionize: eliminated the Intel C/C++ libimf.so dependency - cionize: added small bin kernel - cionize: added setup and cleanup routines for cuda short-range and long-range parts - cionize: factored short-range part into a driver routine that calls either some CUDA kernel or an optimized sequential version or a fallback version - cionize: factored setup/cleanup for geometric hashing from short-range routine - cionize: fixed bug that fortunately never manifested itself - cionize: added data for sequential short-range part, geometric hashing - cionize: added setup and cleanup routines for cuda short-range and long-range parts factored large bin kernel into setup/cleanup and pre/post calls - cionize: added mgpot_cuda_binlarge.cu removed -DMGPOT_GEOMHASH because it is now defined internally - cionize: Eliminated include of cutil.h so we can compile with MCUDA - cionize: rearranged data structures and routines to prepare for short range cuda kernels - cionize: modified clean and added veryclean targets - MeasureSymmetry: Added comparison of bond orientation for each atom. This can distinguish for example if the orientation of a double bond in the transformed image atom is different than in the original position. It cures the falsepositive detection of additional symmetry elements for instance in some antiaromatic systems. Also fixed a bug introduced when I got rid of the gridsearch that would in somme cases lead to wrong idealized coordinates. - cionize: Updated Makefile.specialbuilds to use our CUDA 1.1 install by default. - cionize: Added new 'linux-icc-cuda-thr' build target - cionize: Some loop unrolling combined with shared memory copying to reduce global memory copying gives significant performance improvements on both the GT200 and Tesla D870 even though the register count swells from 40 to 58. - cionize: use latcut04 to experiment with loop unrolling - cionize: Attempted many optimizations in latcut03. major optimizations: SHMEMCOPY - Copy half the amount of subcubes from global memory on each inner loop iteration and shift the shared memory storage. This does not decrease time and it uses more registers. SHIFT - Replace int multiplication by int powers of 2 by bit shifts. This uses 3 fewer registers but slows down computation on both Tesla and GT200 cards. CPARM - Read srad and padding from constant memory rather than passing them as parameters. This does not change the register use and does not appear to change the time. minor optimizations: WTRAD - Pre-compute (8*srad) appearing in inner loop. Doesn't make a difference to runtime or register use. THRIDX - Change tx, ty, and tz to macro expansions of threadIdx.x, etc., rather than variables. Doesn't make a difference. built in: - Calculate "tid = (tz*4 + ty)*4 + tx" as flat thread ID outside of the main loops, rather than inside as "isrc", since tx, ty, and tz don't change. Also reuse at end of kernel for indexing global memory potential to write. Doesn't seem to make a difference. - cionize: generate cubin output for cuda files - cionize: changed text output title - cionize: minor change to text output - MeasureSymmetry: Made execution 2-10 times faster (depending on molecule) by eliminating gridsearch. Improved robustness by comparing atom types instead of just chemical elements. Added more comments - cionize: CUDA thread blocks are no longer assigned to padding subcubes - cionize: latcut02 is cleaned up copy of latcut01 - cionize: select mgpot cuda kernels from command line - Reverted an unintentional change to the "VMDSPACEBALLPORT" environment variable tests that occured during a global search/replace in the source code. With this fixed, one can use multiple Spaceballs concurrently, with some coming from X-windows, and others coming from serial ports. - fix builtin "spaceball" help text - cionize: Lattice cutoff computation on GPU works. Requires padding around all edges with one layer of 0-charge subcubes. For now, each thread block corresponds to a subcube; test for early termination if subcube is padding. - cionize: fixed mgpot lattice cutoff host to device memory copy, start index for weights, qgrid offset - cionize: mgpot will use cuda automatically - cionize: fixed bug with weight indexing in long-range lattice cutoff - xbgfplugin: Increased maximum number of bonds to 16. - timeline: Fixed paste-typo bug - MeasureSymmetry: Add RMSD between original and idealized coordinates to the TCL return string. More comments. - MeasureSymmetry: Enhance robustness of search Handle rotary reflections properly in all cases. Cleanup - cranked version - VMD 1.8.7a29 (June 9, 2008) - The SpaceballTracker and SpaceballButtons UIVR devices are now always compiled in. - Added new code to allow the console Spaceball device to be used as a VMD tracker device, for use with the UIVR tools akin to how the haptic devices are used. The console Spaceball code now has a new "tracker" mode, which just stores incoming spaceball events for reading by the SpaceballTracker and SpaceballButtons classes. The .vmdsensors config lines for the local Spaceball device are: device SpaceballTracker sballtracker://local/vmdlocal device SpaceballButtons sballbuttons://local/vmdlocal - Added new SpaceballButtons class for use with the console spaceball device. - cionize: lattice cutoff cuda kernel setup/cleanup and condense/expand routines - cionize: added data for lattice cutoff cuda kernel - More Spaceball cleanup - The Spaceball UIVR object is now compiled-in in all cases since we have code that's "always on" in the windowing system drivers now. As a result the space ball source files are now built into all builds and so a number of places in the code needed cleanup and portability improvements which are now taken care of. - Redesigned the Spaceball animation velocity scaling to make use of the animation playback speed control in addition to the step size. The control now seems very usable all the way from very slow playback rates all the way up to very fast ones. - Added a new 'spaceball animate' command and matching input control mode to allow the spaceball to be used as a jog/shuttle controller for playing VMD trajectories - cionize: preparation for introducing additional cuda kernels - eliminate compiler warning - Better defaults for Spaceball rotation/translation speeds and null region values. - Added new "spaceball nullregion" command - Eliminated compiler warnings - Added spaceball Tcl command source file - fix missing CVS revision ID tag - cionize: clean also removes gpuionize - renamed the old "SPACEBALL" configure option and corresponding "VMDSPACEBALL" conditional compilation macros to "LIBSBALL" and "VMDLIBSBALL" respectively, in order to differentiate the old direct I/O LibSBall spaceball functionality from the new implementations based on windowing system events, XInput, and other input libraries that also support Spaceball devices. - Added new 'spaceball sensitivity' command - Implemented new "spaceball" command, to accept spaceball mode changes, sensitivity adjustments, input modes, and so on. - Added new Spaceball "user" mode that reports events via TextEvent callbacks. - cionize: eliminted warnings - cionize: correct race conditions in multi-threaded MGPOT part - cionize: Removed all calls to abort(). Now errors in MGPOT propagate back and return an error value to the top level calling routine. - cranked version - VMD 1.8.7a28 (June 7, 2008) - Abbreviated the X-windows ClientMessage device detection message. - MeasureSymmetry: initialize stack variable - Made the XInput startup code less chatty, it only announces when devices are found, rather than when they aren't found. - Added a build setting just for CUDA test compiles of 'cionize' - MeasureSymmetry: Pretty up things. - Updated Spaceball event handling loop so that we accumulate inputs for all of the queued spaceball events since the last redraw, rather than throwing away all but the most recent input. This change makes the input behavior much smoother with wildly varying scene complexity and results in an approximate constant angular rate of rotation or linear rate of translation for a given user-applied Spaceball torque/deflection. We could do even better by adding timers to the code, and scaling rates by the time since the last input event, but this seems to be sufficient at the present moment. - MeasureSymmetry: More function moving into logical order. Pretty up more (Changed order of functions in the file). This is a fairly big change but it could not be cut into smaller ones: Previously the symmetry guess was based on a elements that were found in a single pass. The biggest problem with this is to decide which symmetry elements to keep and which to discard, based on their score. While the point group guess, relying only on certain key features, was generally good, the number of found elements was often wrong. In case additional elements were found this could totally screw up the idealized coordinates. Now we are passing through the element guess in a loop in which we only keep the elements with a really good score and idealize them. The subsequent generation of ideal coordinates will definitely yield "more symmetric" coordinate set than the original one. In the next pass we use these improved coordinates for guessing the elements and we will probably find a few more this time. This is repeated until the number of found symmetry elements converges. The tcl command now also returns a summary string of the found elements along with a string with elements that are missing wrt the ideal number for the guessed point group and with a string containing additional elements that would not be expected. This can provide good hints that something might be wrong with the guess. - updated URL for check sidechains plugin home page - autoionize: forgot to change back name used during testing (autoionize1 vs. autoionize) - cranked version - VMD 1.8.7a27 (June 5, 2008) - Silence debugging info in spaceball event handler - Change XInput spaceball device axis mapping to assume a direct mapping. Added code to skip over the "evdev brain" XInput devices found on Xorg servers since they aren't usable devices for our purposes. Prettied up the device enumeration messages and formatting. - The Spaceball.C source file is now always compiled in, since we now support various native windowing system-based 6DOF input device mechanisms like XInput, ClientMessage, and other schemes that don't require any device-specific serial I/O code to be compiled in. At present all of these devices get mapped to the VMD Spaceball input mechanism, but we may want to generalize this somewhat to allow support for multiple devices simultaneously, etc. - Completed an initial implementation of XInput support for Spaceball 6DOF devices. With minor tweaks, the same logic will work for dial boxes, tablets, and other input devices that are supported by the XInput extension. - Added XINPUT option to all of the normal x86 linux builds. - Built up the XInput device handling implementation significantly - Added new XINPUT compile time configuration option to enable/disable support for the X-Windows XInput Extensions mechanism for advanced input devices such as Spaceballs, Dial/Button boxes, Tablets, etc. - Added MacOS X 32-bit Intel text only build target - Made XInput device attach more robust - Improved XInput device list code - Added skeletal XInput based 6DOF device I/O code with similar structure to the X-Windows event-based Spaceball interface. - Added comments to X-Windows Spaceball driver event decoder - Let the X-Windows Spaceball driver do window focus processing for us, except when the user sets the environment variable VMDSPACEBALLXDRVGLOBALFOCUS which will allow VMD to keep Spaceball focus all the time regardless of the X11 keyboard/mouse focus. - Eliminated redundant code - Apply mouse/keyboard focus state to the processing of Spaceball/Magellan/SpaceNavigator events from the windowing system. - Additional tweak to SpaceballTracker messages - Updated Spaceball device open messages to better indicate which driver interface/method is being used to talk to the device. - Added code to merge direct spaceball and windowed spaceball events if we happen to have two devices attached using different interfaces. - Move CUDA device enumeration earlier in the startup process immediately after the CPU and memory enumeration code. - pretty up CUDA device enumeration - Updated the main Spaceball event handling code to deal with events from both the host windowing system as well as from the direct I/O libsball driver. Ideally we'd beef this up even more to deal with multiple simultaneous devices in a nice way, but even the windowing system drivers are currently pretty weak in that regard. - Added a bit more safety checking for initialization of the spaceball X-Windows driver. Added an environment variable override to disable it if necessary. - Added X-Windows support for 3DConnexion SpaceNavigator, as well as all of the older Magellan, and Spaceball devices using the Magellan style X-Windows driver using Xlib client messages. - timeline: All-residue user-defined function via entering function name (function must exist somewhere, can be in any name space) Definable analysis frame range Default user definable function set, exisits in global namespace. (May change this to very-unlikely name, but should keep as instructs user). - MeasureSymmetry: cleanup - Added workaround for a bug in the MacOS X linker when compiling for X11+OpenGL rather than using the native Aqua windowing system. - Fixed 64-bit MacOS X ifdefs. Disabled the use of OpenGL extensions for 64-bit MacOS X builds until more details are ironed out. - Updated build config for 64-bit MacOS X target using X11/OpenGL - Added support for 64-bit builds on MacOS X. At present, MacOS X doesn't include a version of Carbon for their 64-bit ABI, so 64-bit VMD builds have to be done either for text-mode only, or they must be classical X11 based builds rather than using the native Aqua windowing system interfaces. When building for X11, matching X11 versions of FLTK and Tcl/Tk must be linked against. Until Apple releases a 64-bit ABI version of Carbon, or the Tcl/Tk maintainers port Tk to use 64-bit-capable Cocoa instead of Carbon, there's no other option. - Added MacOS X 64-bit build configurations and configure script logic. Currently, 64-bit MacOS X builds are limited to X11 or text mode only due to the lack of a 64-bit ABI version of Apple's Carbon framework, or a version of Tcl/Tk that uses Cocoa rather than Carbon. - Added a 64-bit build target for MacOS X, so we can do text-only and X11-based builds, despite the lack of a 64-bit Carbon framework that we'd otherwise use for a native aqua version of Tcl/Tk. For now, all 64-bit MacOS X builds have to use X11 or be text-only. - Updated the bigdcd script to Axel Kohlmeyer's new version which incorporates the key improvements people have made over the last couple years with a cleaned up interface and docs. - Applied AK's fix for the HOLE homepage URL - Applied AK's fix for the histogram build for 'measure gofr' - Fixed pkgIndex.tcl for autoionize plugin - Raised optimization level for 64-bit Solaris x86 builds - MeasureSymmetry: Made idealization more robust and efficient. - molefacture: Change tickmark size in dihedral slider - molefacture: Change resolution of dihedral slider - cranked version - VMD 1.8.7a26 (June 1, 2008) - Fixed a bug in the CUDA device enumeration code that skips emulation devices - Added the 'jsplugin' fast trajectory format to the default builds - Added new VMDApp methods used by the Molecule class to inform the main event loop when background I/O is going on so that the CPU throttling code remains inactive until the background I/O is complete for all molecules. With this change one can use VMD interactively and achieve background trajectory I/O rates that approach the performance achieved with the blocking "waitfor all" loading parameter. Using "waitfor all" is still the best way to achieve peak I/O rates, but this eliminates one potential performance bottleneck when people are doing interactive analysis jobs and the like. - Fixed the main event loop logic so that the anti-CPU-hog code allows background I/O to progress at full speed when display update is off. An improved approach would consider background I/O independently of the display update mode. - Fixed bug pointed out by Peter where VMD would crash if measure bond was called with an empty list instead of an atom index. - cgtools: Fix protein cgc file to include glycine hydrogens in with the backbone bead - Added performance instrumentation code for coordinate I/O routines - Updates for Solaris x86 builds - qmtool: Fixed small bug in the Gaussian file reader. Added comments. - added casablanca to build script - Added missing documentation for a couple of arguments to the volmap ligand command. - MeasureSymmetry: Added inversion center to the returned TCL list. Fixed a bug that in some case would return an axis with length zero. - MeasureSymmetry: Improved generation of idealized coordinates. Fixed a bug in the idealization of symmetry elements. - MeasureSymmetry: Switched on and improved idealizing of symmetry elements. - runante: Modify opls typing to not overwrite current charges - runante: Allow user to keep charges if desired - Applied Simon's patch which reverses the colour scale and also fixes a bug in the calculation of the puckering parameters. - MeasureSymmetry: Return rotary reflection to the user. - MeasureSymmetry: Returns idealized coordinates now. The coordinated are generated by taking the average if each coordinate and its transformed image for each symmetry element (currently only planes, will add axes soon). - Added VMD's "residue" index (internally determined unique residue ID) to the atom pick output. - cranked version - VMD 1.8.7a25 (May 16, 2008) - AK's patch to workaround GCC 4.x issues with pointer aliasing - Added safety check to make sure no stale atomselection is used. - Fixed bug that would crash VMD when volmap ligand is accidentally run with a molecule that contains no frames. - VolmapCreate: Fixed memory leak Added comments Renamed a variable for clarity - MeasureSymmetry updates: Reorganized some parts of the code. Improved prediction. Better output. Store weight and overlap score with the found planes and axes. - Fixed a bug eliminating these annoying warnings: "TclVolMap.C", line XXX: Warning: String literal converted to char* in assignment. - Added MeasureSymmetry source files to the win32 builds - Elminated non-portable fmin() call. - Changed call to non-portable random() to vmd_random(). - Added RCS header and comments. Limited the number of atoms on which finding planes and axes is based to a given value (default=100). Now you can also feed large structures into the algorithm without locking the machine. Doxygenized some comments - Added MeasureSymmetry.[Ch] to the build. - Added "measure symmetry" command which guesses the pointgroup of a selection and returns the according symmetry elements (mirror planes rotary axes, rotary reflection axes). The algorithm is fairly forgiving about molecules where atoms are perturbed from the ideal position and tries its best to guess the correct point group anyway. The 'forgivingness' can be controlled with the -sigma parameter which is the average allowed deviation from the ideal position. Works nice on my 30 non-patholocical test cases. what pathological means in this context will be explained in the docs when I add them. If you feed the algorithm with the ribosome it's going to compute for 400,000 years I guess, but for the biggest symmetrical things in my test set (C60/C70 fullerenes) it takes 3s. Smaller molecules often take only a few milliseconds. But these times can probably be still reduced. - Added command 'measure transoverlap' which computes a score value for the structural overlap of a selection and it's image that was transformed according to the given transformation matrix. This is the underlying command for checking symmetry elements. - timeline: Update combining several checkins from (personally maintained) svn, much cleaner, but not such a major resturcture that greatly helped by multi-checkins to CVS. features: "free selections" (arbitart selections, Hh-bonds provided as example), user-defined per-residue functions (e.g. measure contacts) coding: generic per-res property and delta-per-res (e.g. done slightly sanely) ; switchable debug messages (via function edit) Problems: Features slow and hard to use for users, but need to get some feedback on borken things, so must checkin. Hope to get things presentable / usable in next days . Needed: Merge performance, interface for builtin/user-defined functions so one way to register functions. GUI / text UI to show which loaded / available at startup. Move user-defined per-residue to name-of-function via type in function, provide test option on tiny selection (provide adhjustable guess) Debug silencing via proc in place. hardcoded per-res user procedure working. The chosen measure command is slow. Reminds should be more sparing on doing recalcs. H-bonds working, getting 2D graph. improvement, generalization, and move away from selection-text-based indexing still needed. But 2D graph looks good. - Added safety checks to measure inertia and measure pbcneighbors to prevent running with stale atomselections, i.e ones that refer to a deleted molecule. - Added safety checcks into vmd_gridsearch3, so that it is not run with empty atom selections. - autoionize: fixed slow inner loop that selects waters to replace - Simon Cross and James Gain's patch to use cold to hot color ramp for pucker coloring of carbohydrate structures. - molefacture: Fix bug reported by Jan with residue name lengths - correct function signature ambiguity for fmod() - Ring coloring based on Michelle's new coloring scheme. The current implementation calculates the Hill-Reilly puckering parameters and then maps x, the absolute value of their sum (divided by a suitable guess at the range of sums), onto RGB(x) = x, 0.5, 1-x. This gives nice blue and orange colours for the 18 ring glucose chain. - ring utils: General cleanup, conversion of arithmetic to single precision for use of VMD vector routines. - Pretty up CUDA device enumeration a bit more - Added tests and reporting of overlapped I/O during CUDA device enumeration - Updated the CUDA device enumeration routines for CUDA 2.0, improved the display of device attributes, etc. - autopsf: Add some extra aliasing for nucleotides suggested by leo - Improved measure command usage output for better readability - Added new "measure inertia" command that returns the principle axes of inertia. - Updated documentation for display commands - Eliminated more redundant Pi constants and degree-to-radian macros - Make gofr code use VMD_PI constant - Applied AK's bugfix when calculating the r values for measure gofr - Applied AK's patch to enable compilation with Python 2.4.x - Added docs for hbonds plugin - more updates to feature/bug fix lists - Improved error message reporting for Tk menu registration code - cranked version - VMD 1.8.7a24 (April 29, 2008) - Eliminated compiler warnings about volmap parameters hiding class member variables, and a problematic literal string conversion. - Eliminated compiler warnings about gradient parameter hiding class member - Eliminate compiler warning on Solaris - Eliminated unnecessary display command objects - Corrected projection of surface normals into world coordinates for isosurfaces of density maps with non-axis aligned basis vectors, and/or opposite handedness coordinate systems. - Added a routine to return basis direction unit vectors - Added another variant of vec_scale() that accepts double precision values - cgtools: Added an option to assign Lennard-Jones parameters for a shape based coarse-grained structure based on the all-atom one from Anton. Also added docs for said option, as well as docs for the mapping code that I'd added a while back (but hadn't gotten the docs in for yet) - eliminate MSVC compiler warnings - fix floating point consistency for the PBC measure commands - Eliminate MSVC warnings - Fixed inconsistent floating point precision in the dipole and bond/angle/dihed/imprp energy measure commands. - Corrected floating point precision consistency - Made Gelato and RenderMan output classes use self-consistent floating point precision. - correct floating point constant declaration to avoid compiler warning - replace hard-coded constants in the ring finding code with locally defined macros - reduce memory usage for ring finding routines by combining the intree_flag and intree_parents arrays by using sentinel values for atom indices. - cranked version - VMD 1.8.7a23 (April 23, 2008) - Re-enable VRPN for the MacOS X builds after compiling the client library for MacOS X 10.4.x on Intel. - Eliminated a massive proliferation of various forms of PI constants, e.g. M_PI, M_1_PI, QUAT_PI, MYPI, and many others, in favor of VMD_PI, VMD_TWOPI, and VMD_1_PI, now defined in utilities.h Also eliminated a similar proliferation of macros conversion between degrees and radians, and so on. - Eliminate warning on MacOS X - Fix duplicate definition of M_PI on some platforms. - eliminated bogus include of iostream from ring linkage header - Create new variable declaration scopes in switch statement cases for correct compilation on Win32 with MSVC6. - prevent a problem with ambiguous overloading with recent C++ compilers - volmap: * Pretty up the code by replacing multiple object casts by a cast pointer. * Replaced the MYPRINTF by msgInfo stream. * Made file_writing independent of the VolMap class. There is a virtual write_map() method in the base class now that calls the write_dx_dile() (which will eventually be replaced by using molefile plugin). For the FastEnergy derived class there is another write_map definition that adds temperature and weight info to the dataset name string. * When the dataset name string is set now all double quotes are replaced by single quotes because double quotes delimit the name string itself. * Added more comments. - Added a function rotate_axis() to the Matrix4 class that rotates around a given vector. It also corresponds to the TCL command transabout which is currently defined in vectors.tcl. I created a TCL interface to the C++ version such that the TCL script version can go away. - Added safety checks to cap the maximum number of rings that we'll search for in the ring finding code. It was previously possible to crash the the program during ring finding when analyzing large silicon nanodevice structures with high connectivity. - Enable carbohydrate representations by default now that the ring finding code is run on-the-fly rather than at start. - Carbohydrate structure representation update from Simon Cross. The Twister code for rendering the ends of the ribbons when the "start from ring centroid" option is selected has basically been completely re-written. The new implementation actually starts the ribbon at a point X which is lies on the plane formed by the ring centroid and the ring normal. X is chosen to be as close to the point midway between the centroid and the last atom on the path as possible. This is cheating a bit, but it does bring the final sections of all ribbons arriving at a single ring into a common plane so that they line-up nicely. Any possible gaps where the ribbons meet are filled in by rendering a small circular disk (actually it's a regular dodecagon). - Carbohydrate default ring search size patch from Simon Cross. Simple patch to reduce the default maximum ring size from 20 to 10. This just reduces the possibility of really pathalogical molecules files causing problems by having huge numbers of rings. Perhaps less necessary now because the BaseMolecule clean-ups also mean that the ring finding code isn't called by default (Twister or PaperChain already recalculate the results if the maximum ring size or path length differ from the current settings). - Carbohydrate structure analysis patch from Simon Cross. * Removal of call to find_small_rings_and_linkages so that ring finding code is only run on demand. * Fix missing bracket in comment. * Fix small but bad bug in back edge finding code (parent in the spanning tree was being stored very late, resulting in some back edges being missed). * find_small_rings_from_partial(...) modified to excluded barred rings (i.e. ones which are crossed by a single edge). This speeds up ring finding quite a bit since a lot of cases can be quickly discarded. It also reduces the number of rings found in highly linked molecules. * Change ring orientating code to look for "C1" or "C1'" after the oxygen atom, rather than trying to guess the first carbon by looking for links to carbons outside the ring. I'm still not 100% sure that this is a good part of the patch. The old system failed to orientate rings quite often (for example, if the ring was bonded to another ring via something other than a carbon) but the new system relies on the carbons being labelled nicely in the files. A fair number of the test files I have don't. However, at least the new method is predictable and gives the user some more control over the orientation (i.e. they can orientate the rings themselves by changing the labels on the carbons next to the oxygen). * Ring linkage finding code modified to ignore atoms which belong to multiple rings. The ring finding code implicitly assumed that atoms belonged to at most one ring and produced some spurious links between rings which shared atoms as a result. - Added notes file to docs subdirectory, with informal todo list, people assignments for plugins, etc. - Fixed missing timer destroy call - compact Tcl interface code - Removed the update_internal (a misnomer anyway) from VolMap. All that's left now should in some way correspond to stuff that is in VolumetricData. - Deleted further functions from the VolMap class. It is almost ready now to get replaced by VolumetricData. - Added a timer for ILS for subsequent speed tuning - Set menubutton width to avoid truncation in OS X, for the plugins: colorscalebar, dipwatch, molefacture, multimolanim, irspecgui, gofrgui, dowser, contactmap, clonerep. - volmap: Eliminated dead code. - cranked version - VMD 1.8.7a22 (April 18, 2008) - Fix timestep memory leak introduced with the recent reorganization of the Animation class, timestep storage, etc. Timesteps were not getting deleted properly when their parent molecules were being deleted. - biocore: made the error message more descriptive when a login fails - Fixed documentation for exectool, which was still using the old namespace - Moved the material change command immediately prior to the ribbon rendering commands. Coalescing rendering operations into compact groupings makes addition of mutex locks for multithreading much easier. - Improved readability of the ribbon/cartoon spline computation loops, reduced int/float conversions, and explicitly replaced a few divides in favor of multiplies. - Added performance measurement instrumentation for the ribbon extrusion code. - More work on control point precalc code. - Added code to precalculate control point lists used by ribbon/cartoon reps, to help improve interactive trajectory display performance. This will ultimately eliminate all of the on-the-fly traversal of the atoms in residues presently being done to identify control points. It will also allow VMD to use more robust control point selection criteria that would otherwise be too costly to perform at redraw time. - update comments on fragment finding code - Start preparing for precalculated control point storage - Fixed some out of date comments about the color index ranges, and updated examples to query color ranges rather than hard coding them. - ccp4plugin docs: Added a missing space. - xsfplugin docs: Added a missing period. - cranked version - VMD 1.8.7a21 (April 3, 2008) - Updated pbctools makefile for the current version number - Updated to pbctools version 2.2, based on the latest source and documentation updates from Olaf Lenz. - Adjust benchmark grid size and thread block size to get more accurate performance measurements for next-gen GPUs with differing numbers of SMs. - plugin docs: Added new "plugin development best practices" document. - UIText fixed missing "of" in python support message - Fix missing linefeeds in the built-in help for the "measure energy" and "measure surface" commands. - plugin docs: Added basic info about the intricacies of shared library handling on Unix and Windows, with practical examples of why we do things the way we do in the VMD plugin system. - Added CVS ID tags to all of the plugin programmer's docs. - Eliminated holdover code from old residue bond logic. - Added ssrestraints and rnaview to main plugins Makefile. - Added rnaview plugin, which calls the external program RNAView and parses its output, creating a bpseq file with base pair information (or an extended bpseq file with a classification of the base pairs). This is simply a helper plugin to be used by ssrestraints at the moment. - Added ssrestraints plugin, used to create an extraBonds file for NAMD to restrain secondary structure of proteins or nucleic acids in a simulation. - Fix uninitialized curframe member variable found by valgrind. - cranked version - VMD 1.8.7a20 (March 26, 2008) - First full-up test with CUDA on MacOS X, with full graphics etc on 10.5.2. - Starting with MacOS X 10.4 we can use dlopen(), dlsym(), dlclose() natively, so there's no need to emulate these anymore. We'll leave the code in place, but for all current builds we're targeting 10.4 or later anyway. - MacOS X 10.5.x changes the behavior of putenv() such that it no longer makes copies of strings added to the environment. Changed the environment initialization code to use setenv() instead, since it copies parameters and provides a cleaner interface to work with. - Update render code to support Tcl/Tk 8.5.x versions of the Tk_PhotoSetSize() and Tk_PhotoPutBlock() APIs. - Olaf's fixes to vtfplugin correcting linkage scope of the internal plugin functions. - molefacture: Added comment about dealing with SPC water - molefacture: Fix the tert-butyl fragment, which had some incorrect bonds - molefacture: Start using measure commands instead of labels where possible to speed things up - molefacture: Add option to type for opls - cranked version - VMD 1.8.7a19 (March 20, 2008) - Applied Justin's patch to extend the list of default masses guessed by VMD. Added recognition of SPC water. The SPC water code may conflict with a residue in the PDB compound library, but we'll see how it goes. - Applied Justin's patch to write velocities when they exist, and when writing with a plugin that supports them. - Applied Justin's patch to add iterators to the Python atom selection interface. - New version of vtfplugin from Olaf Lenz. - namdenergy: Add ability to turn off switching - Fixed mismatched enum for error return check. - Added CUDA to Mac builds - doc: Eliminated mention of the "make_links" script which has been superceded by the "links" target in the top level VMD makefile. - Added CVS tags to doxygen pages, to be displayed at the end of each page. - Fixed documentation typo - cranked version - VMD 1.8.7a18 (February 29, 2008) - Changed Unix startup script so it no longer starts an xterm. The linux xterm issues w/ LD_LIBRARY_PATH create new cross-platform headaches, it may be preferable just to take xterm out of the equation as some people prefer running from their existing terminal console anyway. We'll try this and see who screams. - Attempt workaround xterm's behavior of stripping LD_LIBRARY_PATH in recent Linux distros due to setgid permissions. This problem also affects other apps: - Further tweaks to rpath to make the shared library search path relative to the location of the installed VMD executable. - Applied Axel Kohlmeyer's patch for the LAMMPS plugin to allow it to correctly interpret both absolute and fractional atom coordinates. - added compiled-in linker shared library search path for libcudart.so when configured with CUDA support. - cgtools: fixed a bug that anton found where the output status wasn't being put into the box correctly (and was throwing an error instead) - cranked version - VMD 1.8.7a17 (February 21, 2008) - Check to see if LD_LIBRARY_PATH is set before attempting to add to it. - Trigger text interpreter frame callbacks when change_ts() calls occur. - Added Justin's patch to scan user-provided plugin directories before loading built-in plugins. - Corrected a problem with label redraws resulting from the previous patch reorganizing timesteps etc. - runante: Add antechamber plugin - mol2plugin: Fix bond order reading for 'ar' bonds - cranked version number - molefacture: Fix the proline parent fragment - molefacture: Add FEP features to molefacture from Jonathan Degois The implementation will likely be changed in the future to make it more user friendly - VMD 1.8.7a16 (February 19, 2008) - Added CUDA to default builds now that the redistributable shared libs are handled by the installers etc. - VMD startup script now manipulates the shared library search path to allow redistributable shared libraries to be found in the VMD installation directory. - Added handling for redistributable runtime libraries needed for things like CUDA, NetCDF or any other shared libraries that are vendor-provided and/or otherwise something we can't compile for static linkage. - cgtools: Added in ability to map a previously generated shape based coarse grain model onto an all atom model. This can then be called multiple times to replicate CG models many times on a large all atom system. Doc updates coming later to describe this in more detail. - report CUDA device clock rates and compute capability during device enumeration - Added more checking for the bogus emulation mode devices, and eliminate them from consideration early on in the device enumeration code. - Emit more info during CUDA device enumeration - mol2plugin: Add recognition for 'ar' bond order output from antechamber - Add a banner with the original idatm citation, and remove some unneccesary puts statements - cranked version number - VMD 1.8.7a16withcarbs (February 7, 2008) - test builds withcarbs - Catch the case where we've been given a CUDA 'emulation device', and ignore it as unusable for our purposes. - molefacture: Add the cyclopropane base fragment (it had been missing) - dowser: Fix help URL. - Add padding for 'volmap interp'. - Counted FLOPS, global memory references, and conditional assignments in the main fmtool CUDA kernel - molefacture: Fix bug in writing topology files with newly added atoms - timeline: Made less chaty on startup, marked debug messages as DEBUG, some others as Info) - Applied Justin's patch reorganizing timestep animation control. Rather than keeping an Animation instance in each molecule, keep just a single instance in VMDApp. Make Animation a UIObject so it can generate animation events as time elapses. Add methods to DrawMolecule to return current frame and override current frame. In this form, the Animation class is much more transparent: it doesn't hold timesteps, it doesn't maintain a current frame, and it doesn't have so much asynchronous behavior. This also fixes a bug that manifests itself when you load two molecules with different numbers of frames. Previously, if the molecule with more frames is top, and you clicked the arrow button in the GUI to start animating, the molecule with the smaller number of frames loops over those frames multiple times as the animation slider goes from left to right. However, if you manually drag the slider from left to right, the molecule with fewer frames will instead clamp its frame to the last frame once the slider goes out of its frame range. Thus you have two different VMD states for the same GUI state, which is inconsistent. It never really made sense to have two Animation instances anyway, since there's only one animation state. Store center of volume and scale factor in DrawMolecule, rather than in individual Timesteps. Recompute cov and scale when required. Use the algorithm from MoleculeList to compute cov and scale, where only selected atoms in displayed reps are considered. The new behavior is smarter about when to update than the old code, and doesn't replicate code in Timestep and MoleculeList for computing the center. - Eliminated the DrawMolecule wrapper methods that were replicating/exporting MoleculeGraphics functionality, in favor of teaching the callers to retrieve and work directly with the MoleculeGraphics class. Updated the Tcl and Python bindings as per Justin's patch. - Updated MSVC builds for current sources - only call the init routine for NumPy when it has been enabled in the build. - Applied Simon Cross's patch adding a maximum ring size control to both the PaperChain and Twister representation controls. However, since there is only one ring size per molecule having multiple representations introduces the problem of synchronising the values of the maximum ring size in the AtomRep values for each representation. If this synchronisation is not done then the list of small rings will get re-calculated every time a different representation is drawn. This patch increases the vertical screen space consumed by the graphical representations window, which is somewhat undesirable. We will need to review the GUI design again later. - inorganicbuilder: Wrapped uses of psfgen in psfcontext commands, to preserve any psfgen state the user may have created. - Applied Justin's patch to preprocess and remap the residue numberings for the data we send to Stride so that it doesn't fail, e.g. when the protein is preceeded by a large water block thus inflating the indexes to larger numbers. It should now work for any molecule with fewer than 10,000 total protein residues and 100,000 total protein atoms. - new version of view_change_render script posted. - mergestructs: Added psfcontext commands to preserve any user psf context - cgtools: The bond determination checkbox was doing the opposite of what it should have been. Changed the if to handle that. Also revised an atom selection to use the molecule id being passed in instead of always using top, per Anton. - Added support for an above/below stereo display mode for use with special stereoscopic movie encoders - Added code to print tracker orientation (disabled for now) - Corrected plugins that emitted diagnostic or error messages without self-identification at the beginning of message strings. - Added new 'mergestructs' plugin for combining multiple structure files into one. - saltbr: Close log file before throwing an error. - cranked version number - VMD 1.8.7a15 (January 3, 2008) - various build and config updates - cranked version number - VMD 1.8.7a14 (December 18, 2007) - inorganicbuilder: Changed naming conventions for relabeling structures according to the number of bonds to be "XX_#", for example SI_2. Also changed the parameter file output to use .inp extension, even though both .par and .inp appear to be used for parameters. Added parameter files for sio2, asio2, and si3n4 - inorganicbuilder: Material library now stores a parameter file name, which can be used to copy a parameter file from the materials directory into the user's working directory, to make it easier to set up a simulation. No files are currently provided. - inorganicbuilder: Added code and GUI to allow each axis to be specified as periodic or non- periodic, for both specified bonds and boundary bonds. - I added a checkbox to the GUI so that renaming the atom types according to the number of bonds is now optional. - inorganicbuilder: Added options to retain file bonds, and updated the wrapped bond search to implement VMD's heuristic 0.6*(r1+r2). - Removed lower performance potential kernels from CUDA source. - inorganicbuilder: Atom type selection for building bonds is now a menu derived from the names in the currently-specified molecule, rather than just text fields. - timeline: NOTE: this is final transfer check in from Barry I. SVN directory Some scale change, (Now up to SVN rev 35) - timeline: Working on startup errors seen on Mac (from Traced sliders) Small edits to remove typo. current changes entered. Likely were just to get running at good speed (commented out puts), some small corrections Creates own font name, so is independent of other plugin (had been relying on Sequence Viewer/zoomseq to do this) - timeline: various changes and corrections - timeline: better menus. Threshold functions in menus. - timeline: Improved appearance, more room for other controls. - timeline: works on syndey (Mac), but outlines for bar and event (blue vox). The event box looks bad, since is made of many lines, not just outline. - timeline: struct is working added thresholding, function only (no gui) may not yet work some thresh graph graphing of threshold looks ok, shows max and min - timeline: highlight looks good, toggleable adding some demo files - timeline: decent packing - timeline: scrub label close - timeline: many bugs gone. button 2 scrub in progress - timeline: small changes (on laptop) - timeline: numframes + 2 gone. now to check out +1 cases - timeline: from VMD CVS tree 1.30, with some changes added not working as of this initial import. Plan to re-merge back to CVS tree after features added - timeline: The next commits will be of changes to timline.tcl that took place in Barry I.'s personal SVN directory. The 34 SVN revisions are combined here to 13 major revisions, which will each be checked into this CVS tree, along with the associated comments for each one (excepting references to extraneous README and test files not included here). These major revisions were made in March and April 2007. - Applied Simon Cross's patch moving the ring finding code into a new method and cleaning things up a bit. - Enabled Carbohydrate code for testing new round of patches. - eliminate unused variable warnings in benchmark code - Updated build for CUDA 1.1 - Eliminated unnecessary display update call that was creating trouble with python callbacks. - inorganicbuilder: Reformatted Start screen, made spacing nicer and added a button Changed bond search method to use atom type instead of element Combined PeriodicBonds and SpecifiedBonds GUIs into one window - inorganicbuilder: Removed commented out code that is no longer used now that the Specific Bonds and Periodic Bonds commands have been merged. Removed Merge Molecules code that is now in Merge Molecules plugin. Added exact-charge adjustement to the charge correction code, so that, after charge adjustments are distributed evenly across all atoms, any remaining correction that is needed due to PSF rounding is applied to atom zero. Other bug fixes. - inorganicbuilder: Separated the angle and dihedral options when creating bonds. - SGI IRIX builds are disabled until we have another build box available - vtfplugin: Updated to Olaf's latest version. This update cures a problem on Windows, and closes a small memory leak. - molefacture: Get rid of hard-coded restriction on recursion depth for bond/angle/dihedral changes - Applied Justin's python module related patch. - inorganicbuilder: New GUI for resolving segment name conflicts when merging two PSF files - Added the ruler GUI to the Extensions-Visualization menu - ruler: By popular request, added a small GUI window to access the VMD ruler - Added Axel's element-by-element vecmul command. - added Justin's config for shared lib builds of VMD - This patch fixes up some inconsistencies that arise when building VMD with the SHARED option, adds -fPIC to config_shared builds on LINUXAMD64, and adds a vmd module available only when the program is loaded as python extension that takes care of proper VMD initialization. - added thread CPU affinity function (linux/NPTL only at present) - Added comments about processor affinity on MacOS X, Solaris, and HP-UX. - added win32 branch of cpu affinity query. - Added a 'vmdinfo cpuaffinity' query text command - Added CPU affinity query code for the main VMD process - Split vmd_numprocessors() routine into two separate routines. The vmd_numprocessors() routine allows user-defined overriding of the number of worker threads to use, falling back to detecting the number of available processors if no preference exists. The vmd_numphysprocessors() routine only counts the number of physically available processors, independent of whatever preferences the user may have, for use by code that needs to do things like set CPU affinity, and so on. - inorganicbuilder: Fixed bug where the material state was not available when loading a saved state... Also sorted material lists for uniform presentation in menus. - inorganicbuilder: Added parameter and GUI to force constructed devices to have an integer charge, so that they can be easily neutralized by the addition of ions. The current method of modifying the charge is to calculate the correction and then add 1/n times the correction factor to every charge. Another possible method is to scale all charges, but that may lead to larger changes in the charge. I'll have to consult with Alek to find out what method is correct. - inorganicbuilder: Set the plugin to return to the Start screen whenever the plugin window is opened/reopened. Replaced charges in .top files with more useful values - inorganicbuilder: Added a Clear Device button, to erase any currently-defined structure Fixed a bug where an old device structure (Draw Box) was not deleted when a new one was loaded Made the "Draw Box" function dynamic, so it occurs automatically whenever the structure changes. This removes the need for the Draw Box button, so that has also been removed. - Prevent the main VMD thread from getting bound to a specific CUDA device by running all CUDA kernels in their own host threads. - Added support for benchmarking single user-specified CUDA devices, or groups of devices in parallel - Added low-level code to allow benchmarks on specific CUDA devices. - Added CUDA device/host bus bandwidth benchmark - Added comments to the multiply-add benchmark code. - Added new 'vmdinfo' subcommands: 'vmdinfo freemem' returns the estimated number of MB of free physical memory 'vmdinfo numcpus' returns the number of CPU cores 'vmdinfo numcudadevices' returns the number of CUDA devices - please the compiler - Added CUDA benchmarking kernels to the build - Added the CUDA multiply-add benchmark to the 'vmdbench' command - Added the CUDA multiply-add benchmark to the kernels header - Added built-in CUDA-based GPU benchmarking routines for use in helping diagnose performance issues, etc. - Replaced inner DMA buffer copy loops with memcpy, added support for pinned/page-locked DMA buffer memory allocations, eliminated the child thread for thread 0 by running in the main thread instead. The new code performs and scales a little better. A 32-bit multi-GPU run on a test system with a dual-QuadroPlex (Quadro FX5600) achieves 157.4 billion atom evals/second, 1160.83 GFLOPS - Added the newest version of the direct Coulomb summation CUDA kernel into VMD. This version achieves 291 GFLOPS, 39.5 billion atom evals/sec on a single GeForce 8800GTX. A 64-bit multi-GPU run on a dual QuadroPlex test system with 4 Quadro FX5600 cards achieves 1078 GFLOPS. A 32-bit multi-GPU run on the system achieves 1108 GFLOPS and 150.3 billion atom evals/sec. - Explicitly added linkage against libtlshook.so since some versions of the GNU compiler/linker tools fail to find it for themselves at link time, even though it's in the same directory with the cuda libs. - qmtool: Minor syntax bugfix. - utilities: Exporting all commands so that they can be imported from other namespaces. Added a couple new commands. - inorganicbuilder: Revised formatting on block input windows - Added Axel's patch to fix a measure gofr frame range checking bug - inorganicbuilder: Added a Start screen to start building a device - paratool: Added proper namespace to call of a procedure that has been moved to utilities. - inorganicbuilder: Added File menu, with options to save and open a state file (for the plugin state, not the complete VMD state) - inorganicbuilder: Added menu options and GUI for viewing materials and adding new ones. - Added a built-in variation of the STREAM benchmark, and Tcl commands to access it. The benchmark commands will be very helpful in collecting performance information on new multi-core systems and compilers used to build VMD. Similar GPGPU benchmarks will be added as time goes on. - cranked version number - VMD 1.8.7a12withcarbs (October 5, 2007) - Enabled carbohydrate code for fresh builds - cranked version number - VMD 1.8.7a12 (October 5, 2007) - correct some non-portable gccisms - Disable force color update for the position based coloring methods, since the user might want to be able to turn this off. We can change the default behavior to enable color updates in the GUI to accomplish the same thing as necessary, but if we enable it in the code itself, then automatic updates cannot be turned off by the user. This is somewhat self-inconsistent as we'd normally want all of the trajectory oriented reps to update every timestep, but position can be an exception as users may want to color atoms by their original position rather than by their current position. For the other trajectory based coloring methods, there isn't a logical reason to do things that way. - A few additional improvements to the menu handling code. - Further cleanup of the name-based color method menuing code - Fix coloring method menu behavior, a few more places needed to do their tests by name rather than by index. - namdenergy: Add option to update selection every frame, so people don't have to do ugly hacks for this - solvate: Fix issues with mixed solvent types - cranked version number - VMD 1.8.7a11 (October 4, 2007) - Fixed DrawMolItem so that it correctly updates the display for coloring by positional, velocity, physical time, and user data per-timestep when animating or when using the draw multiple timesteps feature. - Added support for coloring by physical time (in a trajectory). Significantly reorganized the structure of the Coloring Methods chooser/menu. Hopefully the users don't kill me :-) - Added error checking for filepsec Tcl command arguments per Axel's patch - molefacture: Fix atom ordering for input to bondedsel - initialize user pointer to NULL before testing coloring method for user coloring modes - Fixed the graphical representations coloring method menus to correctly handle coloring method submenus. - Added new X/Y/Z linear position coloring methods and moved all of the position based coloring methods into a new "Position" submenu, and renamed the GUI menu name of "Pos" to "Radial". - cranked version number - VMD 1.8.7a10 (October 3, 2007) - Added several additional text builds - Removed old VMDVOLUMETEXTURE compilation macro now that it's always turned on. Added VMDPBCSMOOTH compilation macro to enable Axel's PBC-aware smoothing code by default for the subsequent test builds. - Removed old VMDVOLUMETEXTURE ifdefs. This is required functionality from now on. - Updated default VdW radii assigned to elements to improve the default behavior for commonly used ions by replacing the Bondi radii with CHARMM27 Rmin/2 parameters for elements that are commonly ions in simulated systems. - Significant update to the mouse handling code. The "mouse pick" command now takes strings instead of mode numbers. * There is no longer a distinction between "picking" modes and simple modes in Tcl. Picking modes have their own names, and no longer have a "submode" number. * To see if we're in addbond mode, the new way is: if {$::vmd_mouse_mode == "addbonds"} {} instead of: if {$::vmd_mouse_mode == 4 && ::vmd_mouse_submode == 12} {} The old way is no longer compatible. * To switch to addbond mode, the new way is mouse mode addbonds as opposed to mouse mode pick 12 * The old way is _still_ compatible (but may be obsoleted later) Internal changes: * enums are used throughout, there is no more reliance on arbitatry constants and order in which the modes are defined, etc... * some functions have been streamlined and/or removed. - Eliminate typecasts that used to be used to please archaic versions of Tcl etc. - Situs plugin: Use %g instead of %e for Situs output. %e was a bit silly, %g is more readable/debuggable and takes as little as 25% of the space - DX plugin: Use %g instead of %e for file output - Added 3 more demand-allocated per-timestep "user" data fields named "user2", "user3", and "user4", added them to the coloring methods list in the GUI, and changed the GUI to create a "User" submenu by splitting the GUI names and the internal strings into two separate lists. This is a reasonable way of implementing this in the short-term, although it add more code to the existing cruft we're maintining. A much better way of doing this would be to build all of this dynamically, but some non-trivial changes need to added to the atom selection classes to allow that to happen, so I'll see about doing that as a second step. Once they can be added and deleted dynamically, we could open this up for as many fields as we want, and we could keep the coloring method choosers relatively organized with more submenus. - Applied Axel's patch for (optional) PBC-aware trajectory smoothing. - VMD 1.8.7a9 (September 28, 2007) - molefacture: Add a nucleic acid builder (still a work in progress, but needs to be committed) Fix up prolines in the protein builder to look better - Updated the nucleic acid structure analysis and ribbon/cartoon rendering code to handle the new PDB atom names "OP1" and "OP2", which have replaced the older "O1P" and "O2P" atom naming convention. - Added ability do create Coulomb potential maps through the GUI Added more options for the output molecule (including a "same as input" option, now used as the default) - Applied Justin's patch to add get_visible / set_visible methods to python molecule module that turn molecules on and off. Make the selection keyword of molecule.write take an atomsel instance intead of a tuple. - Greatly reduced the acceptable error tolerance for the RMS fitting routine by default. The new tolerance is 1e-15, vs. the old tolerance which was 1e-5. The new code also accepts an environment variable VMDFITRMSTOLERANCE which will override the default fit tolerance. - changed Intel C/C++ flags to eliminate an undesirable FP precision reduction flag. - inorganicbuilder: Added a min and max coordinate display in the build window - inorganicbuilder: Improved formatting of Create Box exclusion window. Fixed bug where basis vector setting were getting reset in the Build Specific Bonds window. Reformatted the exclusion list so that all geometric exclusions are listed first, followed by the VMD selection exclusions, to reflect how the exclusions are actually applied to the structure. - inorganicbuilder: Revised GUI for other tasks, consolidated the molecule file dialogs into one function, and fixed a couple of bugs in the solvate routine which occur when the original box is rectangular - inorganicbuilder: Revised look of FindSurface window, consolidated more GUI code between windows. - inorganicbuilder: Revised the layout of the Build Periodic Bonds screen - Applied API changes creating timestep metadata structures and adding support for velocities, for use in trajectory read/write plugins. - update main plugin doc index - inorganicbuilder: Improved layout of the Build Structure window - inorganicbuilder: Added Basis Vector button to Specified Bonds and Find Surface atoms as well - inorganicbuilder: Added a routine to determine basis vectors from the CRYST record in the PDB and GUI code to put it in the Periodic Bonds task window - inorganicbuilder: Added bindings so that the displayed basis vectors get updated whenever the user changes any of the box parameters - multiseq: set mouse picking mode properly - multiseq: use new vmd_pick_event variable for picking trace - aligntool: use new vmd_pick_event variable for picking trace - contactmap: use new vmd_pick_event variable for picking trace - timeline: use the new picking trace variable - stingtool: use new vmd_pick_event variable for picking trace - paratool: use new vmd_pick_event variable and mouse modes for picking trace - resptool: use new vmd_pick_event variable and mouse modes for picking trace - Made all numeric fields only accept numeric input, print a warning if the user tries to use anything besides a positive integer integer for the box size, and pre-initialize many numberic fields to zero - reenabled SOLARISX86_64 builds on taipei - linux builds are now on RHEL4 (dallas), and Sx86 builds are now on taipei - fix unterminated keyword list in the SASA command - inorganicbuilder: Now gets CHARMM topology file from the readcharmmtop plugin, also fixes title of about box - zoomseq: updated atom picking trace to only use "Pick" mode - Rewrote docs for mouse pick callbacks Fixed general callback docs (was using obsolete Tcl commands) Fixed table placement in PDF, this was buggy (use [htp] rather than [htb]) - mouse: added a ::vmd_pick_event callback for plugins to trace to get "pick" events. This callback is only activated by the "Pick" (old "user") mode and it's purpose is to discourage plugins from overloading other inappropriate picking modes (query, label, force, etc) as they have done in the past. The fact that plugins are overloading the wrong picking modes also prevented us from adding new pick callbacks without breaking compatibility. - Cranked version number - VMD 1.8.7a8 (September 19, 2007) - Added the "p" hotkey for the "Pick" mouse mode Rewrote picking hotkeys mouse mode calls to use readable strings instead of cryptic numbers - Added the Pick mode to the GUI Added mention in GUI of pre-existing hotkeys for the force picking modes - "mouse mode pick" is now allowed and goes into "user" pick mode (which from soon on will simply be called "Pick"). This is a first step towards renaming all the picking modes to have their own name. - mouse user mode: wired the user mode so that it now works as intended (previously it did nothing). Note: It's essentially just another name for the 15th "pick" mode, but it looks like and acts as if it were its own mode, which is not a bad idea. - Commented code to warn about importance of not altering the order in which picking modes are defined. - Cranked movie maker version due to bug fixes. - vmdmovie: Applied Jan's patch to correct the transparent surface rendering for movies made using Tachyon. Also fixed the behavior of the ::makemovie method intended for use by external scripts etc. - Cranked version number - VMD 1.8.7a7 (September 12, 2007) - inorganicbuilder: Switched the order of set env() and the source command - inorganicbuilder: Fixed the Help URL, and removed most diagnostic puts - Fixed inorganicbuilder makefile - removed 2 lines of dead code - sorted plugin order in makefile - paratool: Minor bugfixes Moved some commands to ::util:: - qmtool: Some procedures were moved from ::QMtool:: to ::utilities::. - Added inorganic builder to the GUI extensions menu - Added materials directory to the distribution of inorganicbuilder - Added inorganicbuilder to the distrib targets - Changed code to call new measure surface VMD internal command, rather than the external compvacuum utility. - Applied Justin's patch to add velocities to the Timestep data structures along with atom selections and Tcl/Python bindings to query them. - Reordered include directives to prevent compilations of Python related source modules from generating warnings about redefinition of _POSIX_C_SOURCE - Moved functions trans_from_rotate() and print_Matrix4() from Measure.[Ch]. - eliminated unused code fragment. - Eliminated compiler warnings on MacOSX - Force 32-bit builds on 64-bit host ABI when building the "LINUX" target, since RH9 machines are going away fast now... - Updated msvc6 project for recent changes and new source files. - Updated vs2005 project for recent changes and new source files. - Fix M_PI portability issue with new pbc vectors code. - Fixed minor nits that annoy msvc. - Added MeasureSurface to the build. - Added Robert's routines and Tcl bindings to find surface atoms. - Added Justin's multithreaded implementation of find_within(). - Added initial implementation of 'pbwithin' selection using Justin's implementation that builds on top of the existing find_within() function. Some comparison should be made of the algorithm pbwithin uses with what's in pbcneighbors; it might be faster, more correct, or both to do pbwithin the way pbcneighbors does it. In any case, it is highly desirable to have this functionality available from the atom selection interface, and this gets us there until we go back and evaluate whether we can do it in a more intelligent way. - Added Justin's variant of the find_minmax_selected() routine to be used by the new pbwithin selection - Updated the implementation of measure_minmax() to eliminate the need for an atom selection reference, allowing more routines to be able to use it. - Eliminated code duplication in the pbc transform calculation routines - Added comment about the new numpy timestep array structure. - Updated the py_numeric code for Python 2.5 and NumPy 1.x - Added pydocs for the python molecule methods. - Added documentation for the various python color control methods - Updated python atom selection bindings, docs, etc. Added new/updated "write" and "center" methods, and "keywords", "booleans", "functions", and "stringfunctions" parameter listing features. - Turned off python builds for platforms that haven't yet had their respective Python 2.5.1 and matching numeric builds completed yet. - Updated the configure script to reference Python 2.5 for all future builds. - Updated comments and return codes for the secondary structure related calls. The mol reanalyze call should not necessarily force complete ss regeneration, but that will require testing. - Secondary structure calls now correctly propagate error conditions if a STRIDE calculation fails. - Added utilities plugin. - Added utilities plugin with numerous helpful commands for lists, rings and topology. - Cranked version number - VMD 1.8.7a6 (August 31, 2007) - Incorported multiseq 2.1b6 into the a6 build for live testing - Added blank multiseq plugin list and comment indicating when it's appropriate to use. - Add a newline before last line when nvoxels%3 != 0. - Added documentation for new volmap ligand options, for "measure pbc2onc" and for "measure pbcneighbors". - Improved code documentation and "usage" strings. - Two bugfixes that prevent measure energy from crashing and from computing bad vdw energies. - Cranked version number - VMD 1.8.7a5 (August 29, 2007) - disable carbohyrate code in the main build until further testing is completed on the latest version of the ring finding code. - dxplugin: Fixed non-portable loop variable scoping construct. - Added Jan's new 'measure pbc2onc' and 'measure pbcneighbors' commands. - Correct argument parsing for the "measure energy" command - apbsrun: Updated the APBS plugin to allow dimension sizes n = a * 2^b + 1 for values of a other than 1. - namdplot: Added comment to the source code about picking the Y-axis label appropriately - Updated VS2005 project settings for the current code. - Updated win32 project for new source files - Migrated PBC functions to new MeasurePBC source file. Migrated spatial searching routines into new SpatialSearch source file. - correct situsplugin minor version number - Added new SpatialSearch and MeasurePBC source files to the build. - Moved the PBC helper routines from Measure to MeasurePBC. - Reorganized all of the routines that implement spatial searching routines into a new SpatialSearch source file. Separated out the bond search code which has diverged significantly from the other grid search and radial distance and contact searching routines. Updated other modules to reference SpatialSearch.h as appropriate. - dxplugin: Print line containing dataname at the end of dx file. Also, remove any quotes in dataname before printing it. - viewmaster: Added Axel's patch to correct radio button behavior in ViewMaster - fmtool: Implementation of the multiple-beam PSF - fmtool: Additions are made to construct the PSF using multiple interfering beams. - fmtool: Additions to use multiple interfering beams to form the PSF. Additions are ready for the configuration file reader. The actual PSF construction is not changed yet. - fmtool: 3D.conf: the configuration file containing the calls for using multiple beams to construct the PSF, in a right format. - fmtool: When you try to draw a plot with empty data or where X and Y dtata have different lengt, a warning is printed and the drawing is ignored. - inorganicbuilder: Added a line to store box basis to the VMD periodic box variables. - dxplugin: Fixed DX writer. It was printing the the axis size instead of the grid spacing in the header. - Cleaned up text output, made less chatty, removed the unnecessary fflush(stdout)'s - volmap: internally simplified the pmf combination operation. - volmap ligand: use double precision intead of floats whenever dealing with densities (as opposed to energies), since these have a large range that occasionally gets truncated by the single precision. Visible differences are only seen for isosurfaces of very large energies (e.g. 100kT); previously-computed maps are still valid, of course. - volmap: Do range checking on -minmax arguments (reported by Peter Freddolino) - Added Jan Saam's support for PBC cells in the implicit ligand sampling code ("volmap ligand"). - Added Jan Saam's PBC utility functions, to be used by new "measure" and "volmap" options. - Made find_within() non-static. - situsplugin: Implemented situs writer. - ccp4plugin: updated source comments. - edmplugin: Fixed volumetric grid aligmnent for the X-PLOR map reader. It was scaled in each dimension by an extra factor of N/(N-1). - Added comments regarding the beneficial properties of summing subgroups of atoms in the coulombic potential kernels, as applied to floating point precision. -. - fmtool: Updated comments about the shared mem version - fmtool: Added a shared memory variation, though it presently runs quite slow. - fmtool: Added CUDA ptx target - Removed recursion from the loop and path finding routines used by the carbohydrate representations. - Added intstack_empty() needed for the ring finding routines used in carbohydrate analysis. - Added carbohydrate rendering patch from Simon Cross. Only render rings and paths if all atoms in them are selected. Add an option to not display paths which share edges with other paths. Tweaked the position of the "Automatically Apply Changes" button in GraphicsFltkMenu.C and add a shorter version of the IsoSlider widget in an attempt to make the widgets in the interface for Twister and Paperchain parameters not overlap with other widgets or the default window border. -. - Added new 'interp' volmap type. This type interpolates an atomic structure onto a map using an arbitrary weight. - fmtool: print timestep info at the requested output frequency rather than hard-coded at every 256 timesteps. - fmtool: updated the "null" test kernel to measure overhead in the current version, updated the timestep output code to occur at the output frequency rather than every 256 steps. - fmtool: compacted the code in the new kernel, and added comments about the design and performance criteria for both the original kernel used in the 4Pi submission, and the new one. - fmtool: duplicated the kernel used for the 4Pi paper and renamed to calc_grid_cudakernel_4pi() so that we can compare subsequent performance values with those published in the 4Pi paper. - fmtool: Eliminated various testing code since the CUDA version runs well now. - fmtool: fix usage message for CUDA params - inorganicbuilder: Screenshots to go with the docs - inorganicbuilder: Added docs for the GUI. - inorganicbuilder: Changed GUI for entering cylinders and cones, to hopefully use a more intuitive way for users to describe shapes to system - inorganicbuilder: GUI uses either files or loaded molecules for obtaining molecule information. If the user selects a loaded molecule, the GUI gets the files that were used to load that molecule, otherwise the user can browse for PSF and PDB files separately. Numerous other bug fixes and cleanup too. - applied Axel's patch to fix the frame range check in the measure gofr commands as reported by Philipp Schoen. - molefacture: Fix problem with running molefacture multiple times in one vmd session - molefacture: Add ability to merge molefacture edits back into parent molecule - fmtool: more speed tweaks. Got rid of extraneous calls. Cleaned up variable passing to fcts some. Overall, time for test execution went from 6.05 seconds down to <5.2. - fmtool: cuda version is now returning good answers - fmtool: added a -v option to print out all of the repeated input information at the beginning. Default is to not print it. - fmtool: wait for cuda thread to finish before running next timestep, just for paranoia's sake while doing initial performance tests. We will want to maximize asynchronous operations as the kernel matures, but this is a good start. - fmtool: change array organization for the h/h_det/... arrays when copied to the GPU so that only a single index calculation is required. they are copied to be boundary-padded in the same way that pold/pnew are. - fmtool: Added in branches to deal with boundary values in the CUDA kernel. This negatively impacts performance, but for these kernels, we're already very much dominated by global memory load times, and so the minor overhead added by the branching should be insignificant. - fmtool: added a 'outputFrequency' option to the config file that determines how often the observable calculation is saved to the file (and how often it is even calculated). Default value is 1. So, if you don't have the outputFrequency specified the config, it falls back to the current situation. - fmtool: eliminate unused Nz parameter from CUDA kernel - fmtool: remove redundant error check - fmtool: movr GPU data copies out into the observable calcualation area, since that is the only time the CUDA code should really need to propagate the data back to the CPU. - fmtool: Sorted global memory references in the CUDA kernel and eliminated unnecessary parameters for the grid update kernel, since they are only needed for calculating obervables. - fmtool: lots of cleanup and organizational changes for the nascent CUDA kernel - fmtool: more tweaks. double version gets the exact same results as anton's original. single precision version is off by a bit (0.0124% over 300,000 timesteps, for instance). - fmtool: Properly include newly added hydrogens in topology files that are written by molefacture - fmtool: Allow users to add residues to an existing protein chain - fmtool: Added more safety checking int CUDA routines. Both null and real kernels run, but the thread indexing and grid size has to be changed to account for padding layers, etc. - fmtool: Numerous fixes and additions to the CUDA kernel - fmtool: Added pinned/regular buffer allocators for use by the CUDA routines - fmtool: Added CUDA device attach code - fmtool: force 32-bit compiles for fmtool CUDA kernel for the linux-cuda builds - fmtool: uncomment cuda functions - fmtool: updated real cuda function from the threadsim variation, and changed floating point constants to explicit float values for better performance. - Cranked version number - VMD 1.8.7a4 (June 26, 2007) - fmtool: still digging for the bug. committing some other cleanups that don't affect the answers. - fmtool: tweaks to the thread/threadsim fcts to make them produce the same results as the earlier versions. Changes to threadsim still need to be put back into the real cuda version - fmtool: added cubin target and matching cleanup steps - fmtool: Added more prototype cuda code - fmtool: just removed some commented out parms - fmtool: Verified that the float version (CPU) obtains the same answers while using the cudacheck function (as before). - cionize: Updated cionize makefile for CUDA 1.0 - Updated VMD compiler paths for CUDA 1.0 - fmtool: updated compiler path for CUDA 1.0 - autopsf: Avoid a potential buffer overrun - mol2plugin: Allow trajectory read/write (trajectories are represented as several separate complete mol2 blocks) - fmtool: knocked out a couple more bugs. Should now produce the same answers as anton's pre-optimized version - fmtool: cleanup, removed debugging stuff - fmtool: Added multi-build Makefile - fmtool: Added CUDA handling to the main program - fmtool: converted new/delete to malloc/free to make CUDA conversion and comparisons simpler. - fmtool: eliminated unnecessary includes - fmtool: moved tmp1 calculation outside the nested loops. Storing results in an array that then is accessed from the inside. 9.8% speed bump. - fmtool: added CUDA build machinery to the custom Makefile - fmtool: comment/fct ordering tweaks - Cranked version number - VMD 1.8.7a3 (June 22, 2007) - Added the carbohydrate rendering code to the win32 builds - fmtool: Made the default run case do a double precision, no explicit boundary condition checking case. The first two fcts in the time_steps file are the most relevant ones. The first is double precision, the second is single. fmtool -n is now the default (for no explicit boundary condition checking) fmtool -d does double precision with explicit BC checking -s is single precision with no explicit BC checking -e is double prec/explicit/ with observable accumulation pulled out -o is double prec/no explicit/ with observable accumulation pulled out -e and -o can likely go away. Just had them in for testing. added a few more versions of the time_step function. - fmtool: avoid double-counting the corners - updated Win32 registry keys - disable carbs for the present time. - Cranked version number - VMD 1.8.7a2 (June 21, 2007) - fix minor /bin/sh portability nit in shell check - Make Intel C builds use -i-static for static linkage of Intel libs. - prettied up CPU messages - Added a manually unrolled 8-voxel-at-a-time loop for the CPU SSE version of the coulomb map code - Added built-in GFLOP counting for CPU version - Updated the coulomb potential timer code to get along more nicely with the Intel compilers. - Changed timer codes to use the newer timer system, which handles large runs and large system time values much more cleanly. - fmtool: fixed warnings in error output statements - fmtool: Added binary file read/write support through binary_gridio.[ch], define constant BINARY_GRIDFILE to build support. Added timer for initial grid computation. Added keyword MULTIGRID support for config file to enable multilevel sum. - fmtool: added the ability to calculate using single or double precision. Default is double. Single (for the time being) is just a copy of the time_steps_xy_to_r method with doubles replaced by floats. Command line option.. -d specifies double (not needed), -s specifies single precision. At the current time, it is very simply passing in single precision versions of the arrays to the method and getting them back as single. Initial testing seems to show that results are the same out to 6-8 significant figures, but anton will want to test with his large test case. - fmtool: just a couple of comments. - fmtool: moved p, pnew array allocation into the time_step fct. - ruler: Ruler: cosmetic changes + better handling of ruler colors when VMD is in gradient background mode. - Added Twister graphical representation algorithm implementation by Michelle Kuttel and Simon Cross. - Added linkage classes used by the Twister carb display algorithm - Take Jordi's patch to check scene rather than display for querying background mode. - paratool: minor documentation improvement - paratool: simple bugfix that affects fixing/unfixing of internal coords. - inorganicbuilder: Two changes: Made cancel button do a wm withdraw, so that the window gets restored when the Extension menu option is reselected. Added an option (GUI and codE) to solvate hexagonal structures. I just realized however, that my solvate code is not going to produce a complete PSF file. Since I'm using VMD to delete atoms, VMD's writepsf command is not going to generate angles and dihedrals. I'll have to run everything through psfgen once more to fix this. - Split the boundary condition loops from the interior loop - fmtool: removed second grid loop. Didn't think it affected anything, and the resulting dat files seem to be about the same as before. Time went from 25 to 20 seconds - fmtool: prep for splitting of interior/exterior cases - fmtool: Move accumulation of r with dr to the end of the loop so it starts with rmin. - fmtool: move pointers around instead of copying arrays from one to another - inorganicbuilder: Added [file normalize] to all the mol new and mol addfile calls, so that calls to molinfo get filename return path information, in case the current dir changes after the molecule is loaded. - fmtool: Added output file checking - fmtool: made more things const, took out an *= - ruler: Ruler: Now will be visible and look good for almost any background color. - inorganicbuilder: Fixed parameter name for molinfo get - fmtool: Added ICC build - fmtool: more tweaks to clean up compiling. - fmtool: added a secondary makefile to make hacking for special ICC/CUDA builds easier. - docs: updated the Tcl "color" docs - color: Added a "color rbg " command to return the RGB values assigned to a given color. - color: calling "color " now returns the name of the color associated with that setting. - ruler: made it automatically loaded by VMD on startup - ruler: A dynamic ruler plugin for VMD. It display a scale for the top molecule, and its various modes can be activated by calling: "ruler [tape|grid|scale]", and turned off using "ruler off". In this version, the tape and scale modes only work well when using a clear background color (i.e. not Black). - inorganicbuilder: Added GUI for the solvate function, changed Merge molecules function to work with file names extracted from loaded molecules (so we get the real PSF file name, not the incomplete one produced by saving a selection). - fmtool compiles cleanly, ran through indent, and started (very preliminary at this point) cleaning up a few of the conventions - Added Anton's fmtool code and test data, but lots of work needed. - Added C source for the inorganic builder plugin - Added materials files for the inorganic builder - Added Rob's inorganicbuilder plugin - added initial 64-bit CUDA support to the configure script - Added 64-bit CUDA target - Added GFLOP counting and info messages to the CUDA volmap coulomb code. - cionize: eliminated chatty output messages during the ion placement phase - cionize: updated with benchmark from test code with CUDA 0.9 - cionize: Updated unroll4x kernel comments and matched it with the current test kernel codes. - cionize: Fix FLOP count comments for Unroll4x kernel - cionize: eliminate spurious CUDA device messages when placing ions, and added GFLOP counting for the main grid calculations. - cionize: updated for CUDA 0.9 - cionize: use full pathname for NVCC so that it can find its libs etc. - Updated VMD CUDA kernels for CUDA 0.9 - dowserplugin: Fix typo in atom selection found by Chris Harrison. - cionize: Added special makefile used for doing CUDA-enabled builds, test versions of variations of the ML summation kernels, etc. - cionize: Added binary grid I/O files for use with accuracy test builds etc. - Changed write_matrix() output to use %g instead of %f. This allows values lower than 0.00001 to be displayed accurately, which is necessary to implement a Tcl-based dynamic grid/ruler. - Added startup script mods for 64-bit PowerPC - Cranked version number - VMD 1.8.7a1 (May 24, 2007) - added LINUXPPC64 distrib target - cgtools: Per anton, added in the ability to determine the bond cutoff information from the all atom model. Before, it was done using a cutoff. Now the user can choose to use the cutoff distance, but it uses the information from the all atom model by default - Added conditional compilation tests for 64-bit PowerPC Linux builds. - more IU BigRed updates - further PPC64 fixes for IU BigRed - Added IU BigRed as a build target for the plugin tree - cionize: Add tcl command line interface for cionize-based ion placement - cionize: Fix exclusion problem in intel threading case - qmtool: Fixed a weakness of the Gaussian logfile parser that would make it fail on some zmatrix based structures. - Volmap: added extra newline in some cases when writing DX files for greater consistency - autopsf: Reorganize how options are presented (in preparation for adding a bunch more) - autopsf: Add -splitonly option to exit after splitting chains (useful for using autopsf with other applications) - autoimd: AutoIMD: Now remember rep on/off and drawframe states between AutoIMD sessions - cionize: Sort atoms by geometric hashing (define MGPOT_GEOMHASH). It is as good, if not better, for practical use, and it can double the performance of a randomized set of atomic positions. - AutoIMD: If the simulation can't connect and there's an obvious error in the NAMD logfile, it is now relayed to the user (so they don't have to go hunting for the autoimd.log file). - molefacture: Remove some unneeded output Clean up unused temporary molecules - Added target for Intel C SSE builds for GPU comparisons - Added flags and handling logic for Intel C compiler on 32-bit Linux builds, so we can do Intel C SSE benchmarks. - The min/max bounds of the grid used to accelerate the 'within' distance selection was being done after the grid dimensions and memory allocations for the grid were performed, leading to potential trouble in some cases. - Don't import python hotkeys by default, otherwise, we'd be doing both Tcl and Python callbacks on each hotkey event, which is probably not what people want. If people want to build their own VMD with no Tcl interface, they can take it upon themselves to import hotkeys for themselves. - Make UIText do python callbacks whenever a Python interface is present. Currently, python callbacks are called only if a Tcl present is not present, which is effectively never. - Must call PyType_Ready() in py_atomsel; otherwise, for example, setting the frame of an atomsel object fails until after the first time one gets the frame. - Add J.C.'s new hbonds plugin. - Added VMD timer routines based on the portable implementation from Tachyon. - cionize: Define MGPOT_SPACING_0_2 to use mgpot with Coulombic lattice spacing 0.2 A. Mgpot modified to use h=1.6, a=9.6 (to keep ratio same as h=2, a=12 case) so as to give interpolation scaling factor 8 (= h/spacing). - change linkage for the CUDA constant buffers to static so that they are file scope only. - cionize: define MGPOT_SPACING_1_0 to use mgpot with Coulombic lattice spacing 1.0 A - cionize: changed GPU data buffer from entire lattice to slabs to avoid memory limits - cionize: back to using cudaMemset - cionize: For GPU-based placements, only use the GPU for ion placement updates if we have a big enough grid to make it worthwhile - cionize: run long-range and short-range parts in different threads - cionize: set defined constants back to 'CUDA' - cionize: made the __constant__ buffers static, so they have file scope linkage only. - cionize: mgpot short range with CUDA, define MGCUDA to build - molefacture: Allow the use of custom base fragments - improve debuggability of molefacture as suggested by Axel - molefacture: Fix missing brace caught by Axel - Fix incorrect TCL error strings. - Pretty up documentation of new measure commands. - atomedit: Use Courier as the default fixed font. - paratool: Improved control over label sizes Use Courier as the default fixed font. In contrast to tkFixed it does not render with too much size difference on different architectures. Added a flag for analog parameters in the internal parameter listbox - paratool: Replaced Tcl based measure commands by the new C++ based ones. - qmtool: Replaced the Tcl based measure commands with the new C++ versions. - cionize: incorporate performance improvements, vectorize loops on Intel compiler - dowser: Fixed a bug that occurred when the top molecule was a map. - molefacture: Allow inversion of chirality and add a button for it Also, add ability to save mol2 files from molefacture gui - molefacture: Clean up the protein builder to give much nicer alpha helices; also fix a bug where they sometimes 'kink' on long sequences - autopsf: Recognize .rtf files as charmm topology files (silly naming collision with rich text, but this has been bothering people) - fixed the /bin/csh test parameter - cionize: Include the proper headers for updating ion positions with CUDA. - configure: Added check for /bin/csh in the install target and generate a warning message when necessary. Some Ubuntu distributions don't include /bin/csh by default. Eventually we may replace the existing startup script with something written for the POSIX 1003.2 standard (Bourne shell derivative, which is also the basis for bash and others), but until then we should at least generate a warning if /bin/csh is missing. - rmsd_matrix: Fixed bad link in the docs. - Fix additional bgf/xbgf/mol2 badness - cranked minor versions of bgf and xbgf. - Fix a bug in the error handling code for "gettimestep", where a call to Tcl_AppendResult() was missing the final NULL. - cgtools: removed the namespace export and renamed the reverse cg instances to actually be reverse cg (instead of all-atom reconstruction) - updated development hardware lists - Updated source file/directory structure listing - Development plan update begins. - VMD 1.8.6 Final Release (April 7, 2007) Please email any questions to vmd@ks.uiuc.edu. footer
http://www.ks.uiuc.edu/Research/vmd/vmd-new/devel.html
crawl-002
refinedweb
41,658
53.21
dangel 0.6.0 D AngelScript binding To use this package, run the following command in your project's root directory: Manual usage Put the following dependency into your project's dependences section: DAngel D bindings and wrapper for AngelScript with support for D strings. Do note this is still work in progress and there's currently issues with D calling conventions breaking with angelscript (will be working on patching angelscript to support D calling conventions) This library also depends on a patched C binding to angelscript that you will need to compile first, you can find that here you will also need the patched AngelScript with D ABI support (GCC only right now!) Using the binding First compile the patched AngelScript with D ABI support and the patched c bindings AS DYNAMIC LIBRARIES and install the libraries to your system's library path (or whatever the heck you do on Windows) Then put the libraries somewhere that the D linker will be able to find them, in my case that's /usr/lib and /usr/include. You may want to ship the libraries with your application. Once you have that sorted, just compile your application with dub and it should link to the libraries, hopefully... Using D strings To enable D string support register the D string subsystem in angelscript like this: import as.addons.str : registerDStrings; ScriptEngine engine = ScriptEngine.create(); engine.registerDStrings(); // Register all your other stuff and execute your scripts. Returning strings from D functions to the AngelScript VM The strings handled by angelscript are outside the garbage collector's reach, when you pass a string to AngelScript it will be copied in to non-GC memory To return a string from a global method use the StringPtr helper method to get a pointer to the GC memory containing the string, from there it will be copied out of GC memory. // Returns Hello World in 3 languages (English, Japanese and Danish) engine.registerGlobalFunction("string &getHelloString()", () { return StringPtr("Hello, world!\nこんにちは世界!\nHej verden!"); } ); Note: strings in the AngelScript VM are UTF-8 and D UTF-8 text should be compatible. Registering D types Currently DAngel supports registering a few D types automatically, one being integer enums. To register a D integer enum do the following: enum MyEnum { Item1, Item2, Item3 = 42, } // After this call the enum will be available to your scripts. engine.registerEnum!MyEnum; There's experimental and buggy support for registering D structs in as.addons.dwrap. I don't recommend using it currently, though. Why does everything assert? This binding is meant to be used for gamedev so I'd prefer to avoid having a bunch of exceptions thrown and checking status IDs is imho pretty ugly. Therefore this library prefers if you fix bugs during debug builds and have minimal error checking in release builds. Where's the documentation? I plan to write proper documentation with examples at some point when I get time. That might take a while to happen though. I highly recommend checking the C++ documentation as the APIs should be decently similar as well as the Auto-generated documentation - Registered by Clipsey - 0.6.0 released 7 days ago - KitsunebiGames/dangel - BSD 2-Clause - Authors: - - Dependencies: - none - Versions: - Show all 4 versions - Download Stats: 0 downloads today 0 downloads this week 0 downloads this month 0 downloads total - Score: - 0.4 - Short URL: - dangel.dub.pm
https://code.dlang.org/packages/dangel
CC-MAIN-2020-50
refinedweb
566
58.52
[ ] Jing Zhao updated HDFS-6353: ---------------------------- Status: Patch Available (was: Open) > Handle checkpoint failure more gracefully > ----------------------------------------- > > Key: HDFS-6353 > URL: > Project: Hadoop HDFS > Issue Type: Sub-task > Components: namenode > Reporter: Suresh Srinivas > Assignee: Jing Zhao > Attachments: HDFS-6353.000.patch, HDFS-6353.001.patch > > > One of the failure patterns I have seen is, in some rare circumstances, due to some inconsistency the secondary or standby fails to consume editlog. The only solution when this happens is to save the namespace at the current active namenode. But sometimes when this happens, unsuspecting admin might end up restarting the namenode, requiring more complicated solution to the problem (such as ignore editlog record that cannot be consumed etc.). > How about adding the following functionality: > When checkpointer (standby or secondary) fails to consume editlog, based on a configurable flag (on/off) to let the active namenode know about this failure. Active namenode can enters safemode and saves namespace. When in this type of safemode, namenode UI also shows information about checkpoint failure and that it is saving namespace. Once the namespace is saved, namenode can come out of safemode. > This means service unavailability (even in HA cluster). But it might be worth it to avoid long startup times or need for other manual fixes. Thoughts? -- This message was sent by Atlassian JIRA (v6.3.4#6332)
http://mail-archives.apache.org/mod_mbox/hadoop-hdfs-issues/201501.mbox/%3CJIRA.12712918.1399488774000.66674.1421114794995@Atlassian.JIRA%3E
CC-MAIN-2017-39
refinedweb
221
52.29
CS4 Timeline problemsPaul2610 Apr 15, 2010 11:33 AM Hi all New to the forum and flash but have managed to create a short animated movie - unfortunatly the duration of the movie is made as 10 fps and last for 29 seconds (290 frames in total) but when I test the movie it plays to 36 seconds. Any body know why this is happening. Cheers for any help 1. Re: CS4 Timeline problemsNed Murphy Apr 15, 2010 11:43 AM (in response to Paul2610) There can be variations in the frame rate depending on the processing demands of the animations. I don't know of any ready-made fix for this, but someone else might. You might try up-ing the fps to 11 and see how that plays out if the time is critical. You may want to try it on different machines as well. 2. Re: CS4 Timeline problemsPaul2610 Apr 21, 2010 7:09 AM (in response to Ned Murphy) Ye I tried changing the frames, in the end I restricted the time to 29 seconds when saving as a .mov - from that I found out which frame along the time line was being regarded as 29 seconds then extended or removed empty frames to edit the movie. Got another problem now - Once saved as .FLV I attached it onto another flash object I've made which is the portfolio galley on my site - - using dreamweaver the preview of it works OK but when I uploaded it with all the other files all I get is what you see via the link above. my computer is not the greatest and some of you might see the movie and not just the skin - if you do please tell - if not, is there any reason why it should'nt be showing. cheers for any help Paul 3. Re: CS4 Timeline problemsNed Murphy Apr 21, 2010 7:30 AM (in response to Paul2610) You'll need to describe what you mean by "attached it onto" 4. Re: CS4 Timeline problemsPaul2610 Apr 21, 2010 8:02 AM (in response to Ned Murphy) I put the flv movie onto the protfolio via; import - import video (Before this I had used adobe media encoder to create the flv from the .mov of the movie file.) in the import window I imported it as; load external video with playback component. browsed to the location of the flv file - this was in the file of where all the graphics were I used for the movie, but later changed it (via componenent inspector) to point from within my web files (where I had copyied and pasted it from the previous location). next during the import I choose a skin. then once in the library I placed it on the stage on its own timeline. 5. Re: CS4 Timeline problemsPaul2610 Apr 22, 2010 8:33 AM (in response to Paul2610) Finally sorted it and as I thought it was a silly mistake again - during the import stage the file I got the movie from to 'load external video' was not from a web file or a file that was to be publiched so of cause it was not showing up it was looking for it in a file which was'nt publiched online. On another subject - during making the video in flash I did some animation of a man walking - for this I imported individual .ai (illustrator) files of each of his body part then placed them on their own time line and did a motion for each - originally I drew the man and all his parts on one file with the body parts on different layers, if I had imported this file as a movie clip would it have been possible to of just done the simple movement of the arms, legs, mouth etc from within the movie clips own time line? would of saved alot of time. Also I had planned to do movement by bones (hence why I seperated each of the parts into different files) but could'nt get the bone tool working - does an image have to be in a specific format (other then .ai or photoshop) for the bones to work? cheers
https://forums.adobe.com/thread/618189
CC-MAIN-2018-30
refinedweb
700
70.06
Important update regarding LTE modem updates - Xykon administrators last edited by Hello everyone, Due to the increasing number of reports from users that the Sequans modem and FiPy/GPy are becoming unresponsive if the firmware upgrade fails, I have been investigating this issue intensively during the last few days. I have now discovered two issues that cause the modem to become "bricked". We have now received two corrections from Sequans that allow us to update the boot loader of the modem to ensure that the modem will always remain in a recoverable state. While the initial tests looks promising, I require a few more days to make sure that the new scripts and updated files will no longer brick the modem. Due to this we have decided to take the current firmware files and updater scripts offline and we highly suggest you do not try to update your modem until we can deliver scripts to do so safely. For those of you who have already bricked your modems, please let me apologise first of all that it took so long to discover the issue. We have updated more than a hundred modules ourselves without ever having any issues, so it took some serious effort to actually brick the modems in order to analyse and solve the issues. We will keep updating you on this over the coming days. I understand and share your frustration in the matter but we're working as hard as possible to get these issues sorted. Thanks a lot for your patience. - Jordan Reyes last edited by @xykon having an issue now with modem upgrade lte.attach is stuck, same modem worked with code prior to update It appears that there has been some good progress with addressing a number of the issues with lte implimentation. Band 20 users are reporting connection success. What is happening with band 8 support my debelopment functions, along with others are dead in the water until the modem can support this band. Please provide an update on progress. @robert-hh and @Xykon Thanks! I can see it has some bugs, but it has fixed the lte.isattached(). I get occasional OSError when I try a lte.connect() after lte.isattached() returns true @einarj @Xykon has made a trial firmware package addressign this bug. You can find it at [LINK NO LONGER AVAILABLE] Download the matching package and install it using the path "Install from file". Hi, There is something wrong with the lte.isattached() in the 1.18.1.r1 (also in the latest beta-release). When connecting a GPy to the Telenor NB-IoT network, we can verify the unit is attached, but the lte.isattached() gives 'False' Running AT+CEREG and AT+CGATT also shows the device should be attached to the network: lte.send_at_cmd('AT+CEREG?') '\r\n+CEREG: 2,1,"9DD1","0105C06B",9\r\n\r\nOK\r\n' lte.send_at_cmd('AT+CGATT?') '\r\n+CGATT: 1\r\n\r\nOK\r\n' lte.isattached() False Any suggestions? @serafimsaudade There is a problem with the lte.attach() command in parsing the response to the AT+CEREG? command, issued by lte.attach(). What do you get after the attach command with the coommands: from network import LTE lte.send_at_command('AT+CEREG?') Attaching may take some time, like up to 15 Minutes. - cnopicilin last edited by @serafimsaudade said in Important update regarding LTE modem updates: The modem doesn't attach instantly, you should have the lte.isattached() in a loop like in the docs. Attaching can take minutes to complete. while not lte.isattached(): pass print('Attached') @dan please provide an indication as to when band 8 WILL be supported. It is nice to know that you are working on the problem but an expected release date would be greatly appreciated. Could you also please explain why direct emails to support@pycom.io and support team members go unanswered. This makes communication with the support team extremely difficult. @kevin So this is what AT!="showCaps"returns: == CAPS config ============================= .Lock UE on SRV band : false .MFBI support : true .TM8 TDD support : false ============================================ == CAPS ==================================== . access stratum: R13 . catM : 1 . nb-IoT : 1 -- EUTRA bands -- . supported : 28/20/13/12/4/3 . board : 3/4/12/13/20/28 . admin : . pending admin : -- EUTRA carriers -- . admin : . pending admin : ============================================ Definitely no support for band 8. Something like that would have been clear if shown right in the beginning. - Kurt Renauer last edited by We are working on the additional bands with Sequans. We will post an update when we have more information. Thanks for your patience @xykon said in Important update regarding LTE modem updates:. The six bands that Pycom chose - i.e., the only ones currently supported by Sequans FW - are 3/4/12/13/20/28. We raised this issue about 8 months ago (), but still no progress. @tuftec I've read them all, and the conclusion is not obvious. Therefore I ask, if you have another source. @robert-hh suggest you read the other posts in this thread. Particularly those from @Xykon. It appears that the Sequans modem is not currently configured for band 8 support. A new firmware update is required. Peter. @tuftec What is your source of the missing band 8 support? Doers it tell that the Sequans firmware, or the Pycom firmware, not passing the request to the Sequans firmware. If I compare the behavior between band 20 and band 8, it looks pretty similar. All commands are accepted, and then the Sequans modem is reporting alternating CEREG 2 and CEREG 0 on its TX line, only the period is different. For band 20, the period is 45 seconds, for band 8 it is 225 seconds. @robert-hh still wait on a response to band 8 support. It appears that it is currently not supported. This has put a halt to our developments at present. Peter. @xykon Today I got the information that T-Mobile Germany uses band 8 for NBIoT (900 MHz band). So it would be useful to know, if this band is supported by the Sequans firmware is the attach is requested by the command AT!="RRC::addscanband band=8" Trying to do that did not succeed even after 2 hours waiting. At least, AT+CSQtells me, that a cell is seen and a good signal can be received. But I have to go through a hard reset to get that. - serafimsaudade last edited by serafimsaudade There is one more issue. Test application was sending MQTT message once per minute. After approx. 5 hours MQTT client returned exception [Errno 113] EHOSTUNREACH and each following attempt to reconnect to MQTT broker was unsuccessful. The application also checks lte.isattached() and lte.isconnected() in each loop and if there is a change of state it prints out notification. There were no notifications therefore I assume that state of both lte.isattached() and lte.isconnected() remained True.
https://forum.pycom.io/topic/3549/important-update-regarding-lte-modem-updates
CC-MAIN-2022-05
refinedweb
1,150
67.55
#include "config.h" #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "private.h" #include "mutt/lib.h" #include "config/lib.h" #include "email/lib.h" #include "core/lib.h" #include "gui/lib.h" #include "index/lib.h" #include "format_flags.h" #include "muttlib.h" Go to the source code of this file. Sidebar window.c. Check if folder matches the beginning of mbox. Definition at line 100 of file window.c. Abbreviate a Mailbox path using a folder. Definition at line 139 of file window.c. Abbreviate a url-style Mailbox path. Use heuristics to shorten a non-local Mailbox path. Strip the host part (or database part for Notmuch). e.g. imap://user@host.com/apple/bananabecomes apple/banana notmuch:///home/user/db?query=hellobecomes query=hello Definition at line 203 of file window.c. Generate the needed indentation. Definition at line 232 of file window.c. Calculate the colour of a Sidebar row. Definition at line 251 of file window.c. Calculate the depth of a Mailbox path. Definition at line 289 of file window.c. Turn mailbox data into a sidebar string. Take all the relevant mailbox data and the desired screen width and then get mutt_expando_format to do the actual work. mutt_expando_format will callback to us using sidebar_format_str() for the sidebar specific formatting characters. Definition at line 504 of file window.c. Should a SbEntry be displayed in the sidebar? For each SbEntry in the entries array, check whether we should display it. This is determined by several criteria. If the Mailbox: Definition at line 543 of file window.c. Prepare the list of SbEntry's for the sidebar display. Before painting the sidebar, we determine which are visible, sort them and set up our page pointers. This is a lot of work to do each refresh, but there are many things that can change outside of the sidebar that we don't hear about. Definition at line 609 of file window.c. Draw a line between the sidebar and the rest of neomutt. Draw a divider using characters from the config option "sidebar_divider_char". This can be an ASCII or Unicode character. We calculate these characters' width in screen columns. If the user hasn't set $sidebar_divider_char we pick a character for them, respecting the value of $ascii_chars. Definition at line 821 of file window.c. Wipe the remaining Sidebar space. Write spaces over the area the sidebar isn't using. Definition at line 869 of file window.c.
https://neomutt.org/code/sidebar_2window_8c.html
CC-MAIN-2021-39
refinedweb
417
64.07
Flask App routing - It is used to map the specific URL function that is intended to perform some task. The output of that function is rendered on the webpage. - In Our first application, the URL ('/') is associated with the home function that returns a specific string displayed on the web page. - Here, You can reuse the variable by adding that as a parameter into the view function. Sample Code from flask import Flask app = Flask(__name__) @app.route('/home/<name>') def home(name): return "hello,"+name; if __name__ =="__main__": app.run(debug = True) Output Flask App Routing Output - The converter can be used in the URL to map the particular variable to the specified data type. For Ex, You can provide it integer or float like age. Sample Code from flask import Flask app = Flask(__name__) @app.route('/home/<int:age>') def home(age): return "Age = %d"%age; if __name__ =="__main__": app.run(debug = True) Output int or float Converters App Routing Converter - These converters are used to convert the default string type to the associated data type. - string: Default - int: Convert the string to the integer - float: Convert the string to the float - path: It can accept the slashes given in the URL Read Also Converter1 add_url() Function - add_url() function is used to perform routing for the flask Web application. Add Url Syntax add_url_rule(<url rule>, <endpoint>, <view function>) Sample code from flask import Flask app = Flask(__name__) def about(): return "This is about page. "; app.add_url_rule("/about","about",about) if __name__ =="__main__": app.run(debug = True) Output Output If you want to learn about Python Course , you can refer the following links Python Training in Chennai , Machine Learning Training in Chennai , Data Science Training in Chennai , Artificial Intelligence Training in Chennai
https://www.wikitechy.com/tutorial/flask/flask-app-routing
CC-MAIN-2020-50
refinedweb
293
53.31
Attributes AttributeSpecifier: Attribute : Attribute DeclarationBlock Attribute: LinkageAttribute AlignAttribute DeprecatedAttribute ProtectionAttribute Pragma static extern abstract final override synchronized auto scope const immutable inout shared __gshared Property nothrow pure ref Property: @ PropertyIdentifier UserDefinedAttribute PropertyIdentifier: property safe trusted system disable nogc DeclarationBlock: DeclDef { DeclDefsopt } Attributes are a way to modify one or more declarations. The general forms are: attribute declaration; // affects the declaration attribute: // affects all declarations until the end of // the current scope declaration; declaration; ... attribute { // affects all declarations in the block declaration; declaration; ... } Linkage Attribute LinkageAttribute: extern ( LinkageType ) extern ( C++, IdentifierList ) LinkageType: C C++ D Windows Pascal System Objective-C D provides an easy way to call C functions and operating system API functions, as compatibility with both is essential. The LinkageType is case sensitive, and is meant to be extensible by the implementation (they are not keywords). C and D must be supplied, the others are what makes sense for the implementation. C++ offers limited compatibility with C++. Objective-C offers limited compatibility with Objective-C, see the Interfacing to Objective-C documentation for more information. System is the same as Windows on Windows platforms, and C on other platforms. Implementation Note: for Win32 platforms, Windows and Pascal should exist. C function calling conventions are specified by: extern (C): int foo(); // call foo() with C conventions D conventions are: extern (D): Windows API conventions are: extern (Windows): void *VirtualAlloc( void *lpAddress, uint dwSize, uint flAllocationType, uint flProtect ); The Windows convention is distinct from the C convention only on Win32 platforms, where it is equivalent to the stdcall convention. Note that a lone extern declaration is used as a storage class. C++ Namespaces The linkage form extern (C++, IdentifierList) creates C++ declarations that reside in C++ namespaces. The IdentifierList specifies the namespaces. extern (C++, N) { void foo(); } refers to the C++ declaration: namespace N { void foo(); } and can be referred to with or without qualification: foo(); N.foo(); Namespaces create a new named scope that is imported into its enclosing scope. extern (C++, N) { void foo(); void bar(); } extern (C++, M) { void foo(); } bar(); // ok foo(); // error - N.foo() or M.foo() ? M.foo(); // ok Multiple identifiers in the IdentifierList create nested namespaces: extern (C++, N.M) { extern (C++) { extern (C++, R) { void foo(); } } } N.M.R.foo(); refers to the C++ declaration: namespace N { namespace M { namespace R { void foo(); } } } align Attribute AlignAttribute: align align ( AssignExpression ) Specifies the alignment of: - variables - struct fields - union fields - class fields - struct, union, and class types align by itself sets it to the default, which matches the default member alignment of the companion C compiler. struct S { align: byte a; // placed at offset 0 int b; // placed at offset 4 long c; // placed at offset 8 } auto sz = S.sizeof; // 16 AssignExpression specifies the alignment which matches the behavior of the companion C compiler when non-default alignments are used. It must be a positive power of 2. A value of 1 means that no alignment is done; fields are packed together. struct S { align (1): byte a; // placed at offset 0 int b; // placed at offset 1 long c; // placed at offset 5 } auto sz = S.sizeof; // 16 The alignment for the fields of an aggregate does not affect the alignment of the aggregate itself - that is affected by the alignment setting outside of the aggregate. align (2) struct S { align (1): byte a; // placed at offset 0 int b; // placed at offset 1 long c; // placed at offset 5 } auto sz = S.sizeof; // 14 Setting the alignment of a field aligns it to that power of 2, regardless of the size of the field. struct S { align (4): byte a; // placed at offset 0 byte b; // placed at offset 4 short c; // placed at offset 8 } auto sz = S.sizeof; // 12 Do not align references or pointers that were allocated using NewExpression on boundaries that are not a multiple of size_t. The garbage collector assumes that pointers and references to gc allocated objects will be on size_t byte boundaries. If they are not, undefined behavior will result. The AlignAttribute is reset to the default when entering a function scope or a non-anonymous struct, union, class, and restored when exiting that scope. It is not inherited from a base class. deprecated Attribute DeprecatedAttribute: deprecated deprecated ( AssignExpression ) It is often necessary to deprecate a feature in a library, yet retain it for backwards compatibility. Such declarations can be marked as deprecated, which means that the compiler can be instructed to produce an error if any code refers to deprecated declarations: deprecated { void oldFoo(); } oldFoo(); // Deprecated: function test.oldFoo is deprecated Optionally a string literal or manifest constant can be used to provide additional information in the deprecation message. deprecated("Don't use bar") void oldBar(); oldBar(); // Deprecated: function test.oldBar is deprecated - Don't use bar Calling CTFE-able functions or using manifest constants is also possible. import std.format; enum Message = format("%s and all its members are obsolete", Foobar.stringof); deprecated(Message) class Foobar {} auto f = new Foobar(); // Deprecated: class test.Foobar is deprecated - Foobar and all its members are obsolete deprecated(format("%s is also obsolete", "This class")) class BarFoo {} auto bf = new BarFoo(); // Deprecated: class test.BarFoo is deprecated - This class is also obsolete Implementation Note: The compiler should have a switch specifying if deprecated should be ignored, cause a warning, or cause an error during compilation. Protection Attribute ProtectionAttribute: private package package ( IdentifierList ) protected public export Protection is an attribute that is one of private, package, protected, public or export. Private means that only members of the enclosing class can access the member, or members and functions in the same module as the enclosing class. Private members cannot be overridden. Private module members are equivalent to static declarations in C programs. Package extends private so that package members can be accessed from code in other modules that are in the same package. This applies to the innermost package only, if a module is in nested packages. Package may have an optional parameter - dot-separated identifier list which is resolved as the qualified package name. If this optional parameter is present, the symbol is considered to be owned by that package instead of the default innermost one. This only applies to access checks and does not affect the module/package this symbol belongs to. Protected means that only members of the enclosing class or any classes derived from that class, or members and functions in the same module as the enclosing class, can access the member. If accessing a protected instance member through a derived class member function, that member can only be accessed for the object instance which can be implicitly cast to the same type as ‘this’. Protected module members are illegal. Public means that any code within the executable can access the member. Export means that any code outside the executable can access the member. Export is analogous to exporting definitions from a DLL. Protection does not participate in name lookup. In particular, if two symbols with the same name are in scope, and that name is used unqualified then the lookup will be ambiguous, even if one of the symbols is inaccessible due to protection. For example: module A; private class Foo {} module B; public class Foo {} import A; import B; Foo f1; // error, could be either A.Foo or B.Foo B.Foo f2; // ok const Attribute The const attribute changes the type of the declared symbol from T to const(T), where T is the type specified (or inferred) for the introduced symbol in the absence of const. const int foo = 7; static assert(is(typeof(foo) == const(int))); const { double bar = foo + 6; } static assert(is(typeof(bar) == const(double))); class C { const void foo(); const { void bar(); } void baz() const; } pragma(msg, typeof(C.foo)); // const void() pragma(msg, typeof(C.bar)); // const void() pragma(msg, typeof(C.baz)); // const void() static assert(is(typeof(C.foo) == typeof(C.bar)) && is(typeof(C.bar) == typeof(C.baz))); immutable Attribute The immutable attribute modifies the type from T to immutable(T), the same way as const does. inout Attribute The inout attribute modifies the type from T to inout(T), the same way as const does. shared Attribute The shared attribute modifies the type from T to shared(T), the same way as const does. __gshared Attribute By default, non-immutable global declarations reside in thread local storage. When a global variable is marked with the __gshared attribute, its value is shared across all threads. int foo; // Each thread has its own exclusive copy of foo. __gshared int bar; // bar is shared by all threads. __gshared may also be applied to member variables and local variables. In these cases, __gshared is equivalent to static, except that the variable is shared by all threads rather than being thread local. class Foo { __gshared int bar; } int foo() { __gshared int bar = 0; return bar++; // Not thread safe. } Unlike the shared attribute, __gshared provides no safe-guards against data races or other multi-threaded synchronization issues. It is the responsibility of the programmer to ensure that access to variables marked __gshared is synchronized correctly. __gshared is disallowed in safe mode. @disable Attribute A reference to a declaration marked with the @disable attribute causes a compile time error. This can be used to explicitly disallow certain operations or overloads at compile time rather than relying on generating a runtime error. @disable void foo() { } void main() { foo(); // error, foo is disabled } Disabling struct no-arg constructor disallows default construction of the struct. Disabling struct postblit makes the struct not copyable. @nogc Attribute @nogc applies to functions, and means that that function does not allocate memory on the GC heap, either directly such as with NewExpression or indirectly through functions it may call, or through language features such as array concatenation and dynamic closures. @nogc void foo(char[] a) { auto p = new int; // error, operator new allocates a ~= 'c'; // error, appending to arrays allocates bar(); // error, bar() may allocate } void bar() { } @nogc affects the type of the function. } @property Attribute See Property Functions. nothrow Attribute See Nothrow Functions. pure Attribute See Pure Functions. ref Attribute See Ref Functions. override Attribute. class Foo { int bar(); int abc(int x); } class Foo2 : Foo { override { int bar(char c); // error, no bar(char) in Foo int abc(int x); // ok } } static Attribute The static attribute applies to functions and data. It means that the declaration does not apply to a particular instance of an object, but to the type of the object. In other words, it means there is no this reference. static is ignored when applied to other declarations. class Foo { static int bar() { return 6; } int foobar() { return 7; } } ... Foo f = new Foo; Foo.bar(); // produces 6 Foo.foobar(); // error, no instance of Foo f.bar(); // produces 6; f.foobar(); // produces 7; Static functions are never virtual. Static data has one instance per thread, not one per object. Static does not have the additional C meaning of being local to a file. Use the private attribute in D to achieve that. For example: module foo; int x = 3; // x is global private int y = 4; // y is local to module foo auto Attribute The auto attribute is used when there are no other attributes and type inference is desired. auto i = 6.8; // declare i as a double scope Attribute The scope attribute is used for local variables and for class declarations. For class declarations, the scope attribute creates a scope class. For local declarations, scope implements the RAII (Resource Acquisition Is Initialization) protocol. This means that the destructor for an object is automatically called when the reference to it goes out of scope. The destructor is called even if the scope is exited via a thrown exception, thus scope is used to guarantee cleanup. If there is more than one scope variable going out of scope at the same point, then the destructors are called in the reverse order that the variables were constructed. scope cannot be applied to globals, statics, data members, ref or out parameters. Arrays of scopes are not allowed, and scope function return values are not allowed. Assignment to a scope, other than initialization, is not allowed. Rationale: These restrictions may get relaxed in the future if a compelling reason to appears. abstract Attribute If a class is abstract, it cannot be instantiated directly. It can only be instantiated as a base class of another, non-abstract, class. Classes become abstract if they are defined within an abstract attribute, or if any of the virtual member functions within it are declared as abstract. Non-virtual functions cannot be declared as abstract.. User Defined Attributes User Defined Attributes (UDA) are compile time expressions that can be attached to a declaration. These attributes can then be queried, extracted, and manipulated at compile time. There is no runtime component to them. Grammatically, a UDA is a StorageClass: UserDefinedAttribute: @ ( ArgumentList ) @ Identifier @ Identifier ( ArgumentListopt ) @ TemplateInstance @ TemplateInstance ( ArgumentListopt ) And looks like: @(3) int a; @("string", 7) int b; enum Foo; @Foo int c; struct Bar { int x; } @Bar(3) int d; If there are multiple UDAs in scope for a declaration, they are concatenated: @(1) { @(2) int a; // has UDA's (1, 2) @("string") int b; // has UDA's (1, "string") } UDA's can be extracted into an expression tuple using __traits: @('c') string s; pragma(msg, __traits(getAttributes, s)); // prints tuple('c') If there are no user defined attributes for the symbol, an empty tuple is returned. The expression tuple can be turned into a manipulatable tuple: template Tuple (T...) { alias Tuple = T; } enum EEE = 7; @("hello") struct SSS { } @(3) { @(4) @EEE @SSS int foo; } alias TP = Tuple!(__traits(getAttributes, foo)); pragma(msg, TP); // prints tuple(3, 4, 7, (SSS)) pragma(msg, TP[2]); // prints 7 Of course the tuple types can be used to declare things: TP[3] a; // a is declared as an SSS The attribute of the type name is not the same as the attribute of the variable: pragma(msg, __traits(getAttributes, typeof(a))); // prints tuple("hello") Of course, the real value of UDA's is to be able to create user defined types with specific values. Having attribute values of basic types does not scale. The attribute tuples can be manipulated like any other tuple, and can be passed as the argument list to a template. Whether the attributes are values or types is up to the user, and whether later attributes accumulate or override earlier ones is also up to how the user interprets them.
http://dlang.org/spec/attribute.html
CC-MAIN-2016-30
refinedweb
2,431
53.31
The Component Object Model (COM) and .NET platform have vastly different type systems and mechanisms for object lifetime management, interface creation, and interface inheritance. For example, a Variant type in COM is a System.Object data type under .NET. To create an object, a COM client calls CoCreateInstance, whereas a .NET client can use keywords such as new or New that are built-in to a managed programming language. While COM does not support classical inheritance and a COM client manages an internal reference count provided by IUnknown to free a coclass, a .NET client relies on the runtime garbage collector provided by the .NET platform to free an object. Given such differences between COM and .NET, developing a managed client on a COM object model requires a mechanism that resolves these differences. The Runtime Callable Wrapper (RCW) is a mechanism that promotes transparent .NET to COM communication. This topic gives a high-level description of how the RCW facilitates communication between COM and .NET. Note that even though this topic uses Microsoft Visual Studio to illustrate the RCW mechanism, you can use an interop assembly outside of Visual Studio to develop a managed client. An interop assembly defines managed interfaces that map to a COM-based type library and that a managed client can interact with. To use an interop assembly in Visual Studio, first add a reference to the corresponding COM component. Visual Studio will automatically generate a local copy of the interop assembly. The interop assembly contains one namespace, under which there is a managed equivalent interface of each COM object in the COM object model. Figure 1 illustrates a managed client that wants to use a COM type library that defines coclass X. The managed client calls class X, which is the managed equivalent interface for coclass X, as defined in the interop assembly. At compile time, the managed project is compiled with information about class X from the interop assembly. In general, as long as you set a reference to a type library, Visual Studio generates a copy of an interop assembly for that type library. Any number of interop assemblies can exist to describe the same COM type. However, a type library can have only one Primary Interop Assembly (PIA) which is the interop assembly published by the type library. Unlike other interop assemblies, the PIA is not generated every time you add a reference in Visual Studio. Instead, you install the PIA to the global assembly cache (GAC) just once on a computer. When you add a reference to the type library, Visual Studio automatically loads the PIA. To program a managed solution for Outlook, you should use the Outlook PIA. To incorporate information from the Outlook PIA into a managed add-in, first you must install the Outlook 2007 PIA in the GAC. If you are using Visual Studio to create the managed project, after adding a reference to the Outlook 2007 type library, Visual Studio loads the PIA. In the object browser, under the namespace Microsoft.Office.Interop.Outlook, you can see managed interfaces that have names corresponding to objects in the Outlook object model. For example, the Account interface corresponds to the Account object in the Outlook object model. When you compile the managed project, this information is incorporated in your executable. At run time, with the information provided by an interop assembly, the .NET runtime creates an RCW for each coclass the .NET client interacts with. Note that the runtime creates only one RCW for each coclass, regardless of how many interfaces the client has obtained from the coclass. The RCW is a .NET class type that wraps around the COM coclass. The RCW keeps track of the instances of the coclass and releases references to them only when the client no longer needs the RCW. This way, a .NET client does not have to manage the lifetime of an object the way an unmanaged client would under COM. Figure 2 illustrates at runtime, an RCW intercepting an API call from a managed client, and using information from the interop assembly, transparently mapping the call to the corresponding API in the COM coclass. The following process describes how this happens: The managed client calls method A' of class X' as defined in the interop assembly for a COM type library. If an RCW does not yet exist for class X', the .NET run time uses information from the interop assembly and creates an RCW for class X'. The RCW intercepts the call to method A', translates the arguments into corresponding COM types, and invokes method A of coclass X as defined in the COM type library.
http://msdn.microsoft.com/en-us/library/bb610378.aspx
crawl-002
refinedweb
777
55.54
On Fri, Oct 12, 2012 at 4:53 PM, Kevin Fenzi <kevin scrye com> wrote: > On Wed, 10 Oct 2012 13:13:41 -0500 > Greg Swift <gregswift gmail com> wrote: > >> So... I've paid attention to the conversations around this because i >> was a long time zabbix user, so it affected me in that I had to build >> my own 'latest' packages usually or download from the maintainer's >> personal repository. If I remember correctly it has also been >> discussed around lots of web apps like bugzilla as well. > > Yeah. > > There's a lot of apps out there that have a different release cycle > that RHEL has, so we have to try and adjust to that. Keeping in mind > that most people who are using RHEL don't like things changing very > much. I'm all for that. Technically its one of the benefits of them being different package namespaces that conflict, you won't get a change you don't force with intent :) > ...snip... > >> So the two scenarios I'm looking at: >> >> 1: collectd [3] - to make version 5 available in epel5/6 will have to >> submit collectd5 package. Most of the work is done, but right now the >> created package 'conflicts' due to duplicate library files and the >> perl-Collectd module needing to be renamed. I can usually package up >> software pretty readily, and I don't know how to do what is needed to >> do this without more guidance (more admin than dev). Because of what >> the software is, I'd imagine most people are running either version 4 >> or version 5. Some people might be running both environments from the >> server side (separate collectors), but aren't likely to have a >> monitored (client) system active in both. > > Right. I think this may be something we want to ask the Fedora > Packaging folks (who live on the packaging list) about. good plan > The main problem with conflicts is that it's something that is detected > by yum at the 'test' stage. It means you have chosen, downloaded a > bunch of stuff and then yum tells you, "WOAH, these confict, fix it and > try again". This is not very friendly. If you do this in the installer > it's even worse. that is unfortunate > In this case I guess your reasoning makes sense to me, people are > unlikely to want to run both at the same time on clients. However, on > servers they might... what parts of them would conflict?. However, If one of the people that wants that wants to chip in and provide use case, testing, and preferably patches that would be awesome. >> 2: rubygem-rspec (no associated bugzilla entry that I am aware of yet) >> - to make rspec-puppet available in epel 5/6 version 2 of rspec needs >> to be made available. I assume this means that the same general >> concept of rspec2 package needing to be initiated begins. With this >> one there appears to be way more impact as there are at least 3 >> packages that build on top of rspec currently. [4] Because this is >> more of a library set of packages, and most of those packages perform >> different functionality for rspec that may not always be for the same >> end use cases it makes conflicts a harder possibility. So i'd imagine >> either a) have to do a parallel installable rspec2 release of all of >> them that conflicts so that the 'gems' themselves don't need to be >> adjusted or b) adjust the entire rubygem so that it behaves as rspec2 >> and make the other gems use rspec2 rather than rspec. > > Well, this is a reasoning for rspec2 to be completely parallel > installable. Can't those things that wish continue to use rspec1? > Or would that lead to mixing them both since they are in the same > stack??
https://www.redhat.com/archives/epel-devel-list/2012-October/msg00021.html
CC-MAIN-2017-04
refinedweb
637
66.98
Pointer with length in bytes. More... #include <CoinIndexedVector.hpp> Pointer with length in bytes. This has a pointer to an array and the number of bytes in array. If number of bytes==-1 then CoinConditionalNew deletes existing pointer and returns new pointer of correct size (and number bytes still -1). CoinConditionalDelete deletes existing pointer and NULLs it. So behavior is as normal (apart from New deleting pointer which will have no effect with good coding practices. If number of bytes >=0 then CoinConditionalNew just returns existing pointer if array big enough otherwise deletes existing pointer, allocates array with spare 1%+64 bytes and updates number of bytes CoinConditionalDelete sets number of bytes = -size-2 and then array returns NULL Definition at line 533 of file CoinIndexedVector.hpp. Default constructor - NULL. Definition at line 621 of file CoinIndexedVector.hpp. Alternate Constructor - length in bytes - size_ -1. Definition at line 629 of file CoinIndexedVector.hpp. Alternate Constructor - length in bytes mode - 0 size_ set to size mode>0 size_ set to size and zeroed if size<=0 just does alignment If abs(mode) >2 then align on that as power of 2. Copy constructor. Copy constructor.2. Destructor. Get the size. Definition at line 539 of file CoinIndexedVector.hpp. Get the size. Definition at line 544 of file CoinIndexedVector.hpp. See if persistence already on. Definition at line 549 of file CoinIndexedVector.hpp. Get the capacity (just read it) Definition at line 554 of file CoinIndexedVector.hpp. Set the capacity to >=0 if <=-2. Definition at line 559 of file CoinIndexedVector.hpp. Get Array. Definition at line 565 of file CoinIndexedVector.hpp. Set the size. Definition at line 574 of file CoinIndexedVector.hpp. Set the size to -1. Definition at line 586 of file CoinIndexedVector.hpp. Set the size to -2 and alignment. Definition at line 591 of file CoinIndexedVector.hpp. Does what is needed to set persistence. Zero out array. Swaps memory between two members. Extend a persistent array keeping data (size in bytes) Conditionally gets new array. Conditionally deletes. Assignment operator. Assignment with length (if -1 use internal length) Assignment with length - does not copy. Get array with alignment. Really get rid of array with alignment. Get enough space (if more needed then do at least needed) Array. Definition at line 667 of file CoinIndexedVector.hpp. Size of array in bytes. Definition at line 669 of file CoinIndexedVector.hpp. Offset of array. Definition at line 671 of file CoinIndexedVector.hpp. Alignment wanted (power of 2) Definition at line 673 of file CoinIndexedVector.hpp.
https://www.coin-or.org/Doxygen/Clp/classCoinArrayWithLength.html
CC-MAIN-2021-21
refinedweb
423
53.37
Download presentation Presentation is loading. Please wait. Published byAlexia Ramos Modified over 2 years ago 1 D u k e S y s t e m s Some tutorial slides on ABAC Jeff Chase Duke University 2 Preface This slide deck has some introductory slides useful for understanding role-based trust delegation logic: ABAC. Its purpose is to lay some foundations for a longer series on how to use ABAC as a foundation for trust management in GENI. See 3 IdP.faculty D SA Reading the slides IdP.student T GENI users Test Tube Guy and Dr. D, and some of their credentials A coordination service implementing some clearinghouse function, such as a Slice Authority Indicates trust of one principal in another, often associated with some kind of formal agreement: Indicates a request Indicates credential flow A A generic principal AM Aggregate 4 Basic concepts A principal is any entity that may: – Request an action – Respond to a request – Assert or receive a statement – Know a secret Trust is that which a principal must have in order to: – Honor a request – Accept a response – Believe a statement – Reveal a secret trusts Trust is usually limited to a particular function or purpose, which we would like to specify rigorously. A AB 5 Trust graph Trust may derive from a trust path through one or more intermediate principals that endorse another party. ClientServer Each step in the trust path follows a delegation of trust from a principal to its successor in the path, specified by its policy. We would like to constrain each delegation and specify rigorously and exactly what trust is delegated. 6 Certificates and credentials Each principal has at least one keypair that it may use to issue signed assertions. – Assertions represent delegations, policies, name bindings. Any such signed assertion is a certificate or “cert”. – Certificates reference other principals by their public keys. – A credential is a certificate used for authorization. Given knowledge of a public key, it is easy to secure communication with the principal who is using that keypair (authentication). We focus instead on authorization or trust management: how authenticated principals use credentials to establish trust. Certificate Term of validity Issuer’s name (or key) Signature Payload: assertion 7 IEEE Symposium on Security and Privacy, 2002 8 Entities and attributes Entities (principals) have roles, powers, rights. – These are represented as attributes. – An entity may have multiple roles/attributes. Attributes of an entity are asserted by other entities. – Attributes are not permanent. – Attributes are not inherent or absolute. Each actor has policy rules to infer belief in attributes, e.g., based on assertions made by other entities. – An actor bases decisions about trust and authorization on inferences and beliefs about entities and their attributes. – E.g., “Alice is the operator for server S” is an attribute of Alice accepted by S as a consequence of its local policy. 9 A simple example Client EServer A Request Command c on Object o Credentials representing policies Credentials representing attributes + capabilities Query A.c o E? ABAC inference engine query context To authorize the request, A gathers relevant credentials to “prove” it believes that entity E possesses an attribute c o required to issue command c on object o. 10 Constrained delegation in ABAC A principal delegates trust to another by endorsing its public key for possession of an attribute or role. The delegation is limited to the powers conferred by that attribute or role. The delegation is written as a logic statement and issued in a credential. trusts AB A.trusts B Note that the arrows in ABAC syntax run “backwards” from the delegation: they indicate membership of one or more entities in a set associated with a given role. 11 ABAC: facts and rules A.r {E} “A believes:”“These entities {E} have the role r.” A.r (A.king).r “A says:” “If my king decrees E has role r, then I accept it.” These facts/rules are encoded in credentials signed by A. Libabac uses X.509 as a transport: a convenient implementation choice. 12 ABAC in GENI ABAC is a powerful declarative representation that can capture the GENI authorization/trust model. It saves a lot of code, provides a rigorous foundation, and preserves flexibility for future innovation. It can be easy for users, with some new user tools for delegation. Declarative policies can evolve “easily”. Signed credentials introduce interesting new challenges for credential management. – But we can solve them with a distributed service for credential storage, revocation, renewal: an early application of a networked cloud! We return to this topic later… 13 Aaron’s namespace of roles Chip’s namespace of roles Each entity (principal) has its own namespace of roles (attributes). 14 Aaron’s namespace of roles Chip’s namespace of roles Each entity (principal) has its own namespace of roles (attributes). Reader beware: the arrows in this sequence of ABAC tutorial slides follow the ABAC set membership flow: they run backwards from the trust delegations! 15 Aaron’s namespace of roles Bob’s namespace of roles Chip’s namespace of roles Entities may issue credentials (certs) to assert facts and rules about who wields attributes in issuer’s namespace. 16 Aaron’s namespace of roles Bob’s namespace of roles Chip’s namespace of roles E A.r1 B.r2 A.r1 E Type 1: Role definition credential B.r2 E 17 Aaron’s namespace of roles Bob’s namespace of roles Chip’s namespace of roles A.r1 A.r1 B.r2 Type 2: Linked delegation (Restricted delegation) B.r2 18 Aaron’s namespace of roles Bob’s namespace of roles Chip’s namespace of roles A.r1 A.r1 B.r2 Type 2: Linked delegation (Restricted delegation) E B.r2 E B.r2 19 Aaron’s namespace of roles Bob’s namespace of roles Chip’s namespace of roles A.r1 A.r1 B.r2 Type 2: Linked delegation (Restricted delegation) A.r1 E (inferred) E B.r2 E B.r2 20 Aaron’s namespace of roles Bob’s namespace of roles Chip’s namespace of roles A.c o Example access policy: A.c o B.r2 B.r2 21 Aaron’s namespace of roles Bob’s namespace of roles Chip’s namespace of roles A.r1 Example access policy: A.c o B.r2 E B.r2 E B.r2 22 Aaron’s namespace of roles Bob’s namespace of roles Chip’s namespace of roles A.r1 Example access policy: A.c o B.r2 E Access granted. A.c o B.r2 B.r2 E B.r2 23 Aaron’s namespace of roles Bob’s namespace of roles Chip’s namespace of roles A.r1 B.r2 C B.k Type 3: Attribute-based delegation B.k C A.r1 (B.k).r3 C.r3 24 Aaron’s worldview Bob’s worldview Chip’s worldview A.r B.k By convention, we may agree on a global namespace of roles. Then ABAC facts become statements of belief by principals. ABAC rules declare trust structure. B.k C A.r (B.k).r A.r B.r E A.r E B.r E C.r B.r2 25 The RT family of ABAC logics RT (ABAC) logics are trust management languages extending SPKI/SDSI with RBAC concepts and support for attribute delegations and delegation of attribute authority. – See also: Delegation Logic RT0 – Role names are atomic strings. RT1 – Roles may have simple parameters – e.g., literals, integers, enumerated types RT2 – There are objects, which may have attributes with parameters. Attribute parameters may be objects or object-valued variables. 26 ABAC and Extensions Libabac implements basic role-based trust: RT0. RT1 extends RT0 with parameterized roles. – E.g., property lists and policies that consider properties – These extensions seem tractable and will be valuable for capturing Shibboleth identity attributes (e.g., inCommon). RT2 extends RT1 with objects. – Seductive, but the details are out of scope. – RT2 literature seems to presume global object names. – I am skeptical that RT2 can be made practical. Show me! Can we embrace/accept the limits of RT0 or RT1? 27 “Design patterns” for RT0 The purpose of a declarative framework is to specify stuff declaratively, instead of in code. But the framework is too weak to say what we want. – We need global objects: slices and projects. Solution: sprinkle “just a little” code around RT0 to do what we want. Here’s a look ahead: – Global objects rooted in coordination services (SA, PA) – Simple Object Definition Credentials for global objects – Object Specific Roles (OSRs) – Templated rules with fast, practical inference – Support for global objects in server-side guards 28 Next question Credential flow What does it really mean? 29 Credential management Each principal possesses many certs. – Which ones are relevant to a given request? Where are they? Some of those certs are delegated. – Server needs even more certs to validate delegation chain. – Those certs belong to someone else. Server gets them…how? Credentials expire. – How to automate renewal? People change…and people lose their keys. – Revocation: how to do it fast and make it stick? – How to rebuild credentials with new keys? – How to keep the system safe in the real world? 30 Cloud-based credential storage Concept: always-on, highly available credential store. The store is lightly trusted: it cannot forge credentials, but we must trust it not to “forget” them. Server Put issued credentials and policies (certs) in the store. Get certs to “cache or check”. Pass credentials by reference in request. Cert Store See also: Conchord, CERTDIST Similar presentations © 2017 SlidePlayer.com Inc.
http://slideplayer.com/slide/3409067/
CC-MAIN-2017-22
refinedweb
1,600
59.4
Standalone Tracer Window What Tracer Is Tracer is a simple standalone tool that displays useful information for testing/debugging MFC applications. Initially, I made this tool to make programmers' life easier when tracing complex workflows and seeing the long dynamic-built SQL queries. It proved to be much more useful and I extended its using even for intermediary release versions of applications intended to be tested at the client. That saved a lot of time in reporting/finding/fixing troubles that occurred. Its main advantages are: - Allows you to see messages easier than in the 'Output' window of Visual Studio. Also, it's easier than looking in log files. - Does not require Debug mode as for the 'Output' window. It can be used in any type of build configuration (either Debug or Release) and can be easily enabled/disabled by declaring or not a preprocessor constant (USE_TRACER). - Each type of message—'general debug info', 'SQL statement', and 'error'—is displayed with a different color. - You can filter the type of messages to be displayed. For example, you can choose to display only the 'error' messages. - It displays additional info for each message, such as source file name, line number, and timestamp. - Its contents can be saved in a file. How It Looks As shown in the figure above, it is an SDI application that uses a Rich Edit view. Besides the standard menu items/toolbar buttons, it has a few additional ones to toggle always on top and to filter message types. How It Works It simply handles WM_COPYDATA message that is one way to pass data between processes. The COPYDATASTRUCT sent with WM_COPYDATA contains the string to be displayed and the message type. To allow your application to send messages to Tracer, you have to link it with TraceSender.DLL, which effectively searches for the Tracer window and sends to it WM_COPYDATA. See the source code for more implementation details. Using Tracer with Your Application - Include "TraceSender.h". - Link your application with TraceSender.lib using #pragma comment(lib,...); for example: #ifdef USE_TRACER #pragma comment(lib,_T("\\MyProject\\lib/TraceSender.lib")) #endif USE_TRACER Demo Application It's a simple application having a few dummy functions intended just to demonstrate the use of the DEBUG_TRACE, SQL_TRACE, and ERROR_TRACE macros. Below is a sample code snippet. void CMainFrame::OnTestSql() { DEBUG_TRACE(_T("CMainFrame::OnTestSql")); // ... try { CDemoDbAccess db; // SQL_TRACE is called from db.ExecuteSQL db.ExecuteSQL(strSQL); } catch(LPCTSTR pszDemoException) { ERROR_TRACE(pszDemoException); } } void CDemoDbAccess::ExecuteSQL(LPCTSTR pszSQL) { SQL_TRACE(pszSQL); // ... this is just an example; may be any other error here ... throw(_T("You have an error in SQL statement at line 9.")); // ... } Final Notes If, let's say, for a stable considered version of your application, you don't need tracing anymore, you can simply remove USE_TRACER from the preprocessor definitions (or create a new build configuration with no USE_TRACER constant). That way, the TraceSender macros will be ignored, and will no more affect the application speed/size performance. The article describes how to use Tracer for an MFC application made with VC++ 6.0. However, I think there is not any problem using it in newer versions of VC++. Free codePosted by softhor on 12/15/2005 10:23am Hi Ovidius, firstly I want to thank you for this useful tool. Two little questions: Is this tool royalty free? Can I use in in my commercial programs? Thanks a lot, Massimo. Yes.Posted by ovidiucucu on 12/16/2005 10:47am Of course.Reply Best regards Ovidiu PS. Just if sometime you'll meet me, the using of the Tracer may cost you a beer. ;-) Related APIPosted by Clearcode on 12/09/2005 06:32am You can use the OutputDebugString API in your app and if there is a debugger attached it will recieve the trace message... Yes, of course...Posted by ovidiucucu on 12/12/2005 10:36am ...but that is a quite different stuff.Reply
http://www.codeguru.com/cpp/v-s/debug/tracing/article.php/c11063/Standalone-Tracer-Window.htm
CC-MAIN-2014-41
refinedweb
654
58.28
I have problems with functionality of the buttons please write the whole code! Type: Posts; User: newbie_in_java I have problems with functionality of the buttons please write the whole code! Hello! I want to create a program which has three buttons : DrawRectangle, DrawOval and Clear. When click DrawRectangle it draws a rectangle in a textfield. When click clear everything to be... public class LinearArray { private int data[]; private static Random generator = new Random(); public LinearArray(int size) { data = new int[size]; for (int i =... Welcome, people :) I have a problem connected with LinearArray. I can search elements with this method but I have a problem with repeated elements. For example, I have elements 1 2 3 1. When I...
http://www.javaprogrammingforums.com/search.php?s=a25866c403bde9a6d11252a6ae2f0976&searchid=1514474
CC-MAIN-2015-18
refinedweb
119
58.28
namespace::clean - Keep imports and functions out of your namespace 0.13..". You shouldn't need to call any of these. Just use the package at the appropriate place... namespace::clean will clobber any formats that have the same name as a deleted sub. This is due to a bug in perl that makes it impossible to re-assign the FORMAT ref into a new glob.. Robert 'phaylon' Sedlacek <rs@474.at>, with many thanks to Matt S Trout for the inspiration on the whole idea. This program is free software; you can redistribute it and/or modify it under the same terms as perl itself.
http://search.cpan.org/~doy/namespace-clean-0.15-TRIAL/lib/namespace/clean.pm
CC-MAIN-2014-23
refinedweb
106
75.91
Copyright © 2006 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply. The WHATWG version of this specification is available under a more permissive license.izes whatwg@whatwg.org (subscribe, archives) and public-appformats.. This document consists of the initial step along that process, the first public working draft. Web Forms 2.0 is not the only approach to making declarative formats for applications and user interfaces that the Web Application Formats Working Group is examining. The working group expects to publish a requirements document for an alternative solution _charset_field application/x-www-form-urlencoded application/x-www-form+xml: XML submission text/plain http:actions ftp:actions data:actions file:actions mailto4 behavior] does not extend CSS, but it does attempt to forms-related requirements of those specifications, except those modified by this specification, to claim compliance with this one. Implementations may optionally implement only one of HTML4 and XHTML1.1. Implementations and documents must comply to the W3C Character Model specification. [CHARMOD] use the following DOCTYPE: <!DOCTYPE html>.1.1, all XML elements defined or mentioned in this specification are in the namespace, and all attributes defined or mentioned in this specification have no namespace (they are in the per-element partition). (There are elements from other namespaces in this specification, in particular the XML submission format uses the namespace.) The term form control refers to input, output, textarea and button elements. It does not include form, label, datalist, option, optgroup,]. When a comparison is said to be case-insensitive, the comparison must be performed using case folding, as described in Unicode. See Unicode 4.0, section 5.18 "Case Mappings", subsection "Caseless Matching". [UNICODE] Vendor-specific proprietary extensions to this specification are strongly discouraged. Documents must not use such extensions, as doing so reduces interoperability and fragments the user base, allowing only users of specific user agents to access the content in question. If markup extensions are needed, they should be done using XML, with elements or attributes from custom namespaces. If DOM extensions are needed, the members should be prefixed by vendor-specific strings to prevent clashes with future versions of this specification. Extensions must be defined so that the use of extensions does not contradict nor cause the non-conformance of functionality defined in the specification. For example, while strongly discouraged to do so, an implementation "Foo Browser" could add a new DOM. User agents must treat elements and attributes that they do not understand as semantically neutral; leaving them in the DOM (for DOM processors), and styling them according to CSS (for CSS processors), but not inferring any meaning from them. The delivery of Web Forms 2 documents to the user from a remote host and the submission of data from the user to a remote host may be performed using a number of different protocols, and therefore no specific statements can be made regarding the security of those operations. In general, authors are urged to use a secure transport layer such as TLS when information of a confidential nature is to be transmitted. On the client side, implementors must be aware of a number of potential attacks. Since it is relatively easy for a hostile Web site to trick users into loading hostile content, for example by sending e-mails claiming to include links to photos of naked girls, users must be confident that a hostile site cannot access confidential information, perform denial-of-service attacks, or hijack the client's host to perform actions on behalf of the user that the user may not approve of. Confidential information can be stored in several places. Documents from other servers loaded into other browsing contexts (e.g. other windows), documents from other servers that the hostile page has caused to be loaded (of particular concern being pages that include user-specific information using out-of-band authentication and/or authorisation information such as HTTP cookies, HTTP authentication, or the origin host), files on the local system, as well as details of the user's configuration are all potential sources of confidential information. User agents must therefore implement security mechanisms to block cross-domain accesses (where local files are considered a separate domain). Such mechanisms are referred to as cross-domain scripting security mechanisms. Unfortunately, since it is difficult to predict exactly what attack vectors may exist in such a complex system, and in particular because it depends on the exact feature set of the implementation, this specification does not define the exact mechanism that must be implemented. In practice user agents implement quite comprehensive cross-domain scripting security mechanisms. Implementation experience has shown that such security mechanisms must, at a minimum, prevent scripts originating from a site at one domain from accessing the properties and methods of any object (in particular, DOM nodes) associated with a page from another domain. Typically, such an access would cause an exception to be raised. Denial of service attacks are naturally hard to prevent, since they frequently are hard to distinguish from legitimate behavior. Implementors are encouraged to set arbitrary (although high) limits on what an author can do. For instance, user agents might place a limit on the length of the regular expression pattern allowed in the pattern attribute, if a long expression could be made to take unacceptably long to execute. Implementations are also asked to consider how otherwise-legitimate UI could be abused by a hostile page. Naturally, since implementations are not restricted in how they implement their interface, no specific guidelines can be given. One example, however, would be the mailto: submission feature. Since a script can artificially submit a form, it is important that the UA not cause each submission to create a new mail window, since this would allow authors to overwhelm the user with windows containing author-specified text, which could act as both a denial-of-service attack, and an annoying advertising technique. Finally, user agent implementors should prevent pages and scripts in those pages from performing potentially harmful or embarassing actions on behalf of the user without the user's knowledge. For example, it is recommended that user agents limit the ports to which forms may be submitted, excluding, in particular, ports of well-known protocols like SMTP or telnet. The SMTP port in particular has been used by hostile pages in the past as a target of form submissions for the relaying of spam by unsuspecting users. Certain actions, including submitting a form to a third-party site and making HTTP GET requests to remote sites (both of which would be blind attacks, assuming the UA implements a cross-domain scripting security mechanism) have been historically allowed, and many sites depend on these features for quite legitimate uses. User agents should allow them. Servers therefore must also consider security. Servers should never perform non-idempotent actions in response to GET requests, as discussed by the HTTP specification. Servers should also check the Referer header to ensure that only requests from trusted hosts are honored. Servers should also consider the client to be untrusted, since in most scenarios requests can be made to hosts by hostile parties directly, bypassing any security logic included in the page nominally intended to perform the submission. Thus servers should perform validation on all submitted data, whether such validation is expected to be performed on the client or not. Further specific securiy considerations are called out where relevant..valueMissing) { // the quantity field is required but not filled in } else if (qty.validity.typ behavior by hooking into the invalid event: <label>Home page: <input type="url". These types are useful, but limited. This specification expands the list to cover more specific data types, and introduces attributes that are designed to constrain data entry or other aspects of the UA's behavior.> start tag nested in a form element is typically ignored by UAs). an element other than div whose content model includes both block- and inline-level. Authors must not mark more than one radio button per set as being checked. first (non-disabled) option element of a single-select select element with no otherwise-selected items. (If all the items are disabled or there are no items, then no item will be selected.) The optgroup element may now be nested inside other optgroup elements. The label element's exact default presentation and behavior should match the platform's label behavior. For example, on platforms where clicking a checkbox label checks the checkbox, clicking a label element should cause a click event to be synthesized and fired at the checkbox. In any case, events targeted at form controls (or other interactive elements, e.g. links) within a label must not be handled by the label itself. User agents may establish a button in each form as being the form's default button. (This should be the first submit button in the form, but UAs may pick another button if another would be more appropriate for the platform.) If the platform supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then when doing so the form's default submit button must be the one used to initiate form submission (and it will therefore probably be successful). To initiate for submission in such a case, the user agent must fire a click event at the button's element, as if the user had clicked the button himself. Consequently, if the default button is disabled, the form must not be submitted when such an implicit submission mechanism is used. (The default action of a click on a disabled button is to do nothing.) If there is no submit button, then the implicit submission mechanism must submit the form as if there was an enabled, unnamed, default button. No click event is fired in this case. Submit buttons can be associated with multiple forms, but only ever submit to the first form they are associated with. A default button for one form, therefore, could submit a different form when implicitly invoked than the form for which it is a default button. (This, however, is an edge case.) For checkbox and radio form controls, the value attribute defaults to the literal string on, so that if the value content attribute is not specified then the value DOM attribute (and the value used for submission when the controls are checked) is " on". For other controls the default is the empty string. The attributes defined in this specification as accepting a fixed set of values (e.g. type) must be compared to those values using a case-insensitive literal comparison. Whitespace must not be trimmed from attribute values to make that comparison. Whitespace must also not be trimmed from any other attributes (e.g. the value attribute). Whitespace can get trimmed by the parser for other reasons; e.g. if an XML DTD is used, the XML specification can require certain attributes to have whitespace trimmed. its index of a power of ten non-negative numbers, it must simply be omitted). Similarly, .42e2 is invalid (there must be at least one digit before the decimal point).. This input type is not appropriate for things like telephone numbers..) url IRItoken, defined in RFC 3987 section 2.2). UAs could, for example, offer the user URIs from his bookmarks. (See below for notes on IDN.) The value is called url(as opposed to irior uri) for consistency with CSS syntax and because it is generally felt authors are more familiar with the term "URL" than the other, more technically correct terms. Relative URIs and IRIs do not match the IRI token mentioned above. Only absolute addresses (potentially with fragment identifiers) are valid values for this input type. Of course, this does not prevent a user agent from allowing users to enter relative or incomplete values, but such values would have to be expanded to complete addresses before the control's isTypeMismatch flag is cleared. Any string that matches the IRI token must be accepted as a valid value by user agents. For example, user agents are not required to check that given values are in full logical order. Four other new types, add, remove, move-up and move-down, have been introduced. They are defined as part of the repeating form controls model..) A control is said to have no value selected if its value is the empty string. File controls are said to have no value selected if no files have been selected. By default, all of these new types (except range), just like the types from HTML4, must have no value selected unless a default value in a valid format is provided using the value attribute. For all controls, if a value is specified but it is not in a format that is valid for the type (where the valid types are the same as the valid submission types described above) then the defaultValue DOM attribute has the specified value, and the control is left with the value it would have had if the value attribute had not been specified (namely, no value selected, except for range controls, which have the min value selected). User agents may allow users to set a control to its "no value selected" state, but are not required to do so. Fields with no value selected do not need to match the format appropriate for their type. (Although if they are required fields, they will stop submission for that reason instead.) If a control has its type attribute changed to another type, then the user agent must reinterpret the current value (given by the value DOM attribute) and the default value (given by the value content attribute and the defaultValue DOM attribute) in light of the new type. Values that no longer match the format allowed for the control must be handled as described in the error handling section.> If in this example the "time1" field was changed to be of type date, the current value (as picked by the user or as initialized by the value attribute), the default value (given by the value attribute in the markup and the defaultValue attribute in the DOM) and the various constraints ( min and max here) would all be found to be invalid and the control would therefore become a date control with no minimum or maximum, and with no value selected. rangeUnderflow). If absent, or if the minimum value is not in exactly the expected format, there is no minimum restriction, except for the rangeand filetypes, where the default is zero. max rangeOverflow). typeMismatch flag is used for fields whose values do not match their types, and the rangeUnderflow and rangeOverflow flags are used for fields whose values are outside the allowed range. A field with a max less than its min can never fulfill both conditions when it has a value (since that value will always either underflow or overflow the allowed range) and thus must block its forms. If a control has its type attribute changed to another type, then the user agent must reinterpret the min and max attributes. If an attribute has an invalid value according to the new type, then the appropriate default must be used (and not, e.g., the default appropriate for the previous type). Control values that no longer match the range allowed for the control must be handled as described in the error handling section. the zero point. of the step attribute is in seconds, although it may be a fractional number as well to allow fractional times. The format of the step attribute is the number format described above, except that the value must be greater than zero. The default value of the step attribute of the step attribute is in days, weeks, or months, for the date, week, and month types respectively. The format is a non-negative integer; one or more digits 0-9 interpreted as base ten. If the step is zero, it is interpreted as the default. The default for the step attribute. For numeric controls, the default value of the step attribute is 1. If the step is 25e-2 (or 0.25, which is equivalent), and if max is -1.1, then the allowed values would be -1.1, -1.35, -1.60, -1.85, -2.1, ... If you wanted a range control that allowed only even numbers, you could set: <input type="range" step="2" name="evenN"> The following control would have a step of 1, the default, because the given value for the step attribute does not match the allowed values for numbers as defined above (it would need a leading zero before the decimal point): <input type="range" step=".1" name="n"> In addition, for any of the types, the literal value any may be used as the value of the step attribute. This keyword indicates that any value may be used (within the bounds of other restrictions placed on the field). value allowed by the step attribute instead of reporting a stepMismatch validation error. (Such rounding may make the value out of range, causing, for instance, a rangeOverflow] If a control has its type attribute changed to another type, then the user agent must reinterpret the step attribute. If it has an invalid value according to the new type, then the new appropriate default must be used. Control values that no longer match the precision allowed for the control must be handled as described in the error handling section., option, and optgroup elements., url, code points. [CHARMOD]. A newline in a textarea's value must count as two code points for maxlength processing (because newlines in textareas are submitted as U+000D U+000A). This includes the implied newlines that are added for submission when the wrap attribute has the value hard. Authors are discouraged from using maxlength on url and The tooLong flag is used when this attribute is specified on a text, url, textarea control and the control has more than the specified number of code points and the value doesn't match the control's default value. has no value selected (unless, of course, it is a required field, in which case it can never be valid). name Ecom_") are reserved by [RFC3106]. Authors must not use names starting with the string " Ecom_" in ways that conflict with RFC3106. readonly text, url, user interfaces. Other attributes not listed in this specification retain the same semantics as in [HTML4]. patternattribute For the text, url types of the input element, and for the textarea element, the pattern attribute specifies a pattern that the control value must match. When specified, the pattern attribute contains a regular expression that the field's value must match before the form may be submitted ( patternMismatch). <label> Credit Card Number: <input type="text" pattern="[0-9]{13-16}" name="cc" /> </label> The regular expression language used for this attribute is the same as that defined in [ECMA262], except that the pattern attribute because it is expected that the overwhelming majority of use cases will be to require that user input exactly match the given pattern. Authors who forget that these characters are implied will immediately realize [\s\S]* or some equivalent should be used instead, since the dot character in JavaScript regular expressions does not include newlines. The / character is not special in the pattern attribute. The two attributes pattern="/etc/.+" and pattern="\/etc\/.+" are therefore equivalent. In the case of the < be set. When the pattern is not a valid regular expression, it is ignored for the purposes of validation, as if it wasn't specified. Fields with no value selected do not need to match their pattern. (Although if they are required fields, they will stop submission for that reason anyway.) If the pattern attribute is present but empty, it doesn't match any value, and thus the patternMismatch flag shall be set whenever the field's value. For disabled or readonly controls, the attribute has no effect. The valueMissing flag is used for form controls marked as required that do not have values. For checkboxes, the required attribute shall only be satisfied when one or more of the checkboxes with that name in that form><label> Name: <input type="text" name="name" required="required" /></label></li> <li><label> Comment: <input type="text" name="comment" /></label></li> </ul> For other controls, any non-empty value satisfies the required condition, including a simple whitespace character. formattribute All form controls as well as the fieldset element may also changes the association of any descendent form controls, unless they have form attributes of their own or are contained inside forms that are themselves descendants of the fieldset element. In other words, user agents must associated form controls and fieldsets with the forms given in their form attribute, or, if they don't have one, with the nearest ancestor form element or the forms given in the form attribute of the nearest fieldset element with a form attribute, whichever is the nearest. If none of those apply, the element is not associated with any form. When forms are submitted, are reset, or have their form controls enumerated through the DOM, only those controls associated with the form are taken into account. A control can be associated with more than one form at a time. Submit buttons and image controls must only submit the first form they are associated with. Reset buttons must reset all the forms they are associated with. A form attribute that specifies an ID that occurs multiple times in a document must select the same form as would be selected by the getElementById() method for that ID ([DOM3CORE]). (That is, the exact behavior is undefined, but must be the same as if the getElementById() method was used.) If a form is specified multiple times in the form attribute, all occurrences but the first must be ignored. (An element can only be associated with a form once.) A form must not be specified more than once in a form attribute. behavior.) The second button submits the text field to google.cgi, the third button submits the same text field to yahoo.cgi. autocompleteattribute The autocomplete attribute applies to the text, password date-related, time-related, numeric, url controls. The attribute takes two values, on and off. The default, when the attribute is not specified, is on. The off value means that the control's input data is either particularily sensitive (for example the activation code for a nuclear weapon) or that it is a value that will never be reused (for example a one-time-key for a bank login) and indicates that the user should therefore explicitly enter the data each time, instead of being able to rely on the UA to prefill the value for him. The on value indicates that the value is not particularily sensitive and the user should expect to be able to rely on his UA to remember values he has entered for that field. When a control has its autocomplete attribute set to a value other than off, or when the attribute is omitted, the UA may store the value entered by the user so that if the user returns to the page, the UA can prefill the form. When a control has its autocomplete attribute set to off, the UA should not remember that field's value. This specification does not define the autocompletion mechanism. UAs may implement any system within the conformance criteria of this specification, taking into account security and privacy concerns. Banks frequently do not want UAs to prefill login information: <p>Account: <input type="text" name="ac" autocomplete="off" /></p> <p>PIN: <input type="text" name="pin" autocomplete="off" /></p> A UA may allow the user to disable support for this attribute. Support for the attribute should be enabled by default, and the ability to disable support should not be trivially accessible, as there are significant security implications for the user if support for this attribute is disabled. field would be focused when the document was loaded. <input maxlength="256" name="q" value="" autofocus="autofocus"> <input type="submit" value="Search"> In HTML, the minimized, url, and to the textarea element. This attribute is defined to be exactly equivalent to the inputmode attribute defined in the XForms 1.0 specification (sections E1 through E3.2) [XForms]. datalistelement and the listattribute For the text, url, style sheet: local name datalist or the local name select, attribute and the form, selected, defaultSelected, and index DOM attributes on option elements must have no effect on the input and datalist elements when option elements are used in this context. If a document contained the following markup: . This could be useful if there are values along the full range of the control that are especially important, such as preconfigured light levels or typical speed limits in a range control used as a speed control. The following markup fragment: <input type="range" min="-100" max="100" value="0" step="10" name="power" list="powers"> <datalist id="powers"> <option value="0"> <option value="-30"> <option value="30"> <option value="+50"> </datalist> ...with the following style sheet applied: input { height: 75px; width: 49px; background: #D5CCBB; color: black; } ...might render as: Note how the UA determined the orientation of the control from the ratio of the style-sheet-specified height and width properties. The colors were similiarly derived from the style sheet.
http://www.w3.org/TR/web-forms-2
crawl-001
refinedweb
4,245
50.87
pr1ntrMembers Posts13 Joined Last visited pr1ntr's Achievements 3 Reputation - If course! thanks. - I have a timeline kinda with a scrollTrigger attached. I am doing something like mainTimeline.current = gsap.timeline({ scrollTrigger: { trigger: containerRef.current, start: 'top top', end: 'bottom bottom', onSnapComplete, snap: { snapTo: 'labelsDirectional', duration: { min: 0.5, max: 3 }, }, scrub: true, onUpdate, }, }) and then at some predetermined point I want to do this mainTimeline.current.tweenTo(pathLabel, { duration: 1 }) However, while this does initiate the scroll animations, it does not actually scroll the page. Am I missing something? Snap property in ScrollTrigger pr1ntr replied to Klygor's topic in GSAPHey, I spent hours if not days trying to figure out this exact functionality. "labelDirectional" is not documented in the scrollTrigger docs. Is this a brand new thing? Using webpack, TimelineMax has references to TweenLite? pr1ntr replied to folktrash's topic in GSAPI think this has to do with the fact that webpack has a define method as well module - Nevermind, I am dumb. turns i had 2 elements with same ID! I need to not ID my svgs. - I am having this same issue now. However the SVG is inlined to the DOM and is not under any circumstance display:none in any of its parents. Its really pissing me off. The weird thing is in this codepen it works fine: But on my site it NS_ERROR_FAILURE. I can't for the life of me figure out what is going on. Is there anything you guys can think of at all that could cause this if not the display:none issue? btw its pretty much impossible to debug GSAP midtween I had to go turning every tween off/on to figure out which one it was to even isolate the code that was producing it. Maybe adding some error handling that identified the element selector being tweened? onUpdate Easing pr1ntr replied to pr1ntr's topic in GSAPFound it: is the answer. make a proxy object with a property value 0-1.? Nested Paused Timeline or Tween instances don't play in parent timeline pr1ntr replied to pr1ntr's topic in GSAPI totally understand the reasoning behind not "assuming" things. I have to stop myself from that all the time. But just for fun, here is my use case. So I have an animation in which is comprised of 4-5 distinct timelines that control what happens in some sequence. The sequence of these timelines varies upon the "in" or "out" of the total animation. so if the animation is going out I have to rearrange these timelines. What I tried to do initially is create all timelines in a paused state and assign them to vars of some object that is in charge of managing them. Then every time I want to animate in, I create a new timeline and add those tweens to it in a particular order. When I want them to animate out I add them to another tween in reverse an then reverse that timeline. What I had expected is as soon as I added them to another tween they would inherit that tweens paused state. Since the parent tween is ultimately in charge of playback of its children it seemed rational that it would override whatever paused state they had. What I had resolved to do was just remake each timeline every time I wanted to animate in an an out. I guess I don't feel terribly comfortable with constantly instantiating tweens, but I have gotten over it for the most part as I am assured that the tweens GC very well. The profiler also confirms this. I figured it may be easier to manage the same instance of the tweens. Thanks for your input guys. - I discovered today (unless im doing it wrong) that my paused tweens and timlines don't play when added to a timeline. They need to be manually unpaused. Is this a desired effect? Would you guys be open to implementing a switch? Thanks. Draggable.onThrowUpdate stops other timelines? pr1ntr replied to pr1ntr's topic in GSAPturns out i needed a different overwrite Draggable.onThrowUpdate stops other timelines? pr1ntr posted a topic in GSAPI have a draggable instance that is responsive for page scrolling on tablet devices. When the onDrag events fire it runs a function that updates stuff on the page with its current position (0-1) and scrollTop/y to a method that delegates this information to tell stuff to parallax or trigger if it has gotten far enough down the page. A problem is starting to present that when onDrag fires this update method everything parallaxes fine however when onThrowUpdate runs it stops this particular parallax animation. I think it may have something to do with how the animations is run. Here is the code tweenParallax = (pos,tween,min,max,dur) -> amount = ((pos / max) * 1) * dur if pos <= max and pos >= min tween.tweenTo amount , overwrite:'all' ease:Quad.easeOut module.exports.clouds = (setId, min, max, dur) -> minPos = min maxPos = max duration = dur $el = $(".clouds#{setId}") clouds = $el.find(".cloud") tween = new TimelineMax tween.add TweenMax.to clouds , duration , y:"+=400" tween.paused(true) return (pos) -> tweenParallax pos , tween , minPos, maxPos, duration pardon my coffee. Let mek now if you need a codepen, it may take some time to set one up. Dynamically changing a callback pr1ntr posted a topic in GSAPIs there a way to set a callback after instantiation of a TimelineMax object?
https://greensock.com/profile/24093-pr1ntr/
CC-MAIN-2022-27
refinedweb
911
65.52
Building the Right Environment to Support AI, Machine Learning and Deep Learning Watch→ There are times when we need to reflect the changes made to a file in a different file as well. Mostly, they are made available in a common place so that you do not have to navigate to multiple folders looking for them. This idea is supported by Java using the concept of link creation. Now, in the example below, linkedFile.txt will always reflect the changes made to source.txt: import java.nio.file.*; import java.io.*; public class CreateLink{ public static void main(String args[]) { CreateLink createLink = new CreateLink(); createLink.proceed(); } private void proceed() { //The linkedFile will be linked to currentFile and will reflect any changes made to it Path linkedFile = Paths.get("C:\\AdvJava\\linkedFile.txt"); //The file that is the origin Path currentFile = Paths.get("C:\\AdvJava\\source.txt"); try { //Creating a link Files.createLink(linkedFile, currentFile); } catch (IOException ioe) { System.out.println(ioe); } catch (UnsupportedOperationException uoe) { System.out.println(u.
http://www.devx.com/tips/java/creating-a-link-to-a-file-in-java.-170629032014.html
CC-MAIN-2020-05
refinedweb
168
50.94
Hey, I have to code a min-heap, along with other things to help compute minimum spanning tree. I coded up the min-heap pretty easily and I have no compile errors, however my delete fix up does not seem to be working properly. For example, I insert these ints into an empty min heap: 10, 9, 7, 2, 5, 3, 8, 4. I get the min-heap: 2, 4, 3, 5, 7, 9, 8, 10 After the first extract minimum call I get the min-heap: 3, 4, 8, 5, 7, 9, 10 Which is correct, however, if I call min-heap again I get this heap: 8, 4, 10, 5, 7, 9 Which is incorrect, I've check my code and I still can't find the problem. My min-heap consist of "edges" and not ints. An edge is a class that consist of 3 ints that represent two vertices and a cost. My min-heap is sorted by cost. Here is the header file: Here is my heap.cpp file:Here is my heap.cpp file:Code:/* * File: heap.h * Author: Owner * * Created on April 24, 2010, 10:51 PM */ #ifndef _HEAP_H #define _HEAP_H #include <vector> #include "edge.h" using namespace std; class min_heap { public: min_heap(int size); ~min_heap(); int get_min(); void extract_min(); bool isEmpty(); void insert(edge newEdge); void bottom_up(int i); void top_down(int i); void display(); void heapify(int i); vector<edge> theEdges; // private: int heapSize; int arraySize; int* data; int parent(int i); int lchild(int i); int rchild(int i); }; #endif /* _HEAP_H */ The deletion fix up was the "top_down" function, but that didn't seem to work. So I created the "heapify" function, and that gives me the problem that I stated above. Any help at all would be appreciated.The deletion fix up was the "top_down" function, but that didn't seem to work. So I created the "heapify" function, and that gives me the problem that I stated above. Any help at all would be appreciated.Code:#include <vector> #include "heap.h" #include "edge.h" #include <string> #include <iostream> using namespace std; min_heap::min_heap(int size) { arraySize = 0; heapSize = 0; theEdges.resize(size); } min_heap::~min_heap() { delete[] data; } int min_heap::parent(int i) { //return i/2; return (i-1)/2; } int min_heap::lchild(int i) { //return 2*i; return 2*(i+1); } int min_heap::rchild(int i) { //return 2*i+1; return 2*i+2; } bool min_heap::isEmpty() { return (heapSize == 0); } int min_heap::get_min() { if(isEmpty()) ; // throw string("empty the heap is"); else return theEdges[0].cost; } void min_heap::bottom_up(int i) { int p; int temp; if(i != 0) { p = parent(i); if(theEdges[p].cost > theEdges[i].cost) { temp = theEdges[p].cost; theEdges[p].cost = theEdges[i].cost; theEdges[i].cost = temp; bottom_up(p); } } } void min_heap::top_down(int i) { int min_element; int temp; int left = lchild(i); int right = rchild(i); if(right >= heapSize) { if(left >= heapSize) return; else min_element = left; } else { if(theEdges[left].cost <= theEdges[right].cost) min_element = left; else min_element = right; } if(theEdges[i].cost> theEdges[min_element].cost) { temp = data[min_element]; theEdges[min_element].cost = theEdges[i].cost; theEdges[i].cost = temp; top_down(min_element); } } void min_heap:: insert(edge newEdge) { theEdges[heapSize] = newEdge; //top_down(heapSize-1); bottom_up(heapSize); heapSize++; } void min_heap::extract_min() { theEdges[0] = theEdges[heapSize-1]; heapSize--; if(heapSize> 0) { heapify(0); //top_down(0); } } void min_heap::display() { for(int i = 0; i < heapSize; i++) cout<< "i is: " << i << ", data is: " << theEdges[i].cost << ", " << endl;; } void min_heap:: heapify(int i) { int left = lchild(i); int right = rchild(i); int smallest; int temp; if(left <= heapSize && theEdges[left].cost < theEdges[i].cost) smallest = left; else smallest = i; if(right <= heapSize && theEdges[right].cost < theEdges[smallest].cost) smallest = right; if(smallest != i) { temp = theEdges[smallest].cost; theEdges[smallest].cost = theEdges[i].cost; theEdges[i].cost = temp; heapify(smallest); } } Here is the edge.h file if needed: Code:/* * File: edge.h * Author: Owner * * Created on April 28, 2010, 3:30 PM */ #ifndef _EDGE_H #define _EDGE_H class edge { public: int u; int v; int cost; edge() { u = -1; v = -1; cost = -1; } edge (int vertex1,int vertext2,int theCost) { u = vertex1; v = vertext2; cost = theCost; } }; #endif /* _EDGE_H */
http://cboard.cprogramming.com/cplusplus-programming/126333-min-heap-help.html
CC-MAIN-2015-40
refinedweb
695
64
Including <QtGui/...> or <...> I noticed many of the classes in Qt are copied in different directories. At first I thought gui related widgets were only located in <QtGui/...> but many of the classes in QtGui are copied over in <Qt> folder. Does it matter which one we use? - tobias.hunger Moderators No, it does not. Both <Module/Class> and <Class> should include the same file since the include path will contain both "toplevel/Qt" as well as "toplevel/Qt/Module" (at least when using qmake projects). In creator we used to do <QtGui/QLabel> to make explicit which modules we were using. With Qt5 being started and with it moving around classes we switched to <QLabel> style includes to allow building Creator with both Qt4 and Qt5. I prefer the Module/class style as it clearly shows which modules I am using. And if you work with MSVS or other compilers, it also works with setting only one include path. When using qmake (and this is the best method), I suggest to use <module>. For example, in your main.cpp add this line : #include<QtGui> and in the qMakefile add those 2 lines : CONFIG += qt QT += gui the qmake will generate the appropriate Makefile and you will not find any problem :) [quote author="issam" date="1342372394"]#include<QtGui> [/quote] This has some disadvantages as it includes all headers which has an impact on the compile time. I prefer to include only what is needed and if possible only in cpp files and in headers use forward declarations. - sierdzio Moderators [quote author="issam" date="1342372394"]When using qmake (and this is the best method), I suggest to use <module>. For example, in your main.cpp add this line : #include<QtGui> [/quote] This is quite suboptimal, the compilation will take longer if you include the whole module. I know it's harder, but when you include just what you need, the compiler has less stuff to parse. I've recently optimised headers in that manner in a project I'm responsible for, and compilation sped up by about 40%. [quote author="issam" date="1342372394"] @ #include<QtGui> @ [/quote] Please don't do that. It makes your project slow to compile, and it makes it harder to see what is actually used by your class. Furthermore, this style of "just include everything" can cause hard to fix compilation issues (unneeded interdepencies between files) if you also apply it to your own code. Just include what you actually need, but please do include everything you use (even if it also works without). You don't want your compilation to rely on the fact that some other header you included already includes QString because of some internal need for it. As soon as you change that latter class and you remove the include there, the other file that relied on it will stop compiling. That is just plain annoying. I know dear friends ... But I think that this method is suitable for small Qt projects ! Isn't ? No, it may be usable for quick demo's an wips, but not for anything you plan to distrubute and maintain for any amount of time. What starts as (a component in) a small project may end up as (a component in) a big project. So, for the general case, I think it is bad advice to give. It doesn't really help you either. How much work is it to just #include the actual classes you're using anyway? - sierdzio Moderators Well, if you don't stick to including specific headers from the start, and your project is ongoing, it will come to a point (sooner or later) where you will be facing long compilation times and a big effort to fix it. In the optimisation job I've mentioned, I had to look through well over a hundred source and header files and fix them all. It took about 3 days to complete. So, while you are right that it's not necessary, especially for small projects where compilation time is negligible anyway, it sure is easier to do it right from the very start than to be forced to fix it later. All right, I surrender :) and I will confess : In my project I began by this : @# include <QtGui>@ And I ended by : @ #include <QDebug> #include <QApplication> #include <QDesktopWidget> #include <QPushButton> #include <QLineEdit> #include <QHBoxLayout> #include <QVBoxLayout> #include <QGridLayout> #include <QTabWidget> #include <QWizard> #include <QWizardPage> #include <QTableView> #include <QListView> #include <QStringListModel> #include <QStandardItemModel> #include <QFrame> #include <QGroupBox> #include <QMessageBox> #include <QInputDialog> #include <QLabel> @ It's hard to me but very easy to the compiler ... very easy !
https://forum.qt.io/topic/18279/including-qtgui-or
CC-MAIN-2018-51
refinedweb
770
60.24
Hello, I am playing with the codebook, I am trying to use the same code to a .py file, whenever I execute the file, it gives me an error saying: " Your request is prohibited because the request is on loopback from external IP. Here an example of what I am doing. import refinitiv.dataplatform.eikon as ek from datetime import datetime, timedelta ek.set_app_key('My_Key') #Reinvestment Rate RRuson=ek.get_timeseries(['USONFFE='],start_date="2020-10-23",end_date="2020-10-23")['CLOSE'].values[0] ERROR: <HEAD><TITLE>Request on loopback from external IP</TITLE></HEAD> <BODY BGCOLOR="white" FGCOLOR="black"><H1>Request on loopback from external IP</H1><HR> <FONT FACE="Helvetica,Arial"><B> Description: Your request is prohibited because the request is on loopback from external IP.</B></FONT> <HR> <!-- default "Request on loopback from external IP" response (400) --> </BODY> Thanks Thank you for the logs. Now I think I have a reasonably good idea about your case. The fact that you reproduce the same error using Internet browser clearly indicates that the problem is not within your Python environment. It must be due to your proxy settings. What's happening is that, even though the HTTP request is directed to the localhost, your HTTP proxy intercepts it. After intercepting the request the proxy returns the request to your machine, but now to Eikon API Proxy the request appears as coming from a remote machine (as it comes from the IP address of the HTTP proxy). Eikon API Proxy rejects the request with the error message that you've seen because it only allows the requests coming from the same machine. You need to configure your proxy settings to allow HTTP requests directed to the localhost to not be intercepted by your HTTP proxy. How do you execute your .py file? As as quick test I just created a file named APTest.py in the root of my Codebook directory with the code I copied from your post. Then I opened a Jupyter notebook from the root of my Codebook directory and executed the following code in a Jupyter notebook cell import APTest as t print(t.RRuson) The value of the Fed Funds effective rate was printed as expected. Hi, i am just executing the code on vs code and spyder, I am trying to do an automated process to save certain values around 5 PM Is Eikon desktop application running on the machine where you execute your Python code? Eikon Data APIs have runtime dependency on Eikon desktop application. Note that it has to be Eikon desktop application, not Eikon Web that you can access through a browser. Yes, Eikon desktop application is running OK, now that we've covered the basics, could you tell me how you experience the error? Do you see any exceptions raised? If yes, which line of code raises the exception and can you include the traceback? Where does the HTML with the error message in your original post come from? I'm struggling to understand how any error could have manifested as HTML in your scenario. Perhaps you could include a screenshot of the result of your code execution in VS Code? And also try increasing the logging level in RDP Library. Add ek.set_log_level(5) after ek.set_app_key. Finally, instead of using RDP Library, try using Eikon Data APIs library. Both libraries should work, but Eikon Data APIs library may be better for troubleshooting until we figure out what's wrong. To use Eikon Data APIs library follow the Quick Start Guide on this portal. Thank you very much for the screenshots, they are most useful. I'm afraid this is a very puzzling issue. Nothing like I've seen before. To dig a bit deeper, could you try entering the following in the address bar of the Internet browser on the machine where you run your Python code and share the response: I will also need a couple of log files from Eikon desktop application. Please see Chapter 3 "Verify that Eikon Desktop is running properly and APIPROXY service is enabled" in this article. It contains instructions for enabling logging in Eikon application. The specific log files I'm interested in are APIProxy.YYYYMMDD.HHMMSS000.pXXXX.txt and SxS.YYYYMMDD.HHMMSS000.pXXXX.txt. You will need to shut down Eikon, configure logging using Configuration Manager application, then start Eikon, run your Python script and then collect the above log files. Hello, i run on my machine and says: here are the log files requested.
https://community.developers.refinitiv.com/questions/68116/trying-to-execute-code-from-codebook-to-a-python-f.html
CC-MAIN-2021-10
refinedweb
753
63.49
Programming the Thread Pool in the .NET Framework David Carmona Premier Support for Developers Microsoft Spain June 2002 Summary: Provides an in-depth look at the thread pool support in the Microsoft .NET Framework, shows why you need a pool and the implementation provided in .NET, and includes a complete reference for its use in your applications. (25 printed pages) Contents Introduction Thread Pool in .NET Executing Functions on the Pool Using Timers Execution Based on Synchronization Objects Asynchronous I/O Operations Monitoring the Pool Deadlocks About Security Conclusion For More Information Introduction If you have experience with multithreaded programming in any programming language, you are already familiar with the typical examples of it. Usually, multithreaded programming is associated with user interface-based applications that need to perform a time-consuming operation without affecting the end user. Take any reference book and open it to the chapter dedicated to threads: can you find a multithreaded example that can perform a mathematical calculation running in parallel with your user interface? It is not my intention that you throw away your books—don't do that! Multithreaded programming is just perfect for user interface-based applications. In fact, the Microsoft® .NET Framework makes multithreaded programming available to any language using Windows Forms, allowing the developer to design very rich interfaces with a better experience for the end user. However, multithreaded programming is not only for user interfaces; there are times that we need more than one execution stream without having any user interface in our application. Let's use a hardware store client/server application as an example. The clients are the cash registers and the server is an application running on a separate machine in the warehouse. If you think about it, the server application can have no user interface at all. However, what would the implementation be without multithreading? The server would receive requests from the clients via a channel (HTTP, sockets, files, etc.); it would process them and send a response back to the clients. Figure 1 shows how it would work. Figure 1. Server application with one thread The server application has to implement some kind of queue so that no requests are omitted. Figure 1 shows three requests arriving at the same time, but only one can be processed. While the server executes the request, "Decrease stock of monkey wrench," the other two must wait for their turns to be processed in the queue. When the execution of the first request is finished, the second one is next, and so on. This method is commonly used in many existing applications, but it poorly utilizes system resources. Imagine that decreasing the stock requires a modification of a file on disk. While this file is being written, the CPU will not be used even if in the meantime there are requests waiting to be processed. A general indication of these systems is a long response time with low CPU usage, even in stress conditions. Another strategy used in current systems is to create different threads for each request. When a new request arrives, the server creates a new thread dedicated to the incoming request and it is destroyed when the execution finishes. The following diagram shows this case: Figure 2. Multithreaded server application As Figure 2 illustrates, we won't have a low CPU usage now—just the opposite. Even if it is not slow, creating and destroying threads is not optimum. If the operations performed by the thread are not complex, the extra time it takes to create and destroy threads can severely affect the final response time. Another point is the huge impact of these threads in stress conditions. Having all the requests executing at once on different threads would cause the CPU to reach 100% and most of the time would be wasted in context switching, even more than processing the request itself. Typical behaviors in this kind of system are an exponential increment of response time with the number of requests, and a high usage of CPU privileged time (this time can be viewed with the Task Manager and is affected by context switches between threads). An optimum implementation is based on a hybrid of the previous two illustrations and introduces the concept of thread pool. When a request arrives, the application adds it to an incoming queue. A group of threads retrieves requests from this queue and processes them; as each thread is freed up, another request is executed from the queue. This schema is shown in the following figure: Figure 3. Server application using a thread pool In this example, we use a thread pool of two threads. When three requests arrive, they are immediately placed in the queue waiting to be processed; because both threads are free, the first two requests begin to execute. Once the process of any of these requests is finished, the free thread takes the third request and executes it. In this scenario, there is no need to create or destroy threads for each request; the threads are recycled between them. If the implementation of this thread pool is efficient, it will be able to add or remove threads from the pool for best performance. For example, when the pool is executing two requests and the CPU doesn't reach 50% utilization, it means that the executed requests are waiting for events or doing some kind of I/O operation. The pool can detect this situation and increase the number of threads so that more requests can be processed at the same time. In the opposite case when the CPU reaches 100% utilization, the pool decreases the number of threads to get more real CPU time without wasting it in context switches. Thread Pool in .NET Based on the above example, it is crucial to have an efficient implementation of the thread pool in enterprise applications. Microsoft realized this in the development of the .NET Framework; included in the heart of the system is an optimum thread pool ready for use. This pool is not only available to applications that want to use it, but it is also integrated with most of the classes included in the Framework. In addition, there is important functionality of .NET built on the same pool. For example, .NET Remoting uses it to process requests on remote objects. When a managed application is executed, the runtime offers a pool of threads that will be created the first time the code accesses it. This pool is associated with the physical process where the application is running, an important detail when you are using the functionality available in the .NET infrastructure to run several applications (called application domains) within the same process. If this is the case, one bad application can affect the rest within the same process because they all use the same pool. You can use the thread pool or retrieve information about it through the class ThreadPool, in the System.Threading namespace. If you take a look at this class, you will see that all the members are static and there is no public constructor. This makes sense, because there's only one pool per process and we cannot create a new one. The purpose of this limitation is to centralize all the asynchronous programming in the same pool, so that we do not have a third-party component that creates a parallel pool that we cannot manage and whose threads are degrading our performance. Executing Functions on the Pool The ThreadPool.QueueUserWorkItem method allows us to launch the execution of a function on the system thread pool. Its declaration is as follows: The first parameter specifies the function that we want to execute on the pool. Its signature must match the delegate WaitCallback: The state parameter allows any information to be passed to the method and it is specified in the call to QueueUserWorkItem. Let's see the implementation of our application for the hardware store with the new concepts: using System; using System.Threading; namespace ThreadPoolTest { class MainApp { static void Main() { WaitCallback callBack; callBack = new WaitCallback(PooledFunc); ThreadPool.QueueUserWorkItem(callBack, "Is there any screw left?"); ThreadPool.QueueUserWorkItem(callBack, "How much is a 40W bulb?"); ThreadPool.QueueUserWorkItem(callBack, "Decrease stock of monkey wrench"); Console.ReadLine(); } static void PooledFunc(object state) { Console.WriteLine("Processing request '{0}'", (string)state); // Simulation of processing time Thread.Sleep(2000); Console.WriteLine("Request processed"); } } } In this case, just to simplify the example, we have created a static method inside the main class that processes the requests. Because of the flexibility of delegates, we can specify any instance method to process requests, provided that it has the same signature as the delegate. In the example, the method implements a delay of two seconds with a call to Thread.Sleep, simulating the processing time. If you compile and execute the last application you will see the following output: Notice that all the requests have been processed on different threads in parallel. We can see it in more detail by adding the following code to both functions: // Main method Console.WriteLine("Main thread. Is pool thread: {0}, Hash: {1}", Thread.CurrentThread.IsThreadPoolThread, Thread.CurrentThread.GetHashCode()); // Pool method Console.WriteLine("Processing request '{0}'." + " Is pool thread: {1}, Hash: {2}", (string)state, Thread.CurrentThread.IsThreadPoolThread, Thread.CurrentThread.GetHashCode()); We have added a call to Thread.IsThreadPoolThread. This property returns True if the target thread belongs to the thread pool. In addition, we show the result of GetHashCode method from the current thread; this gives us a unique value with which to identify the executing thread. Take a look to the output now: Main thread. Is pool thread: False, Hash: 2 Processing request 'Is there any screw left?'. Is pool thread: True, Hash: 4 Processing request 'How much is a 40W bulb?'. Is pool thread: True, Hash: 8 Processing request 'Decrease stock of monkey wrench '. Is pool thread: True, Hash: 9 Request processed Request processed Request processed You can see how all of our requests execute on different threads belonging to the system pool thread. Launch the example again and notice the CPU utilization of your system. If you don't have any other application running in the background, it should be at almost 0%; because the only processing that is being done is suspending the execution for two seconds. Let's modify the application. This time we don't suspend the thread that is processing the request; instead we will keep our system very busy. To do this, we can build a loop executing two seconds into each request using Environment.TickCount. This property returns the elapsed time in milliseconds since the last reboot of the system. Replace the "Thread.Sleep(2000)" line with the following code: Now examine the CPU utilization from the Task Manager, and you will see that the application utilizes 100% of CPU time. Take a look at the output of our application: Notice that the third request is not processed until the first one finishes, and it reuses thread number 7 for its execution. The reason is that the thread pool detects that the CPU is at 100% and it decides to wait until a thread is free, without creating a new one. This way there are less context switches and overall performance is better. Using Timers If you have developed Microsoft Win32® applications, you know the function SetTimer is part of its API. With this function you can specify a window that receives WM_TIMER messages sent by the system in a given period. The first problem encountered with this implementation is that you need a window to receive the notifications, so you cannot use it in console applications. In addition, messaging-based implementations are not accurate, and the situation can be even worse if your application is busy processing other messages. An important improvement over Win32-based timers is the creation of a different thread that sleeps a specified time and notifies a callback function in .NET. With this, our timer does not need the Microsoft Windows® messaging system, so it's more accurate and can be used in console-based applications. The following code shows a possible implementation of this technique: class MainApp { static void Main() { MyTimer myTimer = new MyTimer(2000); Console.ReadLine(); } } class MyTimer { int m_period; public MyTimer(int period) { Thread thread; m_period = period; thread = new Thread(new ThreadStart(TimerThread)); thread.Start(); } void TimerThread() { Thread.Sleep(m_period); OnTimer(); } void OnTimer() { Console.WriteLine("OnTimer"); } } This code is commonly used in Win32 applications. Each timer creates a separate thread that waits the specified time, calling after that a callback function. As you can see, the cost of this implementation is very high; if our application uses several timers, the number of threads increases with them. Now that we have .NET providing a thread pool, we can change the waiting function to a request to the pool. Even if this is perfectly valid and it would make the performance better, we will encounter two problems: - If the pool is full (all its threads are being used), the request waits in the queue and the timer is no longer accurate. - If several timers are created, the thread pool is busy waiting for them to expire. To avoid these problems, the .NET Framework thread pool offers the possibility of time-dependent requests. With this functionality, we can have hundreds of timers without using any thread—it's the pool itself that will process the request once the timer expires. This feature is available in two different classes: - System.Threading.Timer A simple version of a timer; it allows the developer to specify a delegate for its periodic execution on the pool. - System.Timers.Timer A component version of System.Threading.Timer; it can be inserted in a form and allows the developer to specify the executed function in terms of events. It's important to understand the differences between the aforementioned two classes and another one named System.Windows.Forms.Timer. This class wraps the counters we had in Win32 based on Windows messages. Use this class only if you do not plan to develop a multithreaded application. For the next example, we will use the System.Threading.Timer class, the simplest implementation of a timer. We only need the constructor, defined as follows: With the first parameter (callback), we can specify the function that we want to execute periodically; the second parameter, state, is a generic object passed to the function; the third parameter, dueTime, is the delay until the counter is started; and last parameter, period, is the number of milliseconds between executions. The below example creates two timers, timer1 and timer2: class MainApp { static void Main() { Timer timer1 = new Timer(new TimerCallback(OnTimer), 1, 0, 2000); Timer timer2 = new Timer(new TimerCallback(OnTimer), 2, 0, 3000); Console.ReadLine(); } static void OnTimer(object obj) { Console.WriteLine("Timer: {0} Thread: {1} Is pool thread: {2}", (int)obj, Thread.CurrentThread.GetHashCode(), Thread.CurrentThread.IsThreadPoolThread); } } The output will be the following: As you can see, all the functions associated with both timers are executed on the same thread (ID = 2), minimizing the resources used by the application. Execution Based on Synchronization Objects In addition to timers, the .NET thread pool allows the execution of functions based upon synchronization objects. To share resources among threads within the multithreaded environment, we need to use .NET synchronization objects. If we did not have a pool, threads would block waiting for the event to be signaled. As I mentioned before, this increases the total number of threads in the application, as the result it requires additional system resources and CPU. The thread pool allows us to queue requests that will only be executed when a specified synchronization object is signaled. While this does not happen, the function does not need any thread, so optimization is assured. The ThreadPool class offers the following method: The first parameter, waitObject, can be any object derived from WaitHandle: - Mutex - ManualResetEvent - AutoResetEvent As you can see, only system synchronization objects can be used—that is, objects derived from WaitHandle—and you cannot use any other synchronization mechanism, like monitors or reader-writer locks. The rest of the parameters allow us to specify a function that will be executed once the object is signaled (callBack); a state that will be passed to this function (state); the maximum time that the pool waits for the object (millisecondsTimeOutInterval) and a flag indicating if the function has to be executed once or whenever the object is signaled (executeOnlyOnce). The delegate declaration used for the callback function is the following: This function is called if the timedOut parameter set with the maximum time expires without the synchronization object being signaled. The following example uses a manual event and a Mutex to signal the execution of a function on the thread pool: class MainApp { static void Main(string[] args) { ManualResetEvent evt = new ManualResetEvent(false); Mutex mtx = new Mutex(true); ThreadPool.RegisterWaitForSingleObject(evt, new WaitOrTimerCallback(PoolFunc), null, Timeout.Infinite, true); ThreadPool.RegisterWaitForSingleObject(mtx, new WaitOrTimerCallback(PoolFunc), null, Timeout.Infinite, true); for(int i=1;i<=5;i++) { Console.Write("{0}...", i); Thread.Sleep(1000); } Console.WriteLine(); evt.Set(); mtx.ReleaseMutex(); Console.ReadLine(); } static void PoolFunc(object obj, bool TimedOut) { Console.WriteLine("Synchronization object signaled, Thread: {0} Is pool: {1}", Thread.CurrentThread.GetHashCode(), Thread.CurrentThread.IsThreadPoolThread); } } The output will show again that both functions will be executed on the pool and on the same thread: Asynchronous I/O Operations The most common scenario for a thread pool is I/O (Input/Output) operations. Most applications need to wait for disk reads, data sent to sockets, Internet connections and so on. All of these operations have something in common, that is they do not require CPU time while they are performed. .NET Framework offers in all of its I/O classes the possibility of performing operations asynchronously. When the operation is finished, the specified function is executed on the thread pool. The performance with this feature can be much better, especially if we have several threads performing I/O operations, as in most of the server-based applications. In this first example, we will write a file asynchronously to the hard drive. Take a look to the FileStream constructor used: The last parameter is the interesting one. We should set useAsync for our file to perform asynchronous operations. If we do not do this, even if we can use asynchronous functions, they are executed on the calling thread blocking its execution. The following example illustrates a file write with the FileStream BeginWrite method, specifying a callback function that will be executed on the thread pool once the operation finishes. Notice that we can access the IAsyncResult interface any time, which can be used to know the current status of the operation. We use its CompletedSynchronously property to indicate whether the operation is performed asynchronously, and the IsCompleted property to set a flag when the operation finishes. IAsyncResult offers many others interesting properties, such as AsyncWaitHandle, a synchronization object that will be signaled once the operation is performed. class MainApp { static void Main() { const string fileName = "temp.dat"; FileStream fs; byte[] data = new Byte[10000]; IAsyncResult ar; fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None, 1, true); ar = fs.BeginWrite(data, 0, 10000, new AsyncCallback(UserCallback), null); Console.WriteLine("Main thread:{0}", Thread.CurrentThread.GetHashCode()); Console.WriteLine("Synchronous operation: {0}", ar.CompletedSynchronously); Console.ReadLine(); } static void UserCallback(IAsyncResult ar) { Console.Write("Operation finished: {0} on thread ID:{1}, is pool: {2}", ar.IsCompleted, Thread.CurrentThread.GetHashCode(), Thread.CurrentThread.IsThreadPoolThread); } } The output will show us that the operation is performed asynchronously; once the operation is finished, the user function is executed on the thread pool. In the case of sockets, using the thread pool is even more important because its I/O operations are usually slower than disks. The procedure is the same as before, the Socket class offers methods to perform any operation asynchronously: - BeginReceive - BeginSend - BeginConnect - BeginAccept If your server application uses sockets to communicate with the other clients, always use these methods. This way, instead of needing a thread for each connected client, all the operations are performed asynchronously on the thread pool. The following example uses another class that supports asynchronous operations, HttpWebRequest. With this class, we can establish a connection with a Web server on the Internet. The method used now is called BeginGetResponse, but in this case there's an important difference. In the last example, we wrote a file to disk and we didn't need any results from the operation. However, we now need the response from the Web server when the operation is finished. In order to retrieve this information, all the .NET Framework classes that offer I/O operations have a pair of methods for each one. In the case of HttpWebRequest, the pair is BeginGetResponse and EndGetResponse. With the End version, we can retrieve the result of the operation. In our case, EndGetResponse will return the response from the Web server. Even if EndGetResponse can be called any time, in our example we do it using the callback function, just when we know that the asynchronous request is done. If we call EndGetResponse before that, the call will block until the operation is finished. In the following example, we send a request to Microsoft Web and show the size of the received response: class MainApp { static void Main() { HttpWebRequest request; IAsyncResult ar; request = (HttpWebRequest)WebRequest.CreateDefault( new Uri("")); ar = request.BeginGetResponse(new AsyncCallback(PoolFunc), request); Console.WriteLine("Synchronous: {0}", ar.CompletedSynchronously); Console.ReadLine(); } static void PoolFunc(IAsyncResult ar) { HttpWebRequest request; HttpWebResponse response; Console.WriteLine("Response received on pool: {0}", Thread.CurrentThread.IsThreadPoolThread); request = (HttpWebRequest)ar.AsyncState; response = (HttpWebResponse)request.EndGetResponse(ar); Console.WriteLine(" Response size: {0}", response.ContentLength); } } The output will show at the beginning the following message, indicating that the operation is being performed asynchronously: After a while, when the response is received, the following output will be shown: As you can see, once the response is received, the callback function is executed on the thread pool. Monitoring the Pool The ThreadPool class offers two methods used to query the status of the pool. With the first one we can retrieve the number of free threads: As you can see there are two different kinds of threads: - WorkerThreads The worker threads are part of the standard system pool. They are standard threads managed by the .NET Framework and most of the functions are executed on them, specifically user requests (QueueUserWorkItem method), functions based on synchronization objects (RegisterWaitForSingleObject method), and timers (Timer classes). - CompletionPortThreads This kind of thread is used for I/O operations, whenever is possible. Windows NT, Windows 2000, and Windows XP offer an object specialized on asynchronous operations, called IOCompletionPort. With the API associated with this object we can launch asynchronous I/O operations managed with a thread pool by the system, in an efficient way and with few resources. However, Windows 95, Windows 98, and Windows Me have some limitations with asynchronous I/O operations. For example, IOCompletionPorts functionality is not offered and asynchronous operations on some devices, such as disks and mail slots, cannot be performed. Here you can see one of the greatest features of the .NET Framework: compile once and execute on multiple systems. Depending on the target platform, the .NET Framework will decide to use the IOCompletionPorts API or not, maximizing the performance and minimizing the resources. This section includes an example using the socket classes. In this case we are going to establish a connection asynchronously with the local Web server and send a Get request. With this, we can easily identify both kinds of threads. using System; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text; namespace ThreadPoolTest { class MainApp { static void Main() { Socket s; IPHostEntry hostEntry; IPAddress ipAddress; IPEndPoint ipEndPoint; hostEntry = Dns.Resolve(Dns.GetHostName()); ipAddress = hostEntry.AddressList[0]; ipEndPoint = new IPEndPoint(ipAddress, 80); s = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); s.BeginConnect(ipEndPoint, new AsyncCallback(ConnectCallback),s); Console.ReadLine(); } static void ConnectCallback(IAsyncResult ar) { byte[] data; Socket s = (Socket)ar.AsyncState; data = Encoding.ASCII.GetBytes("GET /\n"); Console.WriteLine("Connected to localhost:80"); ShowAvailableThreads(); s.BeginSend(data, 0,data.Length,SocketFlags.None, new AsyncCallback(SendCallback), null); } static void SendCallback(IAsyncResult ar) { Console.WriteLine("Request sent to localhost:80"); ShowAvailableThreads(); } static void ShowAvailableThreads() { int workerThreads, completionPortThreads; ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); Console.WriteLine("WorkerThreads: {0}," + " CompletionPortThreads: {1}", workerThreads, completionPortThreads); } } } If you run this program on Microsoft Windows NT, Windows 2000, or Windows XP, you will see the following output: As you can see, connecting with a socket uses a worker thread, while sending the data uses a CompletionPort. This following sequence is followed: - We get the local IP address and connect to it asynchronously. - Socket performs the asynchronous connection on a worker thread, since Windows IOCompletionPorts cannot be used to establish connections on sockets. - Once the connection is established, the Socket class calls the specified function ConnectCallback. This callback shows the number of available threads on the pool, this way we can see that it is being executed on a worker thread. - An asynchronous request is sent from the same function ConnectCallback. We use for this the BeginSend method, after encoding the Get / request in ASCII code. - Send/receive operations on a socket can be performed asynchronously with an IOCompletionPort, so when our request is done, the callback function SendCallback is executed on a CompletionPort thread. We can check this because the function itself shows the number of available threads and we can see that only those corresponding to CompletionPorts have been decreased. If we run the same code on a Windows 95, Windows 98, or Windows Me platform, the result will be the same on the connection, but the request will be sent on a worker thread, instead of a CompletionPort. The important thing you should learn about this is that the Socket class always uses the best available mechanism, so you can develop your application without taking into account the target platform. You have seen in the example that the maximum number of available threads is 25 for each type (exactly 25 times the number of processors in your machine). We can retrieve this number using the GetMaxThreads method: Once this maximum value is reached, no new threads are created and requests are queued. If you see all the methods declared in the ThreadPool class, you will notice that none of them allows us to change this maximum value. As we mentioned before, the thread pool is a unique shared resource per process; that is why it is impossible for an application domain to change its configuration. Imagine the consequences if a third-party component changes the maximum number of threads on the pool to 1, the entire application can stop working and even other application domains in the same process will be affected. For the same reason, systems that host the common language runtime do have the possibility to change the configuration. For example, Microsoft ASP.NET allows the Administrator to change the maximum number of threads available on the pool. Deadlocks Before starting to use the thread pool in your applications you should know one additional concept: deadlocks. A bad implementation of asynchronous functions executed on the pool can make your entire application hang. Imagine a method in your code that needs to connect via socket with a Web server. A possible implementation is opening the connection asynchronously with the Socket class' BeginConnect method and wait for the connection to be established with the EndConnect method. The code will be as follows: class ConnectionSocket { public void Connect() { IPHostEntry ipHostEntry = Dns.Resolve(Dns.GetHostName()); IPEndPoint ipEndPoint = new IPEndPoint(ipHostEntry.AddressList[0], 80); Socket s = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); IAsyncResult ar = s.BeginConnect(ipEndPoint, null, null); s.EndConnect(ar); } } So far, so good—calling BeginConnect makes the asynchronous operation execute on the thread pool and EndConnect blocks waiting for the connection to be established. What happens if we use this class from a function executed on the thread pool? Imagine that the size of the pool is just two threads and we launch two asynchronous functions that use our connection class. With both functions executing on the pool, there is no room for additional requests until the functions are finished. The problem is that these functions call our class' Connect method. This method launches again an asynchronous operation on the thread pool, but since the pool is full, the request is queued waiting any thread to be free. Unfortunately, this will never happen because the functions that are using the pool are waiting for the queued functions to finish. The conclusion: our application is blocked. We can extrapolate this behavior for a pool of 25 threads. If 25 functions are waiting for an asynchronous operation to be finished, the situation becomes the same and the deadlock occurs again. In the following fragment of code we have included a call to the last class to reproduce the problem: class MainApp { static void Main() { for(int i=0;i<30;i++) { ThreadPool.QueueUserWorkItem(new WaitCallback(PoolFunc)); } Console.ReadLine(); } static void PoolFunc(object state) { int workerThreads,completionPortThreads; ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); Console.WriteLine("WorkerThreads: {0}, CompletionPortThreads: {1}", workerThreads, completionPortThreads); Thread.Sleep(15000); ConnectionSocket connection = new ConnectionSocket(); connection.Connect(); } } If you run the example, you see how the threads on the pool are decreasing until the available threads reach 0 and the application stops working. We have a deadlock. In general, a deadlock can appear whenever a pool thread waits for an asynchronous function to finish. If we change the code so that we use the synchronous version of Connect, the problem will disappear: If you want to avoid deadlocks in your applications, do not ever block a thread executed on the pool that is waiting for another function on the pool. This seems to be easy, but keep in mind that this rule implies two more: - Do not create any class whose synchronous methods wait for asynchronous functions, since this class could be called from a thread on the pool. - Do not use any class inside an asynchronous function if the class blocks waiting for asynchronous functions. If you want to detect a deadlock in your application, check the available number of threads on the thread pool when your system is hung. The lack of available threads and CPU utilization near 0% are clear symptoms of a deadlock. You should monitor your code to identify where a function executed on the pool is waiting for an asynchronous operation and remove it. About Security If you take a look to the ThreadPool class, you see that there are two methods that we haven't seen yet: UnsafeQueueUserWorkItem and UnsafeRegisterWaitForSingleObject. To fully understand the purpose of these methods we have to remember first how code security works in the .NET Framework. Security in Windows is focused on resources. The operating system itself allows setting permissions on files, users, registry keys or any other resource of the system. This approach is perfect for applications trusted by the user, but it has limitations when the user does not trust the applications he uses, for example those downloaded from the Internet. In this case, once the user installs the application, it can perform any operation allowed by his permissions. For example, if the user is able to delete all the shared files of his company, any application downloaded from the Internet could do it, too. .NET offers security applied to the application, not to the user. This means that, within the limit of the user's permissions, we can restrict resources to any execution unit (Assembly). With the MMC snap-in, we can define groups of assemblies by several conditions and set different security policies for each group. A typical example of this is restricting the disk access to applications downloaded from the Internet. For this to work, the .NET Framework must maintain a calling stack between different assemblies. Imagine an application that has no permission to access to disk, but it calls a class library with full access to the system. When the second assembly performs an operation to disk, the set of permissions associated with it allows the action, but the permissions applied to the calling assembly do not. The .NET Framework must check not only the current assembly permissions, but also the permissions applied to the entire calling stack. This stack is highly optimized, but they add an overhead to calls between functions of different assemblies. UnsafeQueueUserWorkItem and UnsafeRegisterWaitForSingleObject are equivalent functions to QueueUserWorkItem and RegisterWaitForSingleObject, but the unsafe versions do not maintain the calling stack for the asynchronous functions they perform. So, unsafe versions are faster but the callback functions will be executed only with the current assembly security policies, losing all the permissions applied to the calling stack of assemblies. My recommendation is that you should use these unsafe functions with extreme caution and only in situations where the performance is very important and the security is controlled. For example, you can use unsafe versions if you are building an application without the possibility of being called from another assembly or where the policies applied to it allows only another well-known assembly to use it. You should never use these methods if you are developing a class library that can be used by any third-party application, because they could use your library to gain access to limited resources of the system. In the following example, you can see the risk of using UnsafeQueueUserWorkItem. We will build two separated assemblies, in the first one we will use the thread pool to create a file and we will export a class so that this operation can be performed from another assembly: using System; using System.Threading; using System.IO; namespace ThreadSecurityTest { public class PoolCheck { public void CheckIt() { ThreadPool.QueueUserWorkItem(new WaitCallback(UserItem), null); } private void UserItem(object obj) { FileStream fs = new FileStream("test.dat", FileMode.Create); fs.Close(); Console.WriteLine("File created"); } } } The second assembly references the first one and it uses the CheckIt method to create the file: Compile both assemblies and run the main application. By default, your system is configured to allow disk operations to be performed, so the application works perfectly and the file is generated: Now open the Microsoft .NET Framework configuration—in this case, to simplify the example, we create only a code group associated with the main application. To do this, expand the Runtime Security Policy/Machine/Code Groups/All_Code node and add a new group called ThreadSecurityTest. In the wizard, select the Hash condition and import the hash of our application. Now set an Internet permission level and force it with the This policy level will only have the permissions from the permission set associated with this code group option. Run the application again and see what happens: Our policy has worked and the application cannot create the file. Notice that this is possible because the .NET Framework is maintaining the calling stack for us, since the library that created the file had full access to the system. Now change the code of the library and use the UnsafeQueueUserWorkItem method instead of QueueUserWorkItem. Compile the assembly again and run the main application. The output will now be: Even if our application does not have enough permission to access the disk, we have created a library that exposes this functionality to the whole system without maintaining the calling stack. Remember the golden rule: Use unsafe functions only when your code cannot be called from other applications or when you restrict the access to well-known assemblies. Conclusion In this article, we have seen why we need a thread pool to optimize the resources and CPU usage in our server applications. We have studied how a thread pool has to be implemented; taking into account many factors like percentage used of CPU, queued requests, or number of processors in the system. The .NET Framework offers a fully functional implementation of thread pool ready to be used by our application and tightly integrated with the rest of classes of the .NET Framework. This pool is highly optimized, minimizing the privileged CPU time utilization with minimal resources, and is always adapted to the target operating system. Because of the integration with the Framework, most of the classes offered by it use the thread pool internally, offering to the developers a centralized place to manage and monitor the pool in their applications. Third-party components are encouraged to use the thread pool; this way their clients can use all the functionality provided, allowing the execution of user functions, timers, I/O operations or synchronization objects. If you are developing server applications, whenever possible use the thread pool in your request processing system. Otherwise, if your development is a library that can be used by a server application, always offer the possibility of asynchronous processing on the system thread pool. For More Information - .NET Framework Class Library: ThreadPool Class - .NET Framework Developer's Guide: Threading - Multithreaded Programming with Visual Basic .NET - .NET Framework Developer's Guide: Asynchronous File I/O - .NET Framework Developer's Guide: Including Asynchronous Calls - .NET Framework Developer's Guide: Accessing the Internet
http://msdn.microsoft.com/en-us/library/ms973903.aspx
CC-MAIN-2014-41
refinedweb
6,204
54.02
My DP implementation of max sum is below but i need sequence which is giving max sum instead of max sum value. public int maxSum(int arr[]) { int excl = 0; int incl = arr[0]; for (int i = 1; i < arr.length; i++) { int temp = incl; incl = Math.max(excl + arr[i], incl); excl = temp; } return incl; } So 3 2 7 10 should return (3 and 10) or 3 2 5 10 7 should return (3, 5 and 7) or {5, 5, 10, 100, 10, 5} will return (5, 100 and 5) or {1, 20, 3} will return 20 i exactly want this problem solution but return value i need is sequence of elements included in max sum instead of max sum value Update:-no need to handle -ve elements because all elements in sequence(Array) are +ve
http://codeforces.com/blog/abhi55
CC-MAIN-2018-51
refinedweb
137
55.61
table of contents NAME¶ memcpy - copy memory area SYNOPSIS¶ #include <string.h> void *memcpy(void *dest, const void *src, size_t n); DESCRIPTION¶ The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas must not overlap. Use memmove(3) if the memory areas do overlap. RETURN VALUE¶ The memcpy() function returns a pointer to dest. ATTRIBUTES¶ For an explanation of the terms used in this section, see attributes(7). CONFORMING TO¶ POSIX.1-2001, POSIX.1-2008, C89, C99, SVr4, 4.3BSD. NOTES¶¶ bcopy(3), bstring(3), memccpy(3), memmove(3), mempcpy(3), strcpy(3), strncpy(3), wmemcpy(3) COLOPHON¶ This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
https://manpages.debian.org/testing/manpages-dev/memcpy.3.en.html
CC-MAIN-2022-05
refinedweb
140
68.77
/// <summary> /// Get customers data /// </summary> /// <param name="s"></param> /// <returns></returns> [WebMethod] public List<Customer> GetCustomers(string s) { return new DataAccessLayer.DataAccessLayer().GetCustomers(s); } Note that in order to use List<T>, you will need to use System.Collections.Generic namespace. In the above code snippet, I am using GetCustomer() method of a DataAccessLayer class to return customers data. This method (GetCustomer method) is accepting a string parameter to filter the customer whose name starts with the parameter value (This is just a method with added functionality, do not get involve into it to avoid any confusion, just assume that this will return list of customers data.) Let's see the GetCustomer() method of DataAccessLayer class code. /// <summary> /// Get customers /// </summary> /// <returns></returns> public List<Customer> GetCustomers(string startsWith) { List<Customer> list = new List<Customer>(); using (SqlConnection conn = new SqlConnection("[WriteConnectionString]")) { conn.Open(); using (SqlCommand dCmd = new SqlCommand("vs_GetCustomersStartingWith", conn)) { SqlParameter prms = new SqlParameter("@startsWith", SqlDbType.VarChar, 5); prms.Value = startsWith + "%"; dCmd.Parameters.Add(prms); dCmd.CommandType = CommandType.StoredProcedure; using (SqlDataReader reader = dCmd.ExecuteReader()) { while (reader.Read()) { list.Add(new Customer { CustomerID = reader["CustomerID"].ToString(), Address = reader["Address"].ToString(), City = reader["City"].ToString(), Country = reader["Country"].ToString(), ContactName = reader["ContactName"].ToString() }); } } } conn.Close(); // lets close explicitely } return list; } Get solutions of the .NET problems with video explanations, .pdf and source code in .NET How to's. Note: Above method is a sample method, you should customize it based on your requirement. In the above method, I am using a stored procedure to get the data and passing parameter to filter the data. I am instantiating a Customer object that has CustomerID, Address, City, Country, ContactName as property and setting its value inside the while loop. (If you are getting confused, just understand that this method will return list of data having Customer objects into it.) You can run the web project and try this web service. For me, the url of the web service looks like "" So till now, we have our Web Service ready to be called from Silverlight. Let's design Silverlight page now. Create a .xaml file and delete all code except <UserControl> and place following code snippet inside <UserControl> tag. <Grid x: <Canvas> <TextBlock Text="Search" Canvas.</TextBlock> <TextBox x:</TextBox> <Button Content=" Get Data from Web Service " Click="Button_Click" Canvas.</Button> <TextBlock x:</TextBlock> <data:DataGrid x: </data:DataGrid> </Canvas> </Grid> In the above code snippet, I have done following: In the SilverlightApplication project, right click and click "Add Service Reference ....", Place the url of the web service in the Address box and click Go. You should see your Web Service in the Services box. You can keep the default namespace or change it as per your need. Click OK. You will notice that the reference of your web service will be done (look out the Service References folder). Also notice that ServiceReferences.ClientConfig file will be created. This ClientConfig file contains other necessary tag to reference the web service and apart from that it also contains the endpoint tag that has address attribute. This attribute has the url of the web service (we need to change this url when hosting our application on the server, we shall talk about it later in this article). // Fires on click event private void Button_Click(object sender, RoutedEventArgs e) { // call data web service ServiceReference2.DataWebServiceSoapClient dataService = new SilverlightApplication.ServiceReference2.DataWebServiceSoapClient(); dataService.GetCustomersCompleted += new EventHandler<SilverlightApplication.ServiceReference2.GetCustomersCompletedEventArgs>(dataService_Completed); dataService.GetCustomersAsync(txtSearch.Text.Trim()); // call simple web service lblWaiting.Text = "Status: Waiting ..."; } // event that will fire after completion of the web service call private void dataService_Completed(object sender, ServiceReference2.GetCustomersCompletedEventArgs e) { ServiceReference2.Customer[] list = e.Result; dataGrid1.ItemsSource = list; lblWaiting.Text = "Status: Done"; if (list.Length.Equals(0)) lblWaiting.Text = "No records found."; else lblWaiting.Text = list.Length + " records found."; } In the Button_Click method, I have instantiated the web service first. Then attaching method dataService_Completed method with the GetCustomersCompleted event handler. Note that this event handler name is based on your web service method name. (If you web service method name will be GetMyData, this event handler name will become GetMyDataCompleted, same applies to then following line, GetCustomersAsync in this case this method will become GetMyDataAsync). In the next line, I am passing filter parameter to the GetCustomersAsync method. As specified above, once the method call will be completed, dataService_Completed method will fire. In this method, I am getting the result into the array of Customer object and specifying the ItemsSource property of the DataGrid. Just to display the status of what is happening in between, I have also set the value of lblWaiting (TextBlock) in this as well as Button_Click method. Thats it!, just run your application and try clicking the "Get Data From Web Service" button after entering filter criteria, you will see that data will be populated to the DataGrid. To host your Silverlight application on the server, you need to place the ClientBin/xxx.xap file on your server. Create the subdirectory "ClientBin" under root and place your .xap file. But notice that the web service address on your development machine (local) and live server will be different. So if you directly put your local .xap file on the server, it will not work. Lets see what sort of things are necessary to do here. Cool !!! so in this article, we learnt how to create and consume ASP.NET web service in Silverlight. Please let me know your feedback or suggestions. Thanks for reading and happy coding !!! Latest Articles Latest Articles from SheoNarayan Login to post response
http://www.dotnetfunda.com/articles/show/218/consuming-aspnet-web-service-in-silverlight
CC-MAIN-2018-34
refinedweb
922
51.14
Flip, and record “tails” and “heads” (bolded the flips after a heads). You flip T T H T and record “tails” from the 4th position. etc. For each of these result sets, compute the percentage of heads flips. In Scala, import scala.util.Random.nextBoolean // Consider true = Heads, false = Tails. val numberOfFlips = 4 def flipCoins() = Seq.fill(numberOfFlips)(nextBoolean) // Consider the results _after_ a head is flipped def resultsAfterAHeads(l: Seq[Boolean]) = l.sliding(2).collect { case Seq(true, n) => n }.toSeq // Determine the % of flips that are heads of a non-empty list def percentHeads(l: Seq[Boolean]) = { val (heads, tails) = l.sorted.partition(s => s) heads.length.toDouble / (heads.length + tails.length).toDouble } // Flip the coins, collect the results after a heads, compute % heads def trial = resultsAfterAHeads(flipCoins()) match { case Seq() => None case nonEmpty => Some(percentHeads(nonEmpty)) } Run this trial 1,000,000 times, and compute the mean of the percentage of heads. def runTrials = Stream.continually(trial).flatten def mean(s: Seq[Double]) = s.sum / s.length mean(runTrials.take(1000000)) // res0: Double = 0.4050016666669707 How could this be? After a heads is flipped, another heads is only flipped 41% of the time? Perhaps four flips per set isn't enough? You try 10. val numberOfFlips = 10 // ... mean(runTrials.take(1000000)) // res1: Double = 0.44557722142809525 With two million samples of empirical evidence that you can exploit randomness, you head to the race tracks… Obviously there’s no bias in a fair coin. What’s actually happening is that we’re considering the 4-flip trial as the unit of analysis, which over-represents tails in several of the cases. Consider when two heads are flipped. The possible outcomes are—with p(H|H) (probability of heads, given a previous heads): TTHH (1), THTH (0), THHT (½), HTTH (0), HTHT (0), HHTT (½), resulting in an average p(H|H) of ⅓. The one H cases are worse: the average p(H|H) is 0. Still not convinced? Read more about this “effect,” and implications related to Gambler’s Fallacy at Surprised by the Gambler's and Hot Hand Fallacies? A Truth in the Law of Small Numbers by Joshua Benjamin Miller & Adam Sanjurjo.
https://andrewconner.com/posts/gamblers-verity/
CC-MAIN-2020-10
refinedweb
366
60.31
Command options / Setting tags¶ Phono3py is operated with command options or with a configuration file that contains setting tags. In this page, the command options are explained. Most of command options have their respective setting tags. A configuration file with setting tags like phonopy can be used instead of and together with the command options. The setting tags are mostly equivalent to the respective most command options, but when both are set simultaneously, the command options are preferred. An example of configuration (e.g., saved in a file setting.conf) is as follow: DIM = 2 2 2 DIM_FC2 = 4 4 4 PRIMITIVE_AXES = 0 1/2 1/2 1/2 0 1/2 1/2 1/2 0 MESH = 11 11 11 BTERTA = .TRUE. NAC = .TRUE. READ_FC2 = .TRUE. READ_FC3 = .TRUE. CELL_FILENAME = POSCAR-unitcell where the setting tag names are case insensitive. This is run by % phono3py setting.conf [comannd options] or % phono3py [comannd options] -- setting.conf - Utilities to create default input files Supercell and primitive cell - - Reciprocal space sampling mesh and grid points, and band indices Brillouin zone integration - - Non-analytical term correction Imaginary part of self energy - Sampling frequency for distribution functions Mode-Gruneisen parameter from 3rd order force constants --fc2( READ_FC2 = .TRUE.) --fc3( READ_FC3 = .TRUE.) --write-gamma( WRITE_GAMMA = .TRUE.) --read-gamma( READ_GAMMA = .TRUE.) --write-gamma-detail( WRITE_GAMMA_DETAIL = .TRUE.) --write-phonon( WRITE_PHONON = .TRUE.) --read-phonon( READ_PHONON = .TRUE.) --write-pp( WRITE_PP = .TRUE.) and --read-pp( READ_PP = .TRUE.) --hdf5-compression(command option only) - - --io(command option only) Input cell file name¶ -c ( CELL_FILENAME)¶ This specifies input unit cell filename. % phono3py -c POSCAR-unitcell ... (many options) Calculator interface¶ --qe ( CALCULATOR = QE)¶ Quantum espresso (pw) interface is invoked. See the detail at Quantum ESPRESSO (pw) & phono3py calculation. --crystal ( CALCULATOR = CRYSTAL)¶ CRYSTAL interface is invoked. See the detail at CRYSTAL & phono3py calculation. --turbomole ( CALCULATOR = TURBOMOLE)¶ TURBOMOLE interface is invoked. See the details at TURBOMOLE & phono3py calculation. Utilities to create default input files¶ These options have no respective configuration file tags. --cf3 (command option only)¶ This is used to create FORCES_FC3 from disp_fc3.yaml and force calculator outputs containing forces in supercells. disp_fc3.yaml has to be located at the current directory. Calculator interface has to be specified except for VASP (default) case. % phono3py --cf3 disp-{00001..00755}/vasprun.xml % phono3py --qe --cf3 supercell_out/disp-{00001..00111}/Si.out --cf3-file (command option only)¶ This is used to create FORCES_FC3 from a text file containing a list of calculator output file names. disp_fc3.yaml has to be located at the current directory. Calculator interface has to be specified except for VASP (default) case. % phono3py --cf3-file file_list.dat where file_list.dat contains file names that can be recognized from the current directory and is expected to be like: disp-00001/vasprun.xml disp-00002/vasprun.xml disp-00003/vasprun.xml disp-00004/vasprun.xml ... The order of the file names is important. This option may be useful to be used together with --cutoff-pair option. --cf2 (command option only)¶ This is used to create FORCES_FC2 similarly to --cf3 option. disp_fc2.yaml has to be located at the current directory. This is optional. Calculator interface has to be specified except for VASP (default) case. FORCES_FC2 is necessary to run with --dim-fc2 option. % phono3py --cf2 disp_fc2-{00001..00002}/vasprun.xml --cfz (command option only)¶ This is used to create FORCES_FC3 and FORCES_FC2 subtracting residual forces combined with --cf3 and --cf2, respectively. Calculator interface has to be specified except for VASP (default) case. In the following example, it is supposed that disp3-00000/vasprun.xml and disp2-00000/vasprun.xml contain the forces of the perfect supercells. In ideal case, these forces are zero, but often they are not. Here, this is called “residual forces”. Sometimes quality of force constants is improved in this way. % phono3py --cf3 disp3-{00001..01254}/vasprun.xml --cfz disp3-00000/vasprun.xml % phono3py --cf2 disp2-{00001..00006}/vasprun.xml --cfz disp2-00000/vasprun.xml --fs2f2 or --force-sets-to-forces-fc2 (command option only)¶ FORCES_FC2 and disp_fc2.yaml are created from phonopy’s FORCE_SETS file. % phono3py --fs2f2 --cfs or --create-force-sets (command option only)¶ Phonopy’s FORCE_SETS is created from FORCES_FC3 and disp_fc3.yaml. % phono3py --cfs In conjunction with –dim-fc2, phonopy’s FORCE_SETS is created from FORCES_FC2 and disp_fc2.yaml instead of FORCES_FC3 and disp_fc3.yaml. % phono3py --cfs --dim-fc2="x x x" Supercell and primitive cell¶ --dim ( DIM)¶ Supercell dimension is specified. See the detail at . --dim-fc2 ( DIM_FC2)¶ Supercell dimension for 2nd order force constants (for harmonic phonons) is specified. This is optional. A larger and different supercell size for 2nd order force constants than that for 3rd order force constants can be specified with this option. Often interaction between a pair of atoms has longer range in real space than interaction among three atoms. Therefore to reduce computational demand, choosing larger supercell size only for 2nd order force constants may be a good idea. Using this option with -d option, the structure files (e.g. POSCAR_FC2-xxxxx or equivalent files for the other interfaces) and disp_fc2.yaml are created. These are used to calculate 2nd order force constants for the larger supercell size and these force calculations have to be done in addition to the usual force calculations for 3rd order force constants. phono3py -d --dim="2 2 2" --dim-fc2="4 4 4" -c POSCAR-unitcell After the force calculations, --cf2 option is used to create FORCES_FC2. phono3py --cf2 disp-{001,002}/vasprun.xml To calculate 2nd order force constants for the larger supercell size, FORCES_FC2 and disp_fc2.yaml are necessary. Whenever running phono3py for the larger 2nd order force constants, --dim-fc2 option has to be specified. fc2.hdf5 created as a result of running phono3py contains the 2nd order force constants with larger supercell size. The filename is the same as that created in the usual phono3py run without --dim-fc2 option. phono3py --dim="2 2 2" --dim_fc2="4 4 4" -c POSCAR-unitcell ... (many options) --pa, --primitive-axes ( PRIMITIVE_AXES)¶ Transformation matrix from a non-primitive cell to the primitive cell. See phonopy PRIMITIVE_AXES tag ( --pa option) at Displacement creation¶ -d ( CREATE_DISPLACEMENTS = .TRUE.)¶ Supercell with displacements are created. Using with --amplitude option, atomic displacement distances are controlled. With this option, files for supercells with displacements and disp_fc3.yaml file are created. --amplitude ( DISPLACEMENT_DISTANCE)¶ Atomic displacement distance is specified. This value may be increased for the weak interaction systems and descreased when the force calculator is numerically very accurate. The default value depends on calculator. See Default displacement distance created. Force constants¶ --cfc or --compact-fc ( COMPACT_FC = .TRUE.)¶ When creating force constants from FORCES_FC3 and/or FORCES_FC2, force constants that use smaller data size are created. The shape of the data array is (num_patom, num_satom) for fc2 and (num_patom, num_satom, num_satom) for fc3, where num_patom and num_satom are the numbers of atoms in primtive cell and supercell. In the full size force constants case, num_patom is replaced by num_satom. Therefore if the supercell dimension is large, this reduction of data size becomes large. If the input crystal structure has centring –pa is necessary to have smallest data size. In this case, --pa option has to be specified on reading. Otherwise phono3py can recognize if fc2.hdf5 and fc3.hdf5 are compact or full automatically. When using with --sym-fc, the calculated results will become slightly different due to imperfect symmetrization scheme that phono3py employs. % phono3py --dim="2 2 2" --cfc --pa="0 1/2 1/2 1/2 0 1/2 1/2 1/2 0" -c POSCAR-unitcell --sym-fc ( FC_SYMMETRY = .TRUE.)¶ Second- and third-order force constants are symmetrized. The index exchange of real space force constantsand translational invariance symmetry are applied in a simple way. This symmetrization just removes drift force constants evenly from all elements and then applies averaging index-exchange equivalent elements. Therefore the different symmetries are not simultaneously enforced. For better symmetrization, it is recommended to use an external force constants calculator like ALM. The symmetrizations for the second and third orders can be independently applied by --sym-fc2 ( SYMMETRIZE_FC2 = .TRUE.) and --sym-fc3r ( SYMMETRIZE_FC3 = .TRUE.), , respectively. --cutoff-fc3 or --cutoff-fc3-distance ( CUTOFF_FC3_DISTANCE)¶ This option is not used to reduce number of supercells with displacements, but this option is used to set zero in elements of given third-order force constants. The zero elements are selected by the condition that any pair-distance of atoms in each atom triplet is larger than the specified cut-off distance. If one wants to reduce number of supercells, the first choice is to reduce the supercell size and the second choice is using --cutoff-pair option. --cutoff-pair or --cutoff-pair-distance ( CUTOFF_PAIR_DISTANCE)¶ This option is only used together with -d option. A cutoff pair-distance in a supercell is used to reduce the number of necessary supercells with displacements to obtain third order force constants. As the drawback, a certain number of third-order-force-constants elements are abandoned or computed with less numerical accuracy. More details are found in the following link: Reciprocal space sampling mesh and grid points, and band indices¶ --mesh ( MESH or MESH_NUMBERS)¶ Mesh sampling grids in reciprocal space are generated with the specified numbers. This mesh is made along reciprocal axes and is always Gamma-centered. Except for that this mesh is always Gamma-centered, this works in the same way as written here,. --gp ( GRID_POINTS)¶ Grid points are specified by their unique indices, e.g., for selecting the q-points where imaginary parts of self energees are calculated. For thermal conductivity calculation, this can be used to distribute its calculation over q-points (see Workload distribution). Indices of grid points are specified by space or comma ( ,) separated numbers. The mapping table between grid points to its indices is obtained by running with --loglevel=2 option. % phono3py --dim="2 2 2" --pa="0 1/2 1/2 1/2 0 1/2 1/2 1/2 0" -c POSCAR-unitcell --mesh="19 19 19" --fc3 --fc2 --br --write-gamma --gp="0 1 2 3 4 5" where --gp="0 1 2 3 4 5" can be also written --gp="0,1,2,3,4,5". --ga option below can be used similarly for the same purpose. --ga ( GRID_ADDRESSES)¶ This is used to specify grid points like --gp option but in their addresses represented by integer numbers. For example with --mesh="16 16 16", a q-point of (0.5, 0.5, 0.5) is given by --ga="8 8 8". The values have to be integers. If you want to specify the point on a path, --ga="0 0 0 1 1 1 2 2 2 3 3 3 ...", where each three values are recogninzed as a grid point. The grid points given by --ga option are translated to grid point indices as given by --gp option, and the values given by --ga option will not be shown in log files. --bi ( BAND_INDICES)¶ Band indices are specified. The output file name will be, e.g., gammas-mxxx-gxx(-sx)-bx.dat where bxbx... shows the band indices used to be averaged. The calculated values at indices separated by space are averaged, and those separated by comma are separately calculated. % phono3py --fc3 --fc2 --dim="2 2 2" --mesh="16 16 16" -c POSCAR-unitcell --nac --gp="34" --bi="4 5, 6" This may be also useful to distribute the computational demand such like that the unit cell is large and the calculation of phonon-phonon interaction is heavy. --wgp (command option only)¶ Irreducible grid point indices and related information are written into ir_grid_points.yaml. This information may be used when we want to distribute thermal conductivity calculation into small pieces or to find specific grid points to calculate imaginary part of self energy, for which –gp option can be used to specify the grid point indices. grid_address-mxxx.hdf5 is also written. This file contains all the grid points and their grid addresses in integers. Q-points corresponding to grid points are calculated divided these integers by sampling mesh numbers for respective reciprocal axes. % phono3py --dim="2 2 2" --pa="0 1/2 1/2 1/2 0 1/2 1/2 1/2 0" -c POSCAR-unitcell --mesh="19 19 19" --wgp --stp (command option only)¶ Numbers of q-point triplets to be calculated for irreducible grid points for specified sampling mesh numbers are shown. This can be used to estimate how large a calculation is. Only those for specific grid points are shown by using with --gp or --ga option. % phono3py --dim="2 2 2" --pa="0 1/2 1/2 1/2 0 1/2 1/2 1/2 0" -c POSCAR-unitcell --mesh="19 19 19" --stp --gp 20 Brillouin zone integration¶ --thm ( TETRAHEDRON = .TRUE.)¶ Tetrahedron method is used for calculation of imaginary part of self energy. This is the default option. Therefore it is not necessary to specify this unless both results by tetrahedron method and smearing method in one time execution are expected. --sigma ( SIGMA)¶ \(\sigma\) value of Gaussian function for smearing when calculating imaginary part of self energy. See the detail at Brillouin zone summation. Multiple \(\sigma\) values are also specified by space separated numerical values. This is used when we want to test several \(\sigma\) values simultaneously. --sigma-cutoff ( SIGMA_CUTOFF_WIDTH)¶ The tails of the Gaussian functions that are used to replace delta functions in the equation shown at –full-pp are cut with this option. The value is specified in number of standard deviation. --sigma-cutoff=5 gives the Gaussian functions to be cut at \(5\sigma\). Using this option scarifies the numerical accuracy. So the number has to be carefully tested. But computation of phonon-phonon interaction strength becomes much faster in exchange for it. --full-pp ( FULL_PP = .TRUE.)¶ For thermal conductivity calculation using the linear tetrahedron method (from version 1.10.5) and smearing method with --simga-cutoff (from version 1.12.3), only necessary elements (i.e., that have non-zero delta functions) of phonon-phonon interaction strength, \(\bigl|\Phi_{-\lambda\lambda'\lambda''}\bigl|^2\), is calculated due to delta functions in calculation of \(\Gamma_\lambda(\omega)\), But using this option, full elements of phonon-phonon interaction strength are calculated and averaged phonon-phonon interaction strength (\(P_{\mathbf{q}j}\), see –ave-pp) is also given and stored. Method to solve BTE¶ --br ( BTERTA = .TRUE.)¶ Run calculation of lattice thermal conductivity tensor with the single mode relaxation time approximation (RTA) and linearized phonon Boltzmann equation. Without specifying --gp (or --ga) option, all necessary phonon lifetime calculations for grid points are sequentially executed and then thermal conductivity is calculated under RTA. The thermal conductivity and many related properties are written into kappa-mxxx.hdf5. With --gp (or --ga) option, phonon lifetimes on the specified grid points are calculated. To save the results, --write-gamma option has to be specified and the physical properties belonging to the grid points are written into kappa-mxxx-gx(-sx).hdf5. --lbte ( LBTE = .TRUE.)¶ Run calculation of lattice thermal conductivity tensor with a direct solution of linearized phonon Boltzmann equation. The basis usage of this option is equivalent to that of --br. More detail is documented at Direct solution of linearized phonon Boltzmann equation. Scattering¶ --isotope ( ISOTOPE =.TRUE.)¶ Phonon-isotope scattering is calculated based on the formula by Shin-ichiro Tamura, Phys. Rev. B, 27, 858 (1983). Mass variance parameters are read from database of the natural abundance data for elements, which refers Laeter et al., Pure Appl. Chem., 75, 683 (2003). % phono3py --dim="3 3 2" -v --mesh="32 32 20" -c POSCAR-unitcell --br --isotope --mass-variances or --mv ( MASS_VARIANCES)¶ Mass variance parameters are specified by this option to include phonon-isotope scattering effect in the same way as --isotope option. For example of GaN, this may be set like --mv="1.97e-4 1.97e-4 0 0". The number of elements has to correspond to the number of atoms in the primitive cell. Isotope effect to thermal conductivity may be checked first running without isotope calculation: % phono3py --dim="3 3 2" -v --mesh="32 32 20" -c POSCAR-unitcell --br Then running with isotope calculation: % phono3py --dim="3 3 2" -v --mesh="32 32 20" -c POSCAR-unitcell --br --read-gamma --mv="1.97e-4 1.97e-4 0 0" In the result hdf5 file, currently isotope scattering strength is not written out, i.e., gamma is still imaginary part of self energy of ph-ph scattering. --boundary-mfp, --bmfp ( BOUNDARY_MFP)¶ A most simple phonon boundary scattering treatment is included. \(v_g/L\) is just used as the scattering rate, where \(v_g\) is the group velocity and \(L\) is the boundary mean free path. The value is given in micrometre. The default value, 1 metre, is just used to avoid divergence of phonon lifetime and the contribution to the thermal conducitivity is considered negligible. --ave-pp ( USE_AVE_PP = .TRUE.)¶ Averaged phonon-phonon interaction strength (\(P_{\mathbf{q}j}=P_\lambda\)) is used to calculate imaginary part of self energy in thermal conductivity calculation. \(P_\lambda\) is defined as where \(n_\text{a}\) is the number of atoms in unit cell. This is roughly constant with respect to the sampling mesh density for converged \(|\Phi_{\lambda \lambda' \lambda''}|^2\). Then for all \(\mathbf{q}',j',j''\), where \(N\) is the number of grid points on the sampling mesh. \(\Phi_{\lambda \lambda' \lambda''} \equiv 0\) unless \(\mathbf{q} + \mathbf{q}' + \mathbf{q}'' = \mathbf{G}\). This option works only when --read-gamma and --br options are activated where the averaged phonon-phonon interaction that is read from kappa-mxxx(-sx-sdx).hdf5 file is used if it exists in the file. Therefore the averaged phonon-phonon interaction has to be stored before using this option (see –full-pp). The calculation result overwrites kappa-mxxx(-sx-sdx).hdf5 file. Therefore to use this option together with -o option is strongly recommended. First, run full conductivity calculation, % phono3py --dim="3 3 2" -v --mesh="32 32 20" -c POSCAR-unitcell --br Then % phono3py --dim="3 3 2" -v --mesh="32 32 20" -c POSCAR-unitcell --br --read-gamma --ave-pp -o ave_pp --const-ave-pp ( CONST_AVE_PP = .TRUE.)¶ Averaged phonon-phonon interaction (\(P_{\mathbf{q}j}\)) is replaced by this constant value and \(|\Phi_{\lambda \lambda' \lambda''}|^2\) are set as written in –ave-pp for thermal conductivity calculation. This option works only when --br options are activated. Therefore third-order force constants are not necessary to input. The physical unit of the value is \(\text{eV}^2\). % phono3py --dim="3 3 2" -v --mesh="32 32 20" -c POSCAR-unitcell --br --const-ave-pp=1e-10 --nu ( N_U = .TRUE.)¶ Integration over q-point triplets for the calculation of \(\Gamma_\lambda(\omega_\lambda)\) is made separately for normal \(\Gamma^\text{N}_\lambda(\omega_\lambda)\) and Umklapp \(\Gamma^\text{U}_\lambda(\omega_\lambda)\) processes. The sum of them is usual \(\Gamma_\lambda(\omega_\lambda) = \Gamma^\text{N}_\lambda(\omega_\lambda) + \Gamma^\text{U}_\lambda(\omega_\lambda)\) and this is used to calcualte thermal conductivity in single-mode RTA. The separation, i.e., the choice of G-vector, is made based on the first Brillouin zone. Temperature¶ --ts ( TEMPERATURES): Temperatures¶ Specific temperatures are specified by --ts. % phono3py --fc3 --fc2 --dim="2 2 2" -v --mesh="11 11 11" -c POSCAR-unitcell --br --ts="200 300 400" --tmax, --tmin, --tstep ( TMAX, TMIN, TSTEP)¶ Temperatures at equal interval are specified by --tmax, --tmin, --tstep. See phonopy’s document for the same tags at . % phono3py --fc3 --fc2 --dim="2 2 2" -v --mesh="11 11 11" -c POSCAR-unitcell --br --tmin=100 --tmax=1000 --tstep=50 Non-analytical term correction¶ --nac ( NAC = .TRUE.)¶ Non-analytical term correction for harmonic phonons. Like as phonopy, BORN file has to be put on the same directory. Always the default value of unit conversion factor is used even if it is written in the first line of BORN file. --q-direction ( Q_DIRECTION)¶ This is used with --nac to specify reciprocal-space direction at \(\mathbf{q}\rightarrow \mathbf{0}\). See the detail at . Imaginary part of self energy¶ --ise ( IMAG_SELF_ENERGY = .TRUE.)¶ Imaginary part of self energy \(\Gamma_\lambda(\omega)\) is calculated with respect to \(\omega\). The output is written to gammas-mxxx-gx(-sx)-tx-bx.dat in THz (without \(2\pi\)) with respect to frequency in THz (without \(2\pi\)). Frequency sampling points can be specified by --num-freq-points, --freq-pitch (NUM_FREQUENCY_POINTS). % phono3py --fc3 --fc2 --dim="2 2 2" --mesh="16 16 16" -c POSCAR-unitcell --nac --q-direction="1 0 0" --gp=0 --ise --bi="4 5, 6" Joint density of states¶ --jdos ( JOINT_DOS = .TRUE.)¶ Two classes of joint density of states (JDOS) are calculated. The result is written into jdos-mxxx-gx(-sx-sdx).dat in \(\text{THz}^{-1}\) (without \((2\pi)^{-1}\)) with respect to frequency in THz (without \(2\pi\)). Frequency sampling points can be specified by --num-freq-points, --freq-pitch (NUM_FREQUENCY_POINTS)." When temperatures are specified, two classes of weighted JDOS are calculated. The result is written into jdos-mxxx-gx(-sx)-txxx.dat in \(\text{THz}^{-1}\) (without \((2\pi)^{-1}\)) with respect to frequency in THz (without \(2\pi\)). In the file name, txxx shows the temperature." --ts=300 This is an example of Si-PBEsol. Sampling frequency for distribution functions¶ --num-freq-points, --freq-pitch ( NUM_FREQUENCY_POINTS)¶ For spectrum like calculations of imaginary part of self energy and JDOS, number of sampling frequency points is controlled by --num-freq-points or --freq-pitch. Mode-Gruneisen parameter from 3rd order force constants¶ --gruneisen ( GRUNEISEN = .TRUE.)¶ Mode-Gruneisen-parameters are calculated from fc3. Mesh sampling mode: % phono3py --fc3 --fc2 --dim="2 2 2" -v --mesh="16 16 16" -c POSCAR-unitcell --nac --gruneisen Band path mode: % phono3py --fc3 --fc2 --dim="2 2 2" -v -c POSCAR-unitcell --nac --gruneisen --band="0 0 0 0 0 1/2" File I/O¶ --fc2 ( READ_FC2 = .TRUE.)¶ Read 2nd order force constants from fc2.hdf5. --fc3 ( READ_FC3 = .TRUE.)¶ Read 3rd order force constants from fc3.hdf5. --write-gamma ( WRITE_GAMMA = .TRUE.)¶ Imaginary parts of self energy at harmonic phonon frequencies \(\Gamma_\lambda(\omega_\lambda)\) are written into file in hdf5 format. The result is written into kappa-mxxx-gx(-sx-sdx).hdf5 or kappa-mxxx-gx-bx(-sx-sdx).hdf5 with --bi option. With --sigma and --sigma-cutoff options, -sx and --sdx are inserted, respectively, in front of .hdf5. --read-gamma ( READ_GAMMA = .TRUE.)¶ Imaginary parts of self energy at harmonic phonon frequencies \(\Gamma_\lambda(\omega_\lambda)\) are read from kappa file in hdf5 format. Initially the usual result file of kappa-mxxx(-sx-sdx).hdf5 is searched. Unless it is found, it tries to read kappa file for each grid point, kappa-mxxx-gx(-sx-sdx).hdf5. Then, similarly, kappa-mxxx-gx(-sx-sdx).hdf5 not found, kappa-mxxx-gx-bx(-sx-sdx).hdf5 files for band indices are searched. --write-gamma-detail ( WRITE_GAMMA_DETAIL = .TRUE.)¶ Each q-point triplet contribution to imaginary part of self energy is written into gamma_detail-mxxx-gx(-sx-sdx).hdf5 file. Be careful that this is large data. In the output file in hdf5, following keys are used to extract the detailed information. Imaginary part of self energy (linewidth/2) is recovered by the following script: import h5py import numpy as np gd = h5py.File("gamma_detail-mxxx-gx.hdf5") temp_index = 30 # index of temperature temperature = gd['temperature'][temp_index] gamma_tp = gd['gamma_detail'][:].sum(axis=-1).sum(axis=-1) weight = gd['weight'][:] gamma = np.dot(weight, gamma_tp[temp_index]) For example, for --br, this gamma gives \(\Gamma_\lambda(\omega_\lambda)\) of the band indices at the grid point indicated by \(\lambda\) at the temperature of index 30. If any bands are degenerated, those gamma in kappa-mxxx-gx(-sx-sdx).hdf5 or gamma-mxxx-gx(-sx-sdx).hdf5 type file are averaged, but the gamma obtained here in this way are not symmetrized. Apart from this symmetrization, the values must be equivalent between them. To understand each contribution of triptle to imaginary part of self energy, reading phonon-mxxx.hdf5 is useful (see --write-phonon (WRITE_PHONON = .TRUE.)). For example, phonon triplets of three phonon scatterings are obtained by import h5py import numpy as np gd = h5py.File("gamma_detail-mxxx-gx.hdf5", 'r') ph = h5py.File("phonon-mxxx.hdf5", 'r') gp1 = gd['grid_point'][()] triplets = gd['triplet'][:] # Sets of (gp1, gp2, gp3) where gp1 is fixed mesh = gd['mesh'][:] grid_address = ph['grid_address'][:] q_triplets = grid_address[triplets] / mesh.astype('double') # Phonons of triplets[2] phonon_tp = [(ph['frequency'][i], ph['eigenvector'][i]) for i in triplets[2]] # Fractions of contributions of tripltes at this grid point and temperture index 30 gamma_sum_over_bands = np.dot(weight, gd['gamma_detail'][30].sum(axis=-1).sum(axis=-1).sum(axis=-1)) contrib_tp = [gd['gamma_detail'][30, i].sum() / gamma_sum_over_bands for i in range(len(weight))] np.dot(weight, contrib_tp) # is one --write-phonon ( WRITE_PHONON = .TRUE.)¶ Phonon frequencies, eigenvectors, and grid point addresses are stored in phonon-mxxx.hdf5 file. –pa and –nac may be required depending on calculation setting. % phono3py --fc2 --dim="2 2 2" --pa="0 1/2 1/2 1/2 0 1/2 1/2 1/2 0" --mesh="11 11 11" -c POSCAR-unitcell --nac --write-phoonon Contents of phonon-mxxx.hdf5 are watched by: In [1]: import h5py In [2]: ph = h5py.File("phonon-m111111.hdf5", 'r') In [3]: list(ph) Out[3]: ['eigenvector', 'frequency', 'grid_address', 'mesh'] In [4]: ph['mesh'][:] Out[4]: array([11, 11, 11], dtype=int32) In [5]: ph['grid_address'].shape Out[5]: (1367, 3) In [6]: ph['frequency'].shape Out[6]: (1367, 6) In [7]: ph['eigenvector'].shape Out[7]: (1367, 6, 6) The first axis of ph['grid_address'], ph['frequency'], and ph['eigenvector'] corresponds to the number of q-points where phonons are calculated. Here the number of phonons may not be equal to product of mesh numbers (\(1367 \neq 11^3\)). This is because all q-points on Brillouin zone boundary are included, i.e., even if multiple q-points are translationally equivalent, those phonons are stored separately though these phonons are physically equivalent within the equations employed in phono3py. Here Brillouin zone is defined by Wigner–Seitz cell of reciprocal primitive basis vectors. This is convenient to categorize phonon triplets into Umklapp and Normal scatterings based on the Brillouin zone. --read-phonon ( READ_PHONON = .TRUE.)¶ Phonon frequencies, eigenvectors, and grid point addresses are read from phonon-mxxx.hdf5 file and the calculation is continued using these phonon values. This is useful when we want to use fixed phonon eigenvectors that can be different for degenerate bands when using different eigenvalue solvers or different CPU architectures. –pa and –nac may be required depending on calculation setting. % phono3py --fc2 --fc3 --dim="2 2 2" --pa="0 1/2 1/2 1/2 0 1/2 1/2 1/2 0" --mesh="11 11 11" -c POSCAR-unitcell --nac --read-phoonon --br --write-pp ( WRITE_PP = .TRUE.) and --read-pp ( READ_PP = .TRUE.)¶ Phonon-phonon (ph-ph) intraction strengths are written to and read from pp-mxxx-gx.hdf5. This works only in the calculation of lattice thermal conductivity, i.e., usable only with --br or --lbte. The stored data are different with and without specifying --full-pp option. In the former case, all the ph-ph interaction strengths among considered phonon triplets are stored in a simple manner, but in the later case, only necessary elements to calculate collisions are stored in a complicated way. In the case of RTA conductivity calculation, in writing and reading, ph-ph interaction strength has to be stored in memory, so there is overhead in memory than usual RTA calculation. % phono3py --fc2 --fc3 --dim="2 2 2" --pa="0 1/2 1/2 1/2 0 1/2 1/2 1/2 0" --mesh="11 11 11" -c POSCAR-unitcell --nac --write-pp --br --gp=1 % phono3py --fc2 --dim="2 2 2" --pa="0 1/2 1/2 1/2 0 1/2 1/2 1/2 0" --mesh="11 11 11" -c POSCAR-unitcell --nac --read-pp --br --gp=1 --hdf5-compression (command option only)¶ Most of phono3py HDF5 output file is compressed by default with the gzip compression filter. To avoid compression, --hdf5-compression=None has to be set. Other filters ( lzf or integer values of 0 to 9) may be used, see h5py documentation (). -o (command option only)¶ This modifies default output file names to write. Using this option, output file names are slightly modified. For example, with -o iso, a file name kappa-m191919.hdf5 is changed to kappa-m191919.iso gamma_detail-xxx.hdf5(write only) -i (command option only)¶ This modifies default input file names to read. Using this option, input file names are slightly modified. For example, specifying -i iso --fc3, a file name fc3.iso.hdf5 is read instead of fc3 --io (command option only)¶ This modifies default input and output file names. This is equivalent to setting -i and -o simultaneously.
https://phonopy.github.io/phono3py/command-options.html
CC-MAIN-2020-29
refinedweb
4,813
57.77
-13-2012 05:46 AM I have a ZC702 Zynq evaluation board running Linux from the included SD card. What I would like to do is create a std_logic signal in a user IP peripheral, and use that signal to trigger an interrupt to the processor, which in turn causes an interrupt-handler function to run. This is all under the Linux environment, not the standalone OS. I'm getting hung up somewhere, but I'm not entirely sure what my error is, or if I'm going about something completely wrong. Here is what I do in XPS. -- Create a std_logic signal in user_logicl.vhd (we'll call it "PL_INTERRUPT"). Route it to the top level of the user IP peripheral as an output. -- Open the user IP peripheral's MPD file and add this port as an interrupt like this: PORT PL_INTERRUPT = "", DIR = O, SIGIS = INTERRUPT, SENSITIVITY = EDGE_RISING, INTERRUPT_PRIORITY = MEDIUM -- Click Project -> Rescan User Repositories. In the "Ports" tab PL_INTERRUPT should now appear as an interrupt under its peripheral. -- Add an AXI Interrupt Controller from the IP Catalog. When prompted, indicate to have XPS automatically make connections to the processor. -- Click the interrupt's "Connected Port" field in the "Ports" tab, which opens the Interrupt Configuration Dialog. -- Set "Interrupt Controller" to "axi_intc_0", then double-click the PL_INTERRUPT entry to connect it to the AXI INTC. -- Set "Interrupt Controller" to "processing_system7_0" and double-click "axi_intc_0_Irq" to connect it to the processor. -- You can now see the axi_intc's S_AXI_ACLK is connected to one of the processor's FCLKs, and that its "Irq" port is connected to the processor's IRQ_F2P, although its parent "(BUS_IF) INTERRUPT" is indicated as "Not connected to BUS or External Ports". This may or may not be a problem, but it does not seem as though I can actually connect it to anything, other than making it an external port. -- Generate the netlist. This is successful, but it generates a warning: INTC_WARNING:: IRQ is not connected to Processor. Except this is clearly not the case as shown in the "Ports" tab. This may or may not be important. Here is where I presume my work in XPS is done. My major roadblock occurs when I try to register interrupts in a Linux app in SDK. I’m trying to get a simple programmable-logic interrupt input working under the Linux environment on the ZC702 eval board, and nearly all references on this mention a Linux function used to register interrupt channels, "request_irq()", including this Xilinx forum, where they mention this function, although the topic of the forum is different from my issue, and it is possible they're building their Linux ARM code under a different compiler, or they might be using a custom kernel. This function is also mentioned in the scope of Microblaze and PowerPC interrupt handling under Linux on Xilinx chips. Several websites that mention this function indicate a group of header files that need to be brought in to configure interrupts (request_irq() and presumably other interrupt-related functions). These include: #include <linux/interrupt.h> #include <linux/sched.h> #include <linux/signal.h> #include <asm/irq.h> linux/interrupt.h and asm/irq.h don’t seem to exist in 14.2, and so they and their associated functions cannot be called. linux/signal.h does exist, but throws an error at compile time if <stdlib.h> is also included, due to a conflicting definition of the type "sigset_t". This may not be a problem with the SDK libraries specifically. linux/sched.h just defines a set of constants and can be included without any issues, but doesn’t contain any function declarations. I see a lot of references to this function for the Microblaze processor for Linux kernel version 2.6.x, although the ZC702 board is running version “3.0.0-14.1-build3-01350-gffde6d9”. There may be a difference in the header libraries between those versions. There is some mention of modifying DTS device tree files and building separate kernel modules that handle interrupts, but I am not sure what part these might play since mapping and programming interrupts is fairly new to me. Can anyone help with this? I've found reference designs implementing PL-to-PS interrupts for the standalone OS, but after weeks of searching it seems as if there's no documentation whatsover for doing the same thing in a Linux application for Zynq in 14.2. Some of the information I found (which I forgot to save) seemed to hint that configuring interrupts this way does not work on the cortex-a9 architechture under Linux, so that's a possibility as well. It would be really great to get this working, so if I need to provide more information I can. 09-13-2012 07:38 AM Have you filed a webcase? As a customer (you bought the board), you should be able to file a webcase, and get an answer much faster than hoping someone reads your post, and knows what to tell you.... 09-13-2012 07:58 AM I've had a webcase open for about three weeks with little success. Without going into too much detail, it's apparent that the FAE assigned to my case does not really understand my problem or my goal. My hope is that someone here on the forums will have tried to implement something similar, and therefore have some advice to offer. I'm not looking for a how-to, just a push in the right direction. 09-13-2012 08:08 AM I agree that is unacceptable: I will follow up for you. What is the case number? Please email me directly at: austin@xilinx.com 09-21-2012 03:11 AM Hi Eric , Please follow the step by step procedure mentioned in the below link. Regards Jangi Reddy 09-27-2012 07:12 AM Have you looked at UIO? It is a generic linux driver which allows you to do all the device specific stuff inside the user space. I use it for interrupt handling and it is very convenient. You don't have to recompile the kernel if you change bits on the driver of an IP core. 10-09-2012 07:38 AM Hello, I am having the same problem: after adding an AXI Interrupt Controller (1.02a) to my ZedBoard design in Xilinx XPS 14.2, the Design Rule Check says: "INTC_WARNING:: IRQ is not connected to Processor. ERROR:EDK - axi_intc_0 (axi_intc) - can't read "mb_clk": no such variable" As you said, there's no way to connect the "(BUS_IF) INTERRUPT", except to make it external. This is the only Google result for this warning. Did you fix it? Is there a workaround, like modifying the MPD? Thanks, Oriol 01-07-2013 03:49 AM Hello everybody! I'd like to know if this problem has been solved. I'm interested in doing something similar to esagr project. Unfortunately I'm facing another problem: when I try to perform a Design Rule Chek I get " IRQ is not connected to Processor" as an error, not a warning. For this reason I'm not able to synthesize my code and to migrate to SDK. I noticed that is possible to interconnect the interrupt signal coming from the peripheral directly to IRQ_F2P port of the processing system without getting neither error or warning. In this way I'm able to generate bitstream, but I think is not the correct solution especially because I'm planning to use more component able to generate their own interrupts. In brief: 1) I need to instantiate an interrupt controller in PL whithout generating errors (Note: I've already followed esagr steps) 2) I need to manage interrupts from Linux. Assuming that I want to manage them in a bare metal application, what should I do? what libraries/functions do I have to include? Thank you, sticken 01-11-2013 11:04 AM - edited 01-11-2013 11:31 AM This isn't a solution to the AXI interrupt controller connection issue, but it may help you get interrupts working in Linux. The PS has 16 IRQ inputs connected to an interrupt controller (GIC) in the APU. As sticken said, interrupt ports from the PL (such as your PL_INTERRUPT port) can be connected directly to the PS using the IRQ_F2P port without the need for an AXI interrupt controller (this can be done by clicking the IRQ section in the Zynq tab and connecting the interrupts in the same manner as an AXI interrupt controller). Xilinx has a standalone example design that uses this method: You may have more success in Linux by using the PS's IRQ ports and interrupt controller directly instead of trying to handle them in the PL first with an AXI interrupt controller. 05-13-2013 12:46 AM Hey I did project with zedboard I added my simple own ip who copy the status of ths switch on led when the led is on I want call function handler with the xsdk.
https://forums.xilinx.com/t5/Zynq-All-Programmable-SoC/Problems-configuring-PL-generated-interrupts-in-Zynq-running/td-p/261300
CC-MAIN-2016-18
refinedweb
1,513
62.27
OpenCV with pygtk In my previous post, I have shown how to integrate OpenCV with pygtk to show images. In this post, I’ll be showing how to use OpenCV/SimpleCV with pygtk to show multiple images simultaneously, a continuous streaming of images (like a video), etc. I have used multi-threading to call gtk.main() because if I don’t do that, my program will be stuck untill, gtk.main() doesn’t end. It doesn’t end untill gtk.main_quit() is explicitly called. import gtk from threading import Thread import gobject gtk.gdk.threads_init() As I have mentioned before, gtk.gdk.threads_init() is necessary. The gtk.gdk.threads_init() function initializes PyGTK to use the Python macros that allow multiple threads to serialize access to the Python interpreter (using the Python Global Interpreter Lock (GIL)).The gtk.gdk.threads_init() function must be called before the gtk.main() function. At this point in the application the Python GIL is held by the main application thread. You can get more information about gtk.gdk.threads_init() and GIL here in pygtk docs. class DisplayImage(): def __init__(self,title="SimpleCV"): self.img = None self.img_gtk = None self.done = False self.thrd = None self.win = gtk.Window() self.win.set_title(title) self.win.connect("delete_event",self.leave_app) self.image_box = gtk.EventBox() self.win.add(self.image_box) def show_image(self,image): self.img = image if self.img_gtk is None: self.img_flag=0 self.img_gtk = gtk.Image()# Create gtk.Image() only once self.image_box.add(self.img_gtk)# Add Image in the box, only once self.img_pixbuf = gtk.gdk.pixbuf_new_from_data(self.img.tostring(), gtk.gdk.COLORSPACE_RGB, False, self.img.depth, self.img.width, self.img.height, self.img.width*self.img.nChannels) self.img_gtk.set_from_pixbuf(self.img_pixbuf) self.img_gtk.show() self.win.show_all() if not self.img_flag: self.thread_gtk() # gtk.main() only once (first time) self.img_flag=1 # change flag def thread_gtk(self): # changed this function. Improved threading. self.thrd = Thread(target=gtk.main, name = "GTK thread") self.thrd.daemon = True self.thrd.start() def leave_app(self,widget,data): self.done = True self.win.destroy() gtk.main_quit() def isDone(self): return self.done def quit(self): self.done = True self.win.destroy() gtk.main_quit() So, here’s the complete class that I made to show images in OpenCV/SimpleCV. In line 26, self.img_gtk.set_from_pixbuf(self.img_pixbuf) In my previous post it was image = gtk.image_new_from_pixbuf(img_pixbuf) So, here’s the problem with it. Whenever I do gtk.image_new_from_pixbuf(), it would create a new gtk.Image object at a different address, and hence we would have to add the new object in the box every time and destroy the previous image object which was there in the box. So, instead of that I have used gtk.set_from_pixbuf(), which would not create a new gtk.Image object, but just change the image. Now moving on to threading part, it’s very important that you call gtk.main with a thread. And it has to be called only once during the program, otherwise there would be many threading problems. gtk.main has to be called after you have created widgets, added properties and shown. thrd = Thread(target=gtk.main, name = "GTK thread") thrd.daemon = True thrd.start() After creating the thread, thrd.daemon = True is very necessary before you start the thread, otherwise there will be too many errors and complications with gtk. Believe me, I have faced it for two days. And it was not good. I have added more functionalities in DisplayImage class such as getting co-ordinates of mouse click, etc. You can find it here on my GitHub. You can also find some examples that I have worked out for SimpleCV there. So, now some examples. Show image in OpenCV. from cv2.cv import * from pygtk_image import DisplayImage import time image = LoadImage("Image name") image_rgb = CreateImage((image.width,image.height),image.depth,image.channels) CvtColor(image,image_rgb,CV_BGR2RGB) # iplImage has BGR colorspace display = DisplayImage() display.show(image_rgb) time.sleep(3) display.quit() Show image in SimpleCV from SimpleCV import * from pygtk_image import DisplayImage import time image = Image("lenna") display = DisplayImage(title="SimpleCV") display.show(image.toRGB().getBitmap()) time.sleep(3) display.quit() Show multiple images simultaneously in SimpleCV from SimpleCV import * from pygtk_image import * d1 = DisplayImage() d2 = DisplayImage() i1 = Image("lenna") while not (d1.isDone() or d2.isDone()): try: d1.show_image(i1.toRGB().getBitmap()) time.sleep(0.1) d2.show_image(i1.toGray().getBitmap()) time.sleep(0.1) except KeyboardInterrupt: d1.quit() d2.quit() Show images in a series in SimpleCV from SimpleCV import * from pygtk_image import * def loadimage(): image = Image("lenna") d = DisplayImage() d.show_image(image.toRGB().getBitmap()) time.sleep(3) d.show_image(Image("simplecv").toRGB().getBitmap()) time.sleep(2) d.quit() if __name__ == "__main__": loadimage() show captured images from camera in SimpleCV from SimpleCV import * from pygtk_image import * cam = Camera() d = DisplayImage() while not d.isDone(): try: i = cam.getImage() i.drawRectangle(d.mouseX,d.mouseY,50,50,width=5) d.show_image(i.applyLayers().toRGB().getBitmap()) time.sleep(0.1) except KeyboardInterrupt: d.quit() break If you find some better way to show images using pygtk, or a better way to thread gtk.main(), let me know. P.S. Anxiously waiting for GSoC 2012 results. Only 2 days and 8 hours to go. Playing around with Android UI Articles focusing on Android UI - playing around with ViewPagers, CoordinatorLayout, meaningful motions and animations, implementing difficult customized views, etc.
https://jayrambhia.com/blog/opencv-with-pygtk
CC-MAIN-2022-05
refinedweb
902
54.08
11 December 2009 17:49 [Source: ICIS news] WASHINGTON (ICIS news)--US retail and food services sales rose by 1.3% in November, the Commerce Department said on Friday, raising hopes that consumers are gaining confidence in the recovery and are willing to spend. Consumer spending is the principle driving force of the ?xml:namespace> The improvement in retail sales last month was almost twice what market analysts had been expecting. The department said that retail and food services sales were at a seasonally adjusted $352.1bn (€239.4bn) in November, an increase of 1.3% from October and nearly 2% above the retail sales level of November last year. Much of the gain in November’s retail sales was attributed to a 6% rise in gasoline sales at the pump, but as fuel prices were more or less steady in November, the sales increase suggests that consumers were more willing to travel and shop. Increased consumer spending also appeared to be reflected in a 2.8% gain in retail sales at electronics and appliances stores and a 1.5% improvement in sales of building materials and garden supplies at the retail level. Along with modest gains in retail sales at sporting goods, book and music stores and improvements in beverages and restaurant dining, the data suggest that US consumers are increasingly willing to spend on more recreational and leisure items, not just on essentials such as food, clothing and shelter. Much of the chemicals industry ultimately depends on consumer purchasing, which drives sales of such downstream chemicals-consuming products as autos, appliances, electronics, CDs and other storage media and retail product packaging. (
http://www.icis.com/Articles/2009/12/11/9318753/us-retail-sales-rise-1.3-in-nov-signal-recovery-gains.html
CC-MAIN-2013-48
refinedweb
273
59.43
Working with Collections¶ Often we want to do a bit of custom work with dask.delayed (for example, for complex data ingest), then leverage the algorithms in dask.array or dask.dataframe, and then switch back to custom work. To this end, all collections support from_delayed functions and to_delayed methods. As an example, consider the case where we store tabular data in a custom format not known by Dask DataFrame. This format is naturally broken apart into pieces and we have a function that reads one piece into a Pandas DataFrame. We use dask.delayed to lazily read these files into Pandas DataFrames, use dd.from_delayed to wrap these pieces up into a single Dask DataFrame, use the complex algorithms within the DataFrame (groupby, join, etc.), and then switch back to dask.delayed to save our results back to the custom format: import dask.dataframe as dd from dask.delayed import delayed from my_custom_library import load, save filenames = ... dfs = [delayed(load)(fn) for fn in filenames] df = dd.from_delayed(dfs) df = ... # do work with dask.dataframe dfs = df.to_delayed() writes = [delayed(save)(df, fn) for df, fn in zip(dfs, filenames)] dd.compute(*writes) Data science is often complex, and dask.delayed provides a release valve for users to manage this complexity on their own, and solve the last mile problem for custom formats and complex situations.
http://docs.dask.org/en/latest/delayed-collections.html
CC-MAIN-2019-09
refinedweb
227
69.38
Undo actions. Hi, i need to create the actions for the user, but i dont know how to do that. I read the documentation, but i do not understand that. For example, i have one button, and when i press it, it's gonna increment the variable by one, if i understood good that documentation, i need to create something like commands or actions? So one action increment the variable, and the other one decrement it, but how get the result, if i increment it 4 times, and decrement 2 times? I don't understand. Hi It works with QUndoStack. You push the commands to the stack when they are executed, if you want to undo, you take them off the stack. Each command will increase by one or if asked to undo , then decrease by one. So each step of undo, goes back one step for the value. OK, but i need to create my own actions, because the program does custom stuff, so i need to do for example void Undo_Something() { Variable_1-- Variable_2++ } void Redo_Something() { Variable_1++ Variable_2-- } Or it's automatic? I mean, i just need to call undo() and redo(), or i need to edit it? @Loc888 Hi Yes you must create your own commands as the system cannot possible know what variable to alter when doing undo etc. Did you check out the examples? Ye, but as you can see, i am not so good with stuff like that, first time i need to do something like that. I just ask, because maybe he is "smart enough" to know it in some way. But ok, i will try to do that. So, i need to inherrit the class, implement undo() and redo(), and then create the actions? That "QUndoStack" class object need to be created too? @Loc888 Hi Yes you should have a QUndoStack variable too in the class. Its not super complex if u take from the examples. Here is how a "text"command is made. ( it can insert/remove some text in a document); }; Ok i have: #ifndef COMMAND_ACTIONS_H #define COMMAND_ACTIONS_H #include <QUndoCommand> #include <QUndoStack> class Command_Actions : public QUndoCommand { public: Command_Actions(); virtual void redo(); virtual void undo(); }; #endif // COMMAND_ACTIONS_H What should i put in undo() ? Because i want delete the last action, or i just do it in that QUndoStack ? I mean, delete the last action? #include "Command_Actions.h" Command_Actions::Command_Actions() { } void Command_Actions::redo() { } void Command_Actions::undo() { } @Loc888 Hi The undo function should revert its change. Like the sample the cuts the text. in your case, you just need to decrease the variable by one? I think i dont undersand it. Maybe i explain it, so: I create undo() and redo() as general actions, but then i wanna be able to do more stuff. So it's gonna be: Action_Plus_5(); Action_Minus_5(); Action_Increment(); Action_Decrement(); And that's the problem, how i call them in undo() and redo?? I mean, how by undo() delete the last used action, so for example Action_Plus_5() ? @Loc888 Hi Please look at this you can see how it uses the undoStack and how to use the system. Ye, i see that... And i am lost. I read that, and i dont know wher i must declare any functionality.... When i use the Stack.push(Command), how i am gonna tell to the "Command" to do something?? It's a variable, so how can i declare to it any functionality? Add or subtract something? Hi You let the commands points to the data so u can change it from inside them. From sample class MoveCommand : public QUndoCommand { public: enum { Id = 1234 }; MoveCommand(DiagramItem *diagramItem, const QPointF &oldPos, QUndoCommand *parent = 0); void undo() override; void redo() override; bool mergeWith(const QUndoCommand *command) override; int id() const override { return Id; } private: DiagramItem *myDiagramItem; // this would be your data. point to the variable QPointF myOldPos; // this would be old value }; and to restore you do void MoveCommand::undo() { myDiagramItem->setPos(myOldPos); // this would be to decrease or set old value back myDiagramItem->scene()->update(); setText(QObject::tr("Move %1") .arg(createCommandString(myDiagramItem, newPos))); } Ther is no way to just undo a method or funtion? I have alot of this variables, so how many of those diagrams i am gonna create? It's gonna mess up the code, at this point is a lot of stuff ther. Ps. It's not better, just to create one structure with all that data, and maybe then point to it? Hi how would u undo a method ? Yes if u have a lots of single variables that need undo / redo then it will be many small classes. Since i dont know your use case or the code its hard to say if there would be easier way. Do you need for each variable to be able to undo many levels or just last value ? Also, you can make Commands class that can handle all, you just need to specify for what data member the undo applies when undoing etc. But again, there are many ways to do this but it depends on the code u already have what will be easy. -Ps. It's not better, just tocreate one structure with all that data, and maybe then point to it? Yes, using a struct would make is more easy to handle "Do you need for each variable to be able to undo many levels or just last value ?" Ther almost everything must be able to undo, redo is not necessary. Needed 5 levels. How to assign a structure member to that QUndoCommand object? Ther is no way to point to the structure, because it's different type. I dont find any method to set that equal. @Loc888 Hi So each variable need to be able to undo many values back ? - How to assign a structure member to that QUndoCommand object? You just do it. you can use any type u like. class MoveCommand : public QUndoCommand { public: enum { Id = 1234 }; MoveCommand(DiagramItem *diagramItem, const QPointF &oldPos, QUndoCommand *parent = 0); the DiagramItem and QPointF could be ANYTHIng you need MoveCommand(DiagramItem *diagramItem, const QPointF &oldPos, those are jsut what sample need, you can just use the types u need @mrjj said in Undo actions.: diagramItem At this point, i am gonna create a structure, and create 10 objects, and then simply switch them, so: Memory_001 = Memory_002 Memory_002 = Memory_003 // And progress. Is it a good idea? What about performance? (They are not so big, around 200 - 400 variables) @Loc888 On a desktop class pc, it would be nothing for it. But if u need multiple levels on undo such structure would not work. can you show some of the data u need multiple levels of undo for (real code) ? are they int/floats, strings etc ? Are they all of same type or very mixed? @mrjj Need at least5 of them, and max 10. Ther is rly no need to create more in this case. I show you the template: struct:Data { int* int* int* long double* long double* long double* long double* long double* long double* long double* long double* long double* }; Stuff like that, i have around 4 - 6 of them, so it's like 30 objects * 10... I think is much more then 300 variables, but not all must be able to undo, cuz ther is a percentage calculator, so it's gonna re-calculate it again. Ther are around +150 variables of "percent type", so they don't need to be stored, the function gonna recalculate them by current value of variables. So i am gonna create a structure with that six structures, and the total of variables gonna be maybe 800?? (Some long double) Gonna work? @Loc888 Ok so those Data points to somewhere where the real data lives? And you need to be able to undo each "long double*" more than one level back? I still think using the undo system ( if u need more than one level undo) is a better choice than make some sort of your own system. @mrjj I don't remember, i work long time on this program, but i think nothing of long double need to be stored, ther is a structure with a template for percent calculations, so around 5 object's of them, does't need to be stores (Like i said, they gonna be re-calculated). No, they are not pointers, i just put that " * " symbol, because i dont want write any names :) In real it's: struct:Data { // Names for the demonstration purposes int Name_A_Int; int Name_B_Int; int Name_C_Int; long double Name_A; long double Name_B; long double Name_C; long double Name_D; // And progress }; Ps. I am gonna try, will see what happend, i understood a little bit more, how it's gonna work, but i use it first time, and it's hard to use with a little bit bigger program. @Loc888 Ahh next time use xxx as * screams pointer to us old ones :) You could do something like class MyCommand : public QUndoCommand { public: enum { Id = 1234 }; MyCommand (struct_Data*data, long double * varToUse , so you give it the struct with data and the pointer to the member soi knows which of the values to alter. Then when you push the command to the stack, you point the varToUse to the right one inside struct. (else u need biiig if/switch case) You can make this very generic with templates if u know how to use such. I have to go out now but ill be back tonight and can help get it running if still issues. It looks more complicated than it is :)
https://forum.qt.io/topic/88898/undo-actions/20
CC-MAIN-2019-26
refinedweb
1,596
70.94
Reverseme: Easy Windows To get back into the groove, I decided to try a crackme. After searching far and wide, I can’t seem to find where I got this from, other than crackmes.de. One of my favorite sites. Crackme.zip <– here it is in case it’s deleted. And the solution is, with no analysis: #include <iostream> #include <string> using namespace std; int add_name_chars(string name) { int total = 0; for (int i=0; i<name.length(); i++) { total += name[i]; } return total; } int main() { string name; cout<<"Name: "; cin>>name; unsigned int ser1 = 31 * add_name_chars(name) / 629u + 44431400; while (ser1 > 0x3b9ac9ff) { ser1 /= 10; } cout<<"Serial 1: "<<ser1<<endl; unsigned int ser2 = 82 * ser1 - 3; while (ser2 > 0x1869f) { ser2 /= 10; } cout<<"Serial 2: "<<ser2<<endl; return 0; } Ok, one hint. All the logic is at 004013BC. This was rated as 1, for newbies, but it still took me awhile to figure out. I thought it was fun. <– here's the link
https://webstersprodigy.net/2010/06/08/reverseme-easy-windows/
CC-MAIN-2018-17
refinedweb
162
82.14
PyJudy [Download pyjudy-1.0.tar.gz]Requires the Judy. PyJudy arrays are similar to Python dictionaries and sets. The primary difference is that PyJudy keys are sorted; by unsigned value if an integer, byte ordering if a string and object id if a Python object. In addition to wrapping the underlying Judy functions, PyJudy implements a subset of the Python dictionary interface for the JudyL and JudySL API and a subset of the set interface for the Judy1 API, along with some extensions for iterating a subrange of the sorted keys, values and items. INSTALLATION To install this package using the standard distutils package do: - install Judy from - configure setup.py to use the installed Judy. By default setup.py looks for Judy under /usr/local . - Build and install PyJudy using Python's standard distutils python setup.py install - Run the regression test 'test_all.py' in this directory python ./test_all.pyThe last two lines should be All methods tested. All tests passed. Amazing. I have tested this with Python 2.3 and Python 2.4 on an Apple Mac PowerBook G4 and with Python 2.4 on a Intel-based FreeBSD machine. In both cases I used Judy compiled for 32 bits. Please let me know if you get it to work on a 64 bit machine. EXAMPLEGet information about the lines in a file. This program is available from "examples/lineinfo.py" from the distribution. import pyjudy # Get a file to analyze import inspect filename = inspect.__file__ if filename.endswith(".pyc"): filename = filename[:-1] # Count the number of keys in a JudySL array # which start with the given text. def count_startswith(arr, word): # Turns "def " into ("def ", "def!") # Turns "class " into ("class ", "class!") # because "!" is the character after " ". c = chr(ord(word[-1])+1) # JudySL arrays don't support Count so have to # do this manually. it = arr.iterkeys_range(word, word[:-1] + c) n = 0 for x in it: n += 1 return n # Load the file j1arr = pyjudy.JudySLObj() for line in open(filename): j1arr[line] = j1arr.get(line, 0) + 1 print "Analyzing", repr(filename) print "There are", len(j1arr), "unique lines" print j1arr.get("\n", 0), "of them are newlines" print "In sorted order the first line is", repr(j1arr.First()[0]) print " ... and the last is", repr(j1arr.Last()[0]) print count_startswith(j1arr, "def "), print "lines start with a 'def' statement" print count_startswith(j1arr, "class "), print "lines start with a 'class' definition"When I run the above on my machine I get the following output: Analyzing '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/inspect.py' There are 632 unique lines 111 of them are newlines In sorted order the first line is '\n' ... and the last is 'modulesbyfile = {}\n' 43 lines start with a 'def' statement 3 lines start with a 'class' definition PyJudy 1.0 supports the following subset of the Judy API JudyL JudyL arrays map machine words to machine words. In practice the words store unsigned integers or pointers. PyJudy supports all four mappings as distinct classes. - pyjudy.JudyLIntInt - map unsigned integer keys to unsigned integer values - pyjudy.JudyLIntObj - map unsigned integer keys to Python object values - pyjudy.JudyLObjInt - map Python object keys to unsigned integer values - pyjudy.JudyLObjObj - map Python object keys to Python object values Unlike Python dictionaries, keys in JudyL arrays are ordered, with comparisons as unsigned longs. Python does not have an unsigned integer type so normal integers are bitwise converted into signed integers. This means the integer keys ordering is 0, 1, 2, ... -3, -2, -1. 0 is the smallest value and -1 is the largest. The unsigned long value used for a Python object is its id, which at the implementation level is a PyObject *. Two objects are equal only if they have the same id. This is different than a Python dictionary where two object are equal if they have the same hash and pass the test for "==". The distinction is important because there is no guarantee that a duplicate string or number will reuse an existing object. In the following the number "1000" creates a new object each time, so there are two entries in the JudyLObjObj instead of the one you might have expected. >>> import pyjudy >>> arr = pyjudy.JudyLObjObj() >>> arr[1000] = "Andrew" >>> arr[1000] = "Dalke" >>> len(arr) 2 >>> As an implementation optimization in the current version of Python the numbers -5 through 100 (inclusive) will always return the same object as will strings of length one. This may cause confusion unless you are careful. The PyJudyL classses implement methods corresponding to the functions at. These are: arr.Ins(key, value) -- add a given key/value to the array. arr.Del(key) -- delete a key from the array. Return True if the key was present, otherwise return False. arr.Get(key) -- get the value associated with the key. If not present raise an IndexError arr.Count() -- number of elements in the array arr.Count_from(key) -- number of elements in the array from the given key to the end arr.Count_to() -- number of elements in the array from the beginning to the given key, excluding the given key arr.Count_range(start, end) -- number of elements between the start and end keys, excluding the end. arr.ByCount(nth) -- the Nth key/value pair, as a 2-element tuple. Raises IndexError if no matches. ByCount(1) returns the first element. arr.FreeArray() -- remove all elements from the array arr.MemUsed() -- report the amount of memory used by the array arr.First() -- the first key/value pair, as a 2-element tuple. Raises StopIteration if no matches. arr.First(key) -- the first key/value pair at or after the given key, as a 2-element tuple. Raises StopIteration if no matches. arr.Next(key) -- the next key/value pair after the given key, as a 2-element tuple, Raises StopIteration if no matches. arr.Last() -- the last key/value pair, as a 2-element tuple. Raises StopIteration if no matches. arr.Last(key) -- the first key/value pair at or before the given key, as a 2-element tuple. Raises StopIteration if no matches. arr.Prev(key) -- the previous key/value pair before the given key, as a 2-element tuple, Raises StopIteration if no matches. arr.FirstEmpty() arr.FirstEmpty(key) arr.NextEmpty(key) arr.LastEmpty() arr.LastEmpty(key) arr.PrevEmpty(key) -- Similar to the First/Next/Last/Prev methods except they return information about unassigned keys. These return the possible key as an unsigned integer. (Not a 2-element tuple because there is no value.)The JudyL array maps pretty closely to a Python dictionary. At times it may be more appropriate to use a JudyL* array than a Python dictionary, especially if you want sorted keys. PyJudy implements the following methods of the dictionary protocol: len(arr) arr.clear() arr[key] arr[key] = value del arr[key] key in arr arr.get(key, failobj = None) arr.keys() arr.values() arr.items() arr.iterkeys() arr.itervalues() arr.iteritems() iter(arr) arr.__reversed__() -- for 'reversed()' in Python 2.4All of the object iterations (keys(), values(), iteritems(), iter(arr), etc.) return the objects in key order, from smallest to largest. PyJudy introduces the following variations for iterating over a portion of the array: arr.iterkeys_from(key) -- iterate from the first key at or after the given key until the end of the array arr.iterkeys_to(key) -- iterate from the first key up to but not including the given key arr.iterkeys_range(start, end) -- iterate from the first key at or after the start key up to but not including the end key. arr.itervalues_from arr.itervalues_to arr.itervalues_range arr.iteritems_from arr.iteritems_to arr.iteritems_range -- corresponding "values" and "items" iterations arr.iterempty arr.iterempty_from arr.iterempty_to arr.iterempty_range -- corresponding iteration for empty keys (as unsigned integers)PyJudy also introduces the following variations for reverse iteration over a portion of the array: arr.riterkeys_from(key) -- iterate from the first key at or before the given key until the beginning of the array arr.riterkeys_to(key) -- iterate from the end down to but not including the given key arr.riterkeys_range(start, end) -- iterate from the first key at or below the start key down to but not including the end key. arr.ritervalues_from arr.ritervalues_to arr.ritervalues_range arr.riteritems_from arr.riteritems_to arr.riteritems_range -- corresponding "values" and "items" reverse iterations arr.riterempty arr.riterempty_from arr.riterempty_to arr.riterempty_range -- corresponding reverse iteration for empty keys (as unsigned integers)Yes, it did get rather boring to write all of these and their tests. By the way, here's one way to write an ordered iterator in Python. def iterkeys_filtered_by_value(arr, value_filter = lambda x: x > 100): k, v = arr.First() while 1: if value_filter(v): yield k k, v = arr.Next(k) The Judy documentation suggests a memory efficient way to have a JudyL array as a value in another JudyL array. That technique uses low-order bitmasks to distinguish between pointers to JudyL and and non-JudyL structure. PyJudy does not support that technique. With some memory inefficiency you could just use a Python object instead. JudySL JudySL arrays map strings (C-style NUL terminated character strings) to machine words. PyJudy supports JudySL arrays with integer and Python object as values. - pyjudy.JudySLInt - map string to unsigned integer values - pyjudy.JudySLObj - map string to Python object values The strings are stored in order by character code. The smallest string is "" followed by all strings starting with chr(1) then all strings starting with chr(2), etc. The largest string contains only chr(255) characters. The underlying JudySL library supports unlimited strings lengths but for ease of implementation the PyJudy interface has a maximum string size of 100,000 bytes, defined in "pyjudy_common.h" and accessible as pyjudy.MAX_STRING_LEN. If you need a larger but still bounded limit you can change the #define statement. With some straight-forward work you could also write code to use a dynamically sized buffer. I didn't need the complication. Python strings may contain NUL characters. PyJudy checks each string and raises a TypeError if that happens. The PyJudySL classses implement methods corresponding to the functions at. These are: arr.Ins(key, value) arr.Del(key) arr.Get(key) arr.FreeArray() arr.First() arr.First(key) arr.Next(key) arr.Last() arr.Last(key) arr.Prev(key)The details are identical to the JudyL* classes above. Note that the Count*(), ByCount() and MemUsed() methods are not available in a JudySL array and nor are the *Empty() methods. The JudySL array also maps pretty closely to a Python dictionary. The biggest problem is the lack of a Count() method. As a work-around PyJudy tracks all of the successful insertions and deletions itself, at the cost of an extra lookup when setting a key/value pair where the value is an integer. To more closely emulate a Python dictionary the PyJudy wrapper implements the following methods as you would expect them to do: len(arr) arr.clear() arr[key] arr[key] = value del arr[key] key in arr arr.get(key, failobj = None) arr.keys() arr.values() arr.items() arr.iterkeys() arr.itervalues() arr.iteritems() iter(arr) arr.__reversed__() -- for 'reversed()' in Python 2.4As with the JudyL* classes, the JudySL* classes also implement the alternate iteration methods. arr.iterkeys_from(key) arr.iterkeys_to(key) arr.iterkeys_range(key) arr.itervalues_from(key) arr.itervalues_to(key) arr.itervalues_range(key) arr.iteritems_from(key) arr.iteritems_to(key) arr.iteritems_range(key) arr.riterkeys_from(key) arr.riterkeys_to(key) arr.riterkeys_range(key) arr.ritervalues_from(key) arr.ritervalues_to(key) arr.ritervalues_range(key) arr.riteritems_from(key) arr.riteritems_to(key) arr.riteritems_range(key)For ease of implementation each iterator includes a 100,000 byte buffer used to keep the current index into the array. Ideally this would be dynamically resized to just barely hold the largest value in the array, which is likely much less than 100,000 characters. Judy1 arrays map machine words to boolean values. PyJudy supports Judy1 arrays using integers and Python objects as keys. Judy1 - pyjudy.Judy1Int - map integer keys to boolean values - pyjudy.Judy1Obj - map Python object keys to boolean values The PyJudy1 classses implement methods corresponding to the functions at. These are: arr.Set(key) -- map the key to True arr.Unset(key) -- map the key to False arr.Test(key) -- return the key's boolean value as either True or Falseas well as the by-now familiar methods (see the above JudyL documentation): arr.Count(key) arr.Count_from(key) arr.Count_to(key) arr.Count_range(start, end) arr.ByCount(nth) arr.FreeArray() arr.MemUsed() arr.First() arr.First(key) arr.Next(key) arr.Last() arr.Last(key) arr.Prev(key) arr.FirstEmpty() arr.FirstEmpty(key) arr.NextEmpty(key) arr.LastEmpty() arr.LastEmpty(key) arr.PrevEmpty(key)A Judy1 maps more closely to a Python set than a Python dictionary so the PyJudy interface implements the following subset of the standard set protocol. len(arr) iter(arr) key in arr arr.add(key) arr.remove(key) arr.clear()Unlike Python sets, the Judy1 keys are ordered. The PyJudy1* classes implement the iterator and reverse iterator for both keys and empty keys. It does not support iteration of values and items because all the non-empty values would be True and the empty ones would be false. The implemented methods are: arr.keys() arr.iterkeys() arr.iterkeys_to(key) arr.iterkeys_from(key) arr.iterkeys_range(start, end) arr.riterkeys() arr.riterkeys_to(key) arr.riterkeys_from(key) arr.riterkeys_range(start, end) arr.iterempty() arr.iterempty_to(key) arr.iterempty_from(key) arr.iterempty_range(start, end) arr.riterempty() arr.riterempty_to(key) arr.riterempty_from(key) arr.riterempty_range(start, end) PERFORMANCE I have done some performance comparisons using the "timings.py" program found in the examples subdirectory of the distribution. The results from my 1GHz Mac PowerBook G4 using 1,000,000 random numbers are shown here, formatted slightly for better display. *** JudyL timings *** ------- : dict JudyLIntInt JudyLIntObj JudyLObjObj time to load mapping : 1.7334 1.7144 1.8449 1.3231 time to verify subset1 in all_data : 0.4399 0.4036 0.4031 0.3077 time to clear : 0.3433 0.2390 0.7375 0.3592 __contains__ with all hits : 2.9185 3.0687 3.1686 2.7474 number of unique= : 906475 906475 906475 999998 index lookup (all elements exist) : 0.8573 1.0305 0.9815 0.5734 iter : 0.3835 0.4105 0.4104 0.4129 itervalues : 0.1572 0.4141 0.3677 0.3865 iteritems : 0.4865 0.6084 0.5688 0.5431 __contains__ with few matches : 0.5119 0.4180 0.4063 0.3042 % matches= : 0.0951 0.0951 0.0951 0.0000 delete : 0.7797 1.5358 1.6373 0.7591 *** Judy1 timings *** ------- : set Judy1Int Judy1Obj time to load set : 2.5798 1.3992 1.3318 time to verify subset1 in all_data : 0.4551 0.3163 0.2504 time to clear : 0.2957 0.0142 0.3356 verify none of all_data in empty set : 0.4882 0.4033 0.3912 check for overlaps (sparse __contains__) : 0.6842 0.5082 0.4313 number of overlaps : 47557 47557 1 delete subset1 from all_data : 1.0457 1.0985 0.9252 The first conclusion is that Python dictionaries are wicked fast. There are few cases where PyJudy is faster, though perhaps there might be a few more if I knew more about the Python extension API. Bear in mind though that the Judy arrays are in sorted order and the JudyL* classes have ways to access elements by order. The second is that Judy1 arrays are faster than Python's set data type. The above uses the C implementation from the CVS build of Python 2.5a0 (built March 19; I should CVS update). The Python version in 2.3 is about 10 times slower. BUGS AND KNOWN PROBLEMS There are no known bugs in PyJudy 1.0. The iterator type names are not detailed enough to know exactly which container they come from. The keys in the JudySL{Int,Obj} classes have a wrapper-defined hard-limit of 100,000 characters. This is a compile-time constant. Contributes for using a dynamic buffer gladly accepted. There are some inefficiencies because the Judy data structures don't exactly map to Python dictionaries or sets. For example, JudySL arrays don't have a Count function, which is needed for the Python dictionary protocol. The PyJudySL{Int,Obj} wrappers therefore manually track all insertions and deletions. But there's no way for a JudySLInt to know if an added string key created a new entry or replaced an old one. Instead the current implementation first checks to see if the entry exists before doing a delete. This entails a double lookup. For better performance integer keys and values must be exactly Python's integer type. The "__int__" method and subclassing are not supported. PyJudy does not check for Judy errors. Given that the wrapper handles the interface correctly the only time that will be a problem is if you run out of memory. PyJudy does not implement the JudyHS array. I have no need for them. Contributions gladly accepted. PyJudy does not implement the full Python protocols for dictionaries or sets. Contributions gladly accepted. I don't know how much of the API needs to be exposed for C programmers. This is the first time I've delved into Python's extension API for dictionary-like objects. I likely missed some nuances that can make for better performance and extensibility. For example, should I use the METH_COEXIST added in Python 2.4? LEGALThis program and its documentation is copyright (c) 2005 by Dalke Scientific Software, a limited liabiliy company registered in New Mexico, USA. It is released under the MIT license. For details see the file LICENSE in the distribution.
http://www.dalkescientific.com/Python/PyJudy.html
CC-MAIN-2013-20
refinedweb
2,953
59.6
Google Groups [ANN] BBEdit 10.5 (3215) pre-release Rich Siegel Sep 30, 2012 7:00 PM Posted in group: BBEdit Talk Good { morning, afternoon, evening }, We've been busy. :-) A new version is in the works, with a whole bunch of new features, refinements, and improvements. We're happy to make a pre-release build available to the list, so that you have a little extra time to play with it before the rest of the world gets hold of the goodies. :-) Note that this is a _pre-release_ version.. Nobody will be offended if you choose to do so; you're under no obligation to install and use anything but a public release. :-) Following is a summary of the changes in the software since the last public release. The change notes are organized into additions, changes, and fixes, and are annotated where appropriate with case numbers. So if you recognize a number corresponding to a support case that was opened for you, you can now verify that it's been fixed correctly. Please take the time to review the changes before using the new build -- there are a lot of them, and it'll be worth your time. One final note: If you run into a bug in a pre-release version, PLEASE DO NOT REPORT THE BUG TO THE LIST. This includes asking about whether others have seen the same problem. Instead, please send a bug report to < sup...@barebones.com > and we will deal with it there. This will help us keep the list discussion on topic and productive for all list members. ============================================================================ version 10.5 (3215) (9/30/2012) *** The system requirements for BBEdit have changed with version 10. Mac OS X 10.6 is now required (10.6.8 or later recommended). *** BBEdit 10.5 contains extensive internal rework; the primary goal is to achieve proper appearance on Macs with the high-resolution "Retina" displays, but the opportunity was also taken to remove unnecessary code, and to effect various cosmetic and usability improvements. There will be some drawing glitches and fit-and-finish issues; please report anything that you run into that falls into that category (as well as any other functional bugs that you may encounter in new or changed features). Additions --------- * [DOC]). * [DOC]. * [DOC] [225565] When creating a new HTML document (from the dialog or from a template), there's a new substitution available: `#LOCALE#`. This is the "short" locale code corresponding to the "Language" setting in the dialog box, e.g. `en`, `de`, `x-klingon`, and the like. * [DOC]. * [DOC]. * [DOC]. * Tags file discovery has been enhanced, and no longer relies strictly on directory scanning. Tags files are discovered using Spotlight; a file whose name is `tags` or whose name ends in `.tags` and are on their way out. * Text windows get a scripting property: "display magnification". This is a float; 1.0 is normal display. set display magnification of window 1 to 2.0 -- displays text at 2x Note that the display magnification is independent of the font size setting. * [247004] There's a new switch for the `bbedit` tool: `-m` (long form `--language`). This allows you to specify a language name on the command line when piping data in to `bbedit` from a Unix tool. For example: `some-process | bbedit bbedit -m json` (Historical note: `-l` was already taken, which is why we didn't use it here. If it helps, you can use the mnemonic "`-m` is for `*mode*`".) Changes ------- *** Beta Note: The "Sites" tab in the Setup window will be going away before this release is finalized; there will soon be no more separate configuration for web sites. Please take a moment to convert any configured sites to projects. The easiest way to do this is to drop the local site root folder onto BBEdit, and then use "Save Project", then use the Site menu as described above to configure the project. * [DOC] Unix script output logs now live in `~/Library/Logs/BBEdit/`, either in "`Unix Script Output.log`", or, in the case of script-file-specific log files, in `~/Library/Logs/BBEdit/Unix Script Output/{script name}.log`. * [DOC] . * [DOC]. * [DOC]. * [DOC] "` search for or replace with a line break, use `` * [DOC]. * [DOC] "Convert to ASCII" is gone as a discrete menu command; its ability has been rolled into "Zap Gremlins". ("Replace with Code" will replace with the nearest ASCII equivalent.) [NFR] The dialog box hasn't been updated yet. * [DOC]. * [DOC] There's new iconography for the toolbar and navigation bar. * [DOC].) * [DOC] Shell worksheets get a new icon to indicate `sudo` mode. * [DOC] There's a new preference in the Appearance preferences: "Document Lock State". This controls whether the padlock indicator is visible in the status area (next to the save date). When the padlock is visible, you can click on it to unlock (or lock) the document. [246786] * [DOC] In the Multi-File Search window, you can now choose Zip archives (or any file that looks like a Zip, including things like EPUB) as the source for a multi-file search (or replace). * [DOC]. * . [230824, 230828] * [DOC] The Find Differences results windows no longer display the pencil next to the new and old file names. - [DOC] In addition to toggling Soft Wrap, the Text Display menu lets you change the wrap mode. Those options are now also in the toolbar's Text Options menu. * [DOC] The legacy `AutoAssignCommandKeysToWindows` expert preference (which was deprecated in 10.0 and actually never documented) has been removed, along with all of the machinery that used it. *. * [238429] When considering dropped files for insertion or linking, the application will now inspect their contents in cases in which the file metadata doesn't indicate that it's a text file. * [242388]. * [250761]. Fixes ----- * [227319, 227581]. * [227542] Fixed bug in which certain malformations in codeless language modules were not detected early enough to prevent them from causing problems later on. * [227630] Fixed bug in which "Run in Terminal" and "Run in Debugger" were inappropriately sticky for scripts run from the Scripts or Apply Text Filter menus. * [225821] Made a change to reduce the amount of time spent loading names from tags files for syntax coloring. * [228847]. * [228775] Fixed bug in which changing the Soft Wrap Text settings (Page Guide/Window Width/Character Width) in per-language preferences would set them to the wrong value. * [229675]. * [230959] Fixed bug in which the window shape saved by "Save Default Project Window" was not honored when opening a folder or making a new project from scratch. * [231141, 231160] Fixed missing Command-key modifier on the keyboard equivalent for Un/Comment. * Added a few more types to the list of things that BBEdit recognizes as text documents. * [231470] Made a change to avoid tickling a bug on 10.6.x which could cause stalls or a crash while saving file references in projects and a few other locations. * [230888] Attribute values that look like they're dynamically generated are now skipped by the HTML syntax checker, in order to suppress the errors that would result. * [231022]. * [232393] Fixed internal exception and subsequent crash which would occur when trying to save a Grep pattern (via the Setup window) with an empty field. * [232454] Fixed bug in which a now-unused preference from an old version would cause the toolbar to remain visible, even when all of the gating preferences were turned off in the Appearance prefs. * [225989] Fixed bug in which included files were not properly located when specified relative to the site root of a configured web site. * [234061] Fixed bug in which Preview in BBEdit didn't work correctly for Lasso documents. * [231853] Fixed bug in which contextual-menu markup commands were not available in Lasso documents, even when the selection range was in an HTML tag. * [233323]. * [230802] Fixed a bug in which folders in project windows would sometimes refuse to twist open after opening the project. * [238347] Fixed bug in which "Copy as Styled Text" would cause a crash when applied to certain files (dependent on syntax coloring). * [236384] Fixed bug in which "Replace All" or "Replace to End" would fail in cases where the most recent direct search from the Find window was a "Find Previous", and there were no matches between the start of the selection range and the beginning of the document. * [238856]. * [239546]. * [239293] Fixed crash which would occur when decoding AppleDouble files from within Zip archives, and the file was missing an entry for the resource fork. * [239930] Fixed bug in which using the "Close" contextual menu to save and close multiple documents would result in the documents being neither saved nor closed. * [240040] Fixed bug in which the file type filter setting was not correctly retained when closing and reopening a project. Along the way, cleaned up some glitches in the file filter menu. * [239350] Added some missing search keywords for items in the Application preferences. * [239741] Added comment strings to the Verilog and VHDL language modules. * [239744] Changed the embedded Textile preview script to properly use UTF-8 I/O so that non-ASCII characters preview correctly. * [240440] Fixed a crash when starting up with items in our Startup Items folder and DragThing running. * [239046] Fixed crash which would occur when using a service to open items while DragThing was running (and in a couple of other situations). * [241023] Fixed a crash which would occur while trying to locate ctags files relative to a file that had been implicitly created by a command of the form `bbedit ../path/to/some/file.txt`, when the file in question didn't exist yet. * [239609].) * [239609] Fixed bug in which windows created while BBEdit was in full screen mode would end up with their title bars under the menu bar after exiting full screen mode. * [232164] Completion is now allowed in "content" runs of TeX documents. * [241141] When the HTML function scanner sees a `<script>` tag missing an explicit language qualifier, it will now assume the element to contain JavaScript, so that JS function detection and folding work correctly within. * [240781] Fixed bug in which C++ typedefs containing namespace declarations would confuse the function scanner. * [240628]. * [242498] Fixed bug in which using "Save to FTP Server" on an open document would not correctly update the information in the Currently Open Documents list (or in the project). * [242733] Added "rgba" to the CSS keywords list. * [202009] Fixed bug in which automatically generated CSS markup would inappropriately use tabs for indentation, instead of spaces, when "Auto-Expand Tabs" was turned on in the document being marked up. * [243058, 243075]). * [242379] The inline collapsed-text "pill" indicator is now scaled appropriately for a larger range of font sizes (and looks more attractive at all sizes). * [244179, 244195] useable. * [249069]. * [241471] When enumerating an Xcode project, eliminate duplicates to avoid duplicate results in the Open File by Name window (and other places). * [241763, 249599, 249653] Fixed bug in which soft-wrap indentation preferences were not correctly applied when printing. * [237977] Improved guessing of Objective-C/C++ files. * [237712, 237748] Fixed bug in which the last line of the selection would be skipped entirely when doing a "Print Selection", if the selection did not end with a line break. * [233851] Fixed bug in which ridiculously long strings were not selectable in the search history menu. * [214362] "Select Line" and "Select Paragraph" are now disabled in the Find and Multi-File Search windows. * [216755] Fixed bug which allowed disk browser windows to be collapsed to zero width. * [230312] You can now use "Replace to End" when the Find window is in front (assuming that the window immediately behind is also an eligible target for a Replace All operation). * [242436] Truncate the file name in the "Run..." sheet (on the `#!` menu) to avoid wrapping in the control. * [244745] Fixed impedance mismatch in the scripting system internals, in which testing for uniqueness of an item's name was case sensitive, but resolving references to items by name was case *in*sensitive,.) * [239040] Fixed bug in which the Markup Builder panel would appear in outer space if the insertion point (or selection range) had been scrolled out of view. * [237083] Fixed bug in which the "Apply Text Filter" head menu couldn't be hidden, and corrected the name in the Menus & Shortcuts preferences. * [242317] Added plurals for project classes in the scripting terminology. * [222361] Added "`!`" to the list of characters which is considered when deciding whether a string needs to be shell-escaped before sending it to the Terminal. * [219751] Fixed bug in which the HTML checker was looking for the wrong kind of delimiter in 'headers' table attributes. * [242595]). * [241294]. * [250505] Fixed formatting of `<script>`, `<style>`, and other tags with special content considerations when using a profile (including the "Pretty Print" option). * [220727]]). * [217064] Canonicalize filter names for the "Apply [Last] Text Filter" command. * [212349] Fixed bug in which the `ProjectsOpenItemsOnSingleClick` expert preference was not honored for the Project and Recent lists, as it should have been. - [247800] Corrected bug which caused the Text Encodings preference pane to display stale values after Restore Defaults, unless the app was quit and restarted. - [216584] If you dismiss the Markup Builder panel while the combo box is open, we now hide the combo box. * [250819]). * [250673] Fixed bug in which the line number bar didn't always refresh correctly when adjusting the line spacing preference. * [225566] When creating a new HTML document using a Unicode encoding, non-ASCII characters in the title are no longer entity-escaped, since they don't need to be. * [250715] Fixed bug in which list views with keyboard focus wouldn't allow keystrokes that didn't belong to them to propagate to the rest of the system. - [247639] A bug in the python module caused folds to start in the wrong place when a foldable, non-comment block began with a comment. - [232534, 232491] A Java file's fold points and function popup would become confused if, under certain circumstances, a class instance was created and properties were accessed all in the same statement, such as with `new Foo(new Bar(bat).baz())`. * [250556] Attempts to change the soft wrap mode to an invalid value using the scripting interface will now report an error. * [220082] Fixed crash which would occur when leaving certain terms blank in a file filter. * [251132] Fixed bug in which the "Edit" button for editing the `known_hosts` file in case of an SSH host verification failure didn't work on newer versions of the OS. * [250771] "Save As" is now disabled when the active document is "synthetic" (derived from the contents of a Zip archive or tarball, or downloaded directly from a URL). Use "Save a Copy", which behaves correctly in ways that "Save As" did not when it was inappropriately enabled. * [229793] Removed inappropriate attribute specifications from the `<script>` tag definition in the HTML 4.0/4.01 syntax checker definitions. * [238413] The font panel accessory view (with the tab width setting) no longer comes and goes whenever the font panel's event target changes; this in turn eliminates the tendency of the font panel to "shimmy" when closing or opening a bunch of documents. * [227013] Fixed bug in which the per-language tab width setting wasn't properly applied when changing a document's language setting. * Added large and high-resolution icons for the application. =end= The package can be downloaded from our web server: < > Enjoy, R. -- Rich Siegel Bare Bones Software, Inc. < sie...@barebones.com > < >
https://groups.google.com/forum/m/?_escaped_fragment_=msg/bbedit/FKooO9-0o1k/zmFYlTRp6m0J
CC-MAIN-2016-50
refinedweb
2,589
61.26
I am a 'programmer' who cares much about localization. As we work all over the world, this is not always easy. Fortunately most of our clients are highly educated and speak English very well. Nevertheless, I do care about localizing our applications. One of the things that kept irritating me was the fact that, at least under Windows™ XP, the MessageBoxes didn't care about the Thread.CurrentThread.CurrentUICulture. Whatever I set it to, the messagebox buttons would use the language of the installed version of Windows. So, having a bit of time, I decided to search for a solution. I 'Googled' and 'Googled', but none of the articles I found handled the problem to my satisfaction. So after some deliberation I decided to write a MessageBox replacement. MessageBoxes Thread.CurrentThread.CurrentUICulture MessageBox And to thank you all for the many tips and tricks found on CodeProject I decided to write this article as well. The replacement should satisfy a number of requirements: MessageBoxEx And, having decided to write my own messagebox, I liked to include a number of additions that were missing from Microsoft's version. They were: Future addition might be the possibility to define your own captions. So I started the project. Much of it was relatively straightforward. But a number of interesting problems, or better challenges, soon came to light. I don't know how Microsoft does it, but when you support multiple languages (and multiple fonts), you cannot simply give the form and buttons a constant size. On the other hand I didn't want to have the button size varying with the buttons shown. Once a language was selected, all the buttons should have the same size. Luckily the number of texts is fairly small, so the solution was to measure all the possible captions and pick the widest to determine the button size. To give a nice appearance I discovered that a size relative to the measured size worked best. I could have chosen to apply a fixed margin instead, but this looks better. The code that does this: private static System.Drawing.SizeF measureButtons(Font usedFont) { SizeF maxSize = new Size(1,1); SizeF size; // Measure all button captions in current culture and find widest: size = measureString(Deltares.Controls.Properties.Resources.buttonTextAbort, usedFont); if (size.Width > maxSize.Width) maxSize = size; ..... // Apply padding: maxSize = new SizeF((int)(1.6f * maxSize.Width), (int)(1.75f * maxSize.Height)); return maxSize; } The next problem was displaying the help. There are a number of Show methods which cause a messagebox to add a help button. Adding the button was no problem, but how did the messagebox function without knowing which file to display? After some experimenting I discovered that the original box probably used the information from a HelpProvider on the main form. If I did not supply one, pressing the help button did nothing. If I had one and gave it the correct HelpNamespace, a press on the help button would show the file. Okay, now I needed to mimic this behaviour. This took me deep into the System.Reflection namespace. But I did solve it! Just loop over all types in the EntryAssembly (that's the one likely to contain a HelpProvider). Then check if the type is a form. If it is, loop over it's fields to find if any of them is a HelpProvider. If it is, use Activator to create an instance and GetValue on the field to get access to this HelpProvider. Check if the namespace is provided, and if it is, we are done: Show HelpProvider HelpNamespace System.Reflection Activator GetValue Assembly ass = Assembly.GetEntryAssembly(); Type[] types = ass.GetTypes(); foreach (Type type in types) { if (type.BaseType.Equals( typeof(System.Windows.Forms.Form))) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fi in fields) { if (fi.FieldType.Equals(typeof(System.Windows.Forms.HelpProvider))) { // Yes, we have a form with a HelpProvider. Use reflection to create an instance if it: object inst = Activator.CreateInstance(type); System.Windows.Forms.HelpProvider hp = fi.GetValue(inst) as System.Windows.Forms.HelpProvider; // If we have succeeded and the provider has a non-null HelpNamespace, take the value as the helpfile: if ((hp != null) && (hp.HelpNamespace != null)) { return hp.HelpNamespace; } } } } } You will find above code in the getHelpFilePath method of the MessageBoxEx class. getHelpFilePath To pass all the extra information to a messagebox that required it (font, colours, etc), I could have chosen to create a multitude of new overloads. Added to the 21 already existing, that would have created too many variations. So I decided to only add 21 new overloaded methods, each having one extra structure added to the list of arguments. The structure would then contain all the information needed for the extra functionality. Thus the MessageBoxExtras. MessageBoxExtras To specify a time-out, you can enter the number of milliseconds to wait. It has to be a value between 1 and 86400000 (one day). To inform the user that the box will disappear, I display a count-down progressbar. As soon as it reaches 0, the default action as defined by the defaultButton parameter, will be taken. However the system progressbar is so ugly ... so I added a simple 'subclassed' progressbar. The whole progressbar is provided via the MessageBoxExtras, and you can use the system bar as well as the replacement. How prominent the bar is you can decide by setting the height to the correct value before passing it in. defaultButton To count down from the specified time I used a timer. But if you use a System.Windows.Forms.Timer, the thread that is running the screen updates will be blocked so frequently, that the progress bar is not updated often enough. So I use a System.Threading.Timer. But because that timer can be running on any thread from the threadpool, you have to take extra precautions when updating the progress bar. So the code executed each tick checks if an Invoke is required and if so, uses a callback to the method System.Windows.Forms.Timer System.Threading.Timer Invoke There were some other difficulties, but you can inspect the code to find out how I solved them. Even before starting the code for the MessageBoxEx class, I created a sample application to test both the original version and my new version. I simply had to know how the original behaved to be able to create my own version. I could (and should?) have made an application that tested all 42 overloaded Show methods, but decided only to test 4 of them. In the application you can select which messagebox to use: the system one or my version. Of course some options are only available when using the extended version: to use other icons, you can select two additional icons when using the extended box. Of course this is just an example, in real life you can supply your own 32 * 32 pixel icon. To test various fonts and colours, click on the font button or the colour labels. A dialogue will help your select your favourite. Time out (in seconds) is given via the timeout numeric input. The other two checkboxes help you specify that a checkbox should be presented or the form should centre on the owner. And then click on "Try". After selecting an option, you can see that the correct values are returned next to the button. And if a checkbox was present, the state of that checkbox is also displayed. I hope this messagebox replacement helps you create even nicer programs. Any suggestions, criticism and additions (more languages!) are welcome. And don't forget: have fun coding! This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) getButtonCaptions buttonTextHelp // Deltares extra options: if ((buttonFont.Font != this.Font) || (labelBackColour.BackColor != System.Drawing.SystemColors.Control) || (labelForeColour.ForeColor != System.Drawing.SystemColors.ControlText) || (checkBoxTimeOut.Checked) || (checkBoxUseCheckbox.Checked) || (checkBoxCenter.Checked) || ((double)(numericUpDownOpacity.Value) != 1.0)) { if (extras == null) extras = new MessageBoxExtras(); // Apply extra's that differ from default: if (buttonFont.Font != this.Font) extras.Font = buttonFont.Font; if (labelBackColour.BackColor != System.Drawing.SystemColors.Control) extras.BackColor = labelBackColour.BackColor; if (labelForeColour.ForeColor != System.Drawing.SystemColors.ControlText) extras.ForeColor = labelForeColour.ForeColor; if (checkBoxCenter.Checked) extras.CenterOwner = true; if (checkBoxUseCheckbox.Checked) { extras.CheckBox = new CheckBox(); extras.CheckBox.Text = "Do ¬ show again"; extras.CheckBox.Checked = true; } if (checkBoxTimeOut.Checked) { ProgressBarEx p = new ProgressBarEx(); p.Text = null; p.Maximum = (int)(1000 * numericUpDownTimeOut.Value); p.Height = 10; extras.ProgressBar = p; } // Check Opacity here otherwise object extras could be is null and a NullReferenceException is raised. if ((double)(numericUpDownOpacity.Value) != 1.0) extras.Opacity = (double)(numericUpDownOpacity.Value);} } // Moved up into the "Deltares extra options:" block. // if ((double)(numericUpDownOpacity.Value) != 1.0) extras.Opacity = (double)(numericUpDownOpacity.Value); 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/454307/A-versatile-MessageBox-replacement?msg=4397824
CC-MAIN-2015-18
refinedweb
1,492
50.02
"Andrew J. Schorr" <address@hidden> wrote: > > > Are you disabling that ability to create the variable by poking it into > > > SYMTAB > > > > **** THERE IS NO SUCH CAPABILITY ****. The fact that you reference 'age' > > in the program is what puts it into SYMTAB. > > Ah, OK, thanks for clarifying. > > > Your program creates unrelated (non-variable) elements in SYMTAB "name" > > and "weight" that are no different from any other array elements. > > But with your proposed patch, this program will give a fatal error, > won't it? Yes. I think that's an improvement, because people are also confused by SYMTAB["a var"] = 42 > > It is exactly this confusion that I'm trying to avoid. > > I guess there's a question as to whether this is progress or just breaks > sloppy code. Let's break sloppy code! > As I said, I don't like this paradigm because it stomps > on the variable namespace, but I suppose others may be using it... How does it stomp on the variable namespace? It merely misuses SYMTAB. It's not any different than NR == 1 { for (i = 1; i <= NF; i++) PROCINFO[$i] = 0 } You can certainly do that, but it's not what PROCINFO was meant for. In any case, the code is already in master. It'll take a very convincing argument to get me to undo it; I had misgvings when I first implemented SYMTAB about doing it the way I did; expreience has shown that those misgivings were real. Thanks, Arnold
https://lists.gnu.org/archive/html/bug-gawk/2018-12/msg00010.html
CC-MAIN-2019-35
refinedweb
245
71.55
This page describes how to upgrade help files on the secure Symbian platform. Introduction. This section is intended for a general audience. Creating stub SIS files during a build. This section is intended for Licencees. Platform Security makes replacing help files more difficult than it was in earlier, non-secure platform releases. On the secure platform, help files can be loaded only from \resource\help\ on any drive. This directory is read-only and can only be written to by processes with very high capabilities, such as the kernel and the software installer. An exception to the rule that help files cannot be overwritten occurs when the vendor name - held in stub SIS files in the \system\install\ directory on any drive - is the same as that for the previous installation. In this situation the software installer allows the upgrade. The only way to add a help file to a \resource\help\ directory is to install software with the help file packaged in a SIS file. To prevent malicious code from overwriting other applications’ help files (including those of core applications stored in ROM), the software installer will not install a help file if a file with the same name already exists in the \resource\help\ directory, on any drive (unless it is identified by the installer as a valid upgrade). The installer not only prevents you from overwriting another package's help files, but it also prevents you from eclipsing them. For more information, see Language-Neutral Files. Apart from the vendor name, a stub SIS file also contains the information needed to remove the application or file; for example, the full paths of the installed files and application components. Stub SIS files can be distinguised from normal SIS files by their size - stub SIS files are usually several hundred bytes long, much smaller than normal SIS files. Core applications such as Calendar and Contacts are part of the ROM, and so are never installed. To be able to upgrade them and their help files, you must first create stub SIS files for them in the z:\system\install\ directory. You create SIS files from package ( .pkg) files using the makeSIS utility with the -s flag, which excludes binaries and media from the SIS file. For more information, see Upgrading OS Components. Create stub SIS files as part of the build as follows: Create a make file that calls the makeSIS utility (see the example, below). Add the make file to the PRJ_MMPFILES section of the component’s bld.inf file. For example, adding the make file Foo.mk: ///Bld.inf PRJ_MMPFILES makefile Foo.mk An example make file - called Foo.mk, which is used to create Foo.sis - is shown below: # Build Stub SIS file SISNAME=Foo SRCDIR=.\ # Select appropriate directory and ensure it exists !if "$(PLATFORM)"=="WINS" || "$(PLATFORM)"=="WINSCW" TARGETDIR=$(EPOCROOT)EPOC32\RELEASE\$(PLATFORM)\$(CFG)\Z\System\Install !else TARGETDIR=$(EPOCROOT)EPOC32\Data\Z\System\Install !endif $(TARGETDIR) : @perl -S emkdir.pl "$(TARGETDIR)" # Build stub SIS file SISFILE= $(TARGETDIR)\$(SISNAME).sis $(SISFILE) : $(SRCDIR)\$(SISNAME).pkg makesis -s $? $@ do_nothing : rem do_nothing # The targets invoked by abld MAKMAKE : do_nothing RESOURCE : $(TARGETDIR) $(SISFILE) SAVESPACE : BLD BLD : do_nothing FREEZE : do_nothing LIB : do_nothing CLEANLIB : do_nothing FINAL : do_nothing CLEAN : erase $(SISFILE) RELEASABLES : @echo $(SISFILE)
http://devlib.symbian.slions.net/s3/GUID-75E5D15C-83F1-5A32-BFC5-B5DC10FCDB99.html
CC-MAIN-2020-10
refinedweb
541
56.45
Example: Code to generate audio tone793415 Dec 6, 2007 3:18 AM This code shows how to generate and play a simple sinusoidal audio tone using the javax.sound.sampled API (see the generateTone() method for the details). This can be particularly useful for checking a PCs sound system, as well as testing/debugging other sound related applications (such as an audio trace app.). The latest version should be available at.. <> You can launch it directly from.. <> Hoping it may be of use. This can be particularly useful for checking a PCs sound system, as well as testing/debugging other sound related applications (such as an audio trace app.). The latest version should be available at.. <> You can launch it directly from.. <> Hoping it may be of use. package org.physci.sound; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.LineUnavailableException; import java.awt.BorderLayout; import java.awt.Toolkit; import java.awt.Image; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JSlider; import javax.swing.JCheckBox; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.TitledBorder; import java.net.URL; /** Audio tone generator, using the Java sampled sound API. @author andrew Thompson @version 2007/12/6 */ public class Tone extends JFrame { static AudioFormat af; static SourceDataLine sdl; public Tone() { super("Audio Tone"); // Use current OS look and feel. try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(this); } catch (Exception e) { System.err.println("Internal Look And Feel Setting Error."); System.err.println(e); } JPanel pMain=new JPanel(new BorderLayout()); final JSlider sTone=new JSlider(JSlider.VERTICAL,200,2000,441); sTone.setPaintLabels(true); sTone.setPaintTicks(true); sTone.setMajorTickSpacing(200); sTone.setMinorTickSpacing(100); sTone.setToolTipText( "Tone (in Hertz or cycles per second - middle C is 441 Hz)"); sTone.setBorder(new TitledBorder("Frequency")); pMain.add(sTone,BorderLayout.CENTER); final JSlider sDuration=new JSlider(JSlider.VERTICAL,0,2000,1000); sDuration.setPaintLabels(true); sDuration.setPaintTicks(true); sDuration.setMajorTickSpacing(200); sDuration.setMinorTickSpacing(100); sDuration.setToolTipText("Duration in milliseconds"); sDuration.setBorder(new TitledBorder("Length")); pMain.add(sDuration,BorderLayout.EAST); final JSlider sVolume=new JSlider(JSlider.VERTICAL,0,100,20); sVolume.setPaintLabels(true); sVolume.setPaintTicks(true); sVolume.setSnapToTicks(false); sVolume.setMajorTickSpacing(20); sVolume.setMinorTickSpacing(10); sVolume.setToolTipText("Volume 0 - none, 100 - full"); sVolume.setBorder(new TitledBorder("Volume")); pMain.add(sVolume,BorderLayout.WEST); final JCheckBox cbHarmonic = new JCheckBox( "Add Harmonic", true ); cbHarmonic.setToolTipText("..else pure sine tone"); JButton bGenerate = new JButton("Generate Tone"); bGenerate.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { try{ generateTone(sTone.getValue(), sDuration.getValue(), (int)(sVolume.getValue()*1.28), cbHarmonic.isSelected()); }catch(LineUnavailableException lue){ System.out.println(lue); } } } ); JPanel pNorth = new JPanel(new BorderLayout()); pNorth.add(bGenerate,BorderLayout.WEST); pNorth.add( cbHarmonic, BorderLayout.EAST ); pMain.add(pNorth, BorderLayout.NORTH); pMain.setBorder( new javax.swing.border.EmptyBorder(5,3,5,3) ); getContentPane().add(pMain); pack(); setLocation(0,20); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); String address = "/image/tone32x32.png"; URL url = getClass().getResource(address); if (url!=null) { Image icon = Toolkit.getDefaultToolkit().getImage(url); setIconImage(icon); } } /** Generates a tone. @param hz Base frequency (neglecting harmonic) of the tone in cycles per second @param msecs The number of milliseconds to play the tone. @param volume Volume, form 0 (mute) to 100 (max). @param addHarmonic Whether to add an harmonic, one octave up. */ public static void generateTone(int hz,int msecs, int volume, boolean addHarmonic) throws LineUnavailableException { float frequency = 44100; byte[] buf; AudioFormat af; if (addHarmonic) { buf = new byte[2]; af = new AudioFormat(frequency,8,2,true,false); } else { buf = new byte[1]; af = new AudioFormat(frequency,8,1,true,false); } SourceDataLine sdl = AudioSystem.getSourceDataLine(af); sdl = AudioSystem.getSourceDataLine(af); sdl.open(af); sdl.start(); for(int i=0; i<msecs*frequency/1000; i++){ double angle = i/(frequency/hz)*2.0*Math.PI; buf[0]=(byte)(Math.sin(angle)*volume); if(addHarmonic) { double angle2 = (i)/(frequency/hz)*2.0*Math.PI; buf[1]=(byte)(Math.sin(2*angle2)*volume*0.6); sdl.write(buf,0,2); } else { sdl.write(buf,0,1); } } sdl.drain(); sdl.stop(); sdl.close(); } public static void main(String[] args){ Runnable r = new Runnable() { public void run() { Tone t = new Tone(); t.setVisible(true); } }; SwingUtilities.invokeLater(r); } } This content has been marked as final. Show 11 replies 1. Re: Example: Code to generate audio tone843802 Mar 27, 2008 5:05 AM (in response to 793415)Any reason why you call getSourceDataLine() twice? This is quite handy, thank you. 2. Re: Example: Code to generate audio tone793415 Mar 27, 2008 11:12 PM (in response to 843802) JLudwig wrote:Oh wait, I know this one (..snaps fingers. yes) it is because I am a mor0n, and forgot the class level (static) attribute declared earlier in the source when I (re)declared the local attribute and called getSourceDatLine (which was redundant, given the next line, which as you point out also called getSourceDataLine). Any reason why you call getSourceDataLine() twice? .. There are (at least) two ways to correct this problem. 1) Remove the class level attribute and the second call. 2) Remove the local attribute as well as the first call (all on the same code line). Method 1 makes more sense, unless you intend to refactor the code to only instantiate a single SDL for however many times the user presses (what was it? Oh yeah..) 'Generate Tone'. My 'excuse' for my odd programming is that this was 'hacked down' from a longer program to form an SSCCE. I should have paid more attention to the fine details (and perhaps run a lint checker on it). Thanks for pointing that out. I guess from the fact you spotted it, that you have already corrected the problem. That you thought to report it, gives me confidence that you 'will go far (and be well thought of, besides)' in the open source community. ..This is quite handy, thank you.You're welcome. Thanks for letting us know about the error (OK - the pointless redundancy). Thanks to your report, other people who see this code later, will not have to wonder what (the heck) I was thinking when I did that. Another thing I noted, now I run the source on a 400MHz laptop (it's hard times, here) is that the logic could be improved. At the speeds that my laptop can feed data into the SDL, the sound that comes out the speakers approximates the sound of flatulence (with embedded static, as a free bonus!). Edit 1: Changed one descriptive word so that it might get by the net-nanny. Edited by: AndrewThompson64 on Mar 27, 2008 11:09 PM 3. Re: Example: Code to generate audio tone843802 Apr 16, 2008 7:05 AM (in response to 793415)Please help I'm trying to use your code as a guide to create DTMF tones. The DTMF requirements are to produce 2 tones at different frequencies. If you do a search on wikipedia they have a nice little table. I can get the first tone to produce the right note and I can get the second note to produce the right note, individually. However when I do: I dont get the two tones to be produced in the proper manner. Can you help me adjust this code to work? double angle = i / (frequency / hz1)* ttpi; double angle2 = i / (frequency / hz2) * ttpi; buf[0] = (byte) (Math.sin(angle) * volume); buf[1] = (byte) (Math.sin(2*angle2) * (volume)); sdl.write(buf, 0, 2); 4. Re: Example: Code to generate audio tone793415 Apr 16, 2008 8:11 AM (in response to 843802)The problem is most probably in the code you did not write. Post an SSCCE* to a new thread, add some dukes, and if I see it and have time, I'll look into it (assuming somebody else does not see the code and solve it first). * Google it. 5. Re: Example: Code to generate audio tone843802 Apr 16, 2008 8:44 AM (in response to 793415)Started a new thread Edited by: karlmarxxx on Apr 16, 2008 1:43 AM 6. Re: Example: Code to generate audio tone843802 Apr 20, 2008 4:50 AM (in response to 793415) AndrewThompson64 wrote:middle c is certainly not 441 hz. : ) sTone.setToolTipText( "Tone (in Hertz or cycles per second - middle C is 441 Hz)"); frequencies 7. Re: Example: Code to generate audio tone793415 Apr 21, 2008 1:28 AM (in response to 843802) TuringPest wrote:That's a pity. In that case, amend that to.. AndrewThompson64 wrote:middle c is certainly not 441 hz. : ) sTone.setToolTipText( "Tone (in Hertz or cycles per second - middle C is 441 Hz)"); frequencies ;-) sTone.setToolTipText( "Tone (in Hertz or cycles per second)"); 8. Re: Example: Code to generate audio tone843802 Aug 11, 2008 6:35 PM (in response to 793415)First of all I thank you for posting this code. It is very much what I need. Now, when I run the program I get hard sounds at both beginning and end of the tone. Is this just a symptom of a crappy sound system, poor quality headphones, or is it avoidable by coding? I am trying to convert a Morse code training program that I wrote quite a few years ago in C. The hard sounds in the headphones would get very tiring very quickly. Any help you can give me would be greatly appreciated. I think that I might have to ramp up the volume at the beginning of the tone and ramp it down again at the end. First, is this possible and second, is there a better way to eliminate the hard sounds? Thanks. 9. Re: Example: Code to generate audio tone843802 Nov 26, 2008 2:13 PM (in response to 793415)To avoid static: In the generateTone method, you have put sdl.start() just after sdl.open(af). Instead put sdl.start() and put it just after the for loop and just before sdl.drain(). Hope that helps. Ram -- 10. Re: Example: Code to generate audio tone843802 Mar 16, 2009 11:29 PM (in response to 793415)you might want to look at JSyn: [] or leave the world altogether and look at SuperCollider : [] sc3*2 11. Re: Example: Code to generate audio tonePhHein Mar 17, 2009 8:08 AM (in response to 843802)Please stop posting to years old threads. Locking.
https://community.oracle.com/message/5393149
CC-MAIN-2020-34
refinedweb
1,730
51.14
go to bug id or search bugs for Description: ------------ Currently php throws bogus warning with non-compound name in use statement. Reproduce code: --------------- namespace My; use Foo; new Foo\Bar; Expected result: ---------------- Fatal error: Class 'Foo\Bar' not found in ... Actual result: -------------- Warning: The use statement with non-compound name 'Foo' has no effect in ... Fatal error: Class 'Foo\Bar' not found in ... 'use Foo' has effect, because fully qualified name isn't My\Foo\Bar but Foo\Bar. Add a Patch Add a Pull Request Duplicated of Bug #46755 Yes, but bug isn't fixed, 'use ArrayObject' is same as 'use \ArrayObject' manual is wrong. Please consider importing non-compound class or namespace names without \ prefix (remove invalid warning). assign to namespace maintainer This bug has been fixed in CVS. Snapshots of the sources are packaged every three hours; this change will be in the next snapshot. You can grab the snapshot at. Thank you for the report, and for helping us make PHP better.
https://bugs.php.net/bug.php?id=46979
CC-MAIN-2020-24
refinedweb
166
65.62
Created on 2017-01-25 16:03 by Poddster, last changed 2017-02-07 18:35 by vinay.sajip. This issue is now closed. If you write a really big string to an empty file, and that string is > maxBytes, then `RotatingFileHandler` (or even `BaseRotatingHandler`) will roll that empty file into the backup queue. I think it should instead use that empty file for the mega-string. By not doing so it "wastes" a slot in the backup queue. It's a very minor issue: I doubt it really happens IRL, but I noticed it when extending RotatingFileHandler in py2.7 to add gzip stuff and my test cases used a really small size (16 bytes!) Here's a test file: #!/usr/bin/env python3 # coding=utf-8 import logging import os import tempfile from logging.handlers import RotatingFileHandler class MockRecord(object): def __init__(self, msg): self.msg = msg self.stack_info = None self.exc_info = None self.exc_text = None def getMessage(self): return self.msg def test_file_rollover_from_mega_string(temp_dir_path): # This is a pretty weird test. # It tests that writing a huge string to a blank file causes the blank # file to be archived and the huge string written to the next log file. # # Normally the log files would have a large max bytes so we'd have to # be writing a giant string to an empty file for this to happen. # But, even if it does, it's what BaseRotatingHandler does, so... log_path = os.path.join(temp_dir_path, "mylog.log") handler = RotatingFileHandler(log_path, maxBytes=16, backupCount=5) handler.setFormatter(logging.Formatter()) with open(log_path) as log: assert log.read() == "" # ---------------------------------------------- handler.emit(MockRecord("There once was a test from bitbucket")) with open(log_path) as log: log_read = log.read() assert log_read == "There once was a test from bitbucket\n" with open(log_path + ".1") as log: log_read = log.read() assert log_read == "" # ---------------------------------------------- handler.emit(MockRecord("11 chars")) with open(log_path) as log: log_read = log.read() assert log_read == "11 chars\n" with open(log_path + ".1") as log: log_read = log.read() assert log_read == "There once was a test from bitbucket\n" with open(log_path + ".2") as log: log_read = log.read() assert log_read == "" handler.close() test_file_rollover_from_mega_string(tempfile.mkdtemp()) and here's a patch that I think will fix it: ~/src/others/cpython (master *%=)$ cat empty_rollover.patch diff --git a/Lib/logging/handlers.py b/Lib/logging/handlers.py index 7d77973..0dabfd7 100644 --- a/Lib/logging/handlers.py +++ b/Lib/logging/handlers.py @@ -186,7 +186,11 @@ class RotatingFileHandler(BaseRotatingHandler): if self.maxBytes > 0: # are we rolling over? msg = "%s\n" % self.format(record) self.stream.seek(0, 2) #due to non-posix-compliant Windows feature - if self.stream.tell() + len(msg) >= self.maxBytes: + size = self.stream.tell() + if size == 0: + # No point rolling-over an empty file + return 0 + elif size + len(msg) >= self.maxBytes: return 1 return 0 I don't see the point - your proposed solution only works if the log file is completely empty at rollover time, but if the file contains a few bytes from an earlier "short" log message, it might seem just as wasteful of a backup slot as if it had zero bytes. I think the understanding is that maxBytes should be large compared to the size of an average log message, and that if that isn't the case, the user will live with the consequences because it's a contrived scenario (for tests, etc.) rather than a real-life one. There's always the option of subclassing if a user really does need bespoke rollover behaviour.
https://bugs.python.org/issue29372
CC-MAIN-2021-49
refinedweb
585
69.18
for connected embedded systems send() Send a message to a connected socket Synopsis: #include <sys/types.h> #include <sys/socket.h> ssize_t send( int s, const void * msg, size_t len, int flags );(), sendto(), and sendmsg() functions are used to transmit a message to another socket. The send() function can be used only when the socket is in a connected state, while sendto() and send. - EPIPE - An attempt was made to write to a pipe (or FIFO) that isn't open for reading by any process. A SIGPIPE signal is also sent to the process. - EWOULDBLOCK - The socket is marked nonblocking and the requested operation would block. Classification: See also: getsockopt(), ioctl(), recv(), select(), sendmsg(), sendto(), socket(), write()
http://www.qnx.com/developers/docs/6.3.2/neutrino/lib_ref/s/send.html
crawl-003
refinedweb
117
65.73
When do you use Django CBVs or FBVs? Do I use function-based views, class-based views or generic CBVs? It’s no big deal. Right now, there’s three major (built-in) ways to write a view in Django. Either you: - write a simple function - write a class which inherits from the View class or - choose one of the dozen-or-so generic class-based views to extend It can feel like a huge decision – you don’t know if the decision will bite you eventually, or if you’re missing out on something really cool. But it’s not. Simple is better than complex The third line in the Zen of Python is a good guiding rule, and applies in this case. Especially when you’re starting out, you don’t need to find solutions to problems you don’t have. For simple views and apps, you can make a great deal of progress before you run into the reasons why class-based views were introduced. When you feel like you’re repeating yourself too often, is a good time to look into CBVs and mixins. Until then, you can get the same functionality with any of the methods. If you’re comfortable with function-based views, you can continue using them. If you started out with class-based views you can go a long way, just inheriting from the View class. Be wary of trying to customized generic CBVs without learning about them in-depth. Usually, it’s just easier to write your own non-generic view, than trying to use them unprepared. I prefer the class-based views which are based on the View class, unless the project is large enough that there’s a lot of repetition going on. Then you can refactor to be more on the DRY side of things. A Simple Comparison Reading code helps to get a feel for this topic, and move on. Let’s look at how rendering a template would look with all three methods. We’re going to write a class-based view, which inherits from the View class, use a generic TemplateView with a bit of custom context data to pass to the template and a function-based view: from django.shortcuts import render from django.views import View from django.views.generic import TemplateView class TestViewCBV(View): def get(self, request): template_name = 'test.html' # this data dict will be added to the template context data = {} data["message"] = "Hi!" return render(request, template_name, data) def post(self, request): # we don't handle POST requests pass class TestViewGeneric(TemplateView): template_name = "test.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['message'] = "Hi!" # this data dict will be added to the template context return context def test_view(request): if request.method == 'GET': template_name = 'test.html' # this data dict will be added to the template context data = {} data["message"] = "Hi!" return render(request, template_name, data) else: # we don't handle POST requests pass All of them do the same thing - render a template upon receiving a GET request. The class-based view and function-based view simply ignore POST requests. If you want to add more functionality - I’d stick to the class-based view or the function-based view, and ditch the generic TemplateView when starting out, instead of trying to customize it. Either way, you’re fine using FBVs or CBVs - just don’t try to get too fancy with GCBVs in the beginning, and you’ll be fine :)
https://vsupalov.com/django-cbv-vs-fbv-beginner/
CC-MAIN-2019-43
refinedweb
583
64.3
Home -> Community -> Usenet -> c.d.o.server -> SQL Tuning talk - What Oracle Doesn't Know Can Hurt You! I just gave this talk at our local SCIOUG usergroup today and thought I'd post it on the newsgroup. It is about the limitations of the Oracle optimizer and how it sometimes miscalculates the number of rows a query will return (its cardinality) and results in a bad plan. The zip file has a paper, slides, and scripts. The SCIOUG web site is if you live in the Greenville, SC area and want to check it out. Received on Wed Jun 13 2007 - 16:01:33 CDT Original text of this message
http://www.orafaq.com/usenet/comp.databases.oracle.server/2007/06/13/0684.htm
CC-MAIN-2017-51
refinedweb
111
81.73
I'm making a java program beep using some code borrowed from a web page (can't find that helpful page's URL), but the code snipet is below. And it beeps very nicely. I'm running Ubuntu 11.10 ( AMD64) with pulseaudio. While my java beeps just fine if no other application is using sound, if I have any other app making a sound, the beep is never heard. Many other application all seem to work at the same time with pulseaudio, but it seems that java requires exclusive use of the sound system if it is to work at all. Is there any way around this? I want java to beep while I play a some music (for example). I have tried this using sun/oracle java & openjdk. I have also tried running 'padsp java ...' - all with the same negative result. Searching the web throws up quite a few examples of people having similar problems, but none with a workable solution (that I've seen so far). Thanks for any help. ======= byte[] buf = new byte[msecs*8]; for (int i=0; i<buf.length; i++) { double angle = i / (8000.0 / hz) * 2.0 * Math.PI; buf[i] = (byte)( } AudioFormat af = new AudioFormat( SourceDataLine sdl = AudioSystem. sdl.open(af); sdl.start(); sdl.write( sdl.drain(); Question information - Language: - English Edit question - Status: - Solved - Assignee: - No assignee Edit question - Solved: - 2011-10-30 - Last query: - 2011-10-30 - Last reply: - 2011-10-28 Thanks for the suggestion. I have tried those ideas and: 1. java.awt. 2. javax.swing. 3.System. The problem is a bit more general than just a simple beep. It seems that java is not using pulse even though it appears to be configured for it. According to 'sound.properties' # OpenJDK on Ubuntu is configured to use PulseAudio by default javax.sound. javax.sound. javax.sound. javax.sound. But I can change these values to any garbage and java sound still works the same way. (i.e. java sound works ok if no other sound app is running but is silent otherwise). So, as far as I can tell sound.properties is not being used as expected. Further, when I do get sound (while no other sound apps are running), the PulseAusio 'Sound Settings' Applications tab does not show my java app. It is empty. This makes me think that Java is not using Pulse at all. I have been doing some blind hacking and tried to use the icedTea PulseAudioMixer So, I suspect that something is wrong with the configuration of java/sound.propties and whatever makes the java load the PulseAudioMixer Thanks for any help. Some progress: 1. Messing about by directly using PulseAudioMixer 2. Using code from the helpful person at http:// I have been able to make sound work with Pulse, but only when I explicitly run the java program with extra arguments: -Djava. -cp /usr/lib/ While this works, and it is a solution for me, I think it points to a problem with how java is configured on Ubuntu (OK, maybe not just Ubuntu - I've not tried another distro yet). I don't think these extra arguments should be required - shouldn't this be taken care of by the "sounds.properties" config file? Coming back to this today, I find I can run it without the extra args and it works fine. Must have been having a bad week last week. Sorry for the noise. It depends on what you mean by beep. If you want beeps inside a music synthesizer then your solution may be the best. If you want an alert signal then the following should work. public class beep { Toolkit. getDefaultToolk it().beep( ); UIManager. getLookAndFeel( ).provideErrorF eedback( null); System. out.println( "\007\007\ 007"); public static void main(String[] args) { // java.awt. // javax.swing. } } The commented out lines are supposed to work. The AWT and Swing functions seem to assume an onboard sound card, which I don't have -- so they were silent when executed on my computer. The "System. out.println" method works fine.
https://answers.launchpad.net/ubuntu/+source/pulseaudio/+question/176480
CC-MAIN-2021-10
refinedweb
679
75.71
Hi, First time posting in the forum so please excuse any odd formatting. I wonder if anyone could help me with a problem. I created a custom factor called LastTwelveQuarters(...), inspired by Jamie McCorriston where I get the 12 latest quarters of e.g. revenue. I want to take these 12 latest quarters to do as following within the pipeline: Step 1) Calculate the percentage difference between the quarter one year vs the same quarter the year before. An example could be 2019Q1 / 2018Q1, 2018Q1 / 2017Q1 etc. This would give me a total of 8 values from the 12 latest quarters. Step 2) Create a filter that only includes stocks with a revenue growth of at least 10% on average based on the 8 values from step 1. Step 3) Rank the stocks based on the standard deviation of the revenue growth from the 8 values, so that the stocks with the lowest standard deviation has the best rank. The hypothesis is that stocks with non-sporadic and consistent revenue growth are better. I would like to do this in the pipeline but am having trouble understanding how to use my custom factor as a base for step 1-3. I understand that I could use the data from LastTwelveQuarters(...) to send the data for each quarter outside of the pipeline (as shown in the pipeline columns) and then process it there, but I would like all of this to be done in the pipeline. Below is my current code. Thank you in advance! from quantopian.pipeline import Pipeline from quantopian.research import run_pipeline from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.factors import Returns, AverageDollarVolume, Latest, CustomFactor from quantopian.pipeline.filters import QTradableStocksUS, StaticAssets from quantopian.pipeline.data import Fundamentals import numpy as np import pandas as pd class LastTwelveQuarters(CustomFactor): # Get the last 12 reported values of the given timestamp + field. outputs = ['q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10', 'q11', 'q12'] window_length = (195 + 65)*3 # Tell pipeline that this is window_safe even though it really isn't window_safe = True def compute(self, today, assets, out, timestamp, values): for column_ix in range(timestamp.shape[1]): _, unique_indices = np.unique(timestamp[:, column_ix], return_index=True) quarterly_values = values[unique_indices, column_ix] if len(quarterly_values) < 12: quarterly_values = np.hstack([ np.repeat([np.nan], 12 - len(quarterly_values)), quarterly_values, ]) quarterly_values = quarterly_values[-12:] out[column_ix] = quarterly_values def make_pipeline(): universe = StaticAssets(symbols(['AAPL'])) rev_quarters = LastTwelveQuarters(inputs = [Fundamentals.total_revenue_timestamp, Fundamentals.total_revenue], mask=universe) # Step 1) # Step 2) # Step 3) billion = 1000000000 return Pipeline( columns={ 'Rev_1': rev_quarters.q1 / billion, 'Rev_2': rev_quarters.q2 / billion, 'Rev_3': rev_quarters.q3 / billion, 'Rev_4': rev_quarters.q4 / billion, 'Rev_5': rev_quarters.q5 / billion, 'Rev_6': rev_quarters.q6 / billion, 'Rev_7': rev_quarters.q7 / billion, 'Rev_8': rev_quarters.q8 / billion, 'Rev_9': rev_quarters.q9 / billion, 'Rev_10': rev_quarters.q10 / billion, 'Rev_11': rev_quarters.q11 / billion, 'Rev_12': rev_quarters.q12 / billion, }, screen=universe, ) df = run_pipeline(make_pipeline(), '2019-07-01', '2019-07-01') df
https://www.quantopian.com/posts/standard-deviation-slash-computation-on-results-from-custom-factor
CC-MAIN-2019-43
refinedweb
480
51.75
IPX(3) BSD Programmer's Manual IPX(3) ipx_addr, ipx_ntoa - IPX address conversion routines #include <sys/types.h> #include <netipx/ipx.h> struct ipx_addr ipx_addr(const char *cp); char * ipx_ntoa(struct ipx_addr ipx); The routine ipx_addr() interprets character strings representing IPX ad- dresses, returning binary information suitable for use in system calls. The routine ipx_ntoa() takes IPX addresses and returns ASCII strings representing the address in a notation in common use: <network number>.<host number>.<port number> Trailing zero fields are suppressed, and each number is printed in hexa- decimal, in a format suitable for input to ipx_addr(). Any fields lacking super-decimal digits will have a trailing 'H' appended. An effort has been made to ensure that ipx_addr() be compatible with most formats in common use. It will first separate an address into 1 to 3 fields using a single delimiter chosen from period ('.'), colon (':'), or pound-sign ('#'). Each field is then examined for byte separators (colon or period). If there are byte separators, each subfield separated is tak- en separat- ing the millenia. Next, the field is assumed to be a number: It is inter- preted as hexadecimal if there is a leading '0x' (as in C), a trailing 'H' (as in Mesa), or there are any super-decimal digits present. It is interpreted as octal if there is a leading '0' and there are no super- octal digits. Otherwise, it is converted as a decimal number. None. (See BUGS.) hosts(5), networks(5) The precursor ns_addr() and ns_ntoa() functions appeared in 4.3BSD. The string returned by ipx_ntoa() resides in a static memory area. The function ipx_addr() should diagnose improperly formed input, and there should be an unambiguous way to recognize.
http://www.mirbsd.org/htman/i386/man3/ipx_ntoa.htm
CC-MAIN-2014-42
refinedweb
284
55.54
This class interfaces with NumericPad attached to NXShield. More... #include <NumericPad.h> This class interfaces with NumericPad attached to NXShield. class constructor for the NumericPad with an optional custom i2c address parameter Get the key pressed on the keypad. Get all the keys pressed by the user at the present moment function returns: integer value of all keys, each bit that is set to 1 represents a key that is pressed. the bits are set as per keyMap. Only 12 bits can be 1. Initialize the keypad for communication with host. This function also sets up the capacitance values for the keypad with appropriate sensitiviy
http://www.mindsensors.com/reference/NXShield/html/class_numeric_pad.html
CC-MAIN-2018-05
refinedweb
105
58.28
Connect Dart & HTML Write a mini Dart app. To write a Dart web app, you need to understand several topics—the DOM tree, nodes, elements, HTML, and the Dart language and libraries. The interdependencies are circular, but we have to begin somewhere, so we begin with a simple HTML file, which introduces the DOM tree and nodes. From there, you build a bare bones, stripped-down Dart application that contains just enough code to dynamically put text on the page from the Dart side. Though simple, this example shows you how to connect a Dart app to an HTML page and one way that a Dart app can interact with items on the page. These concepts provide the foundation for more interesting and useful web apps. - About the Dart, HTML, and CSS triumvirate - About the DOM - Create a new Dart app - Edit the HTML source code - About the HTML source code - Edit the Dart source code - About the Dart source code - HTML and Dart connections - Give the app some style with CSS - About CSS selectors - Other resources - What next? About the Dart, HTML, and CSS triumvirate If you’ve used DartPad, you’ve already seen the DART, HTML, and CSS tabs that let you write the code for a web app. Each of these three languages is responsible for a different aspect of the web app. A Dart program can respond to events such as mouse clicks, manipulate the elements on a web page dynamically, and save information. Before the web app is deployed, the Dart code must be compiled into JavaScript code. HTML is a language for describing web pages. Using tags, HTML sets up the initial page structure, puts elements on the page, and embeds any scripts for page interactivity. HTML sets up the initial document tree and specifies element types, classes, and IDs, which allow HTML, CSS, and Dart programs to refer to the same elements. CSS, which stands for Cascading Style Sheets, describes the appearance of the elements within a document. CSS controls many aspects of formatting: type face, font size, color, background color, borders, margins, and alignment, to name a few. About the DOM The Document Object Model (DOM) represents the structure of a web document as a tree of nodes. When an HTML file is loaded into a browser, the browser interprets the HTML and displays the document in a window. The following diagram shows a simple HTML file and the resulting web browser page in Chrome. HTML uses tags to describe the document. For example, the simple HTML code above uses the <title> tag for the page title, <h1> for a level-one header, and <p> for a paragraph. Some tags in the HTML code, such as <head> and <body>, are not visible on the web page, but do contribute to the structure of the document. In the DOM, the document object sits at the root of the tree (it has no parent). Different kinds of nodes in the tree represent different kinds of objects in the document. For example, the tree has page elements, text nodes, and attribute nodes. Here is the DOM tree for the simple HTML file above. Notice that some tags, such as the <p> paragraph tag, are represented by multiple nodes. The paragraph itself is an element node. The text within the paragraph is a text node (and in some cases, might be a subtree containing many nodes). And the ID is an attribute node. Except for the root node, each node in the tree has exactly one parent. Each node can have many children. An HTML file defines the initial structure of a document. Dart or JavaScript can dynamically modify that document by adding, deleting, and modifying the nodes in the DOM tree. When the DOM is changed, the browser immediately re-renders the window. The diagram shows a small Dart program that makes a modest change to the DOM by dynamically changing a paragraph’s text. A program could add and delete nodes, or even insert an entire subtree of nodes. Create a new Dart app - Go to DartPad. - Click the New Pad button to undo any changes you might have made the last time you visited DartPad. Edit the HTML source code Click HTML, at the upper left of DartPad. The view switches from Dart code to the (non-existent) HTML code. Add the following HTML code: <p id="RipVanWinkle"> RipVanWinkle paragraph. </p> Click HTML OUTPUT to see how a browser would render your HTML. About the HTML source code This HTML code is similar to the HTML code in the various diagrams earlier in this tutorial, but it’s even simpler. In DartPad you need only the tags you really care about—in this case, <p>. You don’t need surrounding tags such as <html> and <body>. Because DartPad knows where your Dart code is, you don’t need a <script> tag. The paragraph tag has the identifier “RipVanWinkle”. The Dart code you create in the next step uses this ID to get the paragraph element. Edit the Dart source code Click DART, at the upper right of DartPad. The view switches from HTML code to Dart code. Change the Dart code to the following: import 'dart:html'; void main() { querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!'; } Click Run to execute your code. The text in the HTML OUTPUT tab changes to “Wake up, sleepy head!” About the Dart source code Let’s step through the Dart code. Importing libraries The import directive imports the specified library, making all of the classes and functions in that library available to your program. import 'dart:html'; This program imports Dart’s HTML library, which contains key classes and functions for programming the DOM. Key classes include: The Dart core library contains another useful class: List, a parameterized class that can specify the type of its members. An instance of Element keeps its list of child Elements in a List<Element>. Using the querySelector() function This app’s main() function contains a single line of code that is a little like a run-on sentence with multiple things happening one after another. Let’s deconstruct it. querySelector() is a top-level function provided by the Dart HTML library that gets an Element object from the DOM. querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!'; The argument to querySelector(), a string, is a CSS selector that identifies the object. Most commonly CSS selectors specify classes, identifiers, or attributes. We’ll look at these in more detail later, when we add a CSS file to the mini app. In this case, RipVanWinkle is the unique ID for a paragraph element declared in the HTML file, and #RipVanWinkle specifies that ID. querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!'; Another useful function for getting elements from the DOM is querySelectorAll(), which returns multiple Element objects via a list of elements—List Setting the text of an Element In the DOM, the text of a page element is contained in a child node, specifically, a text node. In the following diagram, the node containing the string “RipVanWinkle paragraph.” is a text node. More complex text, such as text with style changes or embedded links and images, would be represented with a subtree of text nodes and other objects. In Dart, you can simply use the Element text property, which has a getter that walks the subtree of nodes for you and extracts their text. querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!'; However, if the text node has styles (and thus a subtree), getting text and then setting it immediately is likely to change the DOM, as a result of losing subtree information. Often, as with our RipVanWinkle example, this simplification has no adverse effects. The assignment operator (=) sets the text of the Element returned by the querySelector() function to the string “Wake up, sleepy head!”. querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!'; This causes the browser to immediately re-render the browser page containing this app, thus dynamically displaying the text on the browser page. HTML and Dart connections The Dart web app changed the text in the browser window dynamically at runtime. Of course, placing text on a browser page and doing nothing else could be accomplished with straight HTML. This little app only shows you how to make a connection from a Dart app to a browser page. In DartPad, the only visible connection between the Dart code and the HTML code is the RipVanWinkle ID. To run your app outside of DartPad, you need to make another connection between the HTML and Dart code: you must add <script> tags to the HTML to tell the browser where to find the Dart code. You must also add other HTML markup to provide additional page information and structure that the browser requires. Here’s the full HTML code for this app, assuming that the Dart code is in a file named main.dart: <!DOCTYPE html> <html> <head> <title>A Minimalist App</title> </head> <body> <p id="RipVanWinkle"> RipVanWinkle paragraph. </p> <script type="application/dart" src="main.dart"></script> <script src="packages/browser/dart.js"></script> </body> </html> The two <script> tags are the only Dart-specific parts of this added HTML. They tie the Dart code into the page, telling the browser where to find the Dart code and what to do with it. The next diagram summarizes all the connections between the Dart and HTML code. Give the app some style with CSS Most HTML uses cascading style sheets (CSS) to define styles that control the appearance of page elements. Let’s customize the CSS for the mini app. Click CSS. The view switches from Dart code to the (non-existent) CSS code. Add the following CSS code: #RipVanWinkle { font-size: 20px; font-family: 'Open Sans', sans-serif; text-align: center; margin-top: 20px; background-color: SlateBlue; color: Yellow; } The display under HTML OUTPUT immediately changes to reflect the new styles, which apply only to the page element that has the ID RipVanWinkle. About CSS selectors IDs, classes, and other information about elements are established in HTML. Your Dart code can use this information to get elements using a CSS selector—a pattern used to select matching elements in the DOM. CSS selectors allow the CSS, HTML, and Dart code to refer to the same objects. Commonly, a selector specifies an ID, an HTML element type, a class, or an attribute. Selectors can also be nested. CSS selectors are important in Dart programs because you use them with querySelector() and querySelectorAll() to get matching elements from the DOM. Most often Dart programs use ID selectors with querySelector() and class selectors with querySelectorAll(). Here are some examples of CSS selectors: Let’s look at the CSS code for the mini app. The CSS file for the mini app has one CSS rule in it. A CSS rule has two main parts: a selector and a set of declarations. In the mini app, the selector #RipVanWinkle is an ID selector, as signaled by the hash tag (#); it matches a single, unique element with the specified ID, our now tired RipVanWinkle paragraph element. RipVanWinkle is the ID in the HTML file. It is referred to in the CSS file and in the Dart code using a hash tag(#). Classnames are specified in the HTML file without a period (.) and referred to in the CSS file and in Dart code with a period (.). Between the curly brackets of a CSS rule is a list of declarations, each of which ends in a semi-colon (;). Each declaration specifies a property and its value. Together the set of declarations define the style sheet for all matching elements. The style sheet is used to set the appearance of the matching element(s) on the web page. The CSS rule for the RipVanWinkle paragraph specifies several properties; for example, it sets the text color to Yellow. Other resources - Dart: Up and Running provides thorough coverage of the Dart language and libraries. - Dart Tools lists IDEs and editors that have Dart plugins. What next? The next tutorial, Add Elements to the DOM, shows you how to dynamically change the HTML page by adding elements to the DOM.
https://www.dartlang.org/docs/tutorials/connect-dart-html/
CC-MAIN-2015-48
refinedweb
2,037
63.19
Opened 6 years ago Closed 17 months ago #15215 closed New feature (duplicate) API for simpler (permission or any) checks for generic view classes Description The generic class based views are difficult and cumbersome to decorate, why even trying to reuse the decorator functions? Why not implement simple functions that would do the checking. I propose following API for checking the class based views (in this case just permissions): from django.contrib.auth.viewchecks import login_required, has_perms class ProtectedView(TemplateView): template_name = 'secret.html' dispatch_checks = (login_required, has_perms('auth.change_user'),) (Notice that I used hypothetical django.contrib.auth.viewchecks) dispatch_checks is list of functions (request, *args, **kwargs) -> bool if allowed to dispatch. Thus the has_perms('auth.change_user') should return function. Above would also allow overriding the dispatch_checks tuple in subclassed views which I think is very important. I'm working on a simple patch for django.contrib.auth and to View class to allow this, these checker functions should be reusable in decorators. Change History (18) comment:1 Changed 6 years ago by comment:2 Changed 6 years ago by Opened up also a thread to django-devs for this if anyone is interested. comment:3 Changed 6 years ago by I'm not convinced that this is exactly the right approach, but after using CBVs in action for a bit, I will grant the premise that it's unnecessarily difficult to add a login_required decorator to a CBV on the class itself. #14512 was an original swing at this with a specific solution aimed at making decorators work for class based views -- it turns out to be inherently complex to do so. The discussions related to that thread provide more detail (thread 1 thread This is (roughly) how I implemented permission checks in one of my projects: def dispatch(self, request, *args, **kwargs): if hasattr(self, 'check_permissions'): self.check_permissions(request, *args, **kwargs) elif self.require_permissions: if not request.user.has_perms(self.require_permissions): raise PermissionDenied return super(TableView, self).dispatch(request, *args, **kwargs) You can use the API in two different ways: class MyView(View): require_permissions = ['app.view_model', 'app2.view_model2'] or: class MyView(View): def check_permissions(self, request, *args, **kwargs): # Custom code If this approach is acceptable, I'm more than happy to try writing a proper patch and tests for inclusion into django. Comments welcome :) If we simply require people to be logged in, we can simply check for login_required boolean attribute on the view: class MyView(View): login_required = True *Edit: added login required check API comment:9 Changed 4 years ago by comment:10 Changed 4 years ago by comment:11 Changed 4 years ago by comment:12 Changed 4 years ago by comment:13 Changed 4 years ago by Accepting the ticket based on the fact that this stuff should be easier. Not sure that the suggested approach is the best way though. comment:14 Changed 3 years ago by I think this ticket and are pretty much the same ticket. Another good spot that has been talked about is here: With all the current comments on the issue I think there are 2 ideas getting mixed with "mixins". 1) A mixin is getting used to only apply decorators, I think that is the case for: @my_decorator class MyView(View): def get: # my code 2) A mixin is being used to define a clean API. (e.g. form_valid, form_invalid, get_context_data) I think point 1 is the one that Django should support, and it should only get applied to dispatch. Looking into a comment by Alex Gaynor I believe this is possible. comment:15 Changed 3 years ago by After spending some time on this, I don't think this is worth the effort at. I think this ticket and the related one should both be closed, in favor of mixins. Thoughts? comment:16 Changed 3 years ago by Talked to Jacob, the solution here is to bring mixins into Django directly. comment:17 Changed 3 years ago by One of these should be kept open to track the issue. This could be implemented as Mixin too, could be more pythonic, kind of like: I have not tested this, but it this ForbiddenMixin should be part of Django it is so general and useful.
https://code.djangoproject.com/ticket/15215
CC-MAIN-2016-44
refinedweb
704
59.84
import a csv file that I created to be used in the plugin CSVTOARRAY, this file is currently in the Files folder in my project. I'm not sure if you can directly use the name of the file, but if you can't you can request it with ajax and use ajax.lastdata.. for more information have a look at the manual for ajax and project-files.. LittleStain I tried the ajax option but the problem is that the project snap can you check the screenshot to see if I am using the ajax correctly "" LittleStain I tried the ajax option but the problem is that the project snap can you check the screenshot to see if I am using the ajax correctly "" If you could give a link that I can open, I could take a look.. This link can't be opened.. Develop games in your browser. Powerful, performant & highly capable. oh sorry here is the link "" Well yeah, that will not work.. How to make a request: The basic usage of the AJAX object consists of: There's an event "Ajax on completed", which will trigger when the request is completed.. Before the request is completed, you won't be able to use the ajax.lastdata.. LittleStain Thank you so much, helped a lot
https://www.construct.net/en/forum/construct-2/how-do-i-18/import-csv-file-used-rex-108480
CC-MAIN-2021-43
refinedweb
218
77.47
#include "avcodec.h" #include "internal.h" #include "aac_ac3_parser.h" #include "ac3.h" #include "ac3_parser.h" #include "ac3dec.h" #include "ac3dec_data.h" Go to the source code of this file. Definition at line 39 of file eac3dec.c. Referenced by ff_eac3_parse_header(). Decode mantissas in a single channel for the entire frame. This is used when AHT mode is enabled. Definition at line 84 of file eac3dec.c. Referenced by decode_transform_coeffs_ch(). Parse the E-AC-3 frame header. This parses both the bit stream info and audio frame header. Definition at line 175 of file eac3dec.c. Referenced by parse_frame_header(). Calculate 6-point IDCT of the pre-mantissas. All calculations are 24-bit fixed-point. Definition at line 54 of file eac3dec.c. Referenced by ff_eac3_decode_transform_coeffs_aht_ch(), and ff_h264_idct8_add_altivec().
http://ffmpeg.org/doxygen/0.5/eac3dec_8c.html
CC-MAIN-2019-09
refinedweb
126
57.74
NetBeans IDE 7 CookbookWelcome to the NetBeans Cookbook. NetBeans is a Java Integrated Development Environment, IDE, which enables fast application development with the most adopted frameworks, technologies, and servers. also read: Different than other IDEs, NetBeans comes already pre-packaged with a wide range of functionality out of the box, such as support for different frameworks, servers, databases, and mobile development. This book does require a minimal knowledge of Java platform, more specifically the language ifself. But the book might as well be used by either beginners, who are trying to dip their toes in new technology, or more experienced developers, who are trying to switch from other IDEs but want to decrease their learning curve of a new environment. NetBeans integrates so many different technologies, many of which are present in this book, that it is beyond the scope of this book to cover all of them in depth. We provide the reader with links and information where to go when further knowledge is required. What This Book Covers Chapter 1, NetBeans Head First introduces the developer to the basics of NetBeans by creating basic Java projects and importing Eclipse or Maven projects. Chapter 2, Basic IDE Usage covers the creation of packages, classes, and constructors, as well as some usability feature. Chapter 3, Designing Desktop GUI Applications goes through the process of creating a desktop application, then connecting it to a database and even modifying it to look more professional. Chapter 4, JDBC and NetBeans helps the developer to setup NetBeans with the most common database systems on the market and shows some of the functionality built-in to NetBeans for handling SQL. Chapter 5, Building Web Applications introduces the usage of web frameworks such as JSF, Struts, and GWT.3 Chapter 6, Using JavaFX explains the basic of JavaFX application states and connecting our JavaFX app to a web service interface. Chapter 7, EJB Application goes through the process of building an EJB application which supports JPA, stateless, and stateful beans and sharing a service through a web service interface. Chapter 8, Mobile Development teaches how to create your own CLDC or CDC applications with the help of NetBeans Visual Mobile Designer. Chapter 9, Java Refactoring lets NetBeans refactor your code to extract classes, interfaces, encapsulate fields, and other options. Chapter 10, Extending the IDE includes handy examples on how to create your own panels and wizards so you can extend the functionality of the IDE. Chapter 11, Profiling and Testing covers NetBeans Profiler, HTTP Monitor, and integration with tools that analyze code quality and load generator. Chapter 12, Version Control shows how to configure NetBeans to be used with the most common version control systems on the market. EJB ApplicationIn this chapter, we will cover: - Creating an EJB project - Adding JPA support - Creating Stateless Session Bean - Creating Stateful Session Bean - Sharing a service through Web Service - Creating a Web Service client Introduction Enterprise Java Beans (EJB) is a framework of server-side components that encapsulates business logic. These components adhere to strict specifications on how they should behave. This ensures that vendors who wish to implement EJB-compliant code must follow conventions, protocols, and classes ensuring portability. The EJB components are then deployed in EJB containers, also called application servers, which manage persistence, transactions, and security on behalf of the developer. If you wish to learn more about EJBs, visit or. For our EJB application to run, we will need the application servers. Application servers are responsible for implementing the EJB specifications and creating the perfect environment for our EJBs to run in. Some of the capabilities supported by EJB and enforced by Application Servers are: - Remote access - Transactions - Security Scalability NetBeans 6.9, or higher, supports the new Java EE 6 platform, making it the only IDE so far to bring the full power of EJB 3.1 to a simple IDE interface for easy development. NetBeans makes it easy to develop an EJB application and deploy on different Application Servers without the need to over-configure and mess with different configuration files. It’s as easy as a project node right-click. Creating EJB project In this recipe, we will see how to create an EJB project using the wizards provided by NetBeans. Getting ready It is required to have NetBeans with Java EE support installed to continue with this recipe. If this particular NetBeans version is not available in your machine, then you can download it from. There are two application servers in this installation package, Apache Tomcat or GlassFish, and either one can be chosen , but at least one is necessary. In this recipe, we will use the GlassFish version that comes together with NetBeans 7.0 installation package. How to do it… - Lets create a new project by either clicking File and then New Project, or by pressing Ctrl+Shift+N. - In the New Project window, in the categories side, choose Java Web and in Projects side, select WebApplication, then click Next. - In Name and Location, under Project Name, enter EJBApplication. - Tick the Use Dedicated Folder for Storing Libraries option box. - Now either type the folder path or select one by clicking on browse. - After choosing the folder, we can proceed by clicking Next. - In Server and Settings, under Server, choose GlassFish Server 3.1. - Tick Enable Contexts and Dependency Injection. - Leave the other values with their default values and click Finish. The new project structure is created. How it works… NetBeans creates a complete file structure for our project. It automatically configures the compiler and test libraries and creates the GlassFish deployment descriptor. The deployment descriptor filename specific for the GlassFish web server is glassfish-web.xml. Adding JPA support The Java Persistence API (JPA) is one of the frameworks that equips Java with object/ relational mapping. Within JPA, a query language is provided that supports the developers abstracting the underlying database. With the release of JPA 2.0, there are many areas that were improved, such as: - Domain Modeling - EntityManager - Query interfaces - JPA query language and others We are not going to study the inner workings of JPA in this recipe. If you wish to know more about JPA, visit or. NetBeans provides very good support for enabling your application to quickly create entities annotated with JPA. In this recipe, we will see how to configure your application to use JPA. We will continue to expand the previously-created project. Getting ready We will use GlassFish Server in this recipe since it is the only server that supports Java EE 6 at the moment. We also need to have Java DB configured. GlassFish already includes a copy of Java DB in its installation folder. Another source of installed Java DB is the JDK installation directory. If you wish to learn how to configure Java DB, please refer to Chapter 4, JDBC and NetBeans. It is not necessary to build on top of the previous recipe, but it is imperative to have a database schema. Feel free to create your own entities by following the steps presented in this recipe. How to do it… - Right-click on EJBApplication node and select New Entity Classes from Database…. - In Database Tables: Under Data Source, select jdbc/sample and let the IDE initialize Java DB. - When Available Tables is populated, select MANUFACTURER, click Add, and then click Next. - In Entity Classes: leave all the fields with their default values and only in Package, enter entities and click Finish. How it works… NetBeans then imports and creates our Java class from the database schema, in our case the Manufacturer.java file placed under the entities package. Besides that, NetBeans makes it easy to import and start using the entity straightaway. Many of the most common queries, for example find by name, find by zip, and find all, are already built into the class itself. The JPA queries, which are akin to normal SQL queries, are defined in the entity class itself. Listed below are some of the queries defined in the entity class Manufacturer.java: @Entity @Table(name = "MANUFACTURER") @NamedQueries({ @NamedQuery(name = "Manufacturer.findAll", query = "SELECT m FROM Manufacturer m"), @NamedQuery(name = "Manufacturer.findByManufacturerId", query = "SELECT m FROM Manufacturer m WHERE m.manufacturerId = :manufacturerId"), The @Entity annotation defines that this class, Manufacturer.java, is an entity and when followed by the @Table annotation , which has a name parameter, points out the table in the Database where the information is stored. The @NamedQueries annotation is the place where all the NetBeans-generated JPA queries are stored. There can be as many @NamedQueries as the developer feels necessary. One of the NamedQueries we are using in our example is named Manufacturer.findAll, which is a simple select query. When invoked, the query is translated to: SELECT m FROM Manufacturer m On top of that, NetBeans implements the equals, hashCode, and toString methods. Very useful if the entities need to be used straight away with some collections, such as HashMap. Below is the NetBeans-generated code for both hashCode and the toString methods: @Override public int hashCode() { int hash = 0; hash += (manufacturerId != null ? manufacturerId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Manufacturer)) { return false; } Manufacturer other = (Manufacturer) object; if ((this.manufacturerId == null && other.manufacturerId != null) || (this.manufacturerId != null && !this.manufacturerId. equals(other.manufacturerId))) { return false; } return true; } NetBeans also creates a persistence.xml and provides a Visual Editor, simplifying the management of different Persistence Units (in case our project needs to use more than one); thereby making it possible to manage the persistence.xml without even touching the XML code. A persistence unit , or persistence.xml , is the configuration file in JPA which is placed under the configuration files, when the NetBeans view is in Projects mode. This file defines the data source and what name the persistence unit has in our example: <persistence-unit <jta-data-source>jdbc/sample</jta-data-source> <properties/> </persistence-unit> The persistence.xml is placed in the configuration folder, when using the Projects view. In our example, our persistence unit name is EJBApplicationPU , using the jdbc/sample as the data source. To add more PUs, click on the Add button that is placed on the uppermost right corner of the Persistence Visual Editor. This is an example of adding another PU to our project: Creating Stateless Session Bean A Session Bean encapsulates business logic in methods, which in turn are executed by a client. This way, the business logic is separated from the client. Stateless Session Beans do not maintain state. This means that when a client invokes a method in a Stateless bean, the bean is ready to be reused by another client. The information stored in the bean is generally discarded when the client stops accessing the bean. This type of bean is mainly used for persistence purposes, since persistence does not require a conversation with the client. It is not in the scope of this recipe to learn how Stateless Beans work in detail. If you wish to learn more, please visit: or ttps:// In this recipe, we will see how to use NetBeans to create a Stateless Session Bean that retrieves information from the database, passes through a servlet and prints this information on a page that is created on-the-fl y by our servlet. the Chapter 4, JDBC and NetBeans. It is possible to follow the steps on this recipe without the previous code, but for better understanding we will continue to build on the top of the previous recipes source code. How to do it… - Right-click on EJBApplication node and select New and Session Bean…. - For Name and Location: Name the EJB as ManufacturerEJB. - Under Package, enter beans. - Leave Session Type as Stateless. - Leave Create Interface with nothing marked and click Finish. Here are the steps for us to create business m ethods: - Open ManufacturerEJB and inside the c lass body, enter: @PersistenceUnit EntityManagerFactory emf; public List findAll(){ return emf.createEntityManager().createNamedQuery("Manufacturer. findAll").getResultList(); } - Press Ctrl+Shift+I to resolve the following imports: java.util.List; javax.persistence.EntityManagerFactory; javax.persistence.PersistenceUnit; Creating the Servlet: - Right-click on the EJBApplication node and select New and Servlet…. - For Name and Location: N ame the servlet as ManufacturerServlet. - Under package, enter servlets. - Leave all the other fields with their default values and click Next. - For Configure Servlet Deployment: Leave all the default values and click Finish. With the ManufacturerServlet open: After the class declaration and before the processRe quest method, add: @EJB ManufacturerEJB manufacturerEJB; Then inside the processRequest method, first line after the try statement, add: List<Manufacturer> l = manufacturerEJB.findAll(); Remove the /* TODO output your page here and also */. And finally replace: out.println("<h1>Servlet ManufacturerServlet at " + request. getContextPath () + "</h1>"); With: for(int i= 0; i< 10; i++ ) out.pr intln("<b>City</b> " + l.get(i).getCity() + ", <b>State</b> " + l.get(i).getState() +"<br>" ); Resolve all the import errors and save the file. How it works… To execute the code produced in this recipe, right-click on the EJBApplication node and select Run. When the browser launches append to the end of the URL/ManufacturerServlet, hit Enter. Our application will return City and State names. One of the coolest features in Java EE 6 is that usage of web.xml can be avoided if annotating the servlet. The following code does exactly that: @WebServlet(name="ManufacturerServlet", urlPatterns={"/ ManufacturerServlet"}) Since we are working on Java EE 6, our Stateless bean does not need the daunting work of creating interfaces, the @Stateless annotation takes care of that, making it easier to develop EJBs. We then add the persistence unit, represented by the EntityManagerFactory and inserted by the @PersistenceUnit annotation. Finally we have our business method that is used from the servlet. The findAll method uses one of the named queries from our entity to fetch information from the database. Creating Stateful Session Beans If Stateless Session Beans do not maintain state, it is easy to guess what Stateful Session Beans do. Yes, they maintain the state. When a client invokes a method in a stateful bean, the variables (state) of that request are kept in the memory by the bean. When more requests come in, the container makes sure that the same bean is used for the same client. This type of bean is useful when multiple requests are required and several steps are necessary for completing a task. Stateful Beans also enjoy the ease of development introduced by Java EE 6, meaning that they can be created by annotating a POJO with @Stateful. It is not in the scope of this recipe to learn how Stateful Beans work in detail. If you wish to learn more, please visit: Or In this recipe, we will see how to use NetBeans to create a stateful session bean that holds a counter of how many times a request for a method was executed. Getting ready Please find the software requirements and configuration instructions for this recipe in the first Getting ready section of this chapter. This recipe builds on the sources of the previous s recipes. How to do it… - Right-click on the EJBApplication node and select New Session Bean…. - For Name and Location: Name the EJB as CounterManufacturerEJB. - Under Package, enter beans. - Mark Session Type as Stateful. - Leave Create Interface with nothing marked and click Finish. Creating the business method With CounterManufacturerEJB open, add the following variable: private int counter = 0; Then right-click inside the class body and select Insert Code… (or press Alt+Insert) and select Add Business Method…. When the Add Business Method… window opens: - Name it as counter and for Return Type, enter String. - Click OK. Replace the code inside the counter method with: counter++; return ""+counter; Save the file. Open ManufacturerServlet and after the class declaration and before the processRequest method: - Right-click and select Insert Code… or press Alt+Insert. - Select Call Enterprise Bean…. - In the Call Enterprise Bean window, expand the EJB Application node. - Select CounterManufacturerEJB and click OK. Below we see how the bean is injected using annotation: @EJB CounterManufacturerEJB counterManufacturerEJB; Resolve the import errors by pressing Ctrl+Shift+I. Then add to the process request: out.println("<b>Number of times counter was accessed<b> " + counterManufacturerEJB.counter() + "<br><br>" ); Save the file. How it works… NetBeans presents the user with a very easy-to-use wizard for creating beans. As with the stateless bean, we are presented with the different options for creating a bean. This time we select the Stateful Bean. When clicking Finish, the IDE will create the EJB POJO class, place it in the beans package, and annotate, with @Stateful, the class signifying that we have created a Stateful Session Bean. We then proceed to add the logic in our EJB. Through another wizard, NetBeans makes it easy to add a business method. After pressing Alt+Insert, we are presented with the choices of what can be done in that context. After adding the code, we are ready to integrate our EJB with the servlet. Again, pressing Alt+Insert comes in handy when we want to create a reference to our EJB. After the correct bean is selected in the Call Enterprise Bean window, NetBeans creates the code: CounterManufacturerEJB counterManufacturerEJB = lookupCounterManufacturerEJBBean(); And also: private CounterManufacturerEJB lookupCounterManufacturerEJBBean() { try { Context c = new InitialContext(); return (CounterManufacturerEJB) c.lookup("java:global/ EJBApplication/CounterManufacturerEJB!beans.CounterManufacturerEJB"); } catch (NamingException ne) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne); throw new RuntimeException(ne); } } This boatload of code is created by the IDE and enables the developer to fine-tune things like logging over exceptions and other customizations. In fact, this is the way that EJB was called prior to annotations being introduced to Java EE. The method is simply calling the application server context with the lookup method, along with the Remote Method Invocation (RMI) naming conventions used to define our EJB and assign the reference to the object itself. Notice that all this code could be simplified to: @EJB CounterManufacturerEJB counterManufacturerEJB; But we tried to show how much liberty and options the developer has in NetBeans. There’s more… Disabling GlassFish alive sessions. GlassFish and sessions To keep sessions alive in our Application Server GlassFish, we need to navigate to the Services window: - There we will need to expand the Servers node. - Right-click on GlassFish and select Properties. - Click on Preserve Sessions Across Redeployment if you do not want this feature. This option preserves the HTTP sessions even when GlassFish has been redeployed. If the data has been stored in a session, it will be available next time a redeployment occurs. Sharing a service through Web Service Web services are APIs which, in the case of this recipe, access some data over a network from any platform and using any programming language. In the world of cloud computing, web services have become an increasingly popular way for companies to let developers create applications using their data. A good example of this is Twitter. Thanks to exposition of Twitter data through web services, it has been possible to create numerous Twitter clients on virtually all platforms. In this recipe, we will create a web service that returns information from a database table; we will see that this information can be transferred either in XML or JavaScript Object Notation (JSON) format. JSON provides the user with data access simplicity, when compared to XML, since it does not need a bunch of tags and nested tags to work Chapter 4, JDBC and NetBeans. It is possible to create this recipe if an existing database schema and an EJB application exists. However, for the sake of brevity, we will use the sources from the previous recipes. How to do it… Right-click on the EJBApplication node, select New then Other then Web Services and RESTFul Web Services from Entity Class…. - For Entity Classes: On Available Entity classes, select Manufacturer, click Add, and click Next. - For Generated Classes: Leave all the fields with their default values and click Finish. A new dialog, REST Resources Configuration, pops-up; select the first option and click OK. How it works… The REST resources configuration asks the user which way the RESTful resources should be accessed, presenting the user with three different options. We have chosen to use javax.ws.rs.core.Application because it is the standard in Java EE 6 and, thus, increases the portability of the application, instead of the web.xml option. The second option allows the developer to code their way through registering the resources and choosing the service path. To take a look at the generated files, expand the service package. Two java files are present: AbstractFacade.java and manufacturerFacadeREST.java. Opening the ManufacturerFacadeREST.java will show that this file is actually a stateless EJB created by the IDE that is used to interface with the database and retrieve information from it. NetBeans also automatically generates a converter for our ManufacturerResource. This converter is used for creating a resource representation from the corresponding entity instance. Those classes can be found in the converter package. There’s more… Using NetBeans to test the web services. Testing the web service Now that we have created a RESTful web service, we need to know if everything is working correctly or not. To test our web service, right-click EJBApplication and select Test RESTful Web Service. NetBeans will be launched; deploy our application in GlassFish and then point the browser to the web service. When the Test RESTful Web Service page opens, click on the Test button on the right side. Upon clicking Test, the test request is sent to the server. The results can be seen in the response section. Under Tabular View, it is possible to click in the URI and get the XML response from the server. Raw View, on the other hand, returns the entire response, as it would be handled by an application. It is also possible to change the format in which the response is generated. Simply click on the drop-down Choose method to test from GET(applicatio n/xml) to GET(application/json) and click Test. Then click on Raw View to get a glimpse of the response. Creating a web service client In this recipe, we will use Google Maps to show how NetBeans enables developers to quickly create an application using web services provided by third parties. Getting ready It is require d. For our recipe to work, we will need a valid key for the Google Maps API. The key can be found at: On the site, we will generate the key. Tick the box that says I have read and agree with the terms and conditions, after reading and agreeing of course. Under My website URL, enter: Or the correct port in which GlassFish is registered. Then click on Generate API key. The generated key looks something like: ABQIAFDAc4cEkV3R2yqZ_ooaRGXD1RT8M0brOpm-All5BF9Po1KBxRWWERQsusT9yyKEXQ AGcYfTLTyArx88Uw Save this key, we will be using it later. How to do it… Creating the Java Web Project - Click File and then New Project or Press Ctrl+Shift+N. - For New Project: On the Categories side, choose Java Web and on the Projects side, select WebApplication. - Click Next. - For Name and Location, under Project Name, enter WebServiceCl ient. - Tick the box on Use Dedicated Folder for Storing Libraries. - Now, either type the folder path or select one by clicking on browse. - After choosing the folder, we can proceed by clicking Next. - For Server and Settings: Under Server, choose GlassFish Server 3.1. - Leave the other options with their default values and click Finish. Creating Servlet Right-click on the WebServiceClient project, and select New and then Servlet…. - For New Servlet: Under Class Name, enter WSClientServlet. - And under package, enter servlet. - Click Finish. When the WSClientServlet opens in the editor, remove the code starting with: /* TODO output your page here And ending with: */ And save the file. Adding a Web Service Navigate to the Services window and expand the Web Services node, followed by Google, and finally Map Service. Accepting a security certificate is required to access this service and to continue with the recipe. Please refer the following screenshot: Drag and drop getGoogleMap into our Servlets processRequest method. A new window, Customize getGoogleMap SaaS Service, pops-up. - Under Input Parameters, double-click the cell on the address row under the Default Value column, to change the value to the desired address (or keep it default if the provided one is okay). - Click OK. When the new block of code is written by NetBeans, uncomment the following line: //out.println(“The SaasService returned: “+result.getDataAsString()); Remember the key generated in the Getting Ready section? In the Projects window, expand the Source Packages node and the package org.netbeans.saas.google, and double-click on googlemapservice.properties. Paste the key after the = operator. The line should look like: api_key=ABQIAFDAc4cEkV3R2yqZ_ooaRGXD1RT8M0brOpm-All5BF9Po1KBxRWWERQsu sT9yyKEXQAGcYfTLTyArx88Uw Save file, open WSClientServlet and press Shift+F6. When the Set Servlet Execution URI window pops-up, click OK. The browser will open with our application path already in place and it will display this: How it works… After dragging and dropping the Google Web Service to our class, a folder structure is created by NetBeans: Let’s check what is in our folder structure: - GoogleMapsService.java: Responsible for checking the coordinates given by the developer, and checks and reads the key from the properties file. - Returns HTML text to access GoogleMap. - RestConnection.java: Responsible for establishing the connection to the Google servers. - RestResponse.java: Holds the actual data returned from Google. - GoogleMapsService: The class that our Servlet uses to interact with the other classes and Google. There’s more… Discovering other web services bundled with the IDE. Other services There are many other web services available in the Web Service section of the IDE. Services such as: - Amazon: EC2 and S3 - Flickr - WeatherBug It is just a matter of checking the documentation of the service provider, and starting to code your own implementation. Try it out!
https://javabeat.net/how-to-create-ejb-project-in-netbeans-7-0/
CC-MAIN-2021-39
refinedweb
4,352
55.44
Matplotlib Animation Tutorial base class, which provides a framework around which the animation functionality is built. The main interfaces are TimedAnimation and FuncAnimation, which you can read more about in the documentation. Here I'll explore using the FuncAnimation tool, which I have found to be the most useful. First we'll use FuncAnimation to do a basic animation of a sine wave moving across the screen: """ Matplotlib Animation Example author: Jake Vanderplas email: vanderplas@astro.washington.edu website: license: BSD Please feel free to use and modify this, but keep the above information. Thanks! """ import numpy as np from matplotlib import pyplot as plt=200, interval=20, blit=True) # # anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264']) plt.show() Let's step through this and see what's going on. After importing required pieces of numpy and matplotlib, The script sets up the plot: fig = plt.figure() ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) line, = ax.plot([], [], lw=2) Here we create a figure window, create a single axis in the figure, and then create our line object which will be modified in the animation. Note that here we simply plot an empty line: we'll add data to the line later. Next we'll create the functions which make the animation happen. init() is the function which will be called to create the base frame upon which the animation takes place. Here we use just a simple function which sets the line data to nothing. It is important that this function return the line object, because this tells the animator which objects on the plot to update after each frame: def init(): line.set_data([], []) return line, The next piece is the animation function. It takes a single parameter, the frame number i, and draws a sine wave with a shift that depends on i: # animation function. This is called sequentially def animate(i): x = np.linspace(0, 2, 1000) y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return line, Note that again here we return a tuple of the plot objects which have been modified. This tells the animation framework what parts of the plot should be animated. Finally, we create the animation object: anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=True) This object needs to persist, so it must be assigned to a variable. We've chosen a 100 frame animation with a 20ms delay between frames. The blit keyword is an important one: this tells the animation to only re-draw the pieces of the plot which have changed. The time saved with blit=True means that the animations display much more quickly. We end with an optional save command, and then a show command to show the result. Here's what the script generates: This framework for generating and saving animations is very powerful and flexible: if we put some physics into the animate function, the possibilities are endless. Below are a couple examples of some physics animations that I've been playing around with. Double Pendulum One of the examples provided on the matplotlib example page is an animation of a double pendulum. This example operates by precomputing the pendulum position over 10 seconds, and then animating the results. I saw this and wondered if python would be fast enough to compute the dynamics on the fly. It turns out it is: """ General Numerical Solver for the 1D Time-Dependent Schrodinger's equation. adapted from code at Double pendulum formula translated from the C code at author: Jake Vanderplas email: vanderplas@astro.washington.edu website: license: BSD Please feel free to use and modify this, but keep the above information. Thanks! """ from numpy import sin, cos import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate import matplotlib.animation as animation class DoublePendulum: """Double Pendulum Class init_state is [theta1, omega1, theta2, omega2] in degrees, where theta1, omega1 is the angular position and velocity of the first pendulum arm, and theta2, omega2 is that of the second pendulum arm """ def __init__(self, init_state = [120, 0, -20, 0], L1=1.0, # length of pendulum 1 in m L2=1.0, # length of pendulum 2 in m M1=1.0, # mass of pendulum 1 in kg M2=1.0, # mass of pendulum 2 in kg G=9.8, # acceleration due to gravity, in m/s^2 origin=(0, 0)): self.init_state = np.asarray(init_state, dtype='float') self.params = (L1, L2, M1, M2, G) self.origin = origin self.time_elapsed = 0 self.state = self.init_state * np.pi / 180. def position(self): """compute the current x,y positions of the pendulum arms""" (L1, L2, M1, M2, G) = self.params x = np.cumsum([self.origin[0], L1 * sin(self.state[0]), L2 * sin(self.state[2])]) y = np.cumsum([self.origin[1], -L1 * cos(self.state[0]), -L2 * cos(self.state[2])]) return (x, y) def energy(self): """compute the energy of the current state""" (L1, L2, M1, M2, G) = self.params x = np.cumsum([L1 * sin(self.state[0]), L2 * sin(self.state[2])]) y = np.cumsum([-L1 * cos(self.state[0]), -L2 * cos(self.state[2])]) vx = np.cumsum([L1 * self.state[1] * cos(self.state[0]), L2 * self.state[3] * cos(self.state[2])]) vy = np.cumsum([L1 * self.state[1] * sin(self.state[0]), L2 * self.state[3] * sin(self.state[2])]) U = G * (M1 * y[0] + M2 * y[1]) K = 0.5 * (M1 * np.dot(vx, vx) + M2 * np.dot(vy, vy)) return U + K def dstate_dt(self, state, t): """compute the derivative of the given state""" (M1, M2, L1, L2, G) = self.params dydx = np.zeros_like(state) dydx[0] = state[1] dydx[2] = state[3] cos_delta = cos(state[2] - state[0]) sin_delta = sin(state[2] - state[0]) den1 = (M1 + M2) * L1 - M2 * L1 * cos_delta * cos_delta dydx[1] = (M2 * L1 * state[1] * state[1] * sin_delta * cos_delta + M2 * G * sin(state[2]) * cos_delta + M2 * L2 * state[3] * state[3] * sin_delta - (M1 + M2) * G * sin(state[0])) / den1 den2 = (L2 / L1) * den1 dydx[3] = (-M2 * L2 * state[3] * state[3] * sin_delta * cos_delta + (M1 + M2) * G * sin(state[0]) * cos_delta - (M1 + M2) * L1 * state[1] * state[1] * sin_delta - (M1 + M2) * G * sin(state[2])) / den2 return dydx def step(self, dt): """execute one time step of length dt and update state""" self.state = integrate.odeint(self.dstate_dt, self.state, [0, dt])[1] self.time_elapsed += dt #------------------------------------------------------------ # set up initial state and global variables pendulum = DoublePendulum([180., 0.0, -20., 0.0]) dt = 1./30 # 30 fps #------------------------------------------------------------ # set up figure and animation fig = plt.figure() ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2)) ax.grid() line, = ax.plot([], [], 'o-', lw=2) time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes) energy_text = ax.text(0.02, 0.90, '', transform=ax.transAxes) def init(): """initialize animation""" line.set_data([], []) time_text.set_text('') energy_text.set_text('') return line, time_text, energy_text def animate(i): """perform animation step""" global pendulum, dt pendulum.step(dt) line.set_data(*pendulum.position()) time_text.set_text('time = %.1f' % pendulum.time_elapsed) energy_text.set_text('energy = %.3f J' % pendulum.energy()) return line, time_text, energy_text # choose the interval based on dt and the time to animate one step from time import time t0 = time() animate(0) t1 = time() interval = 1000 * dt - (t1 - t0) ani = animation.FuncAnimation(fig, animate, frames=300, interval=interval,('double_pendulum.mp4', fps=30, extra_args=['-vcodec', 'libx264']) plt.show() Here we've created a class which stores the state of the double pendulum (encoded in the angle of each arm plus the angular velocity of each arm) and also provides some functions for computing the dynamics. The animation functions are the same as above, but we just have a bit more complicated update function: it not only changes the position of the points, but also changes the text to keep track of time and energy (energy should be constant if our math is correct: it's comforting that it is). The video below lasts only ten seconds, but by running the script you can watch the pendulum chaotically oscillate until your laptop runs out of power: Particles in a Box Another animation I created is the elastic collisions of a group of particles in a box under the force of gravity. The collisions are elastic: they conserve energy and 2D momentum, and the particles bounce realistically off the walls of the box and fall under the influence of a constant gravitational force: """ Animation of Elastic collisions with Gravity author: Jake Vanderplas email: vanderplas@astro.washington.edu website: license: BSD Please feel free to use and modify this, but keep the above information. Thanks! """ import numpy as np from scipy.spatial.distance import pdist, squareform import matplotlib.pyplot as plt import scipy.integrate as integrate import matplotlib.animation as animation class ParticleBox: """Orbits class init_state is an [N x 4] array, where N is the number of particles: [[x1, y1, vx1, vy1], [x2, y2, vx2, vy2], ... ] bounds is the size of the box: [xmin, xmax, ymin, ymax] """ def __init__(self, init_state = [[1, 0, 0, -1], [-0.5, 0.5, 0.5, 0.5], [-0.5, -0.5, -0.5, 0.5]], bounds = [-2, 2, -2, 2], size = 0.04, M = 0.05, G = 9.8): self.init_state = np.asarray(init_state, dtype=float) self.M = M * np.ones(self.init_state.shape[0]) self.size = size self.state = self.init_state.copy() self.time_elapsed = 0 self.bounds = bounds self.G = G def step(self, dt): """step once by dt seconds""" self.time_elapsed += dt # update positions self.state[:, :2] += dt * self.state[:, 2:] # find pairs of particles undergoing a collision D = squareform(pdist(self.state[:, :2])) ind1, ind2 = np.where(D < 2 * self.size) unique = (ind1 < ind2) ind1 = ind1[unique] ind2 = ind2[unique] # update velocities of colliding pairs for i1, i2 in zip(ind1, ind2): # mass m1 = self.M[i1] m2 = self.M[i2] # location vector r1 = self.state[i1, :2] r2 = self.state[i2, :2] # velocity vector v1 = self.state[i1, 2:] v2 = self.state[i2, 2:] # relative location & velocity vectors r_rel = r1 - r2 v_rel = v1 - v2 # momentum vector of the center of mass v_cm = (m1 * v1 + m2 * v2) / (m1 + m2) # collisions of spheres reflect v_rel over r_rel rr_rel = np.dot(r_rel, r_rel) vr_rel = np.dot(v_rel, r_rel) v_rel = 2 * r_rel * vr_rel / rr_rel - v_rel # assign new velocities self.state[i1, 2:] = v_cm + v_rel * m2 / (m1 + m2) self.state[i2, 2:] = v_cm - v_rel * m1 / (m1 + m2) # check for crossing boundary crossed_x1 = (self.state[:, 0] < self.bounds[0] + self.size) crossed_x2 = (self.state[:, 0] > self.bounds[1] - self.size) crossed_y1 = (self.state[:, 1] < self.bounds[2] + self.size) crossed_y2 = (self.state[:, 1] > self.bounds[3] - self.size) self.state[crossed_x1, 0] = self.bounds[0] + self.size self.state[crossed_x2, 0] = self.bounds[1] - self.size self.state[crossed_y1, 1] = self.bounds[2] + self.size self.state[crossed_y2, 1] = self.bounds[3] - self.size self.state[crossed_x1 | crossed_x2, 2] *= -1 self.state[crossed_y1 | crossed_y2, 3] *= -1 # add gravity self.state[:, 3] -= self.M * self.G * dt #------------------------------------------------------------ # set up initial state np.random.seed(0) init_state = -0.5 + np.random.random((50, 4)) init_state[:, :2] *= 3.9 box = ParticleBox(init_state, size=0.04) dt = 1. / 30 # 30fps #------------------------------------------------------------ # set up figure and animation fig = plt.figure() fig.subplots_adjust(left=0, right=1, bottom=0, top=1) ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(-3.2, 3.2), ylim=(-2.4, 2.4)) # particles holds the locations of the particles particles, = ax.plot([], [], 'bo', ms=6) # rect is the box edge rect = plt.Rectangle(box.bounds[::2], box.bounds[1] - box.bounds[0], box.bounds[3] - box.bounds[2], ec='none', lw=2, fc='none') ax.add_patch(rect) def init(): """initialize animation""" global box, rect particles.set_data([], []) rect.set_edgecolor('none') return particles, rect def animate(i): """perform animation step""" global box, rect, dt, ax, fig box.step(dt) ms = int(fig.dpi * 2 * box.size * fig.get_figwidth() / np.diff(ax.get_xbound())[0]) # update pieces of the animation rect.set_edgecolor('k') particles.set_data(box.state[:, 0], box.state[:, 1]) particles.set_markersize(ms) return particles, rect ani = animation.FuncAnimation(fig, animate, frames=600, interval=10,('particle_box.mp4', fps=30, extra_args=['-vcodec', 'libx264']) plt.show() The math should be familiar to anyone with a physics background, and the result is pretty mesmerizing. I coded this up during a flight, and ended up just sitting and watching it for about ten minutes. This is just the beginning: it might be an interesting exercise to add other elements, like computation of the temperature and pressure to demonstrate the ideal gas law, or real-time plotting of the velocity distribution to watch it approach the expected Maxwellian distribution. It opens up many possibilities for virtual physics demos... Summing it up The matplotlib animation module is an excellent addition to what was already an excellent package. I think I've just scratched the surface of what's possible with these tools... what cool animation ideas can you come up with? Edit: in a followup post, I show how these tools can be used to generate an animation of a simple Quantum Mechanical system.
https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/
CC-MAIN-2019-18
refinedweb
2,186
52.46
Created on 2010-02-18 22:19 by jackdied, last changed 2010-12-30 22:14 by georg.brandl. This issue is now closed. Try a demo in the source distribution's Demo/ directory and report here if it doesn't work. Many are unmaintained and should be deleted in favor of examples in the documentation. Why only Python 3.2, why not python 2.7 ? There's only so much free time developers can spend on Python. Also, most demos still work in 2.x, even if they are unmaintained, ugly or demonstrate old concepts. In contrast, most demos weren't tested after porting to 3.x, so many of them don't even run there (and nobody runs them, otherwise we'd have got at least some reports in the tracker). While I was checking 2.7, /Demo/scripts, some of the codes followed the most naive approach (unoptimized) like /Demo/scripts/fact.py which calculate factors and /Demo/scripts/prime.py which calculates prime. Shall I write the optimized version(if no-one have issues), or the rudimentary working versions are good as of now ? Well, these demos are not meant to demonstrate the fastest algorithms, but to demonstrate how easy and readable simple algorithms can be written in Python. That said, if you can write better versions that are also very readable, they'll make a good addition. I've started going through the demos. So far I've gone through cgi and classes. If this is what you're looking for I'll try and go through the rest in the next week or so. Python 3.2a0 /cgi all work /classes Complex.py - fail 1 and Complex(0, 10) -> <class 'TypeError'> Traceback (most recent call last): File "Complex.py", line 314, in <module> test() File "Complex.py", line 310, in test checkop(*(t+item)) File "Complex.py", line 235, in checkop ok = abs(result - value) <= fuzz File "Complex.py", line 184, in __rsub__ return other - self File "Complex.py", line 180, in __sub__ return Complex(self.re - other.re, self.im - other.im) TypeError: unsupported operand type(s) for -: 'type' and 'int' Dates.py - fail Traceback (most recent call last): File "Dates.py", line 227, in <module> test(1850, 2150) File "Dates.py", line 185, in test if (not a < b) or a == b or a > b or b != b: TypeError: unorderable types: Date() < Date() Dbm.py - fail {} key: "myKey" Traceback (most recent call last): File "Dbm.py", line 66, in <module> test() File "Dbm.py", line 49, in test if key in d: File "Dbm.py", line 25, in __getitem__ return eval(self.db[repr(key)]) KeyError: '0' Range.py - fail Exception: error in implementation: correct = range(5, 100, 3) old-style = [5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74, 77, 80, 83, 86, 89, 92, 95, 98] generator = [5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74, 77, 80, 83, 86, 89, 92, 95, 98] Rev.py - fail 1 items had failures: 10 of 17 in Rev ***Test Failed*** 10 failures. Looks like mostly invalid print syntax Vec.py - pass bitvec.py - fail use of __cmp__() use of __*slice__() didn't check further Does “tested” in the title of this issue mean “run” or “unit-tested”? Regarding the 2.7 branch, is this still relevant? I'm assuming tested means "run", and that a good demo is one that "works" for some nominal input. I’m making this a meta-bug to record the evaluation of demos and tools, in followup with the thread “Signs of neglect?” started on. Some of them have already been adopted or deleted. Please add yourself to Misc/maintainers.rst when you adopt one. I also propose adding either a section in the README or a new README.removed file to list the deletions; there are probably people out there using these tools (maybe not demos, though), so it’s more polite to tell them “metaclasses is removed, see this doc for modern built-in metaclasses” than to just remove the file. Regarding testing, please comment on #9153. I fixed Dates.py. See issue9151. I also committed a minimal fix for Complex.py in r82524. I fixed Rev.py in r82550, but I don't think it is worth keeping in the current form. Maybe it can be replaced with a pure python reimplementation of builtins.reversed. Note that slicing does not work for Rev: >>> r = Rev([1,2,3]) >>> r[:] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "Demo/classes/Rev.py", line 69, in __getitem__ return self.forw[-(j + 1)] TypeError: unsupported operand type(s) for +: 'slice' and 'int' Fixed Range.py in r82551. I should note here that I fixed Demo/md5test/md5driver.py in r82351 (py3k) and r82352 (release31-maint). I wonder if it would be possible as a part of Demo and Tools clean-up to move them into packages under Lib. I would really like to be able to do $ python -m demo.turtle instead of (on a Mac) $ cd /Applications/Python\ 2.6/Extras/Demo/turtle/ $ python turtleDemo.py and I still cannot find where Apple decided to put Tools. "instead of (on a Mac) $ cd /Applications/Python\ 2.6/Extras/Demo/turtle/ $ python turtleDemo.py and I still cannot find where Apple decided to put Tools." This has nothing to do with Apple. "/Applications/Python x.y" is created by the python.org OS X installer, not supplied by Apple. See Mac/BuildScript/build-installer.py for the details. AFAIK, the Tools directory is currently not installed by the OS X installer. Should it be? On Mon, Jul 26, 2010 at 11:58 PM, Ned Deily <report. >Does this mean that Apple distributes neither Tools nor Demo? That >would be another reason to move anything anyone cares about to Lib. I believe that neither are included in the Apple-supplied Python in OS X, which resides primarily in /System/Library/Frameworks/Python.framework. In recent OS releases, Apple seems to have taken their cue from the python.org installer framework layouts but tweaked things somewhat. Ronald may have more insight and/or an opinion on this. He's also had some contact with the people inside Apple. What Apple does and doesn't ship is not important for this discussion. FWIW: Apple doesn't ship any of the GUI wrappers installed in /Applications, although they seem to ship Applet Builder as part of Developer tools (beets my why the bother). They don't ship any of the examples or tools, and don't ship documentation as well. Our OSX installer does install most of these, on the assumption that anything that is part of the source distribution might be of interest for users. On Tue, Jul 27, 2010 at 1:49 AM, Ronald Oussoren <report@bugs.python.org> wrote: .. > What Apple does and doesn't ship is not important for this discussion. > I agree. I used Apple as an example because I happened to post from an Apple laptop. I am sure it is similarly hard to find demo programs on every other OS and there is no consistency between different distributions. However they do ship Lib/test. This tells me that they don't try to prune Lib and I think most distributions similarly ship Lib as is. > Our OSX installer does install most of these, on the assumption that anything that is part of the > source distribution might be of interest for users. Installing some of the tools (and I don't think any demos are installed that way) next to python executable presents a namespace problem. Since tools are not consistently prefixed with 'py', they may conflict with system or user tools that happen to be in the path. Support for multiple python versions is also somewhat ad hoc. For example, on my system I have 2to3, 2to32.6 and 2to3-3.1. I do agree that 2to3-3.1 is an improvement over 2to32.6, but how can I guess that idle2.6 gets upgraded to idle3.1 rather than idle-3.1? With -m approach, all I need to know is how to start python of the desired version: python, python2.6, or even ./python.exe from the root of the development tree. It looks like turtle was not the best example for msg111682 because it is already in Lib and python -m turtle runs demo. I am not sure what the relationship between Demo/turtle and the turtle module is. Removed Demo and some of the Tools in a series of commits starting with r87579.
https://bugs.python.org/issue7962
CC-MAIN-2019-47
refinedweb
1,468
76.72
sized-grid Multidimensional grids with sized specified at compile time See all snapshots sized-grid appears in Module documentation for 0.1.1.6 There are no documented modules for this package. sized-grid A way of working with grids in Haskell with size encoded at the type level. Quick tutorial The core datatype of this library is Grid (cs :: '[k]) (a :: *). cs is a type level list of coordinate types. We could use a single type level number here, but by using different types we can say what happened when we move outside the bounds of a grid. There are three different coordinate types provided. Ordinal n: An ordinal can be an integral number between 0 and n - 1. As numbers outside the grid are not possible, this has the most restrictive API. One can convert between an Ordinal and a number of ordinalToNum and numToOrdinal. HardWrap n: Like Oridnal, HardWrap can only hold intergral numbers between 0 and n - 1, but it allows a more permissive API by clamping values outside of its range. It is an instance of Semigroupand Monoid, where memptyis 0 and <>is addition. Periodic n: This is the most permissive. When a value is generated outside the given range, it wraps that around using modular arithmetic. Is is an instance of Semigroupand Monoidlike HardWrap, but also of AdditiveGroupallowing negation. HardWrap and Periodic are both instances of AffineSpace, with their Diff being Integer. This means there are many occasions where one doesn’t have to work directly with these values (which can be cumbersome) and can instead work with their differences as regular numbers. The last type value of Grid is the type of each element. The other main type is Coord cs, where cs is, again, a type level list of coordinate types. For example, Coord '[Periodic 3, HardWrap 4] is a coordinate in a 3 by 4 2D space. The different types ( Periodic and HardWrap) tell how to handle combining theses different numbers. Coord cs is an instance of Semigroup, Monoid and AdditiveGroup as long as each of the coordinates is also an instance of that typeclass. Coord is also an instance of of AffineSpace, where Diff is a n-tuple, meaning we can pattern match and do all sorts of nice things. For working directly with Coords, one can construct them with singleCoord and appendCoord and consume and update them with coordHead and coordTail. They are also instances of FieldN from lens, allowing one to directly update or get a certain dimension. There is a deliberately small number of functions that work over Grid: we instead opt for using typeclasses to create the required functionality. Grid is an instance of the following types (with some required constraints): Functor: Update all values in the grid with the same function Applicative: As the size of the grid is statically known, purejust creates a grid with the same element at each point. <*>combines the grids point wise. Monad: I’m not sure if there is much of a need for this, but an instance exists. Foldable: Combine each element of the grid Traverse: Apply an applicative function over the grid IndexedFunctor, IndexedFoldableand IndexedTraversable: Like Functor, Foldableand Traversable, but with access to the position at each point. These are from the lens package Distributive: Like Traversable, but the other way round. Allows us to put a functor inside the grid Representable: Grid cs ais isomorphic Coord cs -> a, so we can tabulateand indexto make this conversion We also have a FocusedGrid type, which is like Grid but has a certain focused position. This means that we lose many instances, but we gain Comonad and ComonadStore. When dealing with areas around Coords, we can use moorePoints and vonNeumanPoints to generate Moore and von Neuman neighbourhoods. Note that these include the center point. We introduce two new typeclasses: IsCoord and IsGrid. IsGrid has gridIndex, which allows us to get a single element of the grid and lenses to convert between FocusedGrid and Grid. IsCoord has CoordSized, which is the size of the coord and an iso to convert between Ordinal and the Coord. Example - Game of Life As is traditional for anything with grids and comonads in Haskell, we can reimplement Conway’s Game of Life. This is a literate Haskell file, so we start by turning on some language extensions, importing our library and some other utilities. {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE MonoLocalBinds #-} {-# LANGUAGE DataKinds #-} import SizedGrid import Control.Comonad import Control.Lens import Control.Comonad.Store import Data.AdditiveGroup import Data.AffineSpace import Data.Distributive import Data.Functor.Rep import Data.Semigroup (Semigroup(..)) import GHC.TypeLits import qualified GHC.TypeLits as GHC import System.Console.ANSI We create a datatype for alive or dead. data TileState = Alive | Dead deriving (Eq,Show) We encode the rules of the game via a step function. type Rule = TileState -> [TileState] -> TileState gameOfLife :: Rule gameOfLife here neigh = let aliveNeigh = length $ filter (== Alive) neigh in if | here == Alive && aliveNeigh `elem` [2,3] -> Alive | here == Dead && aliveNeigh == 3 -> Alive | otherwise -> Dead We can then write a function to apply this to every point in a grid. applyRule :: ( All IsCoord cs , All Monoid cs , All Semigroup cs , All AffineSpace cs , All Eq cs , AllDiffSame Integer cs , AllSizedKnown cs , IsGrid cs (grid cs) ) => Rule -> grid cs TileState -> grid cs TileState applyRule rule = over asFocusedGrid $ extend $ \fg -> rule (extract fg) $ map (\p -> peek p fg) $ filter (/= pos fg) $ moorePoints (1 :: Integer) $ pos fg We can create a simple drawing function to display it to the screen. displayTileState :: TileState -> Char displayTileState Alive = '#' displayTileState Dead = '.' displayGrid :: (KnownNat (CoordSized x), KnownNat (CoordSized y)) => Grid '[x, y] TileState -> String displayGrid = unlines . collapseGrid . fmap displayTileState Let’s create a glider, and watch it move! glider :: ( KnownNat (CoordSized x GHC.* CoordSized y) , Semigroup x , Semigroup y , Monoid x , Monoid y , IsCoord x , IsCoord y , AffineSpace x , AffineSpace y , Diff x ~ Integer , Diff y ~ Integer ) => Coord '[x,y] -> Grid '[x,y] TileState glider offset = pure Dead & gridIndex (offset .+^ (0,-1)) .~ Alive & gridIndex (offset .+^ (1,0)) .~ Alive & gridIndex (offset .+^ (-1,1)) .~ Alive & gridIndex (offset .+^ (0,1)) .~ Alive & gridIndex (offset .+^ (1,1)) .~ Alive We can now make our glider run! run = let start :: Grid '[Periodic 10, Periodic 10] TileState start = glider (mempty .+^ (3,3)) doStep grid = do clearScreen putStrLn $ displayGrid grid _ <- getLine doStep $ applyRule gameOfLife grid in doStep start main = return () Changes Revision history for sized-grid 0.1.1.5 – 2018-11-21 - Reduced bound on generics-sop 0.1.1.5 – 2018-11-20 - Changed test suite to use QuickCheck 0.1.1.3 – 2018-11-14 - Version bumps 0.1.1.0 – 2018-05-10 - Added Field instances for coord - Added ways of manipulating coords 0.1.0.0 – 2018-04-18 - First version.
https://www.stackage.org/nightly-2018-12-03/package/sized-grid-0.1.1.6
CC-MAIN-2018-51
refinedweb
1,127
64.71
#include <avformat.h> Definition at line 317 of file avformat.h. Definition at line 382 of file avformat.h. If extensions are defined, then no probe is done. You should usually not use extension format guessing because it is not reliable enough Definition at line 370 of file avformat.h. Referenced by av_probe_input_format2(). Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER. Definition at line 366 of file avformat.h. Referenced by av_close_input_file(), av_encode(), av_estimate_timings(), av_open_input_file(), av_probe_input_format2(), av_read_frame_internal(), dump_stream_format(), and img_read_header(). Descriptive name for the format, meant to be more human-readable than name. You should use the NULL_IF_CONFIG_SMALL() macro to define it. Definition at line 324 of file avformat.h. Referenced by show_formats(). Definition at line 392 of file avformat.h. Referenced by av_encode(). Definition at line 318 of file avformat.h. Referenced by av_estimate_timings(), av_find_input_format(), decode_thread(), dump_format(), format_to_name(), set_codec_from_probe_data(), and show_formats(). Definition at line 395 of file avformat.h. Referenced by av_find_input_format(), av_iformat_next(), av_probe_input_format2(), and av_register_input_format(). Size of private data so that it can be allocated in the wrapper. Definition at line 326 of file avformat.h. Referenced by av_open_input_stream(). Close the stream. The AVFormatContext and AVStreams are not freed by this function Referenced by av_close_input_stream(). Read the format header and initialize the AVFormatContext structure. Return 0 if OK. 'ap' if non-NULL contains additional parameters. Only used in raw format right now. 'av_new_stream' should be called to create new streams. Referenced by av_open_input_stream(). Read one packet and put it in 'pkt'. pts and flags are also set. 'av_new_stream' can be called only if the flag AVFMTCTX_NOHEADER is used. Referenced by av_read_packet(). Pause playing - only meaningful if using a network-based format (RTSP). Referenced by av_read_pause(). Start/resume playing - only meaningful if using a network-based format (RTSP). Referenced by av_read_play(). Tell if a given file has a chance of being parsed as this format. The buffer provided is guaranteed to be AVPROBE_PADDING_SIZE bytes big so you do not have to check for that unless you need more. Referenced by av_probe_input_format2(). Seek to a given timestamp relative to the frames in stream component stream_index. Referenced by av_seek_frame(), av_seek_frame_generic(), and open_input_stream(). Seek to timestamp ts. Seeking will be done so that the point from which all active streams can be presented successfully will be closest to ts and within min/max_ts. Active streams are all streams that have AVStream.discard < AVDISCARD_ALL. Gets the next timestamp in stream[stream_index].time_base units. Referenced by av_seek_frame(), and av_seek_frame_binary(). General purpose read-only value that the format can use. Definition at line 372 of file avformat.h.
http://ffmpeg.org/doxygen/0.5/structAVInputFormat.html
CC-MAIN-2014-41
refinedweb
420
54.79
Sometimes it is useful to perform the cross product on a large number of pair of vectors. So a and b may be matrices of N x 3 and: c = cross(a,b) is N x 3 matrix where each row is the dot product of the corresponding rows in a and b. The code may be "vectorized" in the row dimension: > c(:,1)=a(:,2).*b(:,3)-a(:,3).*b(:,2); > c(:,2)=a(:,3).*b(:,1)-a(:,1).*b(:,3); > c(:,3)=a(:,1).*b(:,2)-a(:,2).*b(:,1); This is useful when working with finite element meshes, 3D representation of surfaces, etc... For instance, if a and b are the corresponding sides of a large set of triangles, then c is normal to the triangles and |c| is the area of the triangles. We could check the dimensions of the arrays since there are no possible confusion: > if a and b are 3x1 > compute cross product as column vectors > else if a and b are Nx3 > compute cross product as row vectors > elseif > error > endif Note that we can't consider a and b of the form 3xN since then there is an ambiguity when the matrix is 3x3. I will write such a version and post it to octave-sources in the case that someone else finds it useful. Send comments or suggestions. Cheers, | | |
http://lists.gnu.org/archive/html/help-octave/1997-09/msg00035.html
CC-MAIN-2017-47
refinedweb
229
63.22
numpy.nditer¶ - class numpy. nditer[source]¶ Efficient multi-dimensional iterator object to iterate over arrays. To get started using this object, see the introductory guide to array iteration. Notes nditersupersedes flatiter. The iterator implementation behind nditeris also exposed by the NumPy C API. The Python exposure supplies two iteration interfaces, one which follows the Python iterator protocol, and another which mirrors the C-style do-while pattern. The native Python approach is better in most cases, but if you need the iterator’s coordinates or index, use the C-style pattern. Examples Here is how we might write an iter_addfunction, using the Python iterator protocol: def iter_add_py(x, y, out=None): addop = np.add it = np.nditer([x, y, out], [], [['readonly'], ['readonly'], ['writeonly','allocate']]) with it: for (a, b, c) in it: addop(a, b, out=c) return it.operands[2] Here is the same function, but following the C-style pattern: def iter_add(x, y, out=None): addop = np.add it = np.nditer([x, y, out], [], [['readonly'], ['readonly'], ['writeonly','allocate']]) with it: while not it.finished: addop(it[0], it[1], out=it[2]) it.iternext() return it.operands[2] Here is an example outer product function: def outer_it(x, y, out=None): mulop = np.multiply it = np.nditer([x, y, out], ['external_loop'], [['readonly'], ['readonly'], ['writeonly', 'allocate']], op_axes=[list(range(x.ndim)) + [-1] * y.ndim, [-1] * x.ndim + list(range(y.ndim)), None]) with it: for (a, b, c) in it: mulop(a, b, out=c) return it.operands[2] >>> a = np.arange(2)+1 >>> b = np.arange(3)+1 >>> outer_it(a,b) array([[1, 2, 3], [2, 4, 6]]) Here is an example function which operates like a “lambda” ufunc: def luf(lamdaexpr, *args, **kwargs): "luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)" nargs = len(args) op = (kwargs.get('out',None),) + args it = np.nditer(op, ['buffered','external_loop'], [['writeonly','allocate','no_broadcast']] + [['readonly','nbo','aligned']]*nargs, order=kwargs.get('order','K'), casting=kwargs.get('casting','safe'), buffersize=kwargs.get('buffersize',0)) while not it.finished: it[0] = lamdaexpr(*it[1:]) it.iternext() return it.operands[0] >>> a = np.arange(5) >>> b = np.ones(5) >>> luf(lambda i,j:i*i + j/2, a, b) array([ 0.5, 1.5, 4.5, 9.5, 16.5]) If operand flags “writeonly” or “readwrite” are used the operands may be views into the original data with the WRITEBACKIFCOPY flag. In this case nditer must be used as a context manager or the nditer.close method must be called before using the result. The temporary data will be written back to the original data when the __exit__function is called but not before: >>> a = np.arange(6, dtype='i4')[::-2] >>> with nditer(a, [], ... [['writeonly', 'updateifcopy']], ... casting='unsafe', ... op_dtypes=[np.dtype('f4')]) as i: ... x = i.operands[0] ... x[:] = [-1, -2, -3] ... # a still unchanged here >>> a, x array([-1, -2, -3]), array([-1, -2, -3]) It is important to note that once the iterator is exited, dangling references (like x in the example) may or may not share data with the original data a. If writeback semantics were active, i.e. if x.base.flags.writebackifcopy is True, then exiting the iterator will sever the connection between x and a, writing to x will no longer write to a. If writeback semantics are not active, then x.data will still point at some part of a.data, and writing to one will affect the other. Methods
https://docs.scipy.org/doc/numpy/reference/generated/numpy.nditer.html
CC-MAIN-2018-34
refinedweb
576
53.17
Text Wrangling & Pre-processing: A Practitioner’s Guide to NLP I will highlight some of the most important steps which are used heavily in Natural Language Processing (NLP) pipelines and I frequently use them in my NLP projects. By Dipanjan Sarkar, Intel There are usually multiple steps involved in cleaning and pre-processing textual data. I have covered text pre-processing in detail in Chapter 3 of ‘Text Analytics with Python’ (code is open-sourced). However, in this section, I will highlight some of the most important steps which are used heavily in Natural Language Processing (NLP) pipelines and I frequently use them in my NLP projects. We will be leveraging a fair bit of nltk and spacy, both state-of-the-art libraries in NLP. Typically a pip install <library> or a conda install <library> should suffice. However, in case you face issues with loading up spacy’s language models, feel free to follow the steps highlighted below to resolve this issue (I had faced this issue in one of my systems). # OPTIONAL: ONLY USE IF SPACY FAILS TO LOAD LANGUAGE MODEL # Use the following command to install spaCy > pip install -U spacy OR > conda install -c conda-forge spacy # Download the following language model and store it in disk # Link the same to spacy > python -m spacy link ./spacymodels/en_core_web_md-2.0.0/en_core_web_md en_core Linking successful ./spacymodels/en_core_web_md-2.0.0/en_core_web_md --> ./Anaconda3/lib/site-packages/spacy/data/en_core You can now load the model via spacy.load('en_core') Let’s now load up the necessary dependencies for text pre-processing. We will remove negation words from stop words, since we would want to keep them as they might be useful, especially during sentiment analysis. ❗ IMPORTANT NOTE: A lot of you have messaged me about not being able to load the contractions module. It’s not a standard python module. We leverage a standard set of contractions available in the contractions.pyfile in my repository.Please add it in the same directory you run your code from, else it will not work. import spacy import pandas as pd import numpy as np import nltk from nltk.tokenize.toktok import ToktokTokenizer import re from bs4 import BeautifulSoup from contractions import CONTRACTION_MAP import unicodedata nlp = spacy.load('en_core', parse=True, tag=True, entity=True) #nlp_vec = spacy.load('en_vecs', parse = True, tag=True, #entity=True) tokenizer = ToktokTokenizer() stopword_list = nltk.corpus.stopwords.words('english') stopword_list.remove('no') stopword_list.remove('not') Removing HTML tags Often, unstructured text contains a lot of noise, especially if you use techniques like web or screen scraping. HTML tags are typically one of these components which don’t add much value towards understanding and analyzing text. 'Some important text' It is quite evident from the above output that we can remove unnecessary HTML tags and retain the useful textual information from any document. Removing accented characters Usually in any text corpus, you might be dealing with accented characters/letters, especially if you only want to analyze the English language. Hence, we need to make sure that these characters are converted and standardized into ASCII characters. A simple example — converting é to e. 'Some Accented text' The preceding function shows us how we can easily convert accented characters to normal English characters, which helps standardize the words in our corpus. Expanding Contractions Contractions are shortened version of words or syllables. They often exist in either written or spoken forms in the English language. These shortened versions or contractions of words are created by removing specific letters and sounds. In case of English contractions, they are often created by removing one of the vowels from the word. Examples would be, do not to don’t and I would to I’d. Converting each contraction to its expanded, original form helps with text standardization. We leverage a standard set of contractions available in the contractions.pyfile in my repository. 'You all cannot expand contractions I would think' We can see how our function helps expand the contractions from the preceding output. Are there better ways of doing this? Definitely! If we have enough examples, we can even train a deep learning model for better performance. Removing Special Characters Special characters and symbols are usually non-alphanumeric characters or even occasionally numeric characters (depending on the problem), which add to the extra noise in unstructured text. Usually, simple regular expressions (regexes) can be used to remove them. 'Well this was fun What do you think ' I’ve kept removing digits as optional, because often we might need to keep them in the pre-processed text. Stemming To understand stemming, you need to gain some perspective on what word stems represent. Word stems are also known as the base form of a word, and we can create new words by attaching affixes to them in a process known as inflection. Consider the word JUMP. You can add affixes to it and form new words like JUMPS, JUMPED, and JUMPING. In this case, the base word JUMP is the word stem. Word stem and its inflections (Source: Text Analytics with Python, Apress/Springer 2016) The figure shows how the word stem is present in all its inflections, since it forms the base on which each inflection is built upon using affixes. The reverse process of obtaining the base form of a word from its inflected form is known as stemming. Stemming helps us in standardizing words to their base or root stem, irrespective of their inflections, which helps many applications like classifying or clustering text, and even in information retrieval. Let’s see the popular Porter stemmer in action now! 'My system keep crash hi crash yesterday, our crash daili' The Porter stemmer is based on the algorithm developed by its inventor, Dr. Martin Porter. Originally, the algorithm is said to have had a total of five different phases for reduction of inflections to their stems, where each phase has its own set of rules. Do note that usually stemming has a fixed set of rules, hence, the root stems may not be lexicographically correct. Which means, the stemmed words may not be semantically correct, and might have a chance of not being present in the dictionary (as evident from the preceding output). Lemmatization Lemmatization is very similar to stemming, where we remove word affixes to get to the base form of a word. However, the base form in this case is known as the root word, but not the root stem. The difference being that the root word is always a lexicographically correct word (present in the dictionary), but the root stem may not be so. Thus, root word, also known as the lemma, will always be present in the dictionary. Both nltk and spacy have excellent lemmatizers. We will be using spacy here. 'My system keep crash ! his crash yesterday , ours crash daily' You can see that the semantics of the words are not affected by this, yet our text is still standardized. Do note that the lemmatization process is considerably slower than stemming, because an additional step is involved where the root form or lemma is formed by removing the affix from the word if and only if the lemma is present in the dictionary. Removing Stopwords Words which have little or no significance, especially when constructing meaningful features from text, are known as stopwords or stop words. These are usually words that end up having the maximum frequency if you do a simple term or word frequency in a corpus. Typically, these can be articles, conjunctions, prepositions and so on. Some examples of stopwords are a, an, the, and the like. ', , stopwords , computer not' There is no universal stopword list, but we use a standard English language stopwords list from nltk. You can also add your own domain-specific stopwords as needed. Bringing it all together — Building a Text Normalizer While we can definitely keep going with more techniques like correcting spelling, grammar and so on, let’s now bring everything we learnt together and chain these operations to build a text normalizer to pre-process text data. Let’s now put this function in action! We will first combine the news headline and the news article text together to form a document for each piece of news. Then, we will pre-process them. {'clean_text': 'us unveils world powerful supercomputer beat china us unveil world powerful supercomputer call summit beat previous record holder china sunway taihulight peak performance trillion calculation per second twice fast sunway taihulight capable trillion calculation per second summit server reportedly take size two tennis court', 'full_text': "US unveils world's most powerful supercomputer, beats China. The US has unveiled the world's most powerful supercomputer called 'Summit',."} Thus, you can see how our text pre-processor helps in pre-processing our news articles! After this, you can save this dataset to disk if needed, so that you can always load it up later for future analysis. news_df.to_csv('news.csv', index=False, encoding='utf-8')
https://www.kdnuggets.com/2018/08/practitioners-guide-processing-understanding-text-2.html
CC-MAIN-2019-13
refinedweb
1,500
53.21
In this article we’re going to create a NPM package for React using create-react-app and configure CI/CD using Travis and Heroku. We will create the simplest package — Hello World. This article serves to demonstrate how to publish your NPM package, write tests and configure CI/CD more than how to write code for your package. The first thing we need to do is to create a project. For this we will use create-react-app. This is the best way to start applications based on React library. According to the documentation create-react-app uses Webpack, Babel, EsLint and other projects under the hood. You don’t need to learn and configure many build tools. You can create your own React application using just one command, but if you want an advanced configuration, you can eject from Create React App and edit their config files directly. Before creating the package let’s open the terminal and go to the folder where we will store it. Then let’s create our NPM package: npx create-react-app react-salute cd react-salute npm start Then we open to see our app. Running these commands will create a React application called react-salute in which will be generated the initial project structure and installed the transitive dependencies: react-salute No configuration or complicated folder structures. Everything is quite simple. We will use a src folder as the main folder in our package. We will use it to store our source code, examples and tests. Firstly, let’s create a folder src/lib and inside the folder we create index.js file with the following content: import React from 'react'; import PropTypes from 'prop-types'; const ReactSalute = ({ name }) => { return <h1>Salute {name}!</h1>; }; ReactSalute.propTypes = { name: PropTypes.string.isRequired, }; ReactSalute.defaultProps = { name: 'React', }; export default ReactSalute; Despite the examplesand testsfolders, libfolder will be used to upload to NPM. Great job! Now we have created a component which tells us Salute React! , where we can change React word by passing to the component the name parameter. This code will be compiled and published to NPM. Then we need some ways to check our component locally. For that let’s create a folder /src/examples and there index.js file with the following content: import React from 'react'; import ReactSalute from '../lib'; const Examples = () => { return ( <section> <ReactSalute /> <ReactSalute name="Foo" /> </section> ); }; export default Examples; It’s quite simple. We import our library and create two examples of its use. Now, in order to make things work for us, let’s fix our /src/index.js file: import React from 'react'; import ReactDOM from 'react-dom'; import Examples from './examples'; ReactDOM.render(<Examples />, document.getElementById('root')); To see the result of our work, let’s run npm run and open browser by link. It’s working. Great! We can delete App.css, App.js, App.test.js, index.css, logo.svg, serviceWorker.jsfrom the /srcdirectory. Let’s move on to the next step and create some tests for our package. In this chapter we will follow the create-react-app testing documentation. To test our package, we will use Jest + Enzyme. Enzyme supports full rendering with mount(), and you can also use it for testing state changes and component lifecycle. Let’s install enzyme : npm install --save-dev enzyme enzyme-adapter-react-16 As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React you are using. Create React App uses Jest as its test runner and so it is already installed. The adapter will also need to be configured in our global setup file. To do so, we create an src/setupTests.js file and place the following: import { configure } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; configure({ adapter: new Adapter() }); When we run the npm test command Jest will look for test files with any of the following popular naming conventions: .jssuffix in testsfolders. .test.jssuffix. .spec.jssuffix. The .test.js / .spec.js files (or the tests folders) can be located at any depth under the srctop level folder. Now we can write our tests. Put the index.js file into src/tests folder with the following content: import React from 'react'; import { shallow, mount } from 'enzyme'; import ReactSalute from '../lib'; describe('<ReactSalute />', () => { it('Check default message', () => { const wrapper = shallow(<ReactSalute />); expect(wrapper.text()).toBe('Salute React!'); }); it('Check message passed through props', () => { const name = 'Foo'; const wrapper = shallow(<ReactSalute name={name} />); expect(wrapper.text()).toBe(`Salute ${name}!`); }); it('Check reset props', () => { const name = 'Foo'; const newName = 'Bar'; const wrapper = mount(<ReactSalute name={name} />); expect(wrapper.props().name).toBe(name); wrapper.setProps({ name: newName }); expect(wrapper.props().name).toBe(newName); }); }); We have created 3 test’s cases. The first case checks the default message Salute React!. The second one checks message with passed name. And the final one checks nameparameter change. Our tests are ready, let’s run them: npm test After running the tests, we should see something like the following result in the console: PASS src/tests/index.js <ReactSalute /> ✓ Check default message (7ms) ✓ Check message passed through props (1ms) ✓ Check reset props (32ms)Test Suites: 1 passed, 1 total Tests: 3 passed, 3 total Snapshots: 0 total Time: 2.598s Ran all test suites.Watch Usage: Press w to show more. Our tests are passed and we can move on to the next chapter. The first thing we need to do is to prepare our NPM package and to be exact to compile it. For this, let’s install babel-cli to be able to compile our project using the CLI: npm install --save-dev @babel/cli Since we use create-react-app, all other dependencies for babel are already installed and we don’t need to worry about them. Now we need to tell babel how to process our code correctly. For that we will use presets . Let’s create a .babelrc file with the following content: { "presets": ["react-app"] } As you can see, we have specified only one preset, react-app . It’s required when developing react applications. Then, we add the following command to the scripts section in the package.json : "scripts": { ... "prepublishOnly": "NODE_ENV=production babel src/lib --out-dir dist" }, prepublishOnly — run before the package is prepared and packed, only on npm publish . In our case, we specified telling babel to compile the code into a dist folder, that will be pushed to NPM. Let’s customize our package.json: "name": "react-salute", "version": "0.0.1", "main": "./dist/index.js", "keywords": [ "react", "salute", "react-salute", "hello", "world", "prop-types" ], "repository": { "type": "git", "url": "" }, "author": { "name": "Fedor Yakubovich", "url": "" }, "bugs": { "url": "" }, "files": [ "dist/index.js", "README.md", "LICENSE", "package.json" ], "license": "MIT" ... Let’s figure out how it works: name — name of our package. Required field, when publish to npm. In our case it’s react-salute. version — version of our package. Required field, when publish to npm . Every time we publish our package, the version must be different from the previous one, otherwise there will be an error. main — the main field is a module ID that is the primary entry point to your program. In our case it’s /dist/index.js. keywords — it’s an array of strings which helps people to discover your package as it’s listed in npm search. repository — link to the source code. author —link to the author profile. bugs —the url to your project’s issue tracker and / or the email address to which issues should be reported. files — some special files and directories are also included or excluded regardless of whether they exist in the files array. license — license for our package. You can see the advanced settings package.jsonon the available below link:. Next we need to publish our package to NPM. We need to be registered on the website. So, if you haven’t registered already, let’s do it. Once you have registered, enter the following command and then fill in the data from your account that you will be asked: npm login This command is required to let the installed npm on your PC know who you are and on which behalf you will publish your package. Finally, we can publish our package by running the following command: npm publish Wonderful, we have published our package. In this Chapter, we will not stop on the concept of Continuous Integration. If someone is not familiar with this concept, and in particular with Travis CI, you can read them on the link Core Concepts. It does not take a lot of time. Firstly, we have to register on. All we need is to link our GitHub account to Travis CI. We will use GitHub to store our package, as only GitHub is integrated with Travis CI. Once we have registered, we need to add configuration file of Travis into the root of our project. Let’s create .travis.yml file with the following content: language: node_js node_js: In this file we have described which Travis environment should be used in our project and which command to run. The npm test command is specified in package.json , if we wanted to use a different command for testing, we would have to change our .travis.yml . Then we need to push our changes to GitHub. After we have pushed them, the task should have started in our Travis. If it does not happen we can go to our Dashboard, find our react-salute repository and Trigger a build using the drop-down list on the right. Travis — Trigger a build After the build, we should see something like the following result: Travis — build results It means that our tests are passed. And we, in turn, can move on to the final Chapter. Heroku is a cloud platform which helps to build, deliver, monitor and scale apps. As they call themselves: We’re the fastest way to go from idea to URL. We will use Heroku as a free hosting for our examples. Firstly we need to register on Heroku. We can do this by following the link. Then we have to create a project. To create one, we need to go to the Dashboard and click New->Create new app . Next, we need to enter the name of the project, in our case it is react-salute, and select the region where the server with our application will be located. Choose the region Europe. Heroku — Create new app After submitting the Create app button, we will be redirected to the project deployment settings page. In the Deployment method setup, choose GitHub. Heroku — Deployment method (step 1) Then in the Connected to GitHub setup we will be offered to choose the project that we want to link to Heroku project. We need to choose react-salute . Heroku — Deployment method (step 2) Next, let’s go to setting up Automatic deploys. Here we will be asked to select the branch which will occur the automatic deployment. We need to choose master branch. Also, let’s select Wait for CI to pass before deploy checkbox. It means that Heroku will wait for Travis CI to work successfully. Finally, let’s Enable Automatic Deploys. Heroku — Automatic deploys Now let’s move from the Deploy tab to the Settings tab. In the buildpacks configuration, click the Add buildpack button. In the modal window that opens, in the Buildpack URL field, enter the following address:, and then we save our changes. Heroku — Adding buildpack The create-react-app-buildpack is heroku buildpack, that deploys React.js web apps generated with create-react-app. The buildpack automates deployment with the built-in bundler and serves it up via Nginx. After we have configured Heroku, we need to go to our Github account, and merge our working branch(develop) to master. After merge, Travis CI will start and run our tests. After the tests are successfully passed, Heroku will start build. After successful completion of the build we will be able to enjoy our result. The URL of our package we can look in the Settings tab in the Domains and certificates setup. Heroku — Domains and certificates Let’s open. In this article we have created the simplest NPM package, written the tests for it, configured Travis CI and Heroku for continuous delivery. Using this article, you can create more complex and useful NPM packages and host their live examples for free. You can check out the GitHub repo here. Creating your first npm package ☞ Top 10 npm Security Best Practices ☞ How to publish a React Native component to NPM ☞ npm and the Future of JavaScript ☞ A Beginner’s Guide to npm — the Node Package Manager ☞ Step by step: Building and publishing an NPM Package. ☞ A Beginner’s Guide to npm: The Node Package Manager...
https://morioh.com/p/878fa2b014d4
CC-MAIN-2020-40
refinedweb
2,145
66.23
Re: does VS C++ 2005 actually work???? - From: "Jonathan Wood" <jwood@xxxxxxxxxxxxxxxx> - Date: Wed, 14 Jun 2006 09:50:33 -0600 To each is own. I love the IDE editor and am very productive in it. -- Jonathan Wood SoftCircuits Programming "Joseph M. Newcomer" <newcomer@xxxxxxxxxxxx> wrote in message news:547v82pcoksdbg9jg070gc2u11lh83l1ra@xxxxxxxxxx The new version sounds like it is overly concerned about safety, but #pragma warning() can disable those warnings, so that should be a non-issue. I don't use IntelliSense because it really doesn't work too well; any system that shows the parameter as UINT without giving me a list of the flags I can set or OR into it is pretty useless, so I have to look the function up anyway, and besides, the editor sucks (nobody at Microsoft has a clue how to write a text editor, but they keep pretending, release after release, to have one. I use an external editor which has no Intellisense and works just fine). As I commented in another thread, the desire to use .NET and "trustworthy programming" is not a justification for a crappy interface; you can program Java with a decent interface (see, for example, Eclipse as a platform). People who have never seen VS6 immediately recognize that VS.NET sucks, because they understand how interfaces SHOULD be built, when they are built by mature designers, or at least when built by designers who have adult supervision. Most of my clients are hardcore VS6 users, because it was the last usable version of VS that Microsoft produced. Some have been forced to move to VS.NET because it really does have a great compiler and there are lots of really good features in the newer versions of MFC, and they need one or the other of these (sometimes both), but they well-and-truly despise the IDE. It is an IDE that only its designer can love. And apparently does [further commentary along these lines is not suitable for a family newsgroup, but feel free to use your imaginations] joe On Tue, 13 Jun 2006 18:23:38 -0700, "Sgt. York" <york@xxxxxxxxxxxxxx> wrote: Yeah. Well, our company got the 90-day trial DVD and three of usJoseph M. Newcomer [MVP] volunteered to install the beast for a trial run. We proceeded to import several MFC projects originating from vs.net 2003. In return we were bombed with warnings about the c functions (which is condescending---we know the risk but chose to take it anyway, stop pestering us) and intellisense only worked sometimes (even after rebuilding it numerous times). In fact, I personally found intellisense failing far more often than it ever did in 2003 and given its new, even more enormous size, you'd think nothing would escape it. This is a paraphrase (we had many other issues), but in the end we opted not to upgrade. Admittedly we are a c++ shop that is still not impressed with the evangelical attitude of MS toward .NET (we are also cross-platform), but the whole "feel" of VS 2005 was one of "yeah, this great .NET tool still does some incidental c++ on the side." No thanks, Microsoft. Tom Serface wrote: I also didn't experience any problems. I've been using it for many months now full time and it has worked fine. You could try totally uninstalling it and reinstalling just to make sure something didn't go whacky during installation. Tom "Ian" <Ian00Bell@xxxxxxxxx> wrote in message news:LUFjg.23372$U84.473812@xxxxxxxxxxxxxxxxxxxxxxx I recently purchased Microsoft VS 2005 and just cannot seem to get it working. 1. I tried converting a VS 2002 solution to VS 2005. It took a while to realize there is a bug in Intellisense. The only solution was to disable Intellisense. 2. It seems class view has been rendered inoperable now that Intellisense has been disabled. So this means browsing by namespaces and classes is not possible. 3. I tried debugging the application but it seems the debugger cannot find certain debug libraries such as 'MFC80UD.DLL'. I posted a message and hope someone will know what is happening. I reviewed a number of postings which seemed to suggest it may be necessary to modify the manifest file. I also reviewed several postings regarding redistributable files. But is this all really necessary? After all, I'm just trying debug the application using the IDE. 4. So I downloaded the sample program DBViewer to see if I could run the debugger on this application. The compiler skipped the entire set of files and refused to build it. I am very disappointed with this product and feel like I've wasted my time and money on it. If asked, I would strongly discourage anyone from buying to VS 2005. I really don't know what question to ask at this point. If I cannot even compile and debug a sample program provided by Microsoft then where do I begin???? I've uninstalled and reinstalled VS several times. Are there any Microsoft folks willing to take a stab at helping me out. I suppose if I really wanted a working solution, I should have paid several thousands of dollars for a support contract.... My system: 2.26GHz Pentium 4, 2gig RAM, WinXP Pro, VS 2005 Pro Ian Web: MVP Tips: . - Follow-Ups: - Re: does VS C++ 2005 actually work???? - From: Ian - References: - does VS C++ 2005 actually work???? - From: Ian - Re: does VS C++ 2005 actually work???? - From: Tom Serface - Re: does VS C++ 2005 actually work???? - From: Sgt. York - Re: does VS C++ 2005 actually work???? - From: Joseph M . Newcomer - Prev by Date: Re: DLL linking to another DLL - Next by Date: Re: VS2005 and VS 6.0 - Previous by thread: Re: does VS C++ 2005 actually work???? - Next by thread: Re: does VS C++ 2005 actually work???? - Index(es):
http://www.tech-archive.net/Archive/VC/microsoft.public.vc.mfc/2006-06/msg01074.html
crawl-002
refinedweb
980
73.27
Hello, Build: 3126, OS: Windows I´ve recently been using Sublime and are gradually switching to it for various purposes, as it makes typing extremely efficient. However, what I haven´t come to terms with is a hassle-free typing of Unicode-characters in HEX-format, as I need to do this regulary in my work; I especially encounter weird and seldomly used characters for linguistic purposes very often. What I do at the moment are three different things.(1) I set my keyboard to ISL with special modifications that can be downloaded here: This is especially useful for diacritics. as I can stack them with a few strokes. (2) For certain language-specific characters I hold ALT and type a decimal code, but this doesn´t work with all the characters. (3) The others I just copy from a list which is gradually evolving. I find this procedure especially annoying, and would like to get away from that. What I would like is to be able to type them via Unicode-HEX, for example 03DC for "ϝ" (digamma), then press one or two keys to convert them. In LibreOffice Writer this is possible via 03DC + ALT + c, something like that would suffice. Is there any better way than doing this or some existing packages that can easily be implemented? What are some options? I don´t mind if the characters are displayed in Sublime, as if they don´t exist in the font, as I choose a font in which they will appear in the end. I also don´t mind remembering Unicode-numbers, if there is already a shortcut somewhere involving them. (As you may see from this post, I´m not very apt at programming, and probably even an idiot. If the solutions involve some tinkering with Sublime, I probably need some further elucidation and some kind of starting point.) I am greatful for any help whatsoever. as a super simple (but not-yet-ideal) example of how you could achieve this in ST, you could open the ST console (View menu -> Show Console, which is a Python interpreter), and type \u03DC and it will output the relevant character in the console for you to copy and paste into your main document. A plugin could easily be built around this functionality to make it easier, for example you press a key, it prompts for a hex value, and inserts the character. I realize you said you are not apt at programming, but I don't have time to investigate this right now - just wanted to post a little idea \u03DC you could also look at this proposal for the LaTexTools plugin, which shows a preview of symbols for you to click on:(ovbiously the idea there is a bit different, but you may decide you like the UX) This was a fun little project! You can get the exact same behavior as in LibreOffice, but you have to create some scripts and keybindings for it. Let's start with the TextCommand: import sublime import sublime_plugin class ConvertHexToUnicodeCharacter(sublime_plugin.TextCommand): """Converts all selections to unicode characters, if applicable.""" def run(self, edit): for region in self.view.sel(): candidate = self.view.substr(region) try: number = int(candidate, 16) except Exception as e: sublime.error_message('Failed to convert "{}" into a decimal ' 'number.'.format(candidate)) continue try: character = chr(number) except ValueError as e: sublime.error_message("Failed to convert {} ({} in hex). This " "probably means it's not a valid unicode " "code point.".format(number, candidate)) continue except OverflowError as e: sublime.error_message("{} is too big of a number..." .format(candidate)) continue # Everything went okay. Let's replace the selection by the unicode # character. self.view.replace(edit, region, character) Go to Tools -> Developer -> New Plugin, and paste the above in the new view. Save this as ConvertHexToUnicodeCharacter.py in your Packages/User directory. ConvertHexToUnicodeCharacter.py Now, this command will do something to the current selection, so it's not quite what we want yet. Let's write a macro to change that: [ { // command provided by sublime "command": "move", "args": { "by": "words", "forward": false, "extend": true } }, { // this is the command that we just wrote "command": "convert_hex_to_unicode_character" }, { // command provided by sublime "command": "move", "args": { "by": "characters", "forward": true, "extend": false } } ] Go to Tools -> Developer -> New Plugin and paste the above in there. Save this file as ConvertToUnicodeToTheLeft.sublime-macro, also in your Packages/User directory. ConvertToUnicodeToTheLeft.sublime-macro At this point your new Macro should show up when you go to Tools -> Macros -> User -> ConvertToUnicodeToTheLeft, and it should do precisely what LibreOffice does. To bind it to a shortcut, go to Preferences -> Key Bindings. Sublime will present you with two views. The left view is the default keybindings. The right view is your personal keybindings. If you never wrote a keybinding, just paste this in the right view: [ { "keys": ["alt+c"], "command": "run_macro_file", "args": { "file": "Packages/User/ConvertToUnicodeToTheLeft.sublime-macro" } } ] and save it. Now when you press altC, the hexadecimal number to the left of the cursor should get replaced by its equivalent unicode character. This'll also work with multiple selections. As an alternative approach, surely there must be decent Windows software for inserting characters. Maybe something with a nice, searchable interface: hit the magic keystroke to activate, type “dig”, and pick the lowercase digamma off the list. I can imagine software that provides a better user experience than Sublime possibly could, but as I'm not a Windows user I don't know what's available. Wow, it all worked out nicely! Thank you very much for the detailed instructions of how to implement the code. Now I will start tackling it step by step to understand it! Alternatively, you can enter hex codes in Windows by holding Alt and pressing the + (plus sign) key followed by a hexadecimal character code. For numeric hex codes like 2010 (hyphen), this is very easy if you can memorize them. It's more tedious for hex codes that involve letters. (If that input method doesn't work, you'll need to modify a registry key and reboot to enable hexadecimal character entry support, though I forget what the necessary registry key is off the top of my head. I'm thinking this works out of the box in Windows 10, but didn't in previous versions of Windows.) Also: BabelMap is superior to the Windows Character Map application for character selection. It hasn't been updated for last month's update to Unicode (10) yet though; I'd guess the author is waiting for Windows 10's "Fall Creator's Update" which should include Unicode 10 support.
https://forum.sublimetext.com/t/options-for-typing-unicode-characters/29818
CC-MAIN-2018-09
refinedweb
1,104
54.83
Important: Please read the Qt Code of Conduct - redraw problem with qt quick 5.10 under Mojave (OSX 10.14) I just did an update to 10.14, and after doing it, it seems that Qt Quick Controls 2 objects aren't redrawing when expected. Changing the visibility of an object, for instance, doesn't make it appear and disappear. Interestingly, if I hide my application window behind another window and then bring it to the fore, the object will redraw correctly. Any ideas why this would be happening? I'm attaching a sample project that demonstrates the issue. import QtQuick 2.10 import QtQuick.Window 2.2 import QtQuick.Controls 2.3 Window { visible: true width: 640 height: 480 title: qsTr("Hello World") Button{ id:clickmeButton anchors.centerIn: parent text: "click me" onClicked:{ if (changingText.visible){ changingText.visible = false; } else{ changingText.visible = true; } } } Label{ id:changingText anchors{ horizontalCenter: parent.horizontalCenter top: clickmeButton.bottom topMargin: 25 } font.pixelSize: 48 text:"label" onVisibleChanged:{ console.log("visibility=",visible) } } } Hi, Can you test with a more recent version of Qt ? Qt 5.11 is the current release with 5.12 around the corner. It appears to be fixed under 5.11 I haven't updated to 5.11 because that version drop support for a 32-bit web view, but now it looks as if my hand will be forced... Thanks for the suggestion! Do you mean you were building Qt yourself in 32bit mode ? Because it's been years that 32bit support has been dropped by Apple. @SGaist I'm working on a cross-platform project, but doing development on a mac. On Mac, everything is happy, but on Windows, I wasn't able to move to 5.11 because the 32 bit version of WebView disappeared from Qt. I had other dependencies that kept me from switching to a 64 bit Windows build. Which module are you using for your web view ? Except that WebView can come from different modules: QtWebView and QtWebEngine, hence my question. Ok, then IIRC, on platforms that don't provide a native web view, QtWebEngine is used, hence the inherited limitations on these platforms.
https://forum.qt.io/topic/97254/redraw-problem-with-qt-quick-5-10-under-mojave-osx-10-14/5
CC-MAIN-2021-21
refinedweb
358
61.93
29 August 2012 09:44 [Source: ICIS news] SINGAPORE (ICIS)--Indian major Reliance Industries Ltd (RIL) has withdrawn all export offers for polypropylene (PP) from 28 August, on the back of low stock levels, a company source said on Wednesday. RIL plans to resume offers for export beginning from 3 September for October shipments, the source added. Its low inventories was a result of the healthy domestic sales in early August and the recent low output at one of its PP facilities in Jamnagar, the source said. “Previously in early August, import arrivals were low, so, we had good sales locally. Since then, our inventories were on the lower side,” he said. RIL has begun offering October shipment in mid-August to countries such as ?xml:namespace> Angie Li
http://www.icis.com/Articles/2012/08/29/9590643/indias-ril-withdraws-all-pp-export-offers-to-resume-on-3.html
CC-MAIN-2015-11
refinedweb
129
61.77
12 September 2012 20:23 [Source: ICIS news] WASHINGTON (ICIS)--Increasing ?xml:namespace> Frank Nothaft, chief economist at the Federal Home Loan Mortgage Corp – known colloquially as Freddie Mac – said that “Energy costs have remained high and increased in recent weeks, placing a further dent in consumers’ and businesses’ spending plans”. Freddie Mac is one of two secondary mortgage market entities chartered by Congress to add liquidity to the housing finance market. The other government-sponsored mortgage market agency is known as Fannie Mae. Both agencies purchase mortgage loans from banks, bundle the loans into investment packages and sell them on the global market. Betweens them, they underwrite most mortgage loans in the In his regular monthly outlook for the housing market and the broader “The 15% increase in gasoline prices since early July diverts purchases away from other consumer goods and can forestall business investment spending,” Nothaft said. “This in turn can slow the pace of economic growth and with it the recovery of the housing sector,” he added. The Nothaft said that increasing gasoline and other fuel prices could chill what has been seen as a real beginning for the long-awaited housing sector recovery. He noted that low mortgage rates and still low home prices have helped energise the housing sector, with home sales in the first seven months of 2012 up by 8% from the same period of 2011. In addition, housing starts have shown a 19% year-on-year gain in the same seven-month period. Although rising fuel costs do pose a threat to both the housing sector and the broader economic recovery, Nothaft said the impact of higher energy costs was not as profound now as it has been in prior years. “A fuel-price spike doesn’t pack the same punch it once used to in part because of more efficient energy use in automobiles, homes and appliances,” he
http://www.icis.com/Articles/2012/09/12/9595019/rising-us-energy-costs-could-chill-the-nascent-housing-recovery.html
CC-MAIN-2015-22
refinedweb
317
53.95
When. To highlight the importance of attack containment techniques, consider an analogy between defenses of a distributed computer system and national security defenses. On the morning of September 11, 2001, at the time that the first hijacked airplane hit the north tower of the World Trade Center, our nation’s preventive defense mechanisms had already failed. The FBI, CIA, NSA, and INS had failed to identify and/or detain the terrorists who had entered the country and had been training to fly commercial airliners. The hijackers were let through the airport security checkpoints and were allowed to board. When the first airplane hit the tower, the hijackers were already in control of two other planes in the air.. We now show that the implementation of the serveFile() method takes a fail-safe stance. The implementation of serveFile() is repeated in the following code for convenience:.. Software vendors have recently started taking the concept of secure defaults much more seriously. For example, the Microsoft Windows operating system was originally deployed with all of its features on in the initial configuration. Microsoft configured various functionality offered by their operating system such that it was enabled by default. However, having Internet Information Sever (IIS), Microsoft's web server, on by default made millions of Microsoft Windows computers easier to attack by malicious parties. Worms such as Code Red and Nimda used exploits in IIS to infect the computer on which it was running, and used it as a launching pad to infect other machines. Because other computers running Windows had IIS turned on by default (even if the users were not using it), the worm was able to spread and infect the other computers quickly.." Security Features Do Not Imply Security Using one or more security features in a product does not ensure security. For example, suppose a password is to be sent from a client to the server, and you do not want an attacker to be able to eavesdrop and see the password during transmission. You can take advantage of a security feature (say, encryption) to encrypt the password at the client before sending it to the server. If the attacker eavesdrops, what she will see is encrypted bits. Yet, taking advantage of a security feature, namely encryption, does not ensure that the client/server system is secure, since there are other things that could go wrong. In particular, encrypting the client's password does not ensure protection against weak passwords. The client may choose a password that is too short or easy for the attacker to obtain. Therefore, a system's security is not solely dependent upon the utilization of security features in its design, such as the encryption of passwords, but also depends on how it is used. Another example involves the interaction between a web client and a web server. You may decide to use SSL. SSL is the Secure Sockets Layer protocol that is used to secure communications between most web browsers and web clients. SSL allows the web client and web server to communicate over an encrypted channel with message integrity in which the client can authenticate the server. (Optionally, the server may also authenticate the client.) Our SimpleWebServer code can be modified to use an SSL connection instead of a regular one: import java.security.*; import javax.net.ssl.*; // ... some code excluded ... private static final int PORT = 443; private static SSLServerSocket dServerSocket; public SimpleWebServer () throws Exception { SSLServerSocketFactory factory = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault(); dServerSocket = (SSLServerSocket)factory.createServerSocket(PORT); // ... some code excluded ... public void run () throws Exception { while (true) { /* Wait for a connection from a client. */ SSLSocket s = (SSLSocket)dServerSocket.accept(); // ... some code excluded ... } // ... some code excluded ... Now, for a client to connect to the server, it would connect to port 443, execute an SSL "handshake", and start exchanging HTTP messages over an authenticated, encrypted channel with message integrity in place. A browser that wants to connect to the server would use a URL such as. The s in https signifies that an SSL connection on port 443, by default, should be used. You may decide to take advantage of SSL as a security feature in SimpleWebServer, but using SSL does not ensure security. In fact, using SSL in the preceding code does not protect you from all the other threats (directory traversal attacks, DoS attacks, etc.), even though the client and server might communicate over an SSL connection using this code. Taking advantage of SSL security as a feature may prevent an attacker from being able to snoop on the conversation between the client and server, but it does not necessarily result in overall security, since it does not protect against other possible threats. For instance, if you did not canonicalize the pathname in the HTTP request, an attacker could steal the server's /etc/shadow file over the SSL connection. The security of a system cannot be guaranteed simply by utilizing one or more security features. So, once you have fixed all the implementation vulnerabilities described earlier in this article and added SSL support to SimpleWebServer, is it finally secure? Probably not.6 There may very well be a few additional vulnerabilities in the code. We leave it as an exercise to the reader (that's you!) to find the extra vulnerabilities. Based on how much testing you have done and what you have tested for, you may be able to provide your management with a risk assessment. Generally, the more testing, and the more diverse the testing, the less risky-but all it takes is some discrete hole and all security is blown. To quote Bruce Schneier, "Security is a process, not a product" (Schneier 2000). Security results not from using a few security features in the design of a product, but from how that product is implemented, tested, maintained, and used. In a sense, security is similar to quality. It is often hard to design, build, and ship a product, and then attempt to make it high-quality after the fact. The quality of a product is inherent to how it is designed and built, and is evaluated based on its intended use. Such is the case with security. The bad news about security is that an attacker may often need to find only one flaw or vulnerability to breach security. The designers of a system have a much harder job-they need to design and build to protect against all possible flaws if security is to be achieved. In addition, designing a secure system encompasses much more than incorporating security features into the system. Security features may be able to protect against specific threats, but if the software has bugs, is unreliable, or does not cover all possible corner cases, then the system may not be secure even if it has a number of security features. Footnotes - If you wanted to design an even better valet key system for an automobile, you could limit the number of miles that could be driven with the valet key (but that could introduce other safety issues-for instance, if the car would come to a dead stop upon reaching the limit). - There have been known attacks in which attackers take control of the account used to run the web server and then exploit a vulnerability in the operating system to take control of other accounts that have more privileges. However, if there was only a vulnerability in the web server and not an additional one in the operating system, the least privilege approach would prevent the attacker from being able to obtain additional privileges. - A root account is one that gives a system administrator complete access to all aspects of a system. - Note that getCanonicalPath() may not work as expected in the presence of hard links. - If robbers know that they might be given dye-laced cash, this may also serve as a deterrent, or a preventive measure, since the only way to check for dye-laced cash may be to open the briefcase. Why go through the trouble of robbing the bank if they may not be able to get usable cash? At the same time, the dye-laced cash is not a pure recovery measure, since it doesn't help the bank get the money back; it only makes it useless (in the case that real cash is in the briefcase). - Actually, there definitely are additional vulnerabilities in SimpleWebServer-we are just being facetious. About the Authors Neil Daswani has served in a variety of research, development, teaching, and managerial roles at Stanford University, DoCoMo USA Labs, Yodlee, and Bellcore (now Telcordia Technologies). His areas of expertise include security, wireless data technology, and peer-to-peer systems. He has published extensively in these areas, frequently gives talks at industry and academic conferences, and has been granted several U.S. patents. He received a Ph.D. and a master's in computer science from Stanford University, and he currently works for Google. He earned a bachelor's in computer science with honors with distinction from Columbia University.. Anita Kesavan is a freelance writer and received her M.F.A. in creative writing from Sarah Lawrence College. She also holds a bachelor's in English from Illinois-Wesleyan University. She specializes in communicating complex technical ideas in simple, easy-to-understand language. Source of This Material Foundations of Security: What Every Programmer Needs to Know By Neil Daswani, Christoph Kern, Anita Kesavan Published: February, 2007, Paperback: 320 pages Published by Apress ISBN: 1590597842 Retail price: $39.99, eBook Price: $20.00 This material is from Chapter 3 of the book. Reprinted with the publisher's permission.
https://www.developer.com/java/data/secure-design-principles/
CC-MAIN-2022-40
refinedweb
1,600
52.49
This year I have been working on several systems based on Akka, usually in combination with the excellent Spray framework to build fully asynchronous actor-driven REST servers. All in all this has been going very well but recently I had to reinvent a certain wheel for the third time (on the third project) so I thought it might be good to blog about it so others can benefit from it too. The problem is very simple: Akka has great unit test support but unfortunately (for me) that support is based on ScalaTest. Now there is nothing wrong with ScalaTest but personally I prefer to write my tests using Specs2 and it turns out that mixing Akka TestKit with Specs2 is a little tricky. The Akka documentation does mention these problems and it gives a brief overview of ways to work around them, but I could not find any current example code online. I say "current" because one of Akka's main committers, Roland Kuhn, did at one time commit some specs2 example code but unfortunately it got thrown out again later. Based on that original example, here is my slightly improved and commented version: import org.specs2.mutable._ import org.specs2.time.NoTimeConversions import akka.actor._ import akka.testkit._ import akka.util.duration._ /* A tiny class that can be used as a Specs2 'context'. */ abstract class AkkaTestkitSpecs2Support extends TestKit(ActorSystem()) with After with ImplicitSender { // make sure we shut down the actor system after all tests have run def after = system.shutdown() } /* Both Akka and Specs2 add implicit conversions for adding time-related methods to Int. Mix in the Specs2 NoTimeConversions trait to avoid a clash. */ class ExampleSpec extends Specification with NoTimeConversions { sequential // forces all tests to be run sequentially "A TestKit" should { /* for every case where you would normally use "in", use "in new AkkaTestkitSpecs2Support" to create a new 'context'. */ "work properly with Specs2 unit tests" in new AkkaTestkitSpecs2Support { within(1 second) { system.actorOf(Props(new Actor { def receive = { case x ⇒ sender ! x } })) ! "hallo" expectMsgType[String] must be equalTo "hallo" } } } } Using this little Specs2 context trick bridges the two systems, allowing you to write normal Akka TestKit-based tests but using Specs2 as the test driver and matcher library. Lorrin Nelson - November 5, 2012 at 11:07 pm Thanks so much for posting this! Just what I needed. Nick McCready - December 13, 2012 at 6:25 pm Can you explain why the mutable package for specs2 is being used? Age Mooij - December 13, 2012 at 6:30 pm Purely personal preference. It has nothing to do with Akka or Specs2 in general. I just like the mutable DSL better than the acceptance DSL. If you want, you can easily adjust this code for use with immutable acceptance Specifications by changing the import statement. As ar as I know the immutable package also has an After trait so it should work. Ayose - February 2, 2013 at 5:48 pm Age, thanks for the post. Out of curiosity, why do you prefer Specs2 instead of Scalatest? Age Mooij - February 2, 2013 at 6:23 pm Purely a personal preference and mostly I just ended up using it because all the Open Source Scala projects I studied at the time were all using it too. I couldn't honestly tell you the difference between the two. Age Mooij - February 2, 2013 at 6:27 pm Re-reading this blog now, I notice that I made the sample test use "sequential", which is purely optional and only required if your tests somehow depend on each other.
http://blog.xebia.com/testing-akka-with-specs2/
CC-MAIN-2016-40
refinedweb
597
61.97
KILL(2) BSD Programmer's Manual KILL(2) kill - send signal to a process #include <signal.h> int kill(pid_t pid, int sig);user). A single exception is the signal SIGCONT, which may always be sent to any descendant of the current; this is a variant of killpg(3). If pid is -1: If the user has superuser privileges, the signal is sent to all processes excluding system processes and the process sending the signal. If the user is not the superuser, the signal is sent to all processes with the same uid as the user excluding the process sending the signal. No error is returned if any process could be signaled. Setuid and setgid processes are dealt with slightly differently. For the non-root user, to prevent attacks against such processes, some signal deliveries are not permitted and return the error EPERM. The following signals are allowed through to this class of processes: SIGKILL, SIGINT, SIGTERM, SIGSTOP, SIGTTIN, SIGTTOU, SIGTSTP, SIGHUP, SIGUSR1, SIGUSR2. For compatibility with System V, if the process number is negative but not -1, the signal is sent to all processes whose process group ID is equal to the absolute value of the process number. This is a variant of killpg(3). by pid. [ESRCH] The process ID was given as 0 but the sending process does not have a process group. [EPERM] The sending process is not the superuser and its effective user ID does not match the effective user ID of the receiv- ing process. When signaling a process group, this error is returned if any members of the group could not be signaled. getpgrp(2), getpid(2), sigaction(2), killpg(3), raise(3) The kill() function is expected to conform to IEEE Std 1003.1-1988 ("POSIX")..
http://mirbsd.mirsolutions.de/htman/sparc/man2/kill.htm
crawl-003
refinedweb
294
61.16
What is a function?. Types of Functions Depending on whether a function is predefined or created by programmer; there are two types of function: - Library functions - Functions that are defined already in Swift Framework. - User-defined functions - Functions created by the programmer themselves. Library Functions want, you can see all the functions inside the Swift framework. Just write func keyword. Example 1: Library or Built in Function print("Hello, World!") When you run the above program, the output will be: Hello, World! In the above program, we have invoked a built-in We are able to call print() function because Swift framework is automatically imported into our Playground. Otherwise, we should have imported it ourselves by writing import Swift. User defined Functions Swift also allows you to define your own function. Creating your own function helps to write code to solve problems or perform tasks not available in Swift Framework. You can also reuse your function to perform similar tasks in the future. Likewise, Functions can also be categorized in the basis of parameters and return statements. See the article Swift Function Parameter Types and Return Types. Defining a Function func function_name(args...) -> ReturnType { //statements return value } Lets describe each components in brief: funcis the keyword you must write to create a function function_nameis the name of a function. You can give it any name that defines what a function does. args…defines the input a function accepts. ->This operator is used to indicate the return type of a function. ReturnTypedefines the type of a value you can return from a function. E.g. Int, Stringetc. returnkeyword is used to transfer the control of a program to the function call and also return value from a function. Even if you don’t specify the return keyword the function returns automatically after execution of last statement. valuerepresents the actual data being returned from the function. The value type must match the ReturnType. How function works? In the above diagram, the statement function_name(args) invokes/calls the function with argument values args, which then leaves the current section of code (i.e. stops executing statements below it) and begins to execute the first line inside the function. - The program comes to a line of code func function_name(Args...)and accepts the values args passed during the function call function_name(args). - The program then executes the statements statementsInsideFunctiondefined inside the function. - The statements inside the function are executed in top to bottom order, one after the other. - After the execution of the last statement, the program leaves the function and goes back to where it started from i.e function_name(args). let val =stores the value returned from the function in a constant val. Similarly, you can store in a variable as var val =. - After that, statements statementsOutsideFunctionare executed. Example 2: How to define a function in Swift? func greet(user:String) { print("Good Morning! \(user)") } Above shown is a function definition which consists of following components: - Keyword funcmarks the start of function header. greetis a function name to uniquely identify and call function in the program. (user:String)marks the end of function header and accepts a parameter of type String. See the article Swift Function Parameter Types and Return Types that defines function with parameters. - The function consists of a Calling a function Once you have created a function, you can call it in your program to execute the statements declared inside the function. To call a function you simply write the function name followed by ()and pass the input parameters inside it as: greet(user: "Isac") Example 3: Calling a function in Swift func greet(user:String) { print("Good Morning! \(user)") } greet(user: "Isac") When you run the above program, the output will be: Good Morning! Isac In the above code, greet(user: "Isac") calls the function and passes value Isac of type String. After that, Return Statement The return keyword tells the program to leave the function and return to line where the function call was made. You can also pass value with the return keyword where value is a variable or other information coming back from the function. Example 3: Function with return keyword func greet(user:String)-> String { return "Good Morning! \(user)" } let greeting = greet(user: "Isac") print(""" You have a new message \(greeting) """) When you run the above program, the output will be: You have a new message Good Morning! Isac In the above code, greet(user: "Isac") calls the function and passes value Isac of type String. return "Good Morning! \(user)" statement returns the value of type String and transfers the program to the function call. let greeting = stores the value returned from the function. After the function returns, the Things to remember - Give a function name that reflects the purpose of the function. - A function should accomplish only one task. If a function does more than one task, break down it into multiple functions. - Try to think early and group statements inside a function which makes the code reusable and modular.
https://www.programiz.com/swift-programming/functions
CC-MAIN-2021-04
refinedweb
837
65.52
A React passive effect is what’s used with useEffect and it invokes a new JavaScript task while everything implemented inside the callback can be still run in a sync way. After the React finishes the render and goes to a commit. It collects the passive effect under the fiber. function enqueuePassiveEffectMount(fiber, effect) { passiveEffectsMount.push(effect)if (!rootDoesHavePassiveEffects) { rootDoesHavePassiveEffects = true scheduleCallback(() => { flushPassiveEffects() }) } } But it doesn’t invoke each right away, instead, it does things a bit differently. First of all, it waits for all effects to be collected using a flag rootDoesHavePassiveEffects . … There’s no counterpart of Redux in React, the closest one is called Context. Quite a few of us argue that a context is local comparing to Redux which is quite global to the site, especially when it comes to where the data is stored. However React context isn’t designed as a local variable, like in the similar sense as in a fiber, or a hook, or anything localized to a unit of work. On the contrary, it’s none of that. So we’ll explain why in the following. A context is created by a function createContext, const UserContext = createContext(defaultValue) export default… If you use a React context often, soon you will realize it’s a heavy operation when it’s updated. Therefore people tend to add a React.memo to the children. Then voila, things just get different right away, or sometimes nothing happens at all. :) Say we have a component App providing some value. const App = ({ aProp }) => { const [aState, ] = useState(...) return ( <Context.Provider value={...}> <Indirection /> </Context.Provider> ) } Here’s the mount profile where everything is rendered. React context provides a way so that we can share a value among the fiber tree. Instead of storing this value along with a fiber, it stores it in a separate storage, given the name Context. const Context = React.createContext(0) Now the Context gives us a different kind of component called ContextProvider . Just like FunctionComponent , ClassComponent , MemoComponent , ContextProvider has its own update mechanism. When we reach a FunctionComponent, it renders and reconciles its children and move on to the first child to continue the render work caused by one dispatch (or schedule). It can’t unless you know what is useMemo . React provides quite an optimization engine out of the box where it applies bailout pathway whenever it sees fit. And most of the pathway are built behind the scene, and developer knows them by mouth. Sometimes we get wrong idea about using certain features. What is useMemo? The word “memo” gives us a sense that there’re some memorization scheme used. But on the contrary, if you were calling an assignment a memo, then programming itself is a giant memo engine, which defeats the purpose of using this word. … Let’s start from some common sense. We learned that all props are checked before each fiber is determined to render. Suffice to say a fiber is a component or a node of a tree. In this article we use them interchangeably. Is this right? Putting that aside, it really doesn’t tell us much, ex. where it starts and where it ends. Also it doesn’t tell us the difference between props and states either. Let’s use one example to illustrate this matter. In above figure, a state has been changed in one of the component, the first colored block. … When React receives a dispatch, it goes to render the fibers and later commit the changes to DOM based on the props and states. This is very straight forward when we have one state and one location of action. const Title = () => { cont [count, setCount] = useState(0) const onClick = () => { setCount(1) } return <div onClick={onClick}>{count}</div> } Assuming our tree of components looks like the following, and we have the component Title installed at the red dot. The effect of the above dispatch pretty much does that, although the fact that React has to go… Why you shouldn’t confuse yourself between a useMemo and a memorization Maybe this is just me, but for a long time, I wired myself between a useMemo and a classical memorization. But actually from the study of useMemo source code, I made peace that they are very different, at least they don’t have much in overlap. Maybe the only thing they share is a partial word “memo”. useMemo is very close to useEffect , believe it or not, in terms of the syntax, usage as well as the implementation. … const Title = () => { const [state, setState] = useState(initialState) } I read some implementations of useState from preact and brahmos repositories. And I thought I understood the behavior of useState until I finally read the official version under ReactFiberHooks.old.js. Of course it’s not an easy read, anyway I bite the bullet with a lot of help from other people who read the source code :) In order to understand the official source code, let me strip it down a bit so that we can follow the key workflow without going through hundreds of lines in many repositories. The… you must be kidding me man.
https://windmaomao.medium.com/?source=post_page-----1b1c4fa8f5c7--------------------------------
CC-MAIN-2021-39
refinedweb
854
64
Components and supplies Necessary tools and machines Apps and online services About this project Your garden or backyard needs frequent watering in summer, especially here in Australia. of watering devices. It uses one extra valve in order to be more resistant against valve failure and also implements a leak check if you decide to use the water flow sensor. The three watering devices can water up to 3 different areas of your garden. They are called area 1, area 2 and area 3 and you can configure their duration in minutes separately along with the time each day watering starts. There are two buttons and one color LED to control/show the state of the device. The red button is used to show and switch the mode as well as switching watering off immediately. The black button starts watering and switches to the next area if it is running already. When you press the red button in idle mode, it will first show the current mode on the color LED and then switch between the modes as follows: - mode off (color LED red) - mode on (color LED green) - mode off once (color LED purple) What if you sit in your backyard with your guests and forget to switch it off? For this reason I added a warn activation of the watering devices. When it is time to start watering, the following happens: - Leak check (if activated) - Switch area 1 on for 1 sec - Pause for one minute (to allow you to switch it of if you have guests..) - Start watering of area 1 for the given time in minutes - Switch area 2 on for 1 sec - Pause for one minute - Start watering of area 2 for the given time in minutes - Switch area 3 on for 1 sec - Pause for one minute - Start watering of area 3 for the given time in minutes When you press the red button any time during this time, watering will stop immediately and not start anymore until the next scheduled watering. If you press the black button, it will switch to the next area. Software Prerequisites In order to install the sketch for this project, you obviously need the Arduino IDE installed on your PC. The sketch and some of the test sketches in the assembly section also need the libraries listed below to be installed in the Arduino IDE. The recommended way to install them is as follows (works for all except DS3232RTC). - Menu Sketch->Include Library->Manage Libraries... - On top right in "Filter your search..." type the library's name - Click on it and then click "Install" - For more details see manual Installing Additional Arduino Libraries Required libraries: Electrical Assembly The electrical part consists mainly of Arduino Uno, DS3231 RTC, MOSFET4 board, color LED board and the two buttons. If you are experienced with Arduino, skip the following chapters and assemble according to the image above. Connect and Test DS3231 RTC Put a watch battery on the DS3231 RTC board and connect it as shown in the overview image. The connections are as follows: - RTC PIN SDA = Arduino PIN A4 (SDA) - RTC PIN SCL = Arduino PIN A5 (SCL - RTC PIN SQW = Arduino PIN 8 - RTC PIN GND = Breadboard GND (can also be any of Arduino GND for testing) - RTC PIN VCC = Breadboard VCC (5V, can also be Arduino 5V for testing) Upload the following sketch to Arduino Uno to check if the RTC chip is connected correctly. #include <DS3232RTC.h> // #include <EnableInterrupt.h> // #define SLEEP_MODE SLEEP_MODE_IDLE #include <DeepSleepScheduler.h> // #define RTC_INT_PIN 8 boolean alarmReceived = false; void setup() { Serial.begin(9600); Serial.println(F("Startup ------------")); initRtc(); setSyncProvider(RTC.get); if (timeStatus() != timeSet) { Serial.println(F("RTC not found")); } else { Serial.println(F("RTC found")); Serial.println(F("Testing interrupt connection..")); time_t rtcTime = now(); unsigned int hours = hour(rtcTime); unsigned int minutes = minute(rtcTime); unsigned int seconds = second(rtcTime); // trigger alarm in 5 seconds seconds += 5; if (seconds >= 60) { seconds -= 60; minutes++; } if (minutes >= 60) { minutes -= 60; hours++; } if (hours >= 24) { hours -= 24; } Serial.print(F("Trigger alarm at RTC time ")); Serial.print(hours); Serial.print(F(":")); Serial.print(minutes); Serial.print(F(":")); Serial.println(seconds); RTC.setAlarm(ALM1_MATCH_MINUTES, seconds, minutes, hours, 0); scheduler.scheduleDelayed(checkIfReceived, 10000); } } void loop() { scheduler.execute(); } inline void initRtc() { RTC.alarmInterrupt(ALARM_1, true); RTC.alarmInterrupt(ALARM_2, false); // reset alarms if active RTC.alarm(ALARM_1); RTC.alarm(ALARM_2); delay(1000); pinMode(RTC_INT_PIN, INPUT_PULLUP); enableInterrupt(RTC_INT_PIN, isrRtc, FALLING); } void checkIfReceived() { if (!alarmReceived) { Serial.println(F("Alarm not received, interrupt wire seams not okay.")); } } void isrRtc() { scheduler.schedule(rtcScheduled); } void rtcScheduled() { alarmReceived = true; Serial.println(F("Interrupt received, wire looks fine.")); if (RTC.alarm(ALARM_1)) { Serial.println(F("Alarm received, connection of RTC looks fine.")); } else { Serial.println(F("Alarm not received, something looks wrong with the RTC.")); } } In Arduino IDE click on Menu Tools->Serial Monitor and check the output. Connect and Test Color LED The RGB color LED used in this project contains current limiting resistors on the board itself (see image above). Please make sure that's the case for the one you use too to prevent damage. If it does not have them, you need to put separate resistors. There are different RGB color LEDs. The one I use in this project has a PIN labelled with "GND". If you use one with a PIN labelled as +, the test sketch and the production sketches need to be adjusted accordingly (see COLOR_LED_INVERTED in Constants.h). Connect the color LED as shown in the overview image. The connections are as follows: - Color LED G = Arduino A0 - Color LED R = Arduino A1 - Color LED B = Arduino A2 - Color LED GND = Breadboard GND (can also be any of Arduino GND for testing) Upload the following sketch to Arduino Uno to check if the color LED is connected correctly. #define MODE_COLOR_GREEN_PIN A0 #define MODE_COLOR_RED_PIN A1 #define MODE_COLOR_BLUE_PIN A2 void setup() { Serial.begin(9600); pinMode(MODE_COLOR_GREEN_PIN, OUTPUT); digitalWrite(MODE_COLOR_GREEN_PIN, LOW); pinMode(MODE_COLOR_RED_PIN, OUTPUT); digitalWrite(MODE_COLOR_RED_PIN, LOW); pinMode(MODE_COLOR_BLUE_PIN, OUTPUT); digitalWrite(MODE_COLOR_BLUE_PIN, LOW); } void loop() { Serial.println(F("green")); digitalWrite(MODE_COLOR_GREEN_PIN, HIGH); delay(1000); digitalWrite(MODE_COLOR_GREEN_PIN, LOW); Serial.println(F("red")); digitalWrite(MODE_COLOR_RED_PIN, HIGH); delay(1000); digitalWrite(MODE_COLOR_RED_PIN, LOW); Serial.println(F("blue")); digitalWrite(MODE_COLOR_BLUE_PIN, HIGH); delay(1000); digitalWrite(MODE_COLOR_BLUE_PIN, LOW); } In Arduino IDE click on Menu Tools->Serial Monitor and watch if the color of the LED matches the color printed on the console. Connect and Test MOSFET4 The MOSFET4 board used in this project contains 4 IRF540 MOSFETS including all necessary parts to control them by an Arduino PIN. You can also use other MOSFETs or boards with single IRF540 on them. Connect the MOSFET4 board as shown in the overview image. Pin S is the left pin and pin "-" is the right pin in the input connector as shown above (MOSFET4 inputs). The middle PIN is + what we do not need for this project. The connections are as follows. - MOSFET4 CH1 S = Arduino 4 - MOSFET4 CH2 S = Arduino 5 - MOSFET4 CH3 S = Arduino 6 - MOSFET4 CH4 S = Arduino 7 - MOSFET4 CH1 - = Breadboard GND (can also be any of Arduino GND for testing) Upload the following sketch to Arduino Uno to check if the MOSFET4 board is connected correctly. #define VALVE1_PIN 4 #define VALVE2_PIN 5 #define VALVE3_PIN 6 #define VALVE4_PIN 7 void setup() { Serial.begin(9600); pinMode(VALVE1_PIN, OUTPUT); pinMode(VALVE2_PIN, OUTPUT); pinMode(VALVE3_PIN, OUTPUT); pinMode(VALVE4_PIN, OUTPUT); } void loop() { Serial.println(F("Valve 1")); digitalWrite(VALVE1_PIN, HIGH); delay(1000); digitalWrite(VALVE1_PIN, LOW); Serial.println(F("Valve 2")); digitalWrite(VALVE2_PIN, HIGH); delay(1000); digitalWrite(VALVE2_PIN, LOW); Serial.println(F("Valve 3")); digitalWrite(VALVE3_PIN, HIGH); delay(1000); digitalWrite(VALVE3_PIN, LOW); Serial.println(F("Valve 4")); digitalWrite(VALVE4_PIN, HIGH); delay(1000); digitalWrite(VALVE4_PIN, LOW); } You should see that the 4 LEDs on the MOSFET4 board are lighting up one after the other. Connect and Test Buttons Connect the black and red button as shown in the overview image. The connections are as follows: - Any PIN of black button = Arduino 10 - Other PIN of black button = Breadboard GND (can also be any of Arduino GND for testing) - Any PIN of red button = Arduino 11 - Other PIN of red button = Breadboard GND (can also be any of Arduino GND for testing) Upload the following sketch to Arduino Uno to check if the buttons are connected correctly. #include <EnableInterrupt.h> // #define START_AUTOMATIC_PIN 10 #define MODE_PIN 11 void setup() { Serial.begin(9600); pinMode(START_AUTOMATIC_PIN, INPUT_PULLUP); enableInterrupt(START_AUTOMATIC_PIN, isrStartAutomatic, FALLING); pinMode(MODE_PIN, INPUT_PULLUP); enableInterrupt(MODE_PIN, isrMode, FALLING); } void loop() { // empty } void isrStartAutomatic() { // only done in test, do not println in interrupt in production sketch Serial.println(F("black button")); } void isrMode() { // only done in test, do not println in interrupt in production sketch Serial.println(F("red button")); } In Arduino IDE click on Menu Tools->Serial Monitor and watch if you see "black button" and "red button" on the console while you click the respective buttons. Finish electrical assembly Finally connect the water flow sensor plug and the 12V supply but do not yet connect the orange wire. Mechanical Assembly The mechanical part of this project consists of connectors, water flow sensor, valves and outlets. It is recommended to attach all parts until at least the first valve with threads and not with quick connectors. This means mechanically it is assembled as follows. The order is as follows: - garden tap with thread - connector from garden tap thread to 1/2" valve - main valve: 1/2" male on both ends - connector from main valve to water meter: 1/2" female on both ends - water meter: 1/2" male on both ends - 4 way cross coupling: all threads 1/2" female - area 1/2/3 valve: 1/2" male on both ends - area 1/2/3 thread joint connector: 1/2" female to quick connector of garden houses Connect the valves/water flow sensor: - main valve = mosfet4 CH1 (polarity does not matter) - area 1 valve = mosfet4 CH2 - area 2 valve = mosfet4 CH3 - area 3 valve = mosfet4 CH4 - water flow sensor = water flow sensor plug, see water flow sensor description about what wire is VCC, GND and signal Mount the electrical parts in an appropriate box. I recommend one with a transparent front so that the internals and the color LED can be seen. Please double check that the box is water resistant. I used a box that is sold as water resistant but in reality it was not. As you can image, the system started to behave pretty weird, so I put a plastic foil around the front to better protect it against the rain. Integration test When electrical and mechanical assembly is finished you can test it as a whole. First remove the orange connection on the overview image so that you can use the USB cable of Arduino Uno. It is important to no power the Arduino Uno through its Vin while you use USB, otherwise the USB port of the PC could get in troubles. Configuration - Disconnect the orange connection you see in overview image - Connect Arduino Uno to your PC with its USB cable - Upload Main Sketch "Watering System" - In Arduino IDE click on Menu Tools->Serial Monitor - Choose 9600 Baud - You see initialization output in the console - Press h and the "enter" key - The console shows the available commands - Set the current time with d<YYYY>-<MM>-<DD>T<hh>:<mm> (24 hours day), e.g. d2017-11-11T20:00 - Set watering time with a<hh>:<mm> (24 hours day), e.g. a21:00 - Set zone 1 duration: wz1:<minutes, 3 digits>, e.g. wz1:010 - Set zone 2 duration: wz2:<minutes, 3 digits>, e.g. wz2:010 - Set zone 3 duration: wz3:<minutes, 3 digits>, e.g. wz3:010 - Print status: s - Check if values and time set correctly - The values and time are stored in EEPROM and on the RTC chip. They are kept while powered down as long as the RTCs watch battery is present not empty First test - After configuration press the red button multiple times to see if the mode switches by lighting up the color LED in the colors red, purple and green - Press the black button to see if the main valve and the valve of area 1 correctly release - Press the black button again to switch to area 2 and area 3 - Press the red button to check if watering stops Finish setup - Disconnect the PC - Reconnect the orange wire to power Arduino Uno with the 12V supply - Use the buttons to check if it all still works as expected - Supervise all automated and manual runs from now on to make sure no damage can occur Videos Below you can some some short videos to explain how to operate the watering system. The first video shows how you can see which mode the watering system is in. In this video it lights up in green what means "Mode on". The second video demonstrates how to switch between the three modes "Mode on", "Mode off once" and "Mode off". The following video shows how to manually start watering, switch between the three zones and turn watering off again. Note that the LED lights up in green in the end what indicates that the system is currently in state "Mode on". ..and that's how it looks for your neighbours ;-). Code Arduino Watering System Schematics Author Published onDecember 26, 2017 Members who respect this project you might like
https://create.arduino.cc/projecthub/PRosenb/automatic-watering-system-160d90
CC-MAIN-2018-43
refinedweb
2,227
51.28
Program central hub of information. More... #include <application.h> Program central hub of information. Accessors provide plugins with certain objects and data that is not encapsulated in any singleton. Calling any non-const method from plugin perspective may result in undefined behavior of the program or even other plugins. Definition at line 44 of file application.h. Deinitializes the program; executed when program is shutting down. Doesn't delete the actual instance() but calls destroy() method. That way certain data fields can still be accessed after the program is deinitialized. Actual instance is never deleted explicitly, and OS will clear the memory anyway. Definition at line 51 of file application.cpp. Plugins and other threads can use this to figure out if program is closing. Threads should exit their loops and let the program close gracefully. Definition at line 81 of file application.cpp. MainWindow of the program. Might be NULL if current run doesn't create a MainWindow. Definition at line 86 of file application.cpp. Returns MainWindow as a QWidget. Useful for plugins that need to specify parent widget for dialog boxes or such, as MainWindow class itself is not exported. Might be NULL if current run doesn't create a MainWindow. Definition at line 91 of file application.cpp. Makes isRunning() return false. Called when program is shutting down. Definition at line 101 of file application.cpp.
https://doomseeker.drdteam.org/docs/doomseeker_1.0/classApplication.php
CC-MAIN-2021-43
refinedweb
230
53.37
I’m totally new to coding and am working on a function that gets a name from a potential player of the game. This code works if the player answers “T” on the fourth line istrue = input(f"\nT or F: {first_name} {last_name} is your name? ") But if the player enters “False”, when the loop repeats itself, it returns ‘None’ in the second function. I don’t know why. Also, I don’t know if I am formatting this question properly in the forum. Thanks for any input! def getname(): first_name = input("What is your first name? ") last_name = input("What is your last name? ") istrue = input(f"\nT or F: {first_name} {last_name} is your name? ") if istrue.lower() == 't' or istrue.lower() == 'true': name = first_name + ' ' + last_name[0] return name print(f"\nThank you, {name}!\n") elif istrue.lower() == 'f' or istrue.lower() == 'false': print("\nMy mistake...") getname() else: print("\nI'm sorry, that was not an option.\n") getname() def quest(): print(f"{player}, do you want to go on a quest? ") questing = input("1. Yes \n2. No\n > ") if questing == '1': print(f"Too bad, {player}.") elif questing == '2': print(f"Too bad, {player}...there's no returning now! Muah ha ha!") else: print(f"""{player}, that wasn't an option. \nLet's try this again...\n""") quest() player = getname() playing = quest()
https://forum.learncodethehardway.com/t/why-is-my-if-loop-returning-none/3817
CC-MAIN-2022-40
refinedweb
223
80.17
DISK(9) BSD Kernel Manual DISK(9) disk - generic disk framework #include <sys/types.h> #include <sys/disklabel.h> #include <sys/disk.h> void disk_init(void); void disk_attach(struct disk *); void disk_detach(struct disk *); void disk_busy(struct disk *); void disk_unbusy(struct disk *, long bcount, int read); void disk_resetstat(struct disk *); struct disk * disk_find(char *); The Open */ char *dk_name; /* disk name */. */ int dk_busy; /* busy counter */ u_int64_t dk_xfer; /* total number of transfers */ u_int64_t dk_seek; /* total independent seek operations */ u_int64_t dk_bytes; /* total bytes transferred */ struct timeval dk_attachtime; /* time disk was attached */ struct timeval dk_timestamp; /* timestamp of last unbusy */ struct timeval dk_time; /* total time spent busy */ struct dkdriver *dk_driver; /* pointer to driver */ /* * current- ly make use of the detachment capability of the framework are the ccd(4) and vnd(4) pseudo-device drivers. The following is a brief description of each function in the framework: disk_init() Initialize the disklist and other data structures used by the framework. Called by main() before autoconfi- guration._busy() Increment the disk's "busy counter". If this counter goes from 0 to 1, set the timestamp corresponding to this transfer. disk_unbusy() Decrement a disk's busy counter. If the count drops below zero, print a warning message. Get the current time, subtract it from the disk's timestamp, and add the difference to the disk's running total. Set the disk's timestamp to the current time. If the provided byte count is greater than 0, add it to the disk's run- ning total and increment the number of transfers per- formed by the disk. The third argument read specifies the direction of I/O; if non-zero it means reading from the disk, otherwise it means writing to the disk. disk_resetstat() Reset the running byte, transfer, and time totals. disk_find() Return a pointer to the disk structure corresponding to the name provided, or NULL if the disk does not exist. The functions typically called by device drivers are disk_attach(), disk_detach(), disk_busy(), disk_unbusy(), and disk_resetstat(). The function disk_find() is provided as a utility function. This section includes a description on basic use of the framework and ex- ample usage of its functions. Actual implementation of a device driver which utilizes the framework may vary. A special routine, disk_init(), is provided to perform basic initializa- tion of data structures used by the framework. It is called exactly once by the system, in main(), before device autoconfiguration. Each device in the system uses a "softc" structure which contains auto- configuration and state information for that device. In the case of disks, the softc should also contain one instance of the disk structure, e.g.: struct foo_softc { struct device - list. Note that since this function allocates storage space for the disk- label, it must be called before the disklabel is read from the media or used in any other way. Before disk_attach() is called, a portion of the disk structure must be initialized with data specific to that disk. For example, in the "foo" disk driver, the following would be performed in the autoconfiguration "attach" routine: void fooattach(parent, self, aux) struct device *parent, *self; void *aux; { struct foo_softc *sc = (struct foo_softc *)self; [ . . . ] /* Initialize and attach the disk structure. */ sc->sc_dk.dk_driver = &foodkdriver; sc->sc_dk.dk_name = sc->sc_dev.dv_xname; disk_attach(&sc->sc_dk); /* Read geometry and fill in pertinent parts of disklabel. */ [ . . . ] } The foodkdriver above is the disk's "driver" switch. This switch current- ly includes a pointer to the disk's "strategy" routine. This switch needs to have global scope and should be initialized as follows: void foostrategy(struct buf *); struct dkdriver foodkdriver = { run- ning time. The disk's timestamp is then updated in case there is more than one pending transfer on the disk. A byte count is also added to the disk's running total, and if greater than zero, the number of transfers the disk has performed is incremented. void foodone(xfer) struct foo_xfer *xfer; { struct foo_softc = (struct foo_softc *)xfer->xf_softc; struct buf *bp = xfer->xf_buf; long nbytes; [ . . . ] /* * Get number of bytes transferred.); [ . . . ] } Like disk_busy(), disk_unbusy() must be called at splbio(). At some point a driver may wish to reset the metrics data gathered on a particular disk. For this function, the disk_resetstat() routine is pro- vided. The disk framework itself is implemented within the file sys/kern/subr_disk.c. Data structures and function prototypes for the framework are located in sys/sys/disk.h. The OpenBSD machine-independent SCSI disk and CD-ROM drivers utilize the disk framework. They are located in sys/scsi/sd.c and sys/scsi/cd.c. The OpenBSD ccd(4), raid(4) and vnd(4) drivers utilize the detachment ca- pability of the framework. They are located in sys/dev/ccd.c, sys/dev/raidframe/, and sys/dev/vnd.c. ccd(4), raid(4), vnd(4), spl(9) The OpenBSD generic disk framework first appeared in NetBSD 1.2. The OpenBSD generic disk framework was architected and implemented within NetBSD by Jason R. Thorpe <thorpej@NetBSD.ORG>. MirOS BSD #10-current January 7, 1996.
http://mirbsd.mirsolutions.de/htman/sparc/man9/disk_attach.htm
CC-MAIN-2013-48
refinedweb
832
57.06
OpenERP / Odoo proxyOpenERP / Odoo proxy Contents Overview This project is just RPC client for Odoo. It aims to ease access to openerp data via shell and used mostly for data debuging purposes. This project provides interface similar to Odoo internal code to perform operations on OpenERP / Odoo objects hiding XML-RPC or JSON-RPC behind. - Are You still using pgAdmin for quering Odoo database? - Try this package (especialy with IPython Notebook), and You will forget about pgAdmin! Features - Use odoo-rpc-client under that hood, to get all its power - Python 3.3+ support - You can call any public method on any OpenERP / Odoo object including: read, search, write, unlink and others - Have a lot of speed optimizations (caching, read only requested fields, read data for all records in current set (cache), by one RPC call, etc) - Desinged to take as more benefits of IPython autocomplete as posible - Works nice in Jupyter Notebook providing HTML representation for a most of objects. - Ability to export HTML table recordlist representation to CSV file - Ability to save connections to different databases in session. (By default password is not saved, and will be asked, but if You need to save it, just do this: session.option('store_passwords', True); session.save()) - Provides browse_record like interface, allowing to browse related models too. Supports browse method. Also adds method search_records to simplify search-and-read operations. - Extension support. You can easily modify most of components of this app/lib creating Your own extensions and plugins. It is realy simple. See for examples in openerp_proxy/ext/ directory. - Plugin Support. Plugins are same as extensions, but aimed to implement additional logic. For example look at openerp_proxy/plugins and openerp_proxy/plugin.py - Support of JSON-RPC for version 8+ of Odoo - Support of using named parametrs in RPC method calls (server version 6.1 and higher). - Sugar extension which simplifys code a lot. - Experimental integration with AnyField - Missed feature? ask in Project Issues Quick example from openerp_proxy import Client client = Client('localhost', 'my_db', 'user', 'password') # get current user client.user print(user.name) # simple rpc calls client.execute('res.partner', 'read', [user.partner_id.id]) # Model browsing SaleOrder = client['sale.order'] s_orders = SaleOrder.search_records([]) for order in s_orders: print(order.name) for line in order.order_line: print("\t%s" % line.name) print("-" * 5) print() Supported Odoo server versions Tested with Odoo 10.0, 11.0 But should support all odoo versions that odoo_rpc_client supports Examples Install This project is present on PyPI so it could be installed via PIP: pip install openerp_proxy this will make available python package openerp_proxy and shell command openerp_proxy See Usage for more details If You want to install development version of OpenERP Proxy you can do it via: pip install -e git+ or (faster way): pip install Also it is recommened to install at Jupyter (formely IPython notebook) to get all benefits of Jupyter integration, provided by this project. To install it just type: pip install jupyter Usage Use as shell After instalation run in shell: openerp_proxy And You will get the openerp_proxy shell. If IPython is installed then IPython shell will be used, else usual python shell will be used. There is session variable present in locals. It is instance of Session class and represents current session and usualy is starting point of any shell work. See documentation for more details Next You have to get connection to some Odoo database. It is realy easy, just use connect method of session >>> db = session.connect() This will ask You for host, port, database, etc to connect to and return Client instance which represents database connection. Use as library The one diference betwen using as lib and using as shell is the way connection to database is created. When using as shell the primary object is session, which provides some interactivity. But when using as library in most cases there are no need for that interactivity, so connection should be created manualy, providing connection data from some other sources like config file or something else. So here is a way to create connection from openerp_proxy.core import Client db = Client(host='my_host.int', dbname='my_db', user='my_db_user', pwd='my_password here') And next all there same, no more differences betwen shell and lib usage. Use in Jupyter notebook Jupyter integration is implemented as extension openerp_proxy.ext.repr, so to use it, first, this extension should be enabled (just by importing extension). As a shortcut, there is openerp_proxy.ext.all module, which imports default set of extensions, including openerp_proxy.ext.repr extension. To better suit for HTML capable notebook You would like to use IPython's version of session object and openerp_proxy.ext.repr extension. So in first cell of notebook import session and extensions/plugins You want: # also You may import all standard extensions in one line: from openerp_proxy.ext.all import * # note that extensions were imported before session, # because some of them modify Session class from openerp_proxy.session import Session from openerp_proxy.core import Client session = Session() Now most things same as for shell usage, but... In some old versions of IPython's notebook heve no patched version of getpass func/module, so if You not provide password when getting database (connect, get_db methods, You would be asked for it, but this prompt will be displayed in shell where notebook server is running, not on webpage. To solve this, it is recommended to uses store_passwords option session.option('store_passwords', True) session.save() Next use it like shell, but do not forget to save session, after new connection db = session.connect() session.save() or like lib db = Client(host='my_host.int', dbname='my_db', user='my_db_user', pwd='my_password here') Note: in old version of IPython getpass was not work correctly, so maybe You will need to pass password directly to session.connect method. General usage For example lets try to find how many sale orders in 'done' state we have in our database. (Look above sections to get help on how to connect to Odoo Odoo is to search for required records with search method which return's list of IDs of records, then read data using read method. Both methods mostly same as Odoo Record class instead of dict for each record had been read. Record class provides some orm-like abilities for records, allowing for example access fields as attributes and provide mechanisms to lazily fetch related fields. >>> sale_orders = sale_order_obj.search_records([('state', '=', 'done')]) >>> sale_orders[0] R(sale.order, 9)[SO0011] >>> >>> # So we have list of Record objects. Let's check what they are >>> so = sale_orders[0] >>> so.id 9 >>> so.name SO0011 >>> so.partner_id R(res.partner, 9)[Better Corp] >>> >>> so.partner_id.name Better Corp >>> so.partner_id.active True Additional features Session: db aliases Session provides ability to add aliases to databases, which will simplify access to them. For this feature Session class provides method aliase and property aliases which allows to get all registered aliases in session. To add aliase to our db do the folowing: >>> session.aliase('my_db', db) And now to access this database in future (even after restart) You can use next code >>> db = session.my_db this allows to faster get connection to database Your with which You are working very often Sugar extension This extension provides some syntax sugar to ease access to objects To enable it, just import openerp_proxy.ext.sugar module. By default this extension will also be enabled on import of openerp_proxy.ext.all So to start use it just import this extension just after start import openerp_proxy.ext.sugar And after that You will have folowing features working db['sale.order'][5] # fetches sale order with ID=5 db['sale_order']('0050') # result in name_search for '0050' on sale order # result may be Record if one record found # or RecordList if there some set of records found db['sale.order']([('state','=','done')]) # Same as 'search_records' method db['sale.order'](state='done') # simplified search # Automatic object aliaces. Also supports autocompletition # via implementation of __dir__ method db._sale_order == db['sale.order'] == db['sale_order'] # => True For other extensions look at openerp_proxy/ext code or documentation Session: Start-up imports If You want some modules (extensions/plugins) to be automatiacly loaded/imported at start-up, there are session.start_up_imports property, that points to list that holds names of modules to be imported at session creation time. For example, if You want Sugar extension to be automaticaly imported, just add it to session.start_up_imports list session.start_up_imports.append('openerp_proxy.ext.sugar') After this, when You will start new openerp_proxy shell, sugar extension will be automaticaly enable. Plugins In version 0.4 plugin system was completly refactored. At this version we start using extend_me library to build extensions and plugins easily. Plugins are usual classes that provides functionality that should be available at db.plugins.* point, implementing logic not related to core system. To ilustrate what is plugins and what they can do we will create a simplest one. So let's start create some directory to place plugins in: mkdir ~/oerp_proxy_plugins/ cd ~/oerp_proxy_plugins/ next create simple file called attendance.pyand edit it vim attendance.py write folowing code there (note that this example works and tested for Odoo version 6.0 only) from openerp_proxy.plugin import Plugin class AttandanceUtils(Plugin): # This is required to register Your plugin # *name* - is for db.plugins.<name> class Meta: name = "attendance" def get_sign_state(self): # Note: folowing code works on version 6 of Openerp/Odoo emp_obj = self.client['hr.employee'] emp_id = emp_obj.search([('user_id', '=', self.client.uid)]) emp = emp_obj.read(emp_id, ['state']) return emp[0]['state'] Now your plugin is completed, but it is not on python path. There is ability to add additional paths to session, so when session starts, sys.pathwill be patched with that paths. To add your extra path to session You need do folowing: >>> session.add_path('~/oerp_proxy_plugins/') >>> session.save() Now, each time session created, this path will be added to python path Now we cat test our plugin. Run openerp_proxyand try to import it: >>> #import our plugin >>> import attendance >>> # and use it >>> db = session.connect() >>> db.plugin.attendance.get_sign_state() 'present' >>> # If You want some plugins or extensions or other >>> # modules imported at start-up of session, do this >>> session.start_up_imports.add('attendance') As You see above, to use plugin (or extension), just import it's module (better at startu-up) For more information see source code or documentation.
https://libraries.io/pypi/openerp_proxy
CC-MAIN-2020-34
refinedweb
1,724
57.16
Wrapper Class as a Boolean class instance. All of the primitive wrapper classes in Java...Wrapper Class what is wrapper class in java and why we use it  ... of the primitive wrapper classes in Java are immutable i.e. once assigned a value to a wrapper wrapper classes wrapper classes Explain wrapper classes and their use? Java Wrapper Class Wrapper class is a wrapper around a primitive data type... of the primitive wrapper classes in Java are immutable i.e. once assigned a value \wrapper \wrapper Hands on Exercise on Wrapper Class: Write a Java code that converts integer to Integer converts Integer to String converts String to integer converts int to String converts String to Integer converts Integer Wrapper :/  ... Wrapper Java provides wrapper classes corresponding to each primitive data types in its " wrapper class. wrapper class. Write short note on character wrapper class. Java Character Wrapper class The Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field Wrapper Classes classes in Java are immutable i.e. once assigned a value to a wrapper class...Primitive Wrapper Class In this section you will learn about Wrapper classes.... Wrapper class is a wrapper around a primitive data type. It represents Wrapper Class - Java Beginners Wrapper Class What is Wrapper class? Why are they use Examples of Wrapper Class Examples of Wrapper Class In this page we are giving you the links of tutorials on wrapper classes in Java. Wrapper classes are the classes present...) char 8) boolean Following are the example of wrapper classes in Java.  Wrapper Classes as a Boolean class instance. All of the primitive wrapper classes in Java... In Java 5.0 version, additional wrapper classes were introduced... class instance it can not be changed, anymore. Wrapper Classes wrapper class wrapper class list wrapper class methods wrapper class wrapper class wrapper class methods Wrapper Class - Java Beginners Wrapper Class Please explain the above question on Wrapper class with some examples wrapper class wrapper class why wrapper class does not have a default constructor java-wrapper class java-wrapper class dear people, may i know how to convert primitive data type into corresponding object using wrapper class with example please!!! public class IntToIntegerExample { public static void Wrapper Wrapper 7.Wrapper This new wrapper interface provides a mechanism for accessing an instance of a resource. This is used by many JDBC driver implementations. Earlier the wrapper used to be data wrapper class concept wrapper class concept Write a Java class that stores an integer item id, a string item name and a float price. Store all these in a String member Variable, separated by a space delimiter. Use an overloaded method to add Wrapper Character class. Wrapper Character class. How do the methods 'isIndentifierIgnorable(ch)' and 'isISOControl(ch)' work?? while workin with 'Character' wrapper class... be regarded as an ignorable character in a Java identifier or a Unicode identifier Wrapper Class in Java data type, it can only be achieved by using Wrapper Classes in Java... is required Wrapper Classes and their corresponding primitive data types in Java...(); Example of Wrapper Class in Java: How to insert an element at the specified Character Wrapper Class. Character Wrapper Class. what are Mirrored Unicode Characters?? and whats the use of "isMirrored(ch);method ??.where ch is any character argument..!! Unicode is capable of representing many languages, including those please tell me what is ment by wrapper class in java........ please tell me what is ment by wrapper class in java........ what is ment by wrapper class in java Wrapper Class Tutorial and Examples Wrapper Class Tutorial and Examples Wrapper Classes In this section you will learn about Wrapper classes and all the methods that manipulate Wrapper Class Tutorial and Examples write a program to demonstrate wrapper class and its methods...... write a program to demonstrate wrapper class and its methods...... write a program to demonstrate wrapper class and its methods Use of wrapper objects - Java Interview Questions Use of wrapper objects What is the role & use of Java wrapper objects? Hi Friend, Please visit the following link: Thanks Java Integer class Java Integer class Java provides wrapper classes corresponding to each primitive data types in its "lang" package. These classes represent the primitive values wrapper prob - Java Beginners wrapper prob Hello all Integer k = 128; Integer l = 128; System.out.println("k==l >> "+ (k==l)); Integer i = 127; Integer j = 127; System.out.println("i==j >> "+ (i==j)); Can anybody tell me that why Integer exception in java Integer exception in java The integer class is a wrapper for integer value. Integers are not objects. The Java utility classes require the use of objects. If you Class there are two classes has been used except the main class in which the main function... is using two classes. First class is another and second is the main class which... Class, Object and Methods   which class is super class to all classes which class is super class to all classes in java which class is super class to all classes Object is the super class for all user defined and predefined class. java.lang.Object is the supper class of all What is the base class of all classes? What is the base class of all classes? Hi, What is the base class of all classes? thanks Hi, The base class is nothing but the Abstract class of Java programming. We uses the syntax for base class of all Abstract class,Abstract methods and classes (); Abstract Class In java programming language, abstract classes...). Abstract classes are not instantiated directly. First extend the base class... Abstract methods and classes   Autoboxing in Java types into Wrapper class by Java compiler takes place when: a primitive data... ((int, float, double) into their corresponding Wrapper class object (Integer... he automatic transformation of wrapper class object into their corresponding SCJP Module-6 Question-25 Given below the sample code : class ObjectClass { public static void main(String args[]) { Object[] ObjectsPack = { new Integer(12), new String("zoo"), new Integer(5), new Boolean(true) }; Arrays.sort(ObjectsPack); for (int Class C:\roseindia>java Classtest It's a example of class... Class This section explores the concept of a class in reference to object oriented programming Java classes Java classes Which class is extended by all other classes java classes java classes Which class is the super class for all classes in java.lang package classes classes what is meant by class?why we use class?what is the purpose of class?what is the main theme of class?tell clearly?plz classes classes differnce between class and object please say exact difference between class and object please say exact difference between class and object please say exact difference between class Explain final class, abstract class and super class. Explain final class, abstract class and super class. Explain final class, abstract class and super class. Explain final class, abstract class and super class. A final class cannot be extended. A final class Nested class Nested class What is nested class? when a class is defined within another class then such a class is called a nested class. Nested classes are a feature of Java that is included in jdk1.1. The reasons of why we use Java classes Java classes What is the Properties class java classes java classes What is the ResourceBundle class abstract class abstract class Explain the concept of abstract class and it?s use with a sample program. Java Abstract Class An abstract class is a class that is declared by using the abstract keyword. It may or may not have Java classes Java classes Why default constructor of base class will be called first in java Class Loader ;The Java ClassLoader is a an abstract class which extends the Object class. Java class loader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Generally Java virtual machine load java classes java classes What is the difference between a static and a non-static inner class Class class Java NotesClass class Like a human thinking about his/her own thinking, the process of a running program examining its classes is called reflection or introspection. There is run-time information about classes that you can access Choose a class Choose a class Hi, I am working with java. I was wondering what to type in the start of a program so I can choose between all the classes in the program? How to choose to use only "class A" for example? Thanks for a quick robot class provide the class Robot. It gives the java program much power. It can perform all...robot class i also want the uses of robot classes its applications in the programming. where exactly robot class is useful. why is it necessary Nested classes language that allows us to define a class within another class, such classes... class. ( It can even contain further levels of nested classes, but you... Nested classes   Exception Classes ; The hierarchy of exception classes commence from Throwable class which is the base class for an entire family of exception classes, declared in ... the throwable classes which are defined by you must extend Exception class.  Class in Java Class in Java In this section, we will discuss about java classes and its structure. First of all learn: what is a class in java and then move on to its Inner classes Inner classes Hi I am bharat . I am student learning java course . I have one question about inner classes . question is how to access the instance method of Non-static classes which is defined in the outer abstract class - Java Beginners , In java programming language, abstract classes are those that works only... inherited from the abstract class (base class). Abstract classes...abstract class what exactly is abstract class and in which cases its Class Loader ; The Java ClassLoader is a an abstract class which extends the Object class. Java class loader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Generally Java virtual machine load java class - Java Beginners java class hi sir, i have to compile two classes(eg:controller.java and client.java) and i have imported some packages in it using jar files... it is showing errors for packages which i have imported.? how to run those classes Java Abstract Class Java Abstract Class  ...; --or-- Java provides a special type of class called an abstract class. Which helps us to organize our classes based on common methods. An abstract class Java Nested Class Java Nested Class In Java programming language, when a class is defined within another class then such a class is called a nested class. Nested classes are a feature Which class is extended by all other classes? Which class is extended by all other classes? Hi, Which class is extended by all other classes? thanks Abstract class and interface in Java Abstract class and interface in Java What is the difference between abstract class and interfaces in Java? Differences between an interface and an abstract class: At the same time multiple interfaces can Java exception class Java exception class What classes of exceptions may be caught by a catch clause Inner Class - Java Beginners Inner Class Hi, I have the following question. class Outer{ class Inner{ } public static void main(String[] args) { Outer.Inner..., it will generate two classes, Outer.class & Outer$Inner.class. But If I change the access class - Java Beginners ) Abstract class Shapes has one abstract method-area() and a concrete method display(). Class Rectangle should implement the abstract class shapes Interface Shapes has abstract methods-area(),display(). Classes Rectangle and Triangle should Java Abstract Class Example Java Abstract Class Example In this section we will read about the Abstract class. Abstract class in Java is a class which is created for abstracting the behaviour of classes from the outside environment. Abstract class can be created Abstract class - Java Beginners Abstract class Why can use abstract class in java.?when abstract class use in java.plz Explain with program. abstract class abs{ public void display(){ } public abstract void display1(); } public class win classes in c++ classes in c++ 1- design and implement a class datatype that implement the day of the week in the program.the class datatype should store the day... on this class. Here is the Java code: public class DayType{ final java basics as a Boolean class instance. All of the primitive wrapper classes in Java...java basics What are wrapper classes? When we need to store primitive datatypes as objects, we use wrapper classes. Wrapper class java - JDBC as a Boolean class instance. All of the primitive wrapper classes in Java... to : Thanks...java what is a wraperclass? Hi friend, Wrapper class java - Java Beginners java What is the difference between Wrapper Class and Vector Class? Hi Friend, Differences: Wrapper classes convert primitive data... links: http Classes and Objects and classes are the fundamental parts of object-orientated programming technique. A class...-oriented programming. Nested Classes: One more advantage of Java... a class within another class, such classes are known as nested classes Nested classes: Examples and tutorials ; Nested classes Here is another advantage of the Java... within another class, such class is called a nested class. Inner classes can...; Static Nested Classes A nested class that is declared static is called Use of Local Inner class Use of Local Inner class The Java language enables you to define a class inside another.... The inner class Get Even Integer is same as Java iterators,The work of Get Even Class or Interface Java NotesClass or Interface Declare variables as class or interface type.... Why change the underlying class? The two List classes, ArrayList...(); // Changed underlying class Because the performance characteristics MovieRating class - Java Beginners the movie rating. 12.Create a MovieRating class that contains a private map... the class is instantiated. Also include a method which takes two parameters, rating... class to determine whether the child can watch the movie. 14.Add The link to the outer class,java tutorial,java tutorials Nested Classes: Inner & Outer Class The classes which are defined within... outer class through an object. Static inner classes can't access the member of the outer class direclty. Non Static The non static classes have access What is Abstract classes in Java? What is Abstract classes in Java? What is Abstrack class in Java.... That's why the Abstract class in Java programming language is used to provide... visit Abstract class in Java java inner class - Java Beginners java inner class What is the difference between the nested class... declared inside another class. 2)Nested classes are associated with the enclosing class itself, whereas inner classes are associated with an object Fields in java class Fields in java class  ... will access by the class, subclass or classes in the same package. Private...: The field can be access by any class objects from classes inside the same package Java application that uses the classes and Java application that uses the classes and i have this class diagram with three classes: Curriculum, Course, and Lecture. Your class diagram...) I wish Write a Java application that uses the classes and methods above Java class Java class What is the purpose of the Runtime class JAVA CLASSES/ SUPERCLASS JAVA CLASSES/ SUPERCLASS i. Define a class called Student and its.... A underGraduateStudent has a class status (freshman, sophomore, junior, or senior... as a constant. Define a method called toString which overridden in each class Class Average Program of the class, represent classes and interfaces in a running Java application... Class Average Program This is a simple program of Java class. In this tutorial we Classes in java etc. For more details click on the following link Classes in Java... the objects are categorized in a special group. That group is termed as a class. All the objects are direct interacted with its class that mean almost all Inner Nested Classes Inner Nested Classes Non-static nested classes are slightly different from static nested classes, a non-static nested class is actually associated Interface and Abstract class and Abstract Class 1)Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance...)Members of a Java interface are public by default. A Java abstract class can have Classes and Objects class). This section illustrates how to define our own classes, that includes...; Nested Classes: One more advantage of Java, as an object-oriented... class, such classes are known as nested classes.   creating java classes creating java classes Create a Java class that can be used to store inventory information about a book. Your class should store the book title, the author?s name, the price, and the number of books in stock. The class you Class Diagram - UML Class Diagram Hi Friend, First of all thanks for the answers given to me...... I want to draw class diagram for the following classes 1. Webcrawlerwindow 2. Webcrawler 3. caheurl here class 1 creates the object are defined within the body of a class. We can use member classes anywhere within the body of the containing class. We declare member classes... class. Local classes Local classes are same as local variables, in the sense inner class - Java Interview Questions Java Inner Class How many classes we can create in an inner class? How many classes we can create in an inner class ANS :- Within Main class{} we can create any number of the inner classes according java class java class write a java program to display a msg "window closing" when the user attempts to close the window.(a) create a window class (b) create frame within the window class (c) extends window adapter class to display the msg core java - Java Interview Questions links: Thanks...core java why sun soft people introduced wrapper classes? do we have any other means to achieve the functionality of what a Wrapper class provides Ask Questions? If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions.
http://www.roseindia.net/tutorialhelp/comment/98804
CC-MAIN-2013-20
refinedweb
3,058
56.35
GLFW:Tutorials:Basics The programming interface to GLFW is mercifully small, and setting up a little program with it is a piece of cake. I'll show the basics here. For a more complete description of the library go to Installing GLFW First, you get the source code here and extract it somewhere. Basically you just follow the instructions in readme.html that apply to the compiler you are using, I'm not going to duplicate that information here. If you link your program statically with GLFW (the licence allows this, even for commercial programs), you will not have to distribute any extra DLL's with your program. If you are using Dev-C++ (MinGW), you can simply download the GLFW Devpack and do not have to compile GLFW yourself Conventions All library functions have 'glfw' (lower-case) prefixed to their name. To use the functions you'll have to include the GLFW header file, usually with #include <GL/glfw.h>, this takes care of including <GL/gl.h> for you, and on windows it will also remove the need to include <windows.h> before including gl.h. GLFW functions that return a status value will use GL_TRUE (a constant from the gl.h header file) for success and GL_FALSE for failure. Initialization At the start of your program, you'll have to call glfwInit() to initialize the library. This does not open any windows or do anything, it just does some preparation to allow you to start using GLFW functions. You should check the return value of this function; if it is GL_FALSE, the initialization failed for some reason. Likewise, when your program terminates, you'll have to call the glfwTerminate(), which will free any resources claimed by GLFW and close any open windows created by GLFW. Next, you'll want to open a window. Unsurprisingly, the function to do this is glfwOpenWindow: glfwOpenWindow(int width, int height, int redbits, int greenbits, int bluebits, int alphabits, int depthbits, int stencilbits, int mode) That is an awful lot of parameters. Fortunately, you can set a lot of them to zero. The first two give the resolution for the window, you'll usually want to specify something here (0, 0 gives 640 x 480). Next come the number of bits per color. If you leave these at 0 the color depth of your desktop will be used, if you specify them GLFW will use the color depth that comes closest to what you specified (for example 5, 6, 5 will give you 16 bit color if your OpenGL implementation supports it). Alphabits, depthbits and stencilbits specify will be set to 0, 8, 0 in this example, leave them at that if the words mean nothing to you. The last parameter, mode, is used to indicate whether the window will be full-screen or not. Pass GLFW_FULLSCREEN for a full screen window, and GLFW_WINDOW for a normal one. if (glfwOpenWindow(800, 600, 5, 6, 5, 0, 8, 0, GLFW_FULLSCREEN) != GL_TRUE) Shut_Down(1); // calls glfwTerminate() and exits glfwSetWindowTitle("The GLFW Window"); This initializes an 800x600, 16-bit color, full screen window, or kills the program if it's initialization failed. It also sets the window title. We're ready to start drawing. Do make sure you only use OpenGL functions when there is an open window (that also goes for creating and destroying texture objects and such things), when there is no window there is no OpenGL context, and you can not use OpenGL. You can close your window at any time with glfwCloseWindow(), but you can also just let gflwTerminate() handle that when your program closes. Graphics GLFW does not do much drawing itself, you'll have to use OpenGL library functions. This tutorial does not concern itself with those. One thing GLFW does help you with is loading textures from TGA files, but usage of that function is so interwoven with OpenGL that you'll have to look it up yourself. Input There are two ways of reading input in GLFW, polling for it and registering callback functions. I'll only discuss keyboard input here, but mouse input goes much the same way. One important thing to notice is that GLFW only checks for new input whenever glfwSwapBuffer() or glfwPollEvents() is called, thus if you are not swapping buffers or explicitly polling, no new events will arrive. if (glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS) quit_the_program = 1; if (glfwGetKey('A') == GLFW_PRESS) printf("A is pressed"); This uses the polling method to check for key input. The return value of glfwGetKey is GLFW_PRESS if the key is currently held down, and GLFW_RELEASE if it is not. Keys that have a character associated with them can be indicated by using that character as argument, other keys have their own constants (see the documentation at or glfw.h for all the constants). Using callbacks to get key events goes like this: void GLFWCALL My_Key_Callback(int key, int action) { if (key == GLFW_KEY_ESC && action == GLFW_PRESS) quit_the_program = 1; else if (key == 'A' and action == GLFW_PRESS) printf("A was pressed"); } // And somewhere in the init code glfwSetKeyCallback(My_Key_Callback); Now every time a key is pressed or released, My_Key_Callback is called with information about the event. This allows for more flexible input handling that the other method, but is a bit more work. Timing The function glfwGetTime() returns a 'double' (double-precision floating poing number) containing the number of seconds that elapsed since glfwInit() was called. It uses the highest-precision timer available on the system, so precision might vary on different platforms. An Example The following code will open a window and display a cute animation until escape is pressed. The code should be very easy to read (if it is not, you'll have to study C and OpenGL some more). To compile it on your system, make sure you link with the OpenGL and GLFW libraries, and on Unix systems you'll also need to link with the X libraries and threading libraries (X11, Xxf86vm and c_r on FreeBSD, X11, pthread and maybe some others on Linux). (For example it can be compiled under GNU/Linux with gcc myprog.c -o myprog -lglfw -lGL -lpthread) #include <stdlib.h> #include <GL/glfw.h> void Init(void); void Shut_Down(int return_code); void Main_Loop(void); void Draw_Square(float red, float green, float blue); void Draw(void); float rotate_y = 0, rotate_z = 0; const float rotations_per_tick = .2; int main(void) { Init(); Main_Loop(); Shut_Down(0); } void Init(void) { const int window_width = 800, window_height = 600; if (glfwInit() != GL_TRUE) Shut_Down(1); // 800 x 600, 16 bit color, no depth, alpha or stencil buffers, windowed if (glfwOpenWindow(window_width, window_height, 5, 6, 5, 0, 0, 0, GLFW_WINDOW) != GL_TRUE) Shut_Down(1); glfwSetWindowTitle("The GLFW Window"); // set the projection matrix to a normal frustum with a max depth of 50 glMatrixMode(GL_PROJECTION); glLoadIdentity(); float aspect_ratio = ((float)window_height) / window_width; glFrustum(.5, -.5, -.5 * aspect_ratio, .5 * aspect_ratio, 1, 50); glMatrixMode(GL_MODELVIEW); } void Shut_Down(int return_code) { glfwTerminate(); exit(return_code); } void Main_Loop(void) { // the time of the previous frame double old_time = glfwGetTime(); // this just loops as long as the program runs while(1) { // calculate time elapsed, and the amount by which stuff rotates double current_time = glfwGetTime(), delta_rotate = (current_time - old_time) * rotations_per_tick * 360; old_time = current_time; // escape to quit, arrow keys to rotate view if (glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS) break; if (glfwGetKey(GLFW_KEY_LEFT) == GLFW_PRESS) rotate_y += delta_rotate; if (glfwGetKey(GLFW_KEY_RIGHT) == GLFW_PRESS) rotate_y -= delta_rotate; // z axis always rotates rotate_z += delta_rotate; // clear the buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw the figure Draw(); // swap back and front buffers glfwSwapBuffers(); } } void Draw_Square(float red, float green, float blue) { // Draws a square with a gradient color at coordinates 0, 10 glBegin(GL_QUADS); { glColor3f(red, green, blue); glVertex2i(1, 11); glColor3f(red * .8, green * .8, blue * .8); glVertex2i(-1, 11); glColor3f(red * .5, green * .5, blue * .5); glVertex2i(-1, 9); glColor3f(red * .8, green * .8, blue * .8); glVertex2i(1, 9); } glEnd(); } void Draw(void) { // reset view matrix glLoadIdentity(); // move view back a bit glTranslatef(0, 0, -30); // apply the current rotation glRotatef(rotate_y, 0, 1, 0); glRotatef(rotate_z, 0, 0, 1); // by repeatedly rotating the view matrix during drawing, the // squares end up in a circle int i = 0, squares = 15; float red = 0, blue = 1; for (; i < squares; ++i){ glRotatef(360.0/squares, 0, 0, 1); // colors change for each square red += 1.0/12; blue -= 1.0/12; Draw_Square(red, .6, blue); } }
http://content.gpwiki.org/index.php/GLFW:Tutorials:Basics
CC-MAIN-2014-42
refinedweb
1,386
58.72
zipfile — Work with ZIP archives¶ GiB in size). It supports decryption of encrypted files in ZIP archives, but it currently cannot create an encrypted file. Decryption is extremely slow as it is implemented in native Python rather than C. The module defines the following items: -. Path A pathlib-compatible wrapper for zip files. See section Path Objects for details. New in version 3.8. -. New in version 3.3. Note The ZIP file format specification has included support for bzip2 compression since 2001, and for LZMA compression since 2006. However, some tools (including older Python releases) do not support these compression methods, and may either refuse to process the ZIP file altogether, or fail to extract individual files. See also - 'a'and the file does not exist at all, it is created.). The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp to 1980-01-01. Similar behavior occurs with files newer than 2107-12-31, the timestamp is also set to the limit.. New in version 3.8: The strict_timestamps keyword-only argumentzip('. Note Archive names should be relative to the archive root, that is, they should not start with a path separator. Note If arcname(or filename, if arcname a file into the archive. The contents is data, which may be either a stror a bytesinstance; if it is a str, it is encoded as UTF-8 first.. Path Objects¶ - class zipfile. Path(root, at='')¶ Construct a Path object from a rootzipfile (which may be a ZipFileinstance or filesuitable for passing to the ZipFileconstructor). atspecifies the location of this Path within the zipfile, e.g. ‘dir/file.txt’, ‘dir/’, or ‘’. Defaults to the empty string, indicating the root. Path objects expose the following features of pathlib.Path objects: Path objects are traversable using the / operator. Path. open(*, **)¶ Invoke ZipFile.open()on the current path. Accepts the same arguments as ZipFile.open(). Path. read_text(*, **)¶ Read the current file as unicode text. Positional and keyword arguments are passed through to io.TextIOWrapper(except buffer, which is implied by the context).. basename is intended for internal use only. filterfunc, if given, must be a function taking a single string argument. It will be passed each path (including each individual full file path) before it is added to the archive. If filterfunc returns a false value, the path will not be added, and if it is a directory its contents will be ignored. For example, if our test files are all either in testdirectories or start with the string test_, we can use a filterfunc to exclude them: >>> zf = PyZipFile('myprog.zip') >>> def notests(s): ... fn = os.path.basename(s) ... return (not (fn == 'test' or fn.startswith('test_'))) >>> zf.writepy('myprog', filterfunc=notests) The writepy()method makes archives with file names like this: string.pyc # Top level name test/__init__.pyc # Package directory test/testall.pyc # Module test.testall test/bogus/__init__.pyc # Subpackage directory test/bogus/myfile.pyc # Submodule test.bogus.myfile New in version 3.4: The filterfunc parameter., *, strict_timestamps=True. The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp to 1980-01-01. Similar behavior occurs with files newer than 2107-12-31, the timestamp is also set to the limit. New in version 3.6. Changed in version 3.6.2: The filename parameter accepts a path-like object. New in version 3.8: The strict_timestamps keyword-only argument bytesobject.. Decompression pitfalls¶ The extraction in zipfile module might fail due to some pitfalls listed below. From file itself¶ Decompression may fail due to incorrect password / CRC checksum / ZIP format or unsupported compression method / decryption. File System limitations¶ Exceeding limitations on different file systems can cause decompression failed. Such as allowable characters in the directory entries, length of the file name, length of the pathname, size of a single file, and number of files, etc. Resources limitations¶ The lack of memory or disk volume would lead to decompression failed. For example, decompression bombs (aka ZIP bomb) apply to zipfile library that can cause disk volume exhaustion. Interruption¶ Interruption during the decompression, such as pressing control-C or killing the decompression process may result in incomplete decompression of the archive.
https://docs.python.org/3.8/library/zipfile.html
CC-MAIN-2019-39
refinedweb
717
60.41
I defined a class `test' and also overloaded the << operator for it. It came out that I can apply cout to objects of test to print the contents to the console, but I got stuck when trying to print them to the console using copy. It'll be a compile-time error when using copy! Is there anything wrong with my code? Do I need to overload more operators? Code:#include <algorithm> #include <iostream> #include <iterator> #include <string> #include <vector> using namespace std; class test { friend ostream& operator <<(ostream &out, test &t); public: test(int n) { a = n; } private: int a; }; int main() { vector<test> vec; vec.push_back(1); vec.push_back(2); for ( vector<test>::iterator it = vec.begin(); it != vec.end(); ++it ) { cout << *it << ' '; } // compile-time error when using copy // copy(vec.begin(), vec.end(), ostream_iterator<test>(cout, " ")); cout << endl; } ostream& operator <<(ostream &out, test &t) { return (out << t.a); }
http://cboard.cprogramming.com/cplusplus-programming/90935-help-about-stl-copy-algorithm.html
CC-MAIN-2015-18
refinedweb
151
65.12