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
send Struts performance Java web applications that runs on Java enabled application servers. Struts...Struts How Struts is useful in application development? Where to learn Struts? Thanks Hi, Struts is very useful in writing web Removing the Title Bar of a Frame Removing the Title Bar of a Frame In this section, you will learn how to remove the title bar of a frame or window in java. That means show the frame or window without Removing characters from a string Removing characters from a string Removing characters from a string Example: public class CharReplace{ public static void main(String []args){ String str="Hello 123.you are At 3456"; String Removing existing cookie in jsp Removing existing cookie in jsp How remove existing cookie in jsp ? If you want to remove an existing cookie, you can use the method setMaxAge() of that cookie object to set its timeout to zero.Example <%@page Removing the title bar of the Frame in Java Removing the title bar of the Frame in Java Introducion Here, you will learn how to display the frame or window without title bar in java. This type Removing character from a string in sql. Removing character from a string in sql. Removing special characters from a string in sql J2EE Web Service Development with Attachments Using Axis J2EE Web Service Development with Attachments Using Axis... the development of a java web service that takes DIME or MIME attachment as input... Attachments are becoming increasingly popular in the web service development java - Struts java how to display multiple images on struts using Arraylist java - Struts java How To Connect oracle Database With Struts Project SAAJ stands for SOAP with Attachments API for Java - contains APIs for creating and populating SOAP messages, which may or may not contain attachments. It also... SOAP messages. SOAP message is made of SOAP Envelope with zero or more attachments Removing character from a string in sql. Removing character from a string in sql. How to remove or replace character from a string Session removing - JSP-Servlet interview Question - Struts struts interview question and answer java struts interview question and answer java Java - Struts in DispatchAction in Struts. How can i pass the method name in "action" and how can i map at in struts-config.xml; when i follow some guidelines... more the one action button in the form using Java script. please give me Removing Horizontal Lines to Node Groups Removing Horizontal Lines to Node Groups Introduction In this section, you will learn to create none type tree in Java. None type tree means that children nodes - Struts java i want know the basics of the struts Hi Friend, Please visit the following link: Hope that it will be helpful for you. Thanks java file upload in struts - Struts java file upload in struts i need code for upload and download file using struts in flex.plese help me Hi Friend, Please visit the following links: http Wrapping, replacing, and removing content Wrapping, replacing, and removing content Wrapping, replacing, and removing content The JQuery provide efficient ways for wrapping, replacing, and removing Java - Struts :// Thanks. my doubt is some java - Struts ,struts-config.xml,web.xml,login form ,success and failure page also... code... own code ....ok ..plse do it... LoginForm.java package java; import... getPassword() { return password; } } Struts java - Struts Java JRE latest Which is Java JRE latest Version java - Struts Java string tokenizer What is Java string tokenizer java - Struts Java API Documentation Java API Documentation example in eclipse using captcha with Struts - Struts application using Struts framework, and i would like to use captcha Hi friend,Java Captcha in Struts 2 Application : Jakarta Struts Interview Questions Jakarta Struts Interview Questions Q: What is Jakarta Struts Framework? A: Jakarta Struts is open source implementation of MVC (Model-View-Controller implementing DAO - Struts implementing DAO Hi Java gurus I am pure beginner in java, and have to catch up with all java's complicated theories in a month for exam. Now... appreciated! Thanks virgo25 Hi friend, Java DAO Implementation java - Struts ! Inheriting a class in java constructor Need example of inheriting a class in java constructor java - Struts Java long to string conversion What is the steps to convert a long to String in Java J2EE Web Service Development with Attachments Using Axis java struts - Java Beginners java struts Hi sir i need complete digram of struts... how i can configer the struts in my eclipse... please send me the complete picture diagram what is struts? - Struts of the Struts framework is a flexible control layer based on standard technologies like Java...what is struts? What is struts?????how it is used n what... Commons packages. Struts encourages application architectures based on the Model :// Thanks Struts - Java Interview Questions Struts Interview Questions I need Java Struts Interview Questions and examples you want in your project. Do you want to work in java swing? Thanks java struts - Java Beginners java struts i want to do the project in the struts.... how i can configure the project in my eclipse... can u help me in this issues 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/16906
CC-MAIN-2013-20
refinedweb
891
51.38
Smart Trash Carts Tell If You Haven't Been Recycling samzenpus posted more than 3 years ago | from the clean-up-or-pay-up dept. ." first post (-1, Troll) Anonymous Coward | more than 3 years ago | (#33333434) rape a baby! Recycling is Bullshit (3, Interesting) commodore64_love (1445365) | more than 3 years ago | (#33333454) (5, Insightful) 5pp000 (873881) | more than 3 years ago | (#33333498) From TFA: I wouldn't think Cleveland would spend money on "smart trash carts" unless there were some truth to this claim. Re:Recycling is Bullshit (0) Anonymous Coward | more than 3 years ago | (#33333568) Unless of course there was some other sort of incentive to do so, like a grant from EPA, or some new law or regulation. Also, $26/ton for recyclables - that sounds good, but surely it depends what the recyclables are. A ton of aluminum cans could be worth much more; a ton of barely-recycleable plastic, much less. Don't see how this undermines Penn and Teller at all. Re:Recycling is Bullshit (1) larry bagina (561269) | more than 3 years ago | (#33333678) Re:Recycling is Bullshit (2, Interesting) Gazzonyx (982402) | more than 3 years ago | (#33333622) Some of these "smart trash cans" will never be profitable, but will be a loss for the city and for the environment (more e-waste for the landfill). Re:Recycling is Bullshit (2, Informative) KiloByte (825081) | more than 3 years ago | (#33333638) They do spend money (not theirs, taxpayers') to make it look they do care for the environment, which brings votes. They don't give a flying damn about doing something that actually works. Re:Recycling is Bullshit (1) BigSlowTarget (325940) | more than 3 years ago | (#33333828) I wouldn't count on it. I suspect I could spin a business case to show the exact opposite by tweaking a few assumptions and still have every one of them look reasonable. There's a good chance someone wanted to sell recycling equipment and made the numbers happen. I like the part of the landlords being responsible though. If my landlord ticks me off I just anonomously drop recycling into the dumpster and cost him $100 a shot. Nice. I'm sure the recycling companies make money, but that's easy if you push costs off on someone else. Re:Recycling is Bullshit (4, Insightful) cptdondo (59460) | more than 3 years ago | (#33333518) Depends on where you live. Some places don't have easy access to landfills anymore and it's cheaper to subsidize recycling than to landfill. And some places just believe it's the right thing to do and pay the costs anyway. Re:Recycling is Bullshit (-1, Flamebait) MightyMartian (840721) | more than 3 years ago | (#33333564) Because, of course, having an agent of the government knock on your door and demanding to look through your trash is the "right thing to do". Re:Recycling is Bullshit (4, Insightful) cduffy (652) | more than 3 years ago | (#33333604) Who said anything about knocking on doors? They just have to look through the trash you've put out on the curb... which, last I recall, anyone else could legally do just as easily. Re:Recycling is Bullshit (1, Flamebait) pushing-robot (1037830) | more than 3 years ago | (#33333674) Why? You're giving it to them already, aren't you? If you're concerned about privacy, buy a shredder. If the though of the e-e-evil city gub'mint having your trash bothers you, dispose of it yourself. I'm fairly sure that an unrestricted anonymous waste disposal service wasn't guaranteed in the constitution. Re:Recycling is Bullshit (2) MightyMartian (840721) | more than 3 years ago | (#33333710) I was thinking more along the lines of keeping a few boxes of rotten eggs sitting around and tossing those on top on garbage day. In the immortal words of Russell Casse; "UP... YOURS!!!!" Re:Recycling is Bullshit (5, Informative) nschubach (922175) | more than 3 years ago | (#33333792) (5, Insightful) pushing-robot (1037830) | more than 3 years ago | (#33333926):Recycling is Bullshit (2) pushing-robot (1037830) | more than 3 years ago | (#33334028) (4, Informative) B5_geek (638928) | more than 3 years ago | (#33333532):Recycling is Bullshit (2, Interesting) commodore64_love (1445365) | more than 3 years ago | (#33333642) >> died because it didn't have porn; it's false.) Re:Recycling is Bullshit (1) pijokela (462279) | more than 3 years ago | (#33334022) Here in Finland, recycled paper is quite valuable, because the paper buyers in central Europe want paper that has as much recycled material in it as possible. So if we want to sell paper made from our trees to central Europe, we must have tons of recycled paper too. At some point we were importing recycled paper from Germany, I'm not sure if that's still going on. I just like to recycle paper and cardboard, because they fill the bin so fast I'd need to have it emptied even more often then now. This way I save, maybe 10€ a month. Re:Recycling is Bullshit (-1, Troll) BradleyUffner (103496) | more than 3 years ago | (#33333660) So we are forced to GIVE you our property so that you can sell it for profit? Why aren't you paying us? Re:Recycling is Bullshit (1) Jedi Alec (258881) | more than 3 years ago | (#33333740) Anyone holding a gun to your head and forcing you to put the stuff at the curb? Anyone stopping you from selling your trash? Re:Recycling is Bullshit (1) RapmasterT (787426) | more than 3 years ago | (#33333800) Re:Recycling is Bullshit (1) Velox_SwiftFox (57902) | more than 3 years ago | (#33333956) Still, the economics of recycling versus landfill usage are highly dependent on the lack or presence of what are effectively subsidies. A few decades ago, I recall a legal dispute between a waste recycling company and a municipality. The city had a long term contract that required them to pay "Immense Green-Ish Waste Management Incorporated" some tens of dollars per ton of newsprint recycled. After the contract was negotiated the price of recycled paper happened to boom - at about the same time, recycling coming into favor on the demand end. Enterprising individuals were driving around picking up the newspaper before IGIWMI crews could get it. Last I was paying attention, the city was being sued by the waste management company for not vigorously prosecuting this "grand theft", after the latter refused to at all consider renegotiating the contract terms so that every bit of this theft did not also save the city a grand amount of money. Re:Recycling is Bullshit (5, Insightful) Anonymous Coward | more than 3 years ago | (#33333586):Recycling is Bullshit (2, Insightful) vlm (69642) | more than 3 years ago | (#33333592) (1) decoy256 (1335427) | more than 3 years ago | (#33333908) The waste in an ex-landfill doesn't affect the park above it, since they cover up the landfill with several feet of dirt before building the park. By the time they open the park up, what little harmful substance are still around do not affect you any more than the harmful substances that are already present at regular parks. Re:Recycling is Bullshit (MYTH) (5, Informative) mspohr (589790) | more than 3 years ago | (#33333686) Of course, lots of resources on the web about this as well as "garbage recycling deniers" but a good summary page is here: [harvard.edu] Re:Recycling is Bullshit (MYTH) (0, Troll) LingNoi (1066278) | more than 3 years ago | (#33333942) I'm not saying that recycling shouldn't be done, but you have to admit there is a lot of lying and complete bullshit here. If the people who wrote this site were honest rather then trying to make up any excuse possible then it would make everyone look more credible. I noticed you used the word "deniers", might not want to do that next time when the information you got is lying 20% of the time. Let's look at this link.. So in this answer they completely avoid the question being raised. They state not recycling means paying for disposal, ok but you also have to pay to recycle it. Conveniently forgetting that the garbage truck picks up the recyclables to begin with, at least it does in the context of the article. There is no landfill crisis as the GPs P&T video shows. This is complete bullshit, just because an area is used for landfill doesn't mean it becomes an arid wasteland that it useless for the next 100 years. You can still use it, build on it, just like any other land. If it were popular the article wouldn't be about people being fined for not doing it. Re:Recycling is Bullshit (4, Informative) RevWaldo (1186281) | more than 3 years ago | (#33333732) This show is admittedly and unrepentantly biased, which makes it a poor source of reference. Supposedly their last episode will be entitled " 'Bullshit!' is Bullshit! ", explaining all this. We'll see. . how come (-1, Troll) Dolphinzilla (199489) | more than 3 years ago | (#33333468) if we have the technology for your trashcan to tell what is recyclable or not, they don't just put that technology at the dump and sort the stuff there automatically ? I seriously doubt the reliability or accuracy of a "smart" trashcan - maybe in about 200 years.... Re:how come (1) secondsun (195377) | more than 3 years ago | (#33333486) The trashcans just tell if they have been rolled out to be picked up. If they haven't recorded a roll out then you get fined if your trash has more than 10% recyclable material. How to lose while being correct Re:how come (5, Insightful) mrmeval (662166) | more than 3 years ago | (#33333552) come (1) Dolphinzilla (199489) | more than 3 years ago | (#33333556) yeah - good call - its not a smart trashcan it is just more spying by the man - so I'll pay the kid next door to roll that baby to the curb a couple of times a week, problem solved Re:how come (1) TFAFalcon (1839122) | more than 3 years ago | (#33333676) My guess is that people will just start dumping all of their trash in the recycle trash cans. That way they don't have to worry about sorting the trash + they avoid the fine. Re:how come (1) Cwix (1671282) | more than 3 years ago | (#33333778) Yep, the garbage man wont notice the dirty diaper that comes rolling out of the trashcan marked aluminum. Re:how come (0) Anonymous Coward | more than 3 years ago | (#33333842) Around here they simply won't pick it up if the recycling trash bag (we use semi-transparent plastic bags for non-metal recyclables) contains too much non-recyclable stuff. Re:how come (1) jrmcferren (935335) | more than 3 years ago | (#33333492) The chip IDs whether it is a recycle bin or a regular trash can. This allows the automated trucks to automatically sort where it goes and tell them if you haven't put the recycle bin out in a while. Re:how come (1) mspohr (589790) | more than 3 years ago | (#33333588) (1) mr_mischief (456295) | more than 3 years ago | (#33333982) So put out a soda can in your recycling can every week. Seriously, I recycle for three reasons. I like my city selling the stuff and almost breaking even on picking it up. It really does seem to be better for the environment. Our recycling pickup is free, while we pay $0.50 per bag for trash pickup, so we have a small individual economic incentive. Re:how come (3, Informative) LingNoi (1066278) | more than 3 years ago | (#33333606) Re:how come (0, Offtopic) Fizzl (209397) | more than 3 years ago | (#33333614) And now we have descended from at least reading the blurp to merely having a glimpse at the title before posting most obvious useless post one can imagine. The topics should be color coded by section, so I could only scan for red/blue for politics and shoot off a "GW was a wanker, Obama is teh shit" for instant +5 win. PS. Chrome spell checker doesn't recognize the word 'wanker', curious... Re:how come (3, Insightful) pspahn (1175617) | more than 3 years ago | (#33333754) Re:how come (4, Insightful) brusk (135896) | more than 3 years ago | (#33334046) The only smart trashcan (4, Funny) healyp (1260440) | more than 3 years ago | (#33333510) Bull. Fucking. Shit. (1, Insightful) cosm (1072588) | more than 3 years ago | (#33333520) Re:Bull. Fucking. Shit. (1) LingNoi (1066278) | more than 3 years ago | (#33333630) I think they've got bigger problems then this TBH.. Fined for keeping the trash can by the side of the road too long. Fined for putting it out too early and the best part. They have TARGETS for issuing fines. Re:Bull. Fucking. Shit. (0) Anonymous Coward | more than 3 years ago | (#33333764) in addition, it's not like Cleveland doesn't have more pressing issues to deal with. I'm from the opposite end of the state, and as crappy as Cincinnati is, Cleveland makes us look like the Taj Mahal! Crime, blight, and high unemployment even by today's standards. How are those police layoffs working out up there? How much are you paying the so-called "trash inspectors" to go through your garbage? Yes, lay off the cops, hire trash inspectors. Re:Bull. Fucking. Shit. (5, Interesting) JackDW (904211) | more than 3 years ago | (#33333786). (1) blincoln (592401) | more than 3 years ago | (#33333974) Is it possible to pay more and be allocated more than one bin to use? If not, how are residents who generate a higher-than-average amount of garbage supposed to ever get all of it taken away? I grew up in a rural area, with a publicly-accessible landfill. Right now I live in a city, and the closest publicly-accessible waste transfer station is about ten miles away. I'm not sure how the city expects anyone to drop off their waste if it's more than can fit in the bins, especially with their pipe-dream "urban village" (AKA "we'll make it as difficult as possible to drive anywhere, enjoy taking 300% longer to get to your destination because we'll also refuse to provide useful public transportation") mentality. Re:Bull. Fucking. Shit. (1) TheRaven64 (641858) | more than 3 years ago | (#33333976) Re:Bull. Fucking. Shit. (1) nschubach (922175) | more than 3 years ago | (#33333818) I think we are going to have to change it from "Orwellian" to "Owensian." Re:Bull. Fucking. Shit. (1) pspahn (1175617) | more than 3 years ago | (#33333852) Re:Bull. Fucking. Shit. (5, Insightful) mrnobo1024 (464702) | more than 3 years ago | (#33333668) Oh, get over your entitlement mentality already. You use the waste disposal service, you play by their rules. Don't like it? Buy your own damn landfill. It's not your God-given right to fill ours' up with recyclables. Re:Bull. Fucking. Shit. (3, Insightful) myth24601 (893486) | more than 3 years ago | (#33333694). (0) Anonymous Coward | more than 3 years ago | (#33333904) When you live in the city, you have no choice. Why not? The companies that will collect it out on the county won't come into town, no matter how much you pay them, or is it illegal for them to do that? The dumps that you can go to out in the country refuse to accept trash from people they recognise as townies? Or do you just mean that people in towns will tend not to take certain choices based on the time or costs involved? Re:Bull. Fucking. Shit. (0) Anonymous Coward | more than 3 years ago | (#33333812) It's all about money. The collection companies or local municipalities that do it are not interested in saving valuable resources, or concerned about filling landfill sites, or loading incinerators. It's about the material in the collection bins that they can sell. Being a collection point gives them a huge amount of aluminum, glass, paper, various plastics and cardboard as massive near free bonus for standard practices. There are buyers for each of these, the collectors are only looking to take your recyclables and selling them on. All this "green" effort is pure baloney. When a market sector dives, as paper did, the "collection" outfits decides they no longer was that material, or if they're hiding the fact, they dump it into the real trash at the depots. Don't Recycle; Consume Less (-1, Flamebait) Anonymous Coward | more than 3 years ago | (#33333526) RFID is currently used to identify the owners of waste bins and therefore allows weight quotas and mandatory recycling to be enforced. However, RFID on all clothes, food and luxury items is imminent. Therefore the current RFID monitoring infrastructure could very soon be used to enforce healthy eating, tax collection and a myriad of miscellaneous purposes yet to be devised. Like many technological measures, it rides roughshod over the presumption of innocence before proven guilty by logging everything upfront. Unlike barcodes, RFID identifies individual items uniquely. Therefore, it becomes possible to identify that, for example, a piece of underwear in today's refuse was the same piece of underwear worn five months ago at a civil protest. Even the initial use of using RFID to enforce mandatory recycling is misguided. I recycle but consuming less is far more effective. When recycling schemes are introduced, materials are scarce and valuable. However, an efficient recycling scheme can only lower the value of materials. When the price becomes too low, it is not economic to sort the material. The solution is to export the material to less developed economies with less regulation. In the worst case, illiterate 10 year old girls lead short and stunted lives after sifting medical waste and getting repeated exposure to fatal diseases. Therefore, efficient recycling schemes trap families in a cycle of poverty. Domestic incineration plants don't help. They serve to magnify the capacity of landfill and therefore they lower the disposal cost of unnecessary products. This encourages rampant consumerism. Incineration plants provide unrewarding labor and therefore they depress wages. The energy recovered is also quite low compared to the pollution produced. So, incineration plants to recover energy from waste are counter-productive. If you want to make world a better place, consume less. Enviroment or revenue generation? (5, Insightful) KDN (3283) | more than 3 years ago | (#33333546). (2, Informative) cduffy (652) | more than 3 years ago | (#33333576) Not revenue from the fine -- revenue from selling the recyclables. Re:Enviroment or revenue generation? (4, Interesting) rm999 (775449) | more than 3 years ago | (#33333662):Enviroment or revenue generation? (1) coinreturn (617535) | more than 3 years ago | (#33333900) Until the USPS stops delivering trash to my house, I most certainly would not be a fan. Also, the occurrences of people dumping trash on the side of the road would skyrocket. I saw a TV on the side of a rural road the other day. WTF? Take it to Best Buy or the county recycling event, asshat. Re:Enviroment or revenue generation? (1) guruevi (827432) | more than 3 years ago | (#33333670) You could always incinerate your own trash. Or not buy recyclable goods. Re:Enviroment or revenue generation? (1) FSWKU (551325) | more than 3 years ago | (#33333746) Re:Enviroment or revenue generation? (-1, Troll) commodore64_love (1445365) | more than 3 years ago | (#33333728) Here's your tax payment..... (censored) I was going to put something else here, but somewhere along the line people forgot the lesson of Eastern Europe. (Change comes from revolution.) So instead I censored myself before the mods could do it. Re:Enviroment or revenue generation? (0) Anonymous Coward | more than 3 years ago | (#33334036). We're headed down the same road as England only without all the social services. If I lived in Cleveland... (1, Funny) Anonymous Coward | more than 3 years ago | (#33333548) I'd mix in non-recyclable trash in my recycle bin just to spite this new program. Re:If I lived in Cleveland... (1, Flamebait) mrnobo1024 (464702) | more than 3 years ago | (#33333598) Yeah! Stick it to that evil minimum-wage worker hired to sort through the recycles, who has no influence on the laws or on this program whatsoever. That'll show 'em! Re:If I lived in Cleveland... (-1, Troll) Anonymous Coward | more than 3 years ago | (#33333644) The idea is not so much to punish the city, but rather to disobey or disregard what the city wants. If a minimum wage worker is harmed in the process, it's acceptable collateral damage. Ex: I regularly dump my spent motor oil in the local drainage ditch to spite the wacko environmentalists. Do any of them get directly harmed? No, the wildlife living in the ditch does. Again, just collateral damage. My ultimate objective is the satisfaction of knowing I disregarded some idiot's wishes. Re:If I lived in Cleveland... (1, Insightful) Anonymous Coward | more than 3 years ago | (#33333720) It's not collateral damage when you never actually hit your target at all. The city leaders will never know about your brave, courageous acts of civil disobedience. You're nothing but a douchebag with delusions of grandeur. Re:If I lived in Cleveland... (0) Anonymous Coward | more than 3 years ago | (#33333784) The point is not to get the attention of city leaders, or anyone else for that matter. The idea behind programs such as this one involve (1) revenue generation and (2) behavior modification. I refuse to modify my behavior based on the wishes of some politician or environmentalist lobby. They don't have to know that I didn't change my behavior -- it's good enough for me to know I didn't change it. Re:If I lived in Cleveland... (1) MightyMartian (840721) | more than 3 years ago | (#33333898) Well, I know where I'm dumping my motor oil from now on. Re:If I lived in Cleveland... (0) Anonymous Coward | more than 3 years ago | (#33333946) Your the biggest douche bag ive seen on slashdot all week. YAY. Did you know the auto part stores usually accept used oil.. Does harming the wildlife really do you any good? Your kids, and their kids will end up paying for your smug sense of self satisfaction you fuck tard. Big problem with this idea (2, Insightful) parallel_prankster (1455313) | more than 3 years ago | (#33333584) Re:Big problem with this idea (1) blincoln (592401) | more than 3 years ago | (#33334008) I have to throw trash down the chute into a central container for my entire apt complex and I know a lot of places here have that mechanism. How are they going to figure out then whose trash is it? Here in Seattle, the city uses collective punishment. If an apartment complex's waste bins are found in violation of the recyclable materials limits, the owner of the building is fined, and passes it on to all the tenants in the form of increased rent costs. lol engadget (1) capo_dei_capi (1794030) | more than 3 years ago | (#33333590) Whose recycling is it, anyway? (4, Insightful) Velox_SwiftFox (57902) | more than 3 years ago | (#33333608)? (4, Informative) Rene S. Hollan (1943) | more than 3 years ago | (#33333682) Well, in other news, it is illegal to collect your own rainwater in Washington state. You MUST pay for city water. Dunno about digging a well. It all has to do with "disrupting" the watershed." Re:Whose recycling is it, anyway? (1) eggman9713 (714915) | more than 3 years ago | (#33333716) Re:Whose recycling is it, anyway? (1) blixel (158224) | more than 3 years ago | (#33333940) You asked the grandparent to give you a citation ... out of curiosity I did a google search and found some interesting information. Apparently there is truth to what he was talking about. news video on youtube [youtube.com] google search [google.com] google search [google.com] Re:Whose recycling is it, anyway? (1) grahamd0 (1129971) | more than 3 years ago | (#33333810) You are not forced to buy city water in Washington. When I lived there I had a well, as did most people I knew. I'm sure there are many people in Washington who live who far outside the service area of any city or town's water supply. Perhaps it's a city law you're thinking of and not a state law? Re:Whose recycling is it, anyway? (1) dhovis (303725) | more than 3 years ago | (#33333950) Re:Whose recycling is it, anyway? (0, Flamebait) canajin56 (660655) | more than 3 years ago | (#33333704) Re:Whose recycling is it, anyway? (1) kramerd (1227006) | more than 3 years ago | (#33333906) Depending on your state, you may already be paying a deposit on cans/bottles. In a very accurate way, you pay a fine in advance and get refunded when you recycle. Ridding empty (1, Insightful) Anonymous Coward | more than 3 years ago | (#33333658). Silly (5, Informative) cdrguru (88047) | more than 3 years ago | (#33333718) (1) gbjbaanb (229885) | more than 3 years ago | (#33333954) so: step 1. tax coated paper, coloured neck rings and so forth. Also is it all really worthless, I mean, once you mix coloured and clear plastic together, melt it all down you can at least turn it into the black plastic containers a lot of food comes in. I'm more concerned about recycling different types of plastic - getting those dumped together is muc more of a problem. Anyhow, the way they recycle at the moment (swaw this on a kids TV prog once), is they take the magnetic metal out, then they crush everything else into little tiny pieces and send it up a shaking conveyor belt. The heavier glass stays on the belt, the lighter aluminium gets shaken off. I don't think they considered plastic and metal back then. Re:Silly (1) Renraku (518261) | more than 3 years ago | (#33334016) The reason most people don't recycle is because it's a massive pain in the ass to separate out 6 different kinds of materials when a single plastic ring can ruin the entire batch. It's like a good hour of work every time you go to take the recycling off. Perhaps rather than bitching at the consumers to do this work, they should refine their process and make to where they can process the stuff and still get a decent usable product regardless of the plastic rings? Is it so difficult to automate trash sorting? (1) Powercntrl (458442) | more than 3 years ago | (#33333722) Maybe what we need is something like the X Prize for a reliable way of automatically sorting trash. It seems there's some decent profit in recyclables, so why does sorting through trash still require manual labor? Government is responding to the American people... (2, Interesting) ibsteve2u (1184603) | more than 3 years ago | (#33333730). Why would you _not_ recycle as much as possible? (5, Interesting) warren.oates (925589) | more than 3 years ago | (#33333756) Sometime in the near future... (0, Troll) stimpleton (732392) | more than 3 years ago | (#33333766) August 2011: Trash inspectors become dedicated teams trained in the special volatility of domestic incidents, and liaise the results of the inspection results. October 2011: First worker injury as argument erupts over the fact the little recycle triangle with the 6 in the middle is not on the list of recyclables. January 2012: Police depts are assigned dedicated SRRU teams (Special Refuse Response Unit). August 2012: Controversy, when a neighbor films a family dragged onto the lawn, and sat on their knees with bags on their heads. The 15 yo son gets lippy, and is strangled by an SRRU officer with 6 pack plastic rings "to show the boy the importance" of recycling. Jan 2013: The RRA(Refuse Recycling Act) is introduced and falls under the Dept Homeland Security. Mar 2013: First "Re-education Camp" built. SRRU get new uniforms. The shirts are a trendy brown [wikipedia.org] color. Easily solved (2, Funny) Anonymous Coward | more than 3 years ago | (#33333816) If some city inspector sees that and is still willing to dive in to get the goods on you, I'd say that's a $100 fine well earned. . I welcome our new mechanic overlords (1) fey000 (1374173) | more than 3 years ago | (#33333876) Deposit Scheme (5, Interesting) nbahi15 (163501) | more than 3 years ago | (#33333890). Remember getting $$$ for aluminum cans? (3, Interesting) synaptik (125) | more than 3 years ago | (#33333914) (3, Insightful) supernova87a (532540) | more than 3 years ago | (#33333918) Every kind of recycling incentive program we have is a bandaid to what is really needed -- the prices of things that reflect their true cost to society. If i lived in Cleveland . . (0) Anonymous Coward | more than 3 years ago | (#33333960) First thing I would do with that 'high tech' trash cash is to drill out the RFID tag in it and continue to recycle as normal. Sounds more like a way to create more public sector jobs with titles like 'Manager of Eco-Enforcement' and 'Director of Holistic Environmental Practices'. All to check on garbage. Screw it (1) Zixaphir (845917) | more than 3 years ago | (#33334010) The whole recycling corundum (3, Interesting) Anonymous Coward | more than 3 years ago | (#33334020)... (2, Funny) Charles Dodgeson (248492) | more than 3 years ago | (#33334042)
http://beta.slashdot.org/story/140110
CC-MAIN-2014-15
refinedweb
4,883
70.02
As a long time lurker I finally decided this project was worthy of a write up (also I'm killing for an instructables tshirt). I love this site and hope you enjoy this project. IMPORTANT! Just a quick heads up, there are optional steps in this build. Your horn will be fully functional by step6 however I have included further options to monitor battery levels, change your Bluetooth device name and more! Also if anything isnt clear please let me know! I'll amend this write up with anything I may have missed. Step 1: Tools & Materials Will keep the links updated if any go offline. Components Required: - Arduino Pro Mini 3.3v 8mhz or 5v 16mhz (link) - UART TTL Programmer (link) - HC-05 Bluetooth Module (link) - Header Pins [about ~25 should do] (link) - Hookup Wire (enough to connect the pins on the breadboard) - Air Horn 134A (link) - 180 Degree Servo Motor (link) - Solder-able breadboard [cut to size] (link) 4 x AA Battery Clip [Not Pictured] (link) 4 x AA Batteries (Not Pictured) Optional Extras: Tools Required: - Soldering Iron + Solder - Hot Glue Gun - Flush Cutters - 3D printer (or 3d printing service online) Step 2: Flashing the Arduino First of all you'll want to flash your Arduino. If it didn't come with the header pins soldered you'll need to solder the 6 pins labeled: GND, GND, VCC, RXI, TXO, DTR (these will all be in a row on the bottom of your dev board) Once you have soldered the pins you'll need to connect them to your FTDI Programmer as follows: FTDI ----> Arduino DTR ----> DTR RXD ----> TXO TXD ----> RXI +5v ----> VCC GND ----> GND Now upload our test code (you can find the code here also): #include <Servo.h><br>#include <SoftwareSerial.h><br><br><p>Servo hornServo; // create servo object to control a servo<br>SoftwareSerial BT(10, 11); char a; // stores incoming character from other device int pos = 0; // variable to store the servo position</p><p>void setup() {<br> BT.begin(9600); BT.println("Air Horn Active"); hornServo.attach(9); // attaches the servo on pin 9 to the servo object hornServo.write(10); // sets the servo position</p><p>}</p><p>void loop() {<br> if (BT.available()) { a=(BT.read());</p><p> if (a=='1') { hornServo.write(90); // tell servo to go to position in variable 'pos' delay(15); BT.println(""); delay(350); hornServo.write(10); // tell servo to go to position in variable 'pos' delay(15); } if (a=='2') { hornServo.write(90); // tell servo to go to position in variable 'pos' delay(15); BT.println(""); delay(400); hornServo.write(10); // tell servo to go to position in variable 'pos' delay(15); } if (a=='3') { hornServo.write(90); // tell servo to go to position in variable 'pos' delay(15); BT.println(""); delay(500); hornServo.write(10); // tell servo to go to position in variable 'pos' delay(15); }</p><p> if (a=='4') { hornServo.write(90); // tell servo to go to position in variable 'pos' delay(15); BT.println(""); delay(600); hornServo.write(10); // tell servo to go to position in variable 'pos' delay(15); } if (a=='?') { BT.println("Send '1' for a sharp blast"); BT.println("Send '2' for a longer blast"); BT.println("Send '3' for a decent blast"); BT.println("Send '4' for a deafening blast"); } } }</p> Step 3: Assembling the Board (Placement and Power Soldering) This step will require a few connections and some patience however it is quite straight forward. NOTE: you can also perform this step on a regular breadboard without soldering however it will render your final product a little less portable. Placement: Components for this step: - Arduino - BT Module - 3 Male Header Pins - Wire We must place the flashed Arduino and the Bluetooth module (HC-05) on the breadboard in any orientation we see fit. Ensure that the breadboard you are using does not group and bridge rows of pins. On the PCB-Way breadboard I used, each pin was independent. Solder the following pins together: Wire Out --> Arduino --> BT Module --> Header Pin Red Wire --> VCC --> VCC --> Middle Pin Black Wire --> GND --> GND --> Bottom Pin Note: there are 2 GND pins on the Arduino, you can use either. The final image depicts where I have soldered a single black and red wire to the right of the Arduino for the power connection. Step 4: Assembling the Board (Signal Wiring and Testing) Signal Wiring: Now we must run 3 more wires. As per our code the signal to the Arduino is on pin 9 and our serial communication with the BT Module is on pins 10 and 11. Solder the following pins together: Arduino --> BT Module Pin 10 (D10) --> TXD (Green Wire) Pin 11 (D11) --> RXD (Yellow Wire) and for the signal to the servo we solder as follows: Arduino --> Header Pin Pin 9 (D9) --> Top Pin (White Wire) Finally you can Plug in your servo motor to the header pins. They generally have 3 pin female header coloured Brown, Red and Yellow. The Brown is Ground, Red is VCC and Yellow is Signal. Ensure the plug is on the header with the Yellow pin plugged into the top. Testing: You can now hookup your device to some power to confirm it is running! 5V .5A should be fine for this test, if you don't have a bench power supply you can continue through the steps and test after you have added the battery pack. To test simply power on your device until the BT Module blinks and then scan for 'HC-05' which is the default device ID. Pair with the password '1234' (sometimes '12345' depending on the manufacturer) and install a Bluetooth serial APP. I highly recommend 'Serial Bluetooth Terminal'. Click the hamburger menu in the top left and click on devices. Ensure that HC-05 is highlighted green and then click back to the terminal. Click the dual plug button next to the bin icon in the top right to begin the serial connection. You should be greeted the serial printing out 'Air Horn Active' on a successful connection. Send '?' to pull the menu or the numbers 1 through 4 and your Servo should begin to move. NOTE: If you are having issues Troubleshooting is on the last step! Also feel free to comment issues and I can provide assistance. Step 5: 3D Printing the Parts and Assembly Now for the easy part. I have included the STL files HERE however most 3D printers are different. - No model will require supports if they are oriented as per the final photo on a printer bed. - Your printer settings will be determined by your material used however it is suggested that you opt for a moderate fill method for your print. Weak fill will allow the brace to flex and not enough downward pressure will fail to actuate the horn. - (weak infill = flex = no horn = failed project) Assembly The base print easily snaps onto the bottom of your air horn canister, likewise the side PCB clip should snap to the side of the horn. The servo mount is also quite easy to snap on. For added stability I suggest cutting the circular horn mount and zip tying it to the horn as per the attached photos. This will limit its ability to slip particularly with how much force is required to actuate a full canister. it is recommended that you run some screws through the servo but it isnt required as the 3d print should fit the servo rather snug. I used 2 wood screws that were far too big to seat it in but you could also glue it the choice is yours! You can now attach the double sided servo arm with the provided screw. I ended up super gluing another servo arm from a smaller servo to act as a 'finger' however it was completely unnecessary as there was enough torque from the straight arm alone. Follow up by hot gluing the PCB you tested to the pcb mount (you can also screw this in but hotglue is always the easy way out) and clip it onto the horn. Then you can solder the battery clip to the leads you soldered to the board for power. NOTE: As per the data sheet the regulators on these boards run up to 16v input voltage so 4 fully charged AA batteries will be fine in this configuration. Finally you can wrap those wires in tape or heatshrink them so they dont short out and for added stability you can glue the battery clip to the feet of the bottom stand. The images in this step should cover this assembly. Ensure you have viewed them all. Step 6: GET TOOTING! Signaling a race? Planting it under your colleagues desk? Just really love horns? Well now the power is in your hands! (provided you are in BT range) You are now fully equipped to toot 'till your heart's content. Be responsible as these horns are seriously loud for their size also try not to sound it near animals and be respectful of your neighbors (or don't I'm not a cop). Step 7: Optional Extras + Troubleshooting! Optional Extras: Super Cap: If your device doesn't actuate the horn but presses against the button and restarts you may not have enough current. Firstly change your AA batteries to brand new ones but you may also add an inline capacitor to the build. I had a few laying around and placed them inline with the power lines as per the image attached. Voltage Meter + On/Off Switch: You can also insert a power switch to turn your project on and off by adding it inline with the main voltage line on the common port of the switch and the vcc of the circuit to the top pin. You can then use this circuit with the Volt Meter by adding the supply or red wire to the bottom pin of that switch. When it is turned off you will be able to read the voltage of the batteries. Put a momentary switch in series with the voltmeter to save power when it is turned off. Review images of my second board with this included. Changing BT Name and Password: Use Techbitar's instructable here! Troubleshooting: Will populate as issues arise! 14 Discussions Tip 26 days ago VIDEO PROOF? Reply 25 days ago Posting now :) Reply 16 days ago disappointing thooo. and problems i see. but i LOVE IT. well done now only a IR sensor or HR sensor and it`s wireless, and can be set everywhere. 24 days ago Amazing write-up. I hope you get some instructables merch for this! 26 days ago Brilliant! Now you know it needs to be connected IoT style for remote or IFTTT triggering... Just hooking it up to a video doorbell for Porch Pirates alone is so tempting (you could manually turn it on after getting a "delivered" notice, so it doesn't go off on the poor delivery guy) Thanks for this! Reply 25 days ago An esp32 would certainly be the way to go for this upgrade! I could create an IFTTT trigger maybe even link it to Opencv and a webcamera to run detections.... so many good project ideas. Reply 25 days ago mwa ha ha ha... Nice! I look forward to seeing your next iteration. :) 4 weeks ago Awesome. This would me an perfect April fools project. Reply 25 days ago Maybe with a laser tripwire or timer... Will update for April 1st. 26 days ago Looks great. How about a video of it in operation? Reply 25 days ago Please check my latest edit with the uploaded demonstration video :) 25 days ago on Step 7 Would it be possible to add multiple horns? I am really wanting something like this in various parts of my garden for.... reasons.... :D 26 days ago on Step 2 Good build you could put it in a box on your porch for the package thieves to enjoy! 27 days ago Very cool
https://www.instructables.com/id/Bluetooth-Air-Horn/
CC-MAIN-2019-04
refinedweb
2,013
71.75
LONDON (ICIS)--European bisphenol A (BPA) producers are bullish about their ability to push through price increases in freely-negotiated contracts for March, they confirmed Friday.?xml:namespace> With ongoing tightness in the BPA supply from Asia, BPA spot prices have increased each week throughout February, and most players expect rising price levels to be reflected when producers and buyers sign contracts for March. “The moment there’s anything like this we jump all over it,” explained one producer. “For March pricing we are going to be out there increasing again. There’s certainly an acceptance in the market that BPA prices are going up.”
http://www.icis.com/resources/news/2014/02/21/9756162/european-bpa-players-expect-march-contract-increases/
CC-MAIN-2015-35
refinedweb
105
59.84
Donald Knuth said that “premature optimization is the root of all evil.” But there comes a time, usually in mature projects with high loads, when there is an inevitable need to optimize. In this article, I would like to talk about five common methods to optimize your web project’s code. I will use Django, but the principles should be similar for other frameworks and languages. In this article, I will use these methods to reduce the response time of a query from 77 to 3.7 seconds. The example code is adapted from a real project that I have worked with and is demonstrative of performance optimization techniques. In case you would like to follow along and see the results yourself, you can grab the code at its initial state on GitHub and make the corresponding changes while following along the article. I’ll be using Python 2, since some third-party packages are not yet available for Python 3. Introducing Our Application Our web project simply tracks real estate offers per country. Therefore, there are only two models: # houses/models.py from utils.hash import Hasher class HashableModel(models.Model): """Provide a hash property for models.""" class Meta: abstract = True @property def hash(self): return Hasher.from_model(self) class Country(HashableModel): """Represent a country in which the house is positioned.""" name = models.CharField(max_length=30) def __unicode__(self): return self.name class House(HashableModel): """Represent a house with its characteristics.""" # Relations country = models.ForeignKey(Country, related_name='houses') # Attributes address = models.CharField(max_length=255) sq_meters = models.PositiveIntegerField() kitchen_sq_meters = models.PositiveSmallIntegerField() nr_bedrooms = models.PositiveSmallIntegerField() nr_bathrooms = models.PositiveSmallIntegerField() nr_floors = models.PositiveSmallIntegerField(default=1) year_built = models.PositiveIntegerField(null=True, blank=True) house_color_outside = models.CharField(max_length=20) distance_to_nearest_kindergarten = models.PositiveIntegerField(null=True, blank=True) distance_to_nearest_school = models.PositiveIntegerField(null=True, blank=True) distance_to_nearest_hospital = models.PositiveIntegerField(null=True, blank=True) has_cellar = models.BooleanField(default=False) has_pool = models.BooleanField(default=False) has_garage = models.BooleanField(default=False) price = models.PositiveIntegerField() def __unicode__(self): return '{} {}'.format(self.country, self.address) The abstract HashableModel provides any model that inherits from it a hash property that contains the instance’s primary key and the content type of the model. This hides sensitive data, like instance IDs, by substituting them with a hash. It may also be useful in cases when your project has multiple models and you need a centralized place that unhashes and decides what to do with different model instances of different classes. Note that for our small project, hashing is not really needed, as we can deal without it, but it will help demonstrate some optimization techniques, so I will keep it there. Here is the Hasher class: # utils/hash.py import basehash we would like to serve this data through an API endpoint, we install Django REST Framework and define the following serializers and view: # houses/serializers.py class HouseSerializer(serializers.ModelSerializer): """Serialize a `houses.House` instance.""" id = serializers.ReadOnlyField(source="hash") country = serializers.ReadOnlyField(source="country.hash") class Meta: model = House fields = ( 'id', 'address', 'country', 'sq_meters', 'price' ) # houses/views.py class HouseListAPIView(ListAPIView): model = House serializer_class = HouseSerial() serializer = self.serializer_class(queryset, many=True) return Response(serializer.data) Now, we populate our database with some data (a total of 100,000 house instances generated using factory-boy: 50,000 for one country, 40,000 for another, and 10,000 for a third country) and are ready to test the performance of our app. Performance Optimization Is All About Measuring There are several things we can measure in a project: - Execution time - Number of lines of code - Number of function calls - Allocated memory - Etc. But not all of them are relevant in measuring how good our project performs. Generally speaking, there are two main metrics that are the most important: how long something executes and how much memory it needs. In a web project, response time (the time required for the server to receive a request generated by some user’s action, process it and send back the result) is usually the most important metric, as it doesn’t let users get bored while waiting for a response and switch to another tab in their browser. In programming, analyzing project performance is called profiling. In order to profile the performance of our API endpoint, we will use the Silk package. After installing it and making our /api/v1/houses/?country=5T22RI call (the hash that corresponds to the country with 50,000 house entries), we get this: 200 GET /api/v1/houses/ 77292ms overall 15854ms on queries 50004 queries The overall response time is 77 seconds, out of which 16 seconds are spent on queries in the database, where there have been a total of 50,000 queries made. With such huge numbers, there is plenty room for improvement, so let’s start. 1. Optimizing Database Queries One of the most frequent tips on performance optimization is to make sure your database queries are optimized. This case is no exception. Moreover, we can do several things about our queries to optimize the response time. 1.1 Provide all data at once Taking a closer look at what those 50,000 queries are, you can see that these are all redundant queries to the houses_country table: 200 GET /api/v1/houses/ 77292ms overall 15854ms on queries 50004 queries The source of this problem is the fact that, in Django, query sets are lazy. This means that a query set is not evaluated and it does not hit the database until you actually need to get the data. At the same time, it gets only the data you told it to, making subsequent requests if any additional data is needed. That’s exactly what happened in our case. When getting the query set through House.objects.filter(country=country), Django gets a list of all houses in the given country. However, when serializing a house instance, HouseSerializer requires the country instance of the house for computing the serializer’s country field. As the country data isn’t present in the query set, django makes an additional request to get that data. And it does so for every house in the query set—that’s 50,000 times in all. The solution is very simple, though. In order to extract all required data for serialization, you can use the select_related() method on the query set. Thus, our get_queryset will look like: def get_queryset(self): country = get_object_or_404(Country, pk=self.country) queryset = self.model.objects.filter(country=country).select_related('country') return queryset Let’s see how this impacted the performance: 200 GET /api/v1/houses/ 35979ms overall 102ms on queries 4 queries The overall response time dropped to 36 seconds and the time spent in the database is ~100ms with only 4 queries! That’s great news, but we can do more. 1.2 Provide only the relevant data By default, Django extracts all fields from the database. However, when you have huge tables with many columns and rows, it makes sense to tell Django what specific fields to extract, so that it won’t spend time to get information that won’t be used at all. In our case, we need only five fields for serialization, but we have 17 fields. It makes sense to specify exactly what fields to extract from the database, so that we further cut down the response time. Django has the defer() and the only() query set methods for doing exactly this. The first one specifies what fields not to load and the second one specifies what fields to load only. def get_queryset(self): country = get_object_or_404(Country, pk=self.country) queryset = self.model.objects.filter(country=country)\ .select_related('country')\ .only('id', 'address', 'country', 'sq_meters', 'price') return queryset This cut the time spent on queries in half, which is good, but 50ms is not that much. The overall time also slightly dropped, but there is more space to cut it. 200 GET /api/v1/houses/ 33111ms overall 52ms on queries 4 queries 2. Optimizing Your Code You can’t infinitely optimize the database queries, and our last result just showed that. Even if we hypothetically decrease the time spent on queries to 0, we would still face the reality of waiting for half a minute to get the response. It’s time to switch to another level of optimization: business logic. 2.1 Simplify your code Sometimes, third-party packages come with a lot of overhead for simple tasks. One such example is our task to return serialized house instances. Django REST Framework is great, with lots of useful features out of the box. However, our main goal right now is to cut down the response time, so it is a great candidate for optimization, especially that the serialized objects are quite simple. Let’s write a custom serializer for this purpose. To keep it simple, we will have a single static method that does the job. In reality, you might want to have the same class and method signatures to be able to use serializers interchangeably: # houses/serializers.py class HousePlainSerializer(object): """ Serializes a House queryset consisting of dicts with the following keys: 'id', 'address', 'country', 'sq_meters', 'price'. """ @staticmethod def serialize_data(queryset): """ Return a list of hashed objects from the given queryset. """ return [ { 'id': Hasher.from_pk_and_class(entry['id'], House), 'address': entry['address'], 'country': Hasher.from_pk_and_class(entry['country'], Country), 'sq_meters': entry['sq_meters'], 'price': entry['price'] } for entry in queryset ] # houses/views.py class HouseListAPIView(ListAPIView): model = House serializer_class = HouseSerializer plain_serializer_class = HousePlainSerializer # <-- added custom serial() data = self.plain_serializer_class.serialize_data(queryset) # <-- serialize return Response(data) 200 GET /api/v1/houses/ 17312ms overall 38ms on queries 4 queries This looks better now. The response time was almost halved due to the fact that we didn’t employ DRF serializers code. Another measurable result—the number of total function calls made during the request/response cycle—dropped from 15,859,427 calls (from the request made in section 1.2 above) to 9,257,469 calls. This means that around 1/3 of all function calls were made by Django REST Framework. 2.2 Update/substitute third-party packages The optimization techniques described above are the most common, the ones you can do without thorough analysis and thought. However, 17 seconds still feels pretty long; in order to reduce this number, we will need to dive deeper into our code and analyze what happens under the hood. In other words, we will need to profile our code. You can do the profiling yourself, using the built-in Python profiler, or you can use some third party packages for it (that are using the built-in Python profiler). As we already use silk, it can profile the code and generate a binary profile file, that we can further visualize. There are several visualization packages that transform a binary profile into some insightful visualizations. I will be using the snakeviz package. Here is the visualization of the binary profile of the last request from above, hooked at the view’s dispatch method: From top to bottom is the call stack, displaying the file name, method/function name with its line number and the corresponding cumulative time spent in that method. Now it is easier to see that a lion’s share of time is dedicated to computing the hash (the __init__.py and primes.py rectangles of violet color). Currently, this is the main performance bottleneck in our code, but at the same time it is not really our code—it’s a third-party package. In such situations, there are a limited number of things we can do: - Check for a new version of the package (that hopefully has a better performance). - Find another package that performs better on tasks we need. - Write our own implementation that will beat the performance of the package we currently use. Luckily for me, there is a newer version of the basehash package that is responsible for hashing. The code uses v.2.1.0, but there is a v.3.0.4. Such situations, when you are able to update to a newer version of a package, are more probable when you are working on an existing project. When checking release notes for v.3, there is this specific sentence that sounds very promising: A massive overhaul was done with the primality algorithms. Including (sic) support for gmpy2 if it available (sic) on the system for that much more of an increase. Let’s find this out! pip install -U basehash gmpy2 200 GET /api/v1/houses/ 7738ms overall 59ms on queries 4 queries We cut down the response time from 17 to under 8 seconds. Great result, but there is one more thing we should look at. 2.3 Refactor your own code So far, we have improved our queries, substituted third-party complex and generic code with our own very specific functions, and updated third-party packages, but we left our existing code untouched. But sometimes a small refactoring of existing code can bring impressive results. But for this we need again to analyze the profiling results. Taking a closer look, you can see that hashing is still a problem (not surprisingly, it is the only thing we do with our data), although we did improve in that direction. However, the greenish rectangle that says that __init__.py consumes 2.14 seconds bothers me, along with the grayish __init__.py:54(hash) that goes right after it. This means that some initialization takes a long time. Let’s take a look at the source code of the basehash package. # basehash/__init__.py # Initialization of `base36` class initializes the parent, `base` class. class base36(base): def __init__(self, length=HASH_LENGTH, generator=GENERATOR): super(base36, self).__init__(BASE36, length, generator) class base(object): def __init__(self, alphabet, length=HASH_LENGTH, generator=GENERATOR): if len(set(alphabet)) != len(alphabet): raise ValueError('Supplied alphabet cannot contain duplicates.') self.alphabet = tuple(alphabet) self.base = len(alphabet) self.length = length self.generator = generator self.maximum = self.base ** self.length - 1 self.prime = next_prime(int((self.maximum + 1) * self.generator)) # `next_prime` call on each initialized instance As you can see, the initialization of a base instance requires a call of the next_prime function; that is quite heavy as we can see in the bottom left rectangles of the visualization above. Let’s take a look at my Hash class again:() # <-- initializing on each method call() # <-- initializing on each method call you can see, I have labeled two methods that are initializing a base36 instance on each method call, which is not really required. As hashing is a deterministic procedure, meaning that for a given input value it must always generate the same hash value, we can make it a class attribute without fearing that it will break something. Let’s check out how it will perform: class Hasher(object): base36 = basehash.base36() # <-- initialize hasher only once @classmethod def from_model(cls, obj, klass=None): if obj.pk is None: return None return cls.make_hash(obj.pk, klass if klass is not None else obj) @classmethod def make_hash(cls, object_pk, klass): content_type = ContentType.objects.get_for_model(klass, for_concrete_model=False) return cls.base36.hash('%(contenttype_pk)03d%(object_pk)06d' % { 'contenttype_pk': content_type.pk, 'object_pk': object_pk }) @classmethod def parse_hash(cls, obj_hash): unhashed = '%09d' % cls.base36.unhash(obj_hash) contenttype_pk = int(unhashed[:-6]) object_pk = int(unhashed[-6:]) return contenttype_pk, object_pk @classmethod def to_object_pk(cls, obj_hash): return cls.parse_hash(obj_hash)[1] 200 GET /api/v1/houses/ 3766ms overall 38ms on queries 4 queries The final result is under four seconds, which is much smaller than what we started with. Further optimization of response time can be achieved using caching, but I won’t tackle it in this article. Conclusion Performance optimization is a process of analysis and discovery. There are no hard rules that apply to all cases, as each project has its own flow and bottlenecks. However, the first thing you should do is profile your code. And if in such a short example I could reduce the response time from 77 seconds to 3.7 seconds, huge projects have even more optimization potential.
https://www.toptal.com/python/performance-optimization-testing-django
CC-MAIN-2022-40
refinedweb
2,675
57.16
Eclipse Community Forums - RDF feed Eclipse Community Forums how to create tables using persistence.xml (glassfish, oracle xe) <![CDATA[Originally posted by: mateusz.blaz.e-surf.pl Hi! I'm quite new to Eclipse in JEE applications, but I've been using Netbeans for some time. My problem is that I can't make Eclipse create tables depending on my entities. I would like to have creating database schema automated as it was in Netbeans. It seems to me, that it's possible in Eclipse with Dali too. I'm using Oracle 10g XE and the newest Eclipse Europe. My application server is Glassfish v2. I have created and tested connection pool and JDBS resource in glassfish. There is one enabled on JNDI adress: "TEST". In Elipse I have defined the connetion. I have tested it using ping. In Data Source Explorer I can view database elements. I am using JPA implementation provided by server and the generic platform. I have created such a persistence.xml file: <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="" xmlns: <persistence-unit <jta-data-source>TEST</jta-data-source> <class>test.ejb.JPATest</class> <properties> <property name="toplink.ddl-generation" value="create-tables"/> <property name="toplink.logging.level" value="ALL"/> </properties> </persistence-unit> </persistence> My test.ejb.JPATest java class looks like this: import javax.persistence.Entity; import javax.persistence.Id; @Entity public class JPATest { @Id Long id; } In the problems box i can see errors: table JPATest doesn't exist collumn Id doesn't exist I have tried running my module on server, publishing it, restarting the server in order to create this table on my database, but it didn't work.. There are no exceptions in Glassfish logs, I couldn't find any error in Eclipse log either. It seems just like properties in persistence.xml were ignored. I cannot use Generate DDL as I'm using generic platform. Can you help me please and give any suggestions, what am I doing wrong? Is there any way I have to force interpreting the persistence.xml configuration during deploy? Thanks a lot for any help! Sorry for my english. Best wishes Mateusz B]]> 2008-03-07T12:18:01-00:00
http://www.eclipse.org/forums/feed.php?mode=m&th=191443&basic=1
CC-MAIN-2016-22
refinedweb
371
53.37
> > So... is this settled now?> > > > If so, could you (Tim) please send out a fresh, changelogged version of the> > patch for review?> > > > Thanks.> > I still want to do some basic testing, (boot with different values of HZ /> USER_HZ, check that I didn't spoil the OOM killer), and we might have some> arguments about the helper functions, but it might already go into -mm as> it is:I rediffed it for 2.6.9-rc1-mm1 and did some more testing(HZ/USER_HZ = 1000/100, 1024/1024, 60/60, verified the oom killer still selects the right task).Crosschecking an unpatched kernel I once got a whooping 15 minutes error in process start times, again emphasizing that something needs to be done about this. Of course no such error occured with the patch.All tests went ok, but wondering about the difference between /proc/stat and /proc/uptimes it strikes me that with this patch userland now might detect wrong HZ values. Sigh.So I think we should not apply the patch, but rather back out the patch that rebased uptime on a ntp-corrected timesource.There are too many statistics that are still based on jiffies or clock ticks, and we cannot immediately change that without a large rework(although this might eventually happen according to John's proposal).And mixing two different timesources just won't work, regardles where we draw the borderline between them.George, please excuse my lack of understanding. What again where theprecise reasons to have an ntp-corrected uptime?TimJust for reference, the current patch against 2.6.9-rc1-mm1:Derive process start times from the posix_clock_monotonic notion of uptime instead of "jiffies", consistent with the earlier change to /proc/uptime itself.()Process start times are reported to userspace in units of 1/USER_HZ sinceboot, thus applications as procps need the value of "uptime" to convertthem into absolute time.Currently "uptime" is derived from an ntp-corrected time base, but processstart time is derived from the free-running "jiffies" counter.This results in inaccurate, drifting process start times as seen by theuser, even if the exported number stays constant, because the users notionof "jiffies" changes in time.It's John Stultz's patch anyways, which I only messed up a bit, but sincepeople started trading signed-off lines on lkml:Signed-off-by: Tim Schmielau <tim@physik3.uni-rostock.de>--- linux-2.6.9-rc1-mm1/fs/proc/array.c 2004-08-30 21:51:05.000000000 +0200+++ linux-2.6.9-rc1-mm1-uf/fs/proc/array.c 2004-08-30 21:51:36.000000000 +0200@@ -359,7 +359,11 @@ int proc_pid_stat(struct task_struct *ta read_unlock(&tasklist_lock); /* Temporary variable needed for gcc-2.96 */- start_time = jiffies_64_to_clock_t(task->start_time - INITIAL_JIFFIES);+ /* convert timespec -> nsec*/+ start_time = (unsigned long long)task->start_time.tv_sec * NSEC_PER_SEC + + task->start_time.tv_nsec;+ /* convert nsec -> ticks */+ start_time = nsec_to_clock_t(start_time); res = sprintf(buffer,"%d (%s) %c %d %d %d %d %d %lu %lu \ %lu %lu %lu %lu %lu %ld %ld %ld %ld %d %ld %llu %lu %ld %lu %lu %lu %lu %lu \--- linux-2.6.9-rc1-mm1/include/linux/acct.h 2004-08-17 21:38:55.000000000 +0200+++ linux-2.6.9-rc1-mm1-uf/include/linux/acct.h 2004-08-30 21:51:36.000000000 +0200@@ -172,17 +172,24 @@ static inline u32 jiffies_to_AHZ(unsigne #endif } -static inline u64 jiffies_64_to_AHZ(u64 x)+static inline u64 nsec_to_AHZ(u64 x) {-#if (TICK_NSEC % (NSEC_PER_SEC / AHZ)) == 0-#if HZ != AHZ- do_div(x, HZ / AHZ);-#endif-#else- x *= TICK_NSEC;+#if (NSEC_PER_SEC % AHZ) == 0 do_div(x, (NSEC_PER_SEC / AHZ));+#elif (AHZ % 512) == 0+ x *= AHZ/512;+ do_div(x, (NSEC_PER_SEC / 512));+#else+ /* + * max relative error 5.7e-8 (1.8s per year) for AHZ <= 1024,+ * overflow after 64.99 years.+ * exact for AHZ=60, 72, 90, 120, 144, 180, 300, 600, 900, ...+ */+ x *= 9;+ do_div(x, (unsigned long)((9ull * NSEC_PER_SEC + (AHZ/2))+ / AHZ)); #endif- return x;+ return x; } #endif /* __KERNEL */--- linux-2.6.9-rc1-mm1/include/linux/sched.h 2004-08-30 21:51:06.000000000 +0200+++ linux-2.6.9-rc1-mm1-uf/include/linux/sched.h 2004-08-30 21:52:34.000000000 +0200@@ -515,7 +515,7 @@ struct task_struct { struct timer_list real_timer; unsigned long utime, stime; unsigned long nvcsw, nivcsw; /* context switch counts */- u64 start_time;+ struct timespec start_time; /* mm fault and swap info: this can arguably be seen as either mm-specific or thread-specific */ unsigned long min_flt, maj_flt; /* process credentials */--- linux-2.6.9-rc1-mm1/include/linux/times.h 2004-08-17 00:13:35.000000000 +0200+++ linux-2.6.9-rc1-mm1-uf/include/linux/times.h 2004-08-30 21:51:36.000000000 +0200@@ -55,6 +55,26 @@ static inline u64 jiffies_64_to_clock_t( } #endif +static inline u64 nsec_to_clock_t(u64 x)+{+#if (NSEC_PER_SEC % USER_HZ) == 0+ do_div(x, (NSEC_PER_SEC / USER_HZ));+#elif (USER_HZ % 512) == 0+ x *= USER_HZ/512;+ do_div(x, (NSEC_PER_SEC / 512));+#else+ /* + * max relative error 5.7e-8 (1.8s per year) for USER_HZ <= 1024,+ * overflow after 64.99 years.+ * exact for HZ=60, 72, 90, 120, 144, 180, 300, 600, 900, ...+ */+ x *= 9;+ do_div(x, (unsigned long)((9ull * NSEC_PER_SEC + (USER_HZ/2))+ / USER_HZ));+#endif+ return x;+}+ struct tms { clock_t tms_utime; clock_t tms_stime;--- linux-2.6.9-rc1-mm1/kernel/acct.c 2004-08-17 21:38:55.000000000 +0200+++ linux-2.6.9-rc1-mm1-uf/kernel/acct.c 2004-08-30 21:51:36.000000000 +0200@@ -384,6 +384,8 @@ static void do_acct_process(long exitcod unsigned long vsize; unsigned long flim; u64 elapsed;+ u64 run_time;+ struct timespec uptime; /* * First check to see if there is enough free_space to continue@@ -401,7 +403,13 @@ static void do_acct_process(long exitcod ac.ac_version = ACCT_VERSION | ACCT_BYTEORDER; strlcpy(ac.ac_comm, current->comm, sizeof(ac.ac_comm)); - elapsed = jiffies_64_to_AHZ(get_jiffies_64() - current->start_time);+ /* calculate run_time in nsec*/+ do_posix_clock_monotonic_gettime(&uptime);+ run_time = (u64)uptime.tv_sec*NSEC_PER_SEC + uptime.tv_nsec; + run_time -= (u64)current->start_time.tv_sec*NSEC_PER_SEC + + current->start_time.tv_nsec;+ /* convert nsec -> AHZ */+ elapsed = nsec_to_AHZ(run_time); #if ACCT_VERSION==3 ac.ac_etime = encode_float(elapsed); #else--- linux-2.6.9-rc1-mm1/kernel/fork.c 2004-08-30 21:51:07.000000000 +0200+++ linux-2.6.9-rc1-mm1-uf/kernel/fork.c 2004-08-30 21:51:36.000000000 +0200@@ -996,7 +996,7 @@ static task_t *copy_process(unsigned lon p->utime = p->stime = 0; p->lock_depth = -1; /* -1 = no lock */- p->start_time = get_jiffies_64();+ do_posix_clock_monotonic_gettime(&p->start_time); p->security = NULL; p->io_context = NULL; p->io_wait = NULL;--- linux-2.6.9-rc1-mm1/mm/oom_kill.c 2004-08-30 21:51:07.000000000 +0200+++ linux-2.6.9-rc1-mm1-uf/mm/oom_kill.c 2004-08-30 21:51:36.000000000 +0200@@ -26,6 +26,7 @@ /** *@@ -41,7 +42,7 @@ * of least surprise ... (be careful when you change it) */ -static unsigned long badness(struct task_struct *p)+static unsigned long badness(struct task_struct *p, unsigned long uptime) { unsigned long points, cpu_time, run_time, s; @@ -56,12 +57,16 @@ static unsigned long badness(struct task points = p->mm->total_vm; /*- * CPU time is in seconds and run time is in minutes. There is no- * particular reason for this other than that it turned out to work- * very well in practice.+ * CPU time is in tens of seconds and run time is in thousands+ * of seconds. There is no particular reason for this other than+ * that it turned out to work very well in practice. */ cpu_time = (p->utime + p->stime) >> (SHIFT_HZ + 3);- run_time = (get_jiffies_64() - p->start_time) >> (SHIFT_HZ + 10);++ if (uptime >= p->start_time.tv_sec)+ run_time = (uptime - p->start_time.tv_sec) >> 10;+ else+ run_time = 0; s = int_sqrt(cpu_time); if (s)@@ -111,10 +116,12 @@ static struct task_struct * select_bad_p unsigned long maxpoints = 0; struct task_struct *g, *p; struct task_struct *chosen = NULL;+ struct timespec uptime; + do_posix_clock_monotonic_gettime(&uptime); do_each_thread(g, p) if (p->pid) {- unsigned long points = badness(p);+ unsigned long points = badness(p, uptime.tv_sec); if (points > maxpoints) { chosen = p; maxpoints = points;-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2004/8/30/260
CC-MAIN-2016-26
refinedweb
1,322
57.98
' :::=== ::: === === ::: :::==== :::===== ::: === ' ::: ::: === === ::: :::==== ::: ::: === ' ===== === === === === === === ======== ' === =========== === === === === === ' ====== ==== ==== === === ======= === === ' Switch Description An iOS switch control implemented in Swift with full Interface Builder support. To run the demo project: pod try RoundedSwitch Usage Either config the switch in the Interface Builder or programatically as follow: import Switch ... let mySwitch = Switch() mySwitch.leftText = "Windows" mySwitch.rightText = "Mac" mySwitch.rightSelected = true mySwitch.tintColor = UIColor.purple mySwitch.disabledColor = mySwitch.tintColor.withAlphaComponent(0.4) mySwitch.backColor = mySwitch.tintColor.withAlphaComponent(0.05) mySwitch.sizeToFit() mySwitch.addTarget(self, action: #selector(ViewController.switchDidChangeValue(_:)), for: .valueChanged) Please note that the module name is Switch. However, when installed with CocoaPods, it is RoundedSwitch. Please see the Reference Documentation for details. Installation Carthage Add the line below to your Cartfile: github "T-Pham/Switch" CocoaPods Add the line below to your Podfile: pod 'RoundedSwitch' Manually Add the file Switch.swift to your project. You are all set. Compatibility From version 2.0.0, Swift 3 syntax is used. If your project is still using Swift version 2, please use a UITextField-Navigation version prior to 2.0.0. Podfile pod 'RoundedSwitch', '~> 1.0.3' or Cartfile github "T-Pham/Switch" ~> 1.0.3 License Switch is available under the MIT license. See the LICENSE file for more info. Latest podspec { "name": "RoundedSwitch", "version": "2.0.2", "summary": "An iOS switch control implemented in Swift with full Interface Builder support.", "description": "RoundedSwitch is an iOS switch control implemented in Swift with full Interface Builder support.", "homepage": "", "screenshots": [ "", "" ], "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "Thanh Pham": "[email protected]" }, "source": { "git": "", "tag": "2.0.2" }, "platforms": { "ios": "8.0" }, "source_files": "Switch.swift", "frameworks": "UIKit" } Sun, 29 Jul 2018 15:00:04 +0000
https://tryexcept.com/articles/cocoapod/roundedswitch
CC-MAIN-2019-39
refinedweb
270
54.49
OwnTech Timer driver Zephyr Module is in charge of STM32 G4 Timers. [[TOC]] Driver capabilities The Timer driver module allows you to control a timer on the STM32 G4 board. Currently, only Timer 6 and 7 are supported. The following functions are provided by the Timer driver module: void timer_config(const struct device* dev, const struct timer_config_t* config) void timer_start(const struct device* dev, uint32_t t_usec) uint32_t timer_get_count(const struct device* dev) How to use Getting access to the driver To use the Timer driver module, you have to include "timer.h" in your source file: Zephyr uses device-tree macros to interact with drivers. The correct macro must be declared and used to obtain a pointer to the driver structure from Zephyr: #define TIMER6_LABEL DT_PROP(DT_NODELABEL(timers6), label) const struct device* timer6 = device_get_binding(TIMER6_LABEL); Using this pointer, the user is able to interact with the driver functions. The pointer must be provided as first argument of all driver-related functions. timer_config() The timer_config() function takes a parameter which is a configuration structure, defined as follows: This structure is used to configure the callback function called when the timer times out. timer_start() The timer_start() function is used to start the timer. It takes as a parameter the duration of the timer, in µs. The allowed values for duration is an integer within range [ 1 : 6553 ]. timer_get_count() Finally, the timer_get_count() function can be called to read the current value of the timer counter. Example #include "timer.h" #define TIMER6_LABEL DT_PROP(DT_NODELABEL(timers6), label) static const struct device* timer6 = NULL; static void user_defined_isr() { // Place your code here } void main(void) { timer6 = device_get_binding(TIMER6_LABEL); struct timer_config_t timer_cfg = { .timer_enable_irq = 1, .timer_callback = user_defined_isr }; timer_config(timer6, &timer_cfg); timer_start(timer6, 50); // user_defined_isr() will be called every 50 µs } Technical information This driver has a Zephyr-style implementation. It does use the standard DEVICE_DT_DEFINE() macro that allows it to be loaded automatically if the module is enabled and the device is activated in the device tree. It also provides a board-agnostic layer that would allow, if wanted, to write Timer drivers for other boards. The only difference with a Zephyr driver would be that it explicitly and individually checks for the presence and status of timers6 and timers7 nodes in the device tree instead of being fully generic and run as many drivers as there are compatible nodes. Enabling or disabling the module The module is loaded by default. The user explicitly has to set CONFIG_OWNTECH_TIMER_DRIVER=n in prj.conf to prevent the driver from loading. Do not disable the module if you're using the Quick Start library as it makes use to Timer 6.
https://www.owntech.org/en/timer-driver/
CC-MAIN-2021-49
refinedweb
439
52.19
On Sunday 25 September 2011, 00:27:54, Ovidiu Deac wrote: > Thanks a lot! It took me a while to understand what you meant but > eventually I got it. > > This is the final version and it looks much better: > > f :: MyMonad String > f = do > liftIO $ putStrLn "Please enter a file name: " > name ← liftIO getLine > hFile ← ErrorT $ (openFile name ReadMode ↠ return.Right) > `catch` λ_ → return.Left $ KnownErr "open failed" Note that action >>= return . function is liftM function action (and ought to be the same as `fmap function action' if the Monad has a Functor instance). It's mostly a matter of taste, but I prefer the fmap/liftM version (and fmap can be more efficient). > content ← liftIO $ hGetContents hFile > return content These two lines can be replaced by the shorter liftIO $ hGetContents hFile By desugaring and the Monad laws, do value <- action return value ~> (desugaring) action >>= \value -> return value === action >>= return === action (the first === is eta-reduction (\value -> return value) === return, the second is a Monad law - I don't remember the canonical numbering, but the Monad laws are return x >>= f === f x action >>= return === action (action >>= g) >>= h === action >>= (\x -> h x >>= g) ) > > Somehow I understand but I don't have the feeling yet why I apply > ErrorT to the whole catched expression instead of liftIO. Do you have > a nice explanation for it? Hm, not sure whether I can come up with something nice. Let's look at the types. newtype ErrorT e m a = ErrorT { runErrorT :: m (Either e a) } Thus, in your case, the value constructor ErrorT is a function with type ErrorT :: IO (Either MyType a) -> MyMonad a On the other hand, again specialised to your situation, liftIO :: IO a -> MyMonad a liftIO lifts any IO-action (which in general has no knowledge of MyType) to a MyMonad-action. That lifting consists of two steps, first the IO-action is transformed into an IO-action with return type (Either MyType a), then that is wrapped in ErrorT. In particular, liftIO action = ErrorT $ do { x <- action; return (Right x); } or, by the definition of liftM, liftIO action = ErrorT (liftM Right action) pointfree: liftIO = ErrorT . liftM Right -- [1] The first part of that, adding the (Either MyType), is done in the catch, so after the catch, only the second half of liftIO remains to be done, applying the value constructor ErrorT. [1] In particular, liftIO cannot produce any actions that fail in the (ErrorT e IO) monad, and IO-failures cannot be caught or handled there. To handle IO-failures in (ErrorT e IO), you need a construct as above, it could have the general form catchIO :: IO a -> (IOError -> e) -> ErrorT e IO a catchIO action trans = ErrorT $ liftM Right action `catch` (\err -> return (Left $ trans err)) or ErrorT $ liftM Right action `catch` (return . Left . trans) if you use Prelude.catch, with Control.Exception.catch, the type would be catchIO :: Exception ex => IO a -> (ex -> e) -> ErrorT a IO a with the same implementation. With that, the line above would become hFile <- openFile name ReadMode `catchIO` const (KnownErr "open failed") But that is rather limited, it would often be desirable to do some IO immediately upon encountering the error, and maybe one can even completely recover from the error, so a more useful type would be liftCatchIO :: Exception ex => IO a -> (ex -> IO (Either e a)) -> ErrorT e IO a liftCatchIO action handler = ErrorT $ liftM Right action `catch` handler and the above hFile <- liftCatchIO (openFile name ReadMode) (\_ -> return (Left $ KnownErr "open failed"))
http://www.haskell.org/pipermail/beginners/2011-September/008590.html
CC-MAIN-2014-15
refinedweb
587
52.53
jsp code for display of data from database and snap shot of the output jsp code for display of data from database and snap shot of the output i am using JSP.i want to insert data into database and also want to display... Jsp Code to store date in database - JSP-Servlet Jsp Code to store date in database Hi, Can u give me jsp code to store current date in to database. Thanks Prakash for insert the value from jsp to access database code for insert the value from jsp to access database code for insert the value from jsp to access database jsp jsp how to connect the database with jsp using mysql Hi Friend, Please visit the following links: jsp code jsp code hi i am Ruchi can anybody plz tell me the jsp code for searching fromwhole database. I am using Oracle10g Database. Please visit the following links: http JSP CODE JSP CODE what is the code for downloading images from database using JSP? Please visit the following link: code to establish jdbc database connectivity in jsp code to establish jdbc database connectivity in jsp Dear sir, i'm in need of code and procedure to establish jdbc connectivity in jsp java - JSP-Servlet example code for JSP and MySql Database Connectivity Need an example code for JSP and MySql Database Connectivity Hi here i am giving you a link that is having a example code for JSP and MySql Database Connectivity JSP code JSP code I get an error when i execute the following code : <... the following code its getting connected to database import java.sql.Connection... the following code its getting connected to database import java.sql.Connection; code - JSP-Servlet ; For the above code, we have created following database tables...jsp code hi my requirement is generate dynamic drop down lists... statement? pls provide code how to get first selected drop down list value jsp code - JSP-Servlet jsp code i want to add below code data in mysql database using jsp... using below code we got data in text box i want to add multiple data in database... Add/Remove dynamic rows in HTML table connec to database - JSP-Servlet connec to database Need code to connect the application to database. I have developed the application JSP and Servlet program - JSP-Servlet for more information. hi friends... i hv faced a problem of jsp code.my problem... to concated with a textbox that is selected from database. my database is postgresql.i jst Navigation in a database table through jsp . Create a database: Before run this jsp code first create a database named... Navigation in a database table through jsp This is detailed jsp code that shows how line chart from database in jsp line chart from database in jsp how can i create line chart from database in jsp code Regarding JSP code interfaces in JSP code I am using Oracle 10g database .Exactly problem with me is that i cant be able to write the code for navigate different users from same login page...Regarding JSP code hello sir tell me the way to navigate different jsp with database.. - Development process jsp with database.. Hello i need code for..... I have a car... Thanks For the above code, create database table named... of that brand should be retrieved from database.i have created a table in database jsp fix Update Database from jsp Update Database from jsp I want to update my oracle database... UPDATE button the database field should be updated . I have a drop down menu... should be updated. I have written the code but its not working . Please help me out code - JSP-Servlet code how can i connect SQl database in javascript. and how to execute the query also i think u can not connect to SQL database in javascript. thanks sandeep code - JSP-Servlet know how can i call database connection in javascript. please help me use some server side script like servlet or jsp, call these when user click..., u can not conncet to database in javascript code for JSP and Servlet - JSP-Servlet code for JSP and Servlet i have to create a jsp page that contains username and password, so how to code servlet according to it? Hi... ServletException("unable to get database cooenction."); }//catch }//init public edit values of database using jsp edit values of database using jsp hi i want a code to edit the row from tye database and display in a page which containd radio buttons and drop down boxes using jsp code> Jsp Code - Java Beginners Jsp Code Hi, I am new to java programming & as per the requirement, i need to implement a 'SEARCH' functionality which will search the database & should display a unique record. The design contains the 4 input boxes code for jsp - Ajax code for jsp please give code for using jsp page and Ajax.Retrive the data from database if we select a country display the states of particular country.By using jsp and Ajax. Hello Friend I send the code you   code - JSP-Servlet code how to retrieve database value in array Hi friend, Code to help in solving the problem : import java.sql.*; import... = null; String url = "jdbc:mysql://localhost:3306/"; String db = "database JSP Code - Java Beginners JSP Code Dear frnds, I have a problem where i need to display...;Hi Friend, Try the following code: function city(){ var cid...:8080/examples/jsp/country.jsp?value="+val); } --Please Select-- "> Source code of a website in HL and JSP. Source code of a website in HL and JSP. I want the source code of a website of 10 pages with database connectivity. Source code should be in HTML and JSP. Thanks servlet code - JSP-Servlet code, we have used following database table: CREATE TABLE `student...servlet code how to implement paging or pagination in java code using servlets. Hi Friend, Try the following code: import java.io. Dropdown code to retrieve result from oracle database Dropdown code to retrieve result from oracle database Hi Friends, I... contains dropdowns in frontend(Javascript or JSP).If i choose an option,it should... with code if possible.Oracle db.Using SQL developer,we manually execute queries code for selected checkbox columns data from database is the jsp code for this thanks in advance kalyani...code for selected checkbox columns data from database in my page iam getting all column names of a particular table with checkboxes. when iam select Draw graph using jsp without database connection Draw graph using jsp without database connection Draw graph using jsp code without database connection paging in Jsp: jsp code - JSP-Servlet friend, pagination using jsp with database <...paging in Jsp: jsp code Sir/Madam- i m working on jsp . i want to perform paging in jsp file so that we don't need to scroll page connecting to a database dynamically - JSP-Servlet with database dynamically. Plz debug the code and explain the reasons for the exception...connecting to a database dynamically abc.html :- abc.jsp :- Above code gives the following database database the code for initializing the database connection error in accessing database - JSP-Servlet database cud ne1 help me out plss Hi friend, Code to help in solving... database to the servlet i hv succeeded in connectivity but im stuck to nother... to the database"); conn.close(); System.out.println("Disconnected from- database dependent dropdown list respective to that class from database. please help by providing the code in jsp...jsp- database dependent dropdown list i want 2 dropdown list 1...); } %> For the above code, we have created two database tables: CREATE jsp database jsp database I want to retrive value in my jsp page but i dont want show my database query in my jsp page. is there any other method to show value in my jsp page using java class how to execute this code - JSP-Servlet how to execute this code hi guys can any help me in executing this bank application, i need to use any database plz tell me step-to-step procedure for executing this,i need to create Jaa - JSP-Servlet Jaa How to access data from the database using JSP program Hi Friend, Please visit the following links: database database how to search data from database using jsp & how... the following links: database links: Connect JSP with database Mysql Connect Java with database Mysql...database tell me use about database and give me a small program. It is secure and can easily be accessed, managed, and updated. Moreover javascript code problem - JSP-Servlet ; "> in above code which is jsp and struts form bean concept,the above code gets database values when the page is requested...javascript code problem Thanks for sending answer.but actually what To insert attachment file in database in JSP. To insert attachment file in database in JSP. I am doing project in JSP. How to insert attachment file in mysql database? Please suggest some... code: 1)page.jsp: <HTML> <HEAD><TITLE>Display file upload form database database i need to insert time in my database. i need a code to insert time in my database. its very urgent jsp code jsp code what are the jsp code for view page in online journal jsp code compilation error - JSP-Servlet jsp code compilation error hai, iam doing online banking project.i created two database tables in mysql.Table1: user (username,password) Table2... is the error and also what is the proper code for funds transfer. HTTP jsp -sevlet connecting to database using dropdown jsp -sevlet connecting to database using dropdown How can I get my dropdown list from oracle database and then submit it to another table in JSP. I... code that can do this. Most specifically I need the code of the JSP used Database Database Can i get a code for database connectivity Myeclipse 3.3 to MySql manager 2005 download code from database download code from database how to download files from database Database Database from java code i have to retrieve some data from a database, which is present in a different timezone. Scenario :- My database... in database timezone is 9PM 15APR2012. I want to retrieve something from database Code Code code for connecting c lang to database database database Im doing my project in java swings...netbeans I wanted java source code to establish connection to postgresql_8.1 using jdbc and create a user defined database and a table in that database and insert values Plz help me Database Database is it possible to view the query code after executing it.if yes tell me the procedure. Yes, if you want to retrieve the data that is stored in database, then use the given query: select * from student Database Database select * from student i am not asking this.i am asking about that the command line code like create table student(..........) like this way database in corresponding tables ? in mysql database on linux environment Here is a code.... The given code retrieve table names and their fields from the particular database...database how to get information about database like, what how to retrive data grom database in jsp pages. immediately. i want sample code of jsp to retrieving data from table of database to html...how to retrive data grom database in jsp pages. sir, i have problem to retrieve data from table of the database on the html web pages , so would jsp code for storing login and logout time to an account jsp code for storing login and logout time to an account I need simple jsp code for extracting and storing login and logout time in a database table...:// validation before entering values into database in jsp validation before entering values into database in jsp Hi, my project involves entering data into database from jsp form.but before entering into database it should pop up a alert message that "you have selected product:name getting values from database - JSP-Servlet JSP code separately.If it will not display database values then try your code...getting values from database I tried the following code abc.html aaa.jsp I am not getting exceptions now jsp code jsp code i want health management system project code using jsp.its urgent database database when i am writing this code CREATE TABLE student...; Have you run this query directly into the Mysql database? Here it works properly. Have you run this query directly into the Mysql database? Here database database How can i get combo box values from database?? or how... of combo box in java - from database? you had given me the answer <%@page... u give me the code in microsoft access of this program. and also can u tell me Database Database in my database i insert the first name and last name as('abc','def')but it gives error.plz send me the query how can we insert the first...('Roseindia','Technologies','rose@roseindia.net','2011-04-14',1111); For the above code Database Database in my database i insert the first name and last name as('abc','def')but it gives error.plz send me the query how can we insert the first...','Technologies','rose@roseindia.net','2011-04-14',1111); For the above code java with jsp and dynamic database retrival for bar charts java with jsp and dynamic database retrival for bar charts Hi, I... dynamically for the table values logintime and userid from database.. can u please send me the code for this. very urgent! have to get the values dynamically from database connectivty database connectivty i have two tables employee and adduser so this syntax is possible to use in jsp code insert into adduser(Emp_Id,Ename... and designation are displayed how it is possible in jsp employee->(Ename varchar Modifying a single row of database based on selection in jsp Modifying a single row of database based on selection in jsp Hi guys, i have a problem, I am Fetching the results from database and displaying... to a radio button is unique... Now i ve to write a code wherein i wil be able to modify database - SQL am doing project in JSP Question & Answers. In my home page i have to display everyday 1 question as "Question of the day" from database. It should not change... with source code to solve the problem. Thanks database database i am created one table in mysql database with one of the column name is emailid.now i want to write a java code that if the mail id... you can register now. thanks pls reply soon The given code accepts
http://roseindia.net/tutorialhelp/comment/86665
CC-MAIN-2013-48
refinedweb
2,449
62.78
Abstract: In this article we introduce a real buffer overflow in an application. We'll show that it's an easily exploitable security hole and how to avoid it. This article assumes that you have read the 2 previous articles: to avoid this problem. /* vulnerable.c */ #include <string.h> int main(int argc, char * argv []) { char buffer [500]; if (argc > 1) strcpy(buffer, argv[1]); return (0); } buffer is an automatic variable, the space used by the 500 bytes is reserved in the stack as soon as we enter the main() function. When running the vulnerable program with an argument longer than 500 characters, the data overflows the buffer and "invades" the process stack. As we've seen before, the stack holds the address of the next instruction to be executed (aka return address). To exploit this security hole, it is enough to replace the return address of the function with the shellcode address we want to execute. This shellcode is inserted into the body buffer, followed by its address in memory. Getting the memory address of the shellcode is rather tricky. We must discover the offset between the %esp register pointing to the top of the stack and the shellcode address. To benefit from a margin of safety, the beginning of the buffer is filled up with the NOP assembly instruction; it's a one byte neutral instruction having no effect at all. Thus, when the starting address points before the true beginning of the shellcode, the CPU goes from NOP to NOP till it reaches our code. To get more chance, we put the shellcode in the middle of the buffer, followed by the starting address repeated till the end, and preceded by a NOP block. The diagram 1 illustrates , next it copies the shellcode there and fills it up with the addresses and the NOP codes as explained above. It then prepares an argument array and runs the target application using the execve() instruction, this last replacing the current process with the invoked one. The generic_exploit the setuid()/setgid() function from the shellcode. /* generic_exploit.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #define NOP 0x90 char shellcode[] = "\xeb\x1f\x5e\x89\x76\xff\x31\xc0\x88\x46\xff\x89\x46\xff\xb0\x0b" "\x89\xf3\x8d\x4e\xff\x8d\x56\xff\xcd\x80\x31\xdb\x89\xd8\x40\xcd" "\x80\xe8\xdc\xff\xff\xff"; unsigned long get_sp(void) { __asm__("movl %esp,%eax"); } #define A_BSIZE 1 #define A_OFFSET 2 #define A_ALIGN 3 #define A_VAR 4 #define A_FORCE 5 #define A_PROG2RUN 6 #define A_TARGET 7 #define A_ARG 8 int main(int argc, char *argv[]) { char *buff, *ptr; char **args; long addr; int offset, bsize; int i,j,n; struct stat stat_struct; int align; if(argc < A_ARG) { printf("USAGE: %s bsize offset align (var / novar) (force/noforce) prog2run target param\n", argv[0]); return -1; } if(stat(argv[A_TARGET],&stat_struct)) { printf("\nCannot stat %s\n", argv[A_TARGET]); return 1; } bsize = atoi(argv[A_BSIZE]); offset = atoi(argv[A_OFFSET]); align = atoi(argv[A_ALIGN]); if(!(buff = malloc(bsize))) { printf("Can't allocate memory.\n"); exit(0); } addr = get_sp() + offset; printf("bsize %d, offset %d\n", bsize, offset); printf("Using address: 0lx%lx\n", addr); for(i = 0; i < bsize; i+=4) *(long*)(&buff[i]+align) = addr; for(i = 0; i < bsize/2; i++) buff[i] = NOP; ptr = buff + ((bsize/2) - strlen(shellcode) - strlen(argv[4])); if(strcmp(argv[A_FORCE],"force")==0) { if(S_ISUID&stat_struct.st_mode) { printf("uid %d\n", stat_struct.st_uid); *(ptr++)= 0x31; /* xorl %eax,%eax */ *(ptr++)= 0xc0; *(ptr++)= 0x31; /* xorl %ebx,%ebx */ *(ptr++)= 0xdb; if(stat_struct.st_uid & 0xFF) { *(ptr++)= 0xb3; /* movb $0x??,%bl */ *(ptr++)= stat_struct.st_uid; } if(stat_struct.st_uid & 0xFF00) { *(ptr++)= 0xb7; /* movb $0x??,%bh */ *(ptr++)= stat_struct.st_uid; } *(ptr++)= 0xb0; /* movb $0x17,%al */ *(ptr++)= 0x17; *(ptr++)= 0xcd; /* int $0x80 */ *(ptr++)= 0x80; } if(S_ISGID&stat_struct.st_mode) { printf("gid %d\n", stat_struct.st_gid); *(ptr++)= 0x31; /* xorl %eax,%eax */ *(ptr++)= 0xc0; *(ptr++)= 0x31; /* xorl %ebx,%ebx */ *(ptr++)= 0xdb; if(stat_struct.st_gid & 0xFF) { *(ptr++)= 0xb3; /* movb $0x??,%bl */ *(ptr++)= stat_struct.st_gid; } if(stat_struct.st_gid & 0xFF00) { *(ptr++)= 0xb7; /* movb $0x??,%bh */ *(ptr++)= stat_struct.st_gid; } *(ptr++)= 0xb0; /* movb $0x2e,%al */ *(ptr++)= 0x2e; *(ptr++)= 0xcd; /* int $0x80 */ *(ptr++)= 0x80; } } /* Patch shellcode */ n=strlen(argv[A_PROG2RUN]); shellcode[13] = shellcode[23] = n + 5; shellcode[5] = shellcode[20] = n + 1; shellcode[10] = n; for(i = 0; i < strlen(shellcode); i++) *(ptr++) = shellcode[i]; /* Copy prog2run */ printf("Shellcode will start %s\n", argv[A_PROG2RUN]); memcpy(ptr,argv[A_PROG2RUN],strlen(argv[A_PROG2RUN])); buff[bsize - 1] = '\0'; args = (char**)malloc(sizeof(char*) * (argc - A_TARGET + 3)); j=0; for(i = A_TARGET; i < argc; i++) args[j++] = argv[i]; if(strcmp(argv[A_VAR],"novar")==0) { args[j++]=buff; args[j++]=NULL; return execve(args[0],args,NULL); } else { setenv(argv[A_VAR],buff,1); args[j++]=NULL; return execv(args[0],args); } } To benefit from vulnerable.c, we must have a buffer bigger than the one expected by the application. to the time the program to exploit is called. Here, we succeeded in activating an exploitable overflow with a -1900 bytes offset. Of course, to complete the experience, the vulnerable target must be Set-UID root. $ cc vulnerable.c -o vulnerable $ cc generic_exploit.c -o generic_exploit $ su Password: # chown root.root vulnerable # chmod u+s vulnerable # exit $ ls -l vulnerable -rws--x--x 1 root root 11732 Dec 5 15:50 vulnerable $ ./generic_exploit 600 -1900 0 novar noforce /bin/sh ./vulnerable bsize 600, offset -1900 Using address: 0lxbffffe54 Shellcode will start /bin/sh bash# id uid=1000(raynal) gid=100(users) euid=0(root) groups=100(users) bash# exit $ ./generic_exploit 600 -1900 0 novar force /bin/sh /tmp/vulnerable bsize 600, offset -1900 Using address: 0lxbffffe64 uid 0 Shellcode will start /bin/sh bash# id uid=0(root) gid=100(users) groups=100(users) bash# exitIn the first case ( noforce), our uiddoesn't change. Nevertheless we have a new euidproviding us with all the rights. Thus, even if: #! /bin/sh # find_exploit.sh BUFFER=600 OFFSET=$BUFFER OFFSET_MAX=2000 while [ $OFFSET -lt $OFFSET_MAX ] ; do echo "Offset = $OFFSET" ./generic_exploit $BUFFER $OFFSET 0 novar force /bin/sh ./vulnerable OFFSET=$(($OFFSET + 4)) doneIn our exploit we didn't take into account the potential alignment problems. Then, it's possible that this example doesn't work for you with the same values, or doesn't work at all because of the alignment. (For those wanting to test anyway, the alignment parameter has to be changed to 1, 2 or 3 (here, 0). Some systems don't accept writing in memory areas not being a whole word, but this is not true for Linux. Unfortunately, sometimes the obtained shell is unusable since it ends on its own or when pressing a key. We use another program to keep privileges that we so carefully acquired: /* set_run_shell.c */ #include <unistd.h> #include <sys/stat.h> int main() { chown ("/tmp/run_shell", geteuid(), getegid()); chmod ("/tmp/run_shell", 06755); return 0; } Since our exploit is only able to do one task at a time, we are going to transfer the rights gained from the run_shell program with the help of the set_run_shell program. We'll then get the desired shell. /* run_shell.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> int main() { setuid(geteuid()); setgid(getegid()); execl("/tmp/shell","shell","-i",0); exit (0); }The -ioption corresponds to interactive. Why not giving the rights directly to a shell ? Just because the sbit is not available for every shell. The recent versions check that uid is equal to euid, same for gid and egid. Thus bash2and tcshincorporate this defense line, but neither bash, nor ashhave it. This method must be refined when the partition on which run_shellis located (here, /tmp) is mounted nosuidor noexec. Since we have a Set-UID program with a buffer overflow bug and its source code, we are able to prepare an attack allowing execution of arbitrary code under the ID of the file owner. However, our goal is to avoid security holes. Now we are going to examine a few rules to prevent buffer overflows. The first rule to follow is just a matter of good sense : the indexes used to manipulate an array must always be checked carefully. A "clumsy" loop like : for (i = 0; i <= n; i ++) { table [i] = ...probably holds an error because of the <since an access is done beyond the end of the array. If it's easy to one byte overflow is enough to create a security hole, inserting the shellcode into an environment variable, for instance. #define BUFFER_SIZE 128 void foo(void) { char buffer[BUFFER_SIZE+1]; /* end of string */ buffer[BUFFER_SIZE] = '\0'; for (i = 0; i<BUFFER_SIZE; i++) buffer[i] = ... } strcpy(3)function copies These functions have an ` n' in the middle of their name, for instance strncpy(3)as a replacement for strcpy(3), strncat(3)for strcat(3)or even strnlen(3)for strlen(3). However, you must be careful with the strncpy(3) limitation since it generates edge effects : when the source string is shorter than the destination one, the copy will be completed with null characters till the n limit and makes the application less performant. On the other hand, if the source string is longer, it will be truncated and the copy will then not end with a null character. Then you must add it manually. Taking this into account, the previous routine becomes : #define LG_IDENT 128 int fonction (const char * name) { char identity [LG_IDENT+1]; strncpy (identity, name, LG_IDENT); identity [LG_IDENT] = '\0'; ... }Of course, the same principles apply to routines manipulating of the number of bytes to copy. Such a hole in BIND (Berkeley Internet Name Daemon) made a lot of crackers busy : struct hosten *hp; unsigned long address; ... /* copy of an address */ memcpy(&address, hp->h_addr_list[0], hp->h_length); ...This should always copy 4 bytes. Nevertheless, if you can change hp->h_length, then you are able to modify the stack. Accordingly, it's compulsory to check the data length before copying : struct hosten *hp; unsigned long address; ... /* test */ if (hp->h_length > sizeof(address)) return 0; /* copy of an address */ memcpy(&address, hp->h_addr_list[0], hp->h_length); ...In some circumstances it's impossible to truncate that way (path, hostname, URL...) and things have to be done earlier in the program as soon as data is typed. First of all, this concerns string by an ill-intentioned user. Using the getenv() routine requires some caution, especially when it's about return string length (arbitrarily long) and its content (where you can find any character, ` =' included). The string returned by getenv() will be treated like the one provided by fgets(char *array, int size, FILE stream), taking care of its length and validating it one character after the other. Using such filters is done like accessing a computer : default is to forbid everything ! Next, you can allow a few things : #define GOOD "abcdefghijklmnopqrstuvwxyz\ BCDEFGHIJKLMNOPQRSTUVWXYZ\ 1234567890_" char *my_getenv(char *var) { char *data, *ptr /* Getting the data */ data = getenv(var); /* Filtering Rem : obviously the replacement character must be in the list of the allowed ones !!! */ for (ptr = data; *(ptr += strspn(ptr, GOOD));) *ptr = '_'; return data; } The strspn() function makes it easy : it looks for the first character not. 2001-05-01, generated by lfparser version 2.13
http://www.ibiblio.org/pub/Linux/docs/LDP/linuxfocus/English/May2001/article190.shtml
CC-MAIN-2013-20
refinedweb
1,878
64.2
Tải bản đầy đủ Công Nghệ Thông Tin Quản trị mạng 1264 mapreduce design patterns MapReduce Design Patterns Donald Miner and Adam Shook MapReduce Design Patterns by Donald Miner and Adam Shook Copyright © 2013 Donald Miner and Adam Mike Hendrickson Production Editor: Christopher Hearse December 2012: Proofreader: Dawn Carelli Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest First Edition Revision History for the First Edition: 2012-11-20 First release See for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. MapReduce Design Patterns, the image of Père David’s deer,-32717-0 [LSI] For William Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. Design Patterns and MapReduce. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Design Patterns MapReduce History MapReduce and Hadoop Refresher Hadoop Example: Word Count Pig and Hive 2 4 4 7 11 2. Summarization Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Numerical Summarizations Pattern Description Numerical Summarization Examples Inverted Index Summarizations Pattern Description Inverted Index Example Counting with Counters Pattern Description Counting with Counters Example 14 14 17 32 32 35 37 37 40 3. Filtering Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Filtering Pattern Description Filtering Examples Bloom Filtering Pattern Description Bloom Filtering Examples Top Ten Pattern Description Top Ten Examples 44 44 47 49 49 53 58 58 63 v Distinct Pattern Description Distinct Examples 65 65 68 4. Data Organization Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Structured to Hierarchical Pattern Description Structured to Hierarchical Examples Partitioning Pattern Description Partitioning Examples Binning Pattern Description Binning Examples Total Order Sorting Pattern Description Total Order Sorting Examples Shuffling Pattern Description Shuffle Examples 72 72 76 82 82 86 88 88 90 92 92 95 99 99 101 5. Join Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 A Refresher on Joins Reduce Side Join Pattern Description Reduce Side Join Example Reduce Side Join with Bloom Filter Replicated Join Pattern Description Replicated Join Examples Composite Join Pattern Description Composite Join Examples Cartesian Product Pattern Description Cartesian Product Examples 104 108 108 111 117 119 119 121 123 123 126 128 128 132 6. Metapatterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 Job Chaining With the Driver Job Chaining Examples With Shell Scripting vi | 139 140 141 150 Table of Contents With JobControl Chain Folding The ChainMapper and ChainReducer Approach Chain Folding Example Job Merging Job Merging Examples 153 158 163 163 168 170 7. Input and Output Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Customizing Input and Output in Hadoop InputFormat RecordReader OutputFormat RecordWriter Generating Data Pattern Description Generating Data Examples External Source Output Pattern Description External Source Output Example External Source Input Pattern Description External Source Input Example Partition Pruning Pattern Description Partition Pruning Examples 177 178 179 180 181 182 182 184 189 189 191 195 195 197 202 202 205 8. Final Thoughts and the Future of Design Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Trends in the Nature of Data Images, Audio, and Video Streaming Data The Effects of YARN Patterns as a Library or Component How You Can Help 217 217 218 219 220 220 A. Bloom Filters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 Table of Contents | vii Preface Welcome to MapReduce Design Patterns! This book will be unique in some ways and familiar in others. First and foremost, this book is obviously about design patterns, which are templates or general guides to solving problems. We took a look at other design patterns books that have been written in the past as inspiration, particularly Design Patterns: Elements of Reusable Object-Oriented Software, by Gamma et al. (1995), which is commonly referred to as “The Gang of Four” book. For each pattern, you’ll see a template that we reuse over and over that we loosely based off of their book. Repeatedly seeing a similar template will help you get to the specific information you need. This will be especially useful in the future when using this book as a reference.. This book is mostly about the analytics side of Hadoop or MapReduce. We intentionally try not to dive into too much detail on how Hadoop or MapReduce works or talk too long about the APIs that we are using. These topics have been written about quite a few times, both online and in print, so we decided to focus on analytics. In this preface, we’ll talk about how to read this book since its format might be a bit different than most books you’ve read. Intended Audience The motivation for us to write this book was to fill a missing gap we saw in a lot of new MapReduce developers. They had learned how to use the system, got comfortable with ix. This book is also intended for anyone wanting to learn more about the MapReduce paradigm. The book goes deeply into the technical side of MapReduce with code ex‐ amples and detailed explanations of the inner workings of a MapReduce system, which will help software engineers develop MapReduce analytics. However, quite a bit of time is spent discussing the motivation of some patterns and the common use cases for these patterns, which could be interesting to someone who just wants to know what a system like Hadoop can do. To get the most out of this book, we suggest you have some knowledge of Hadoop, as all of the code examples are written for Hadoop and many of the patterns are discussed in a Hadoop context. A brief refresher will be given in the first chapter, along with some suggestions for additional reading material. Pattern Format The patterns in this book follow a single template format so they are easier to read in succession. Some patterns will omit some of the sections if they don’t make sense in the context of that pattern. Intent This section is a quick description of the problem the pattern is intended to solve. Motivation This section explains why you would want to solve this problem or where it would appear. Some use cases are typically discussed in brief. Applicability This section contains a set of criteria that must be true to be able to apply this pattern to a problem. Sometimes these are limitations in the design of the pattern and sometimes they help you make sure this pattern will work in your situation. Structure This section explains the layout of the MapReduce job itself. It’ll explain what the map phase does, what the reduce phase does, and also lets you know if it’ll be using any custom partitioners, combiners, or input formats. This is the meat of the pattern and explains how to solve the problem. x | Preface Consequences This section is pretty short and just explains what the output of the pattern will be. This is the end goal of the output this pattern produces. Resemblances For readers that have some experience with SQL or Pig, this section will show anal‐ ogies of how this problem would be solved with these other languages. You may even find yourself reading this section first as it gets straight to the point of what this pattern does. Sometimes, SQL, Pig, or both are omitted if what we are doing with MapReduce is truly unique. Known Uses This section outlines some common use cases for this pattern. Performance Analysis This section explains the performance profile of the analytic produced by the pat‐ tern. Understanding this is important because every MapReduce analytic needs to be tweaked and configured properly to maximize performance. Without the knowl‐ edge of what resources it is using on your cluster, it would be difficult to do this. The Examples in This Book All of the examples in this book are written for Hadoop version 1.0.3. MapReduce is a paradigm that is seen in a number of open source and commercial systems these days, but we had to pick one to make our examples consistent and easy to follow, so we picked Hadoop. Hadoop was a logical choice since it a widely used system, but we hope that users of MongoDB’s MapReduce and other MapReduce implementations will be able to extrapolate the examples in this text to their particular system of choice. In general, we try to use the newer mapreduce API for all of our exam‐ ples, not the deprecated mapred API. Just be careful when mixing code from this book with other sources, as plenty of people still use mapred and their APIs are not compatible. Our examples generally omit any sort of error handling, mostly to make the code more terse. In real-world big data systems, you can expect your data to be malformed and you’ll want to be proactive in handling those situations in your analytics. We use the same data set throughout this text: a dump of StackOverflow’s databases. StackOverflow is a popular website in which software developers can go to ask and Preface | xi answer questions about any coding topic (including Hadoop). This data set was chosen because it is reasonable in size, yet not so big that you can’t use it on a single node. This data set also contains human-generated natural language text as well as “structured” elements like usernames and dates. Throughout the examples in this book, we try to break out parsing logic of this data set into helper functions to clearly distinguish what code is specific to this data set and which code is general and part of the pattern. Since the XML is pretty simple, we usually avoid using a full-blown XML parser and just parse it with some string operations in our Java code. The data set contains five tables, of which we only use three: comments, posts, and users. All of the data is in well-formed XML, with one record per line. We use the following three StackOverflow tables in this book: Comments are follow-up questions or suggestions users of the site can leave on posts (i.e., questions or answers). CreationDate="2011-08-04T09:50:25.043" Score="4" ViewCount="" Body="<p>You should have imported Poll with <code> from polls.models import Poll</code></p> " OwnerUserId="634150" LastActivityDate="2011-08-04T09:50:25.043" CommentCount="1" /> CreationDate="2011-08-04T09:50:58.910" Score="1" ViewCount="26" Body="<p>Is it possible to gzip a single asp.net 3.5 page? my site is hosted on IIS7 and for technical reasons I cannot enable gzip compression site wide. does IIS7 have an option to gzip individual pages or will I have to override OnPreRender and write some code to compress the output?</p> " OwnerUserId="743184" LastActivityDate="2011-08-04T10:19:04.107" Title="gzip a single asp.net page" Tags="<asp.net><iis7><gzip>" AnswerCount="2" /> Posts contain the questions and answers on the site. A user will post a question, and then other users are free to post answers to that question. Questions and answers can be upvoted and downvoted depending on if you think the post is constructive or not. In order to help categorize the questions, the creator of the question can specify a number of “tags,” which say what the post is about. In the example above, we see that this post is about asp.net, iis, and gzip. xii | Preface One thing to notice is that the body of the post is escaped HTML. This makes parsing it a bit more challenging, but it’s not too bad with all the tools available. Most of the questions and many of the answers can get to be pretty long! Posts are a bit more challenging because they contain both answers and questions intermixed. Questions have a PostTypeId of 1, while answers have a PostTypeId of 2. Answers point to their related question via the ParentId, a field that questions do not have. Questions, however, have a Title and Tags. users The users table contains all of the data about the account holders on StackOverflow. Most of this information shows up in the user’s profile. Users of StackOverflow have a reputation score, which goes up as other users upvote questions or answers that user has submitted to the website. To learn more about the data set, refer to the documentation included with the download in README.txt. In the examples, we parse the data set with a helper function that we wrote. This function takes in a line of StackOverflow data and returns a HashMap. This HashMap stores the labels as the keys and the actual data as the value. package mrdp.utils; import java.util.HashMap; import java.util.Map; public class MRDPUtils { // This helper function parses the stackoverflow into a Map for us. public static Map transformXmlToMap(String xml) { Map map = new HashMap (); try { // exploit the fact that splitting on double quote // tokenizes the data nicely for us String[] tokens = xml.trim().substring(5, xml.trim().length() - 3) .split("\""); for (int i = 0; i < tokens.length - 1; i += 2) { String key = tokens[i].trim(); String val = tokens[i + 1]; map.put(key.substring(0, key.length() - 1), val); } } catch (StringIndexOutOfBoundsException e) { Preface | xiii System.err.println(xml); } return map; } }. xiv | Preface We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “MapReduce Design Patterns by Donald Min‐ er and Adam Shook (O’Reilly). Copyright 2013 Donald Miner and Adam Shook, 978-1-449-32717. Preface | xv For more information about our books, courses, conferences, and news, see our website at. Find us on Facebook: Watch us on YouTube: Acknowldgements Books published by O’Reilly are always top notch and now we know why first hand. The support staff, especially our editor Andy Oram, has been extremely helpful in guiding us through this process. They give freedom to the authors to convey the message while supporting us in any way we need. A special thanks goes out to those that read our book and provided useful commentary and reviews: Tom Wheeler, Patrick Angeles, Tom Kulish, and Lance Byrd. Thanks to Jeff Gold for providing some early encouragement and comments. We appreciate Eric Sammer’s help in finding reviewers and wish him luck with his book Hadoop Operations. The StackOverflow data set, which is used throughout this book, is freely available under the Creative Commons license. It’s great that people are willing to spend the time to release the data set so that projects like this can make use of the content. What a truly wonderful contribution. Don would like to thank the support he got from coworkers at Greenplum, who provided slack in my schedule to work on this project, moral support, and technical suggestions. These folks from Greenplum have helped in one way or another, whether they realize it or not: Ian Andrews, Dan Baskette, Nick Cayou, Paul Cegielski, Will Davis, Andrew Ettinger, Mike Goddard, Jacque Istok, Mike Maxey, Michael Parks, and Parham Parvizi. Also, thanks to Andy O’Brien for contributing the chapter on Postgres. Adam would like to thank his family, friends, and caffeine. xvi | Preface CHAPTER 1 Design Patterns and MapReduce MapReduce is a computing paradigm for processing data that resides on hundreds of computers, which has been popularized recently by Google, Hadoop, and many others. The paradigm is extraordinarily powerful, but it does not provide a general solution to what many are calling “big data,” so while it works particularly well on some problems, some are more challenging. This book will teach you what problems are amenable to the MapReduce paradigm, as well as how to use it effectively. At first glance, many people do not realize that MapReduce is more of a framework than a tool. You have to fit your solution into the framework of map and reduce, which in some situations might be challenging. MapReduce is not a feature, but rather a con‐ straint. This makes problem solving easier and harder. It provides clear boundaries for what you can and cannot do, making the number of options you have to consider fewer than you may be used to. At the same time, figuring out how to solve a problem with con‐ straints requires cleverness and a change in thinking. Learning MapReduce is a lot like learning recursion for the first time: it is challenging to find the recursive solution to the problem, but when it comes to you, it is clear, concise, and elegant. In many situations you have to be conscious of system resources being used by the MapReduce job, especially inter-cluster network utilization. The tradeoff of being confined to the MapReduce framework is the ability to process your data with dis‐ tributed computing, without having to deal with concurrency, robustness, scale, and other common challenges. But with a unique system and a unique way of problem solving, come unique design patterns. 1 What is a MapReduce design pattern? It is a template for solving a common and general data manipulation problem with MapReduce. A pattern is not specific to a domain such as text processing or graph analysis, but it is a general approach to solving a problem. Using design patterns is all about using tried and true design principles to build better software. Designing good software is challenging for a number of reasons, and similar challenges face those who want to achieve good design in MapReduce. Just as good programmers can produce bad software due to poor design, good programmers can produce bad MapReduce algorithms. With MapReduce we’re not only battling with clean and main‐ tainable code, but also with the performance of a job that will be distributed across hundreds of nodes to compute over terabytes and even petabytes of data. In addition, this job is potentially competing with hundreds of others on a shared cluster of machines. This makes choosing the right design to solve your problem with MapReduce extremely important and can yield performance gains of several orders of magnitude. Before we dive into some design patterns in the chapters following this one, we’ll talk a bit about how and why design patterns and MapReduce together make sense, and a bit of a history lesson of how we got here. Design Patterns pro‐ gramming. Since the book was published in 1994, most individuals interested in good design heard about patterns from word of mouth or had to root around conferences, journals, and a barely existent World Wide Web. Design patterns have stood the test of time and have shown the right level of abstraction: not too specific that there are too many of them to remember and too hard to tailor to a problem, yet not too general that tons of work has to be poured into a pattern to get things working. This level of abstraction also has the major benefit of providing devel‐ 2 | Chapter 1: Design Patterns and MapReduce opers with a common language in which to communicate verbally and through code. Simply saying “abstract factory” is easier than explaining what an abstract factory is over and over. Also, when looking at a stranger’s code that implements an abstract factory, you already have a general understanding of what the code is trying to accomplish. MapReduce design patterns fill this same role in a smaller space of problems and solu‐ tions. They provide a general framework for solving your data computation issues, without being specific to the problem domain. Experienced MapReduce developers can pass on knowledge of how to solve a general problem to more novice MapReduce de‐ velopers. This is extremely important because MapReduce is a new technology with a fast adoption rate and there are new developers joining the community every day. Map‐ Reduce design patterns also provide a common language for teams working together on MapReduce problems. Suggesting to someone that they should use a “reduce-side join” instead of a “map-side replicated join” is more concise than explaining the lowlevel mechanics of each. The MapReduce world is in a state similar to the object-oriented world before 1994. Patterns today are scattered across blogs, websites such as StackOverflow, deep inside other books, and inside very advanced technology teams at organizations across the world. The intent of this book is not to provide some groundbreaking new ways to solve problems with MapReduce that nobody has seen before, but instead to collect patterns that have been developed by veterans in the field so that they can be shared with everyone else. Even provided with some design patterns, genuine experience with the MapReduce paradigm is still necessary to understand when to apply them. When you are trying to solve a new problem with a pattern you saw in this book or elsewhere, be very careful that the pattern fits the problem by paying close attention to its “Applicability” section. For the most part, the MapReduce design patterns in this book are intended to be plat‐ form independent. MapReduce, being a paradigm published by Google without any actual source code, has been reimplemented a number of times, both as a standalone system (e.g., Hadoop, Disco, Amazon Elastic MapReduce) and as a query language within a larger system (e.g., MongoDB, Greenplum DB, Aster Data). Even if design patterns are intended to be general, we write this book with a Hadoop perspective. Many of these patterns can be applied in other systems, such as MongoDB, because they con‐ form to the same conceptual architecture. However, some technical details may be dif‐ ferent from implementation to implementation. The Gang of Four’s book on design patterns was written with a C++ perspective, but developers have found the concepts conveyed in the book useful in modern languages such as Ruby and Python. The patterns in this book should be usable with systems other than Hadoop. You’ll just have to use the code examples as a guide to developing your own code. Design Patterns | 3 MapReduce History How did we get to the point where a MapReduce design patterns book is a good idea? At a certain point, the community’s momentum and widespread use of the paradigm reaches a critical mass where it is possible to write a comprehensive list of design patterns to be shared with developers everywhere. Several years ago, when Hadoop was still in its infancy, not enough had been done with the system to figure out what it is capable of. But the speed at which MapReduce has been adopted is remarkable. It went from an interesting paper from Google in 2004 to a widely adopted industry standard in dis‐ tributed data processing in 2012. The actual origins of MapReduce are arguable, but the paper that most cite as the one that started us down this journey is “MapReduce: Simplified Data Processing on Large Clusters” by Jeffrey Dean and Sanjay Ghemawat in 2004. This paper described how Google split, processed, and aggregated their data set of mind-boggling size. Shortly after the release of the paper, a free and open source software pioneer by the name of Doug Cutting started working on a MapReduce implementation to solve scal‐ ability in another project he was working on called Nutch, an effort to build an open source search engine. Over time and with some investment by Yahoo!, Hadoop split out as its own project and eventually became a top-level Apache Foundation project. Today, numerous independent people and organizations contribute to Hadoop. Every new re‐ lease adds functionality and boosts performance. Several other open source projects have been built with Hadoop at their core, and this list is continually growing. Some of the more popular ones include Pig, Hive, HBase, Mahout, and ZooKeeper. Doug Cutting and other Hadoop experts have mentioned several times that Hadoop is becoming the kernel of a distributed operating system in which distributed applications can be built. In this book, we’ll be explaining the examples with the least common denominator in the Hadoop ecosystem, Java MapReduce. In the resemblance sections of each pattern in some chapters, we’ll typically outline a parallel for Pig and SQL that could be used in Hive. MapReduce and Hadoop Refresher The point of this section is to provide a quick refresher on MapReduce in the Hadoop context, since the code examples in this book are written in Hadoop. Some beginners might want to refer to a more in-depth resource such as Tom White’s excellent Hadoop: The Definitive Guide or the Apache Hadoop website. These resources will help you get started in setting up a development or fully productionalized environment that will allow you to follow along the code examples in this book. Hadoop MapReduce jobs are divided into a set of map tasks and reduce tasks that run in a distributed fashion on a cluster of computers. Each task works on the small subset 4 | Chapter 1: Design Patterns and MapReduce. It is incredible what a wide range of problems can be solved with such a straightforward paradigm, from simple numerical aggregations to complex join operations and Cartesian products.oriented view of a chunk of the file to be loaded by a map task. Each map task in Hadoop is broken into the following phases: record reader, mapper, combiner, and partitioner. The output of the map tasks, called the intermediate keys and values, are sent to the reducers. The reduce tasks are broken into the following phases: shuffle, sort, reducer, and output format. The nodes in which the map tasks run are optimally on the nodes in which the data rests. This way, the data typically does not have to move over the network and can be computed on the local machine. record reader The record reader translates an input split generated by input format into records. The purpose of the record reader is to parse the data into records, but not parse the record itself. It passes the data to the mapper in the form of a key/value pair. Usually the key in this context is positional information and the value is the chunk of data that composes a record. Customized record readers are outside the scope of this book. We generally assume you have an appropriate record reader for your data. map In the mapper, user-provided code is executed on each key/value pair from the record reader to produce zero or more new key/value pairs, called the intermediate pairs. The decision of what is the key and value here is not arbitrary and is very important to what the MapReduce job is accomplishing. The key is what the data will be grouped on and the value is the information pertinent to the analysis in the reducer. Plenty of detail will be provided in the design patterns in this book to explain what and why the particular key/value is chosen. One major differentiator between MapReduce design patterns is the semantics of this pair. combiner The combiner, an optional localized reducer, can group data in the map phase. It takes the intermediate keys from the mapper and applies a user-provided method to aggregate values in the small scope of that one mapper. For example, because the count of an aggregation is the sum of the counts of each part, you can produce an intermediate count and then sum those intermediate counts for the final result. In many situations, this significantly reduces the amount of data that has to move over the network. Sending (hello world, 3) requires fewer bytes than sending (hello MapReduce and Hadoop Refresher | 5 world, 1) three times over the network. Combiners will be covered in more depth with the patterns that use them extensively. Many new Hadoop developers ignore combiners, but they often provide extreme performance gains with no downside. We will point out which patterns benefit from using a combiner, and which ones cannot use a combiner. A combiner is not guaranteed to execute, so it cannot be a part of the overall algorithm. partitioner The partitioner takes the intermediate key/value pairs from the mapper (or combin‐ er if it is being used) and splits them up into shards, one shard per reducer. By default, the partitioner interrogates the object for its hash code, which is typically an md5sum. Then, the partitioner performs a modulus operation by the number of reducers: key.hashCode() % (number of reducers). This randomly distributes the keyspace evenly over the reducers, but still ensures that keys with the same value in different mappers end up at the same reducer. The default behavior of the par‐ titioner can be customized, and will be in some more advanced patterns, such as sorting. However, changing the partitioner is rarely necessary. The partitioned data is written to the local file system for each map task and waits to be pulled by its respective reducer. shuffle and sort The reduce task starts with the shuffle and sort step. This step takes the output files written by all of the partitioners and downloads them to the local machine in which the reducer is running. These individual data pieces are then sorted by key into one larger data list. The purpose of this sort is to group equivalent keys together so that their values can be iterated over easily in the reduce task. This phase is not cus‐ tomizable and the framework handles everything automatically. The only control a developer has is how the keys are sorted and grouped by specifying a custom Comparator object. reduce The reducer takes the grouped data as input and runs a reduce function once per key grouping. The function is passed the key and an iterator over all of the values associated with that key. A wide range of processing can happen in this function, as we’ll see in many of our patterns. The data can be aggregated, filtered, and com‐ bined in a number of ways. Once the reduce function is done, it sends zero or more key/value pair to the final step, the output format. Like the map function, the re duce function will change from job to job since it is a core piece of logic in the solution. output format The output format translates the final key/value pair from the reduce function and writes it out to a file by a record writer. By default, it will separate the key and value 6 | Chapter 1: Design Patterns and MapReduce with a tab and separate records with a newline character. This can typically be customized to provide richer output formats, but in the end, the data is written out to HDFS, regardless of format. Like the record reader, customizing your own output format is outside of the scope of this book, since it simply deals with I/O. Hadoop Example: Word Count Now that you’re refreshed on the steps of the whole MapReduce process, let’s dive into a quick and simple example. The “Word Count” program is the canonical example in MapReduce, and for good reason. It is a straightforward application of MapReduce and MapReduce can handle it extremely efficiently. Many people complain about the “Word Count” program being overused as an example, but hopefully the rest of the book makes up for that! In this particular example, we’re going to be doing a word count over user-submitted comments on StackOverflow. The content of the Text field will be pulled out and pre‐ processed a bit, and then we’ll count up how many times we see each word. An example record from this data set is: This record is the 8,189,677th comment on Stack Overflow, and is associated with post number 6,881,722, and is by user number 831,878. The number of the PostId and the UserId are foreign keys to other portions of the data set. We’ll show how to join these datasets together in the chapter on join patterns. The first chunk of code we’ll look at is the driver. The driver takes all of the components that we’ve built for our MapReduce job and pieces them together to be submitted to execution. This code is usually pretty generic and considered “boiler plate.” You’ll find that in all of our patterns the driver stays the same for the most part. This code is derived from the “Word Count” example that ships with Hadoop Core: import import import import java.io.IOException; java.util.StringTokenizer; java.util.Map; java.util.HashMap; import import import import import import import import import org.apache.hadoop.conf.Configuration; org.apache.hadoop.fs.Path; org.apache.hadoop.io.IntWritable; org.apache.hadoop.io.Text; org.apache.hadoop.mapreduce.Job; org.apache.hadoop.mapreduce.Mapper; org.apache.hadoop.mapreduce.Reducer; org.apache.hadoop.mapreduce.lib.input.FileInputFormat; org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; Hadoop Example: Word Count | 7 Tài liệu liên quan Gang of Four Design Patterns 2.0 Head First Design Patterns 2.0 Design Patterns and Best Practices Design Patterns for Building Message-Oriented Web Services Design Patterns for Building Service-Oriented Web Services Design Patterns for SOAP Messaging with WS-Addressing and Routing Test Harness Design Patterns Introduction to Design Patterns in C# Module 2: Architecture and Structural Design Patterns Module 3: Logical Design and Behavioral Design Patterns Tài liệu bạn tìm kiếm đã sẵn sàng tải về (9.55 MB) - 1264 mapreduce design patterns Tải bản đầy đủ ngay × 9houz
https://text.123doc.org/document/5030987-1264-mapreduce-design-patterns.htm
CC-MAIN-2018-47
refinedweb
5,530
59.74
c Copyright 2008 by Peter C. Chapin August 31, 2008 Contents 1 Introduction 2 Creating and Destroying Threads 2.1 2.2 Creating Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . Returning Results from Threads . . . . . . . . . . . . . . . . . . 2 3 3 5 8 8 10 14 17 18 19 20 20 21 22 23 23 25 26 3 Thread Synchronization 3.1 3.2 3.3 3.4 Mutual Exclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . Condition Variables . . . . . . . . . . . . . . . . . . . . . . . . . Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Reader/Writer Locks . . . . . . . . . . . . . . . . . . . . . . . . . 4 Thead Models 4.1 4.2 4.3 4.4 4.5 Boss/Worker Model . . . . . . . . . . . . . . . . . . . . . . . . . Pipeline Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . Background Task Model . . . . . . . . . . . . . . . . . . . . . . . Interface/Implementation Model . . . . . . . . . . . . . . . . . . General Comments . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Thread Safety 5.1 5.2 5.3 Levels of Thread Safety . . . . . . . . . . . . . . . . . . . . . . . Writing Thread Safe Code . . . . . . . . . . . . . . . . . . . . . . Exception Safety vs Thread Safety . . . . . . . . . . . . . . . . . 1 6 Rules for Multithreaded Programming 6.1 Shared Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.1.1 6.1.2 6.1.3 6.1.4 6.2 What data is shared? . . . . . . . . . . . . . . . . . . . . What data is not shared? . . . . . . . . . . . . . . . . . . What type of simultaneous access causes a problem? . . . What type of simultaneous access is safe? . . . . . . . . . 26 27 27 27 27 28 28 What can I count on? . . . . . . . . . . . . . . . . . . . . . . . . Legal A included in the file GFDL.txt distributed with the L TEX source of this document. 1 Introduction This document is intended to be a short but useful tutorial on how to use POSIX threads (pthreads). In this document I do not attempt to give a full description of all pthread features. Instead I hope to give you enough information to use pthreads in a basic, yet effective way. Please refer to a text on pthreads for the more esoteric details of the standard. In addition to talking about the pthread interface itself, I also spend time in this document discussing issues regarding concurrent programming in general. While such issues are not specific to pthreads, it is a must that you understand them if you are to use pthreads—or any thread library—effectively. I will assume that you are compiling pthreads programs on a Unix system. However, you should be aware that the pthreads interface is not necessarily specific to Unix. It is a standard application program interface that could potentially be implemented on many different systems. However, pthreads is the usual way multi-threaded support is offered in the Unix world. Although many systems support their own internal method of handling threads, virtually every Unix system that supports threads at all offers the pthreads interface. The pthreads API can be implemented either in the kernel of the operating system or in a library. It can either be preemptive or it can be non-preemptive. 2 A portable program based on pthreads should not make any assumptions about these matters. When you compile a program that uses pthreads, you will probably have to set special options on the compiler’s command line to indicate extra (or different) libraries and/or alternative code generating stratagies. Consult your compiler’s documentation for more information on this. Often you can indicate your desire to use pthreads by supplying the “-pthread” option at the end of the compiler command line. For example $ gcc -o myprog myprog.c -pthread This single option specifies that the pthreads library should be linked and also causes the compiler to properly handle the multiple threads in the code that it generates. 2 Creating and Destroying Threads Clearly the first step required in understanding how to build a multithreaded program is to understand how to create and destroy threads. There are a number of subtle issues associated with this topic. Normally one wants to not only create a thread but also to send that thread one or more parameters. When a thread ends, one normally wants to be able to retieve one or more values that are returned from the thread. In this section I will describe how these things can be done with pthreads. 2.1 Creating Threads To create a new thread you need to use the pthread create() function. Listing 1 shows a skeleton program that creates a thread that does nothing and then waits for the thread to terminate. The pthread create() function gives back a thread identifier that can be used in other calls. The second parameter is a pointer to a thread attribute object that you can use to set the thread’s attributes. The null pointer means to use default attributes. The third parameter is a pointer to the function the thread is to execute. The final parameter is the argument to the function. By using void pointers here, any sort of data could potentially be sent to the thread function provided proper casts are applied. In the skeleton example I show how a single integer can be used as a thread argument, but in practice one might send a pointer to a structure containing multiple arguments to the thread. 3 Listing 1: Skeleton Thread Program #include <p t h r e a d . h> /* * The function to be executed by the thread should take a * void * parameter and return a void * exit status code . */ void ∗ t h r e a d f u n c t i o n ( void ∗ a r g ) { // Cast the parameter into what is needed . i n t ∗ incoming = ( i n t ∗ ) a r g ; // Do whatever is necessary using * incoming as the argument . // The thread terminates when this function returns . return NULL; } i n t main ( void ) { pthread t thread ID ; void ∗ exit status ; int value ; // Put something meaningful into value . value = 42; // Create the thread , passing & value for the argument . p t h r e a d c r e a t e (& t h r e ad I D , NULL, t h r e a d f u n c t i o n , &v a l u e ) ; // The main program continues while the thread executes . // Wait for the thread to terminate . p t h r e a d j o i n ( t h r ea d I D , &e x i t s t a t u s ) ; // Only the main thread is running now . return 0 ; } 4 You should plan to collect the exit status of all the threads you create by calling pthread join() on each thread eventually. Alternatively you can create a detached thread. The exit status for such threads are thrown away. The problem with detached threads is that, unless you make special arrangements, you are never sure when they complete. Usually you want to make sure all your threads have terminated cleanly before you end the process by returning from main(). If you want to kill a thread before its thread function returns normally, you can use pthread cancel(). However, there are difficulties involved in doing that. You must be sure the thread has released any resources that it has obtained before it actually dies. For example if a thread has dynamcially allocated memory and you cancel it before it can free that memory, your program will have a memory leak. This is different than when you kill an entire process. The operating system will typically clean up (certain) resources that are left dangling by the process. In particular, the entire address space of a process is recovered. However, the operating system will not do that for a thread since all the threads in a process share resources. For all the operating system knows, the memory allocated by one thread will be used by another thread. This situation makes canceling threads carelessly a bad idea. Exercies 1. Write a program that creates 10 threads. Have each thread execute the same function and pass each thread a unique number. Each thread should print “Hello, World (thread n)” five times where ‘n’ is replaced by the thread’s number. Use an array of pthread t objects to hold the various thread IDs. Be sure the program doesn’t terminate until all the threads are complete. Try running your program on more than one machine. Are there any differences in how it behaves? 2.2 Returning Results from Threads The example in the last section illustrated how you can pass an argument into your thread function if necessary. In this section I will describe how to return results from thread functions. Note that the thread functions are declared to return a pointer to void. However, there are some pitfalls involved in using that pointer appropriately. The code below shows one attempt at returning an integer status code from a thread function. void ∗ t h r e a d f u n c t i o n ( void ∗ ) { i n t code = DEFAULT VALUE; // Set the value of ’ code ’ as appropriate . 5 return ( void ∗ ) code ; } This method will only work on machines where integers can be converted to a pointer and then back to an integer without loss of information. On some machines such conversions are dangerous. In fact this method will fail in all cases where one attempts to return an object, such as a structure, that is larger than a pointer. In contrast, the code below doesn’t fight the type system. It returns a pointer to an internal buffer where the return value is stored. While the example shows an array of characters for the buffer, one can easily imagine it being an array of any necessary type, or a single object such as an integer status code or a structure with many members. void ∗ t h r e a d f u n c t i o n ( void ∗ ) { char b u f f e r [ 6 4 ] ; // Fill up the buffer with something good . return b u f f e r ; } Alas, the code above fails because the internal buffer is automatic and it vanishes as soon as the thread function returns. The pointer given back to the calling thread points at undefined memory. This is another example of the classic dangling pointer error. In the next attempt the buffer is made static so that it will continue to exist even after the thread function terminates. This gets around the dangling pointer problem. void ∗ t h r e a d f u n c t i o n ( void ∗ ) { s t a t i c char b u f f e r [ 6 4 ] ; // Fill up the buffer with something good . return b u f f e r ; } This method might be satisfactory in some cases, but it doesn’t work in the common case of multiple threads running the same thread function. In such a situation the second thread will overwrite the static buffer with its own data and destroy that left by the first thread. Global data suffers from this same problem since global data always has static duration. The version below is the most general and most robust. 6 void ∗ t h r e a d f u n c t i o n ( void ∗ ) { char ∗ b u f f e r = ( char ∗ ) m a l l o c ( 6 4 ) ; // Fill up the buffer with something good . return b u f f e r ; } This version allocates buffer space dynamically. This approach will work correctly even if multiple threads execute the thread function. Each will allocate a different array and store the address of that array in a stack variable. Every thread has its own stack so automatic data objects are different for each thread. In order to receive the return value of a thread the higher level thread must join with the subordinate thread. This is shown in the main function of Listing 1. In particular void ∗ e x i t s t a t u s ; // Wait for the thread to terminate . p t h r e a d j o i n ( t h r ea d I D , &e x i t s t a t u s ) ; The pthread join() function blocks until the thread specified by its first argument terminates. It then stores into the pointer pointed at by its second argument the value returned by the thread function. To use this pointer, the higher level thread must cast it into an appropriate type and dereference it. For example char ∗ t h r e a d r e s u l t ; t h r e a d r e s u l t = ( char ∗ ) e x i t s t a t u s ; p r i n t f ( "I got %s back from the thread .\ n" , t h r e a d r e s u l t ) ; free ( exit status ); If the thread function allocated the space for the return value dynamically then it is essential for the higher level thread to free that space when it no longer needs the return value. If this isn’t done the program will leak memory. Exercises 1. Write a program that computes the square roots of the integers from 0 to 99 in a separate thread and returns an array of doubles containing the results. In the meantime the main thread should display a short message to the user and then display the results of the computation when they are ready. 7 2. Imagine that the computations done by the program above were much more time consuming than merely calculating a few square roots. Imagine also that displaying the ”short message” was also fairly time consuming. For example, perhaps the message needed to be fetched from a network server as HTML and then rendered. Would you expect the multithreaded program to perform better than a single threaded program that, for example, did the calculations first and then fetched the message? Explain. 3 Thread Synchronization In order to effectively work together the threads in a program usually need to share information or coordinate their activity. Many ways to do this have been devised and such techniques usually go under the name of thread synchronization. In this section I will outline several common methods of thread synchronization and show how they can be done using POSIX threads. 3.1 Mutual Exclusion When writing multi-threaded programs it is frequently necessary to enforce mutually exclusive access to a shared data object. This is done with mutex objects. The idea is to associate a mutex with each shared data object and then require every thread that wishes to use the shared data object to first lock the mutex before doing so. Here are the particulars 1. Declare an object of type pthread mutex t. 2. Initialize the object by calling pthread mutex init(). 3. Call pthread mutex lock() to gain exclusive access to the shared data object. 4. Call pthread mutex unlock() to release the exclusive access and allow another thread to use the shared data object. 5. Get rid of the object by calling pthread mutex destroy(). The program of Listing 2 demonstrates the basic approach. It is important to understand that if a thread attempts to lock the mutex while some other thread has it locked, the second thread is blocked until the first releases the mutex with pthread mutex unlock(). The code above uses dynamic initialization. However, it is also possible to initialize a mutex object statically using the special symbol PTHREAD MUTEX INITIALIZER as the initializer. Be sure to observe these points 8 Listing 2: Mutex Example #include <p t h r e a d . h> #include <u n i s t d . h> pthread mutex t lock ; int shared data ; // Often shared data is more complex than just an int . void ∗ t h r e a d f u n c t i o n ( void ∗ a r g ) { int i ; f o r ( i = 0 ; i < 1 0 2 4 ∗ 1 0 2 4 ; ++i ) { // Access the shared data here . p t h r e a d m u t e x l o c k (& l o c k ) ; s h a r e d d a t a ++; p t h r e a d m u t e x u n l o c k (& l o c k ) ; } return NULL; } i n t main ( void ) { pthread t thread ID ; void ∗ exit status ; int i; // Initialize the mutex before trying to use it . p t h r e a d m u t e x i n i t (& l o c k , NULL ) ; p t h r e a d c r e a t e (& t h r e ad I D , NULL, t h r e a d f u n c t i o n , NULL ) ; // Try to use the shared data . f o r ( i = 0 ; i < 1 0 ; ++i ) { sleep (1); p t h r e a d m u t e x l o c k (& l o c k ) ; p r i n t f ( "\ rShared integer ’s value = %d\n" , s h a r e d d a t a ) ; p t h r e a d m u t e x u n l o c k (& l o c k ) ; } p r i n t f ( "\n" ) ; p t h r e a d j o i n ( t h r ea d I D , &e x i t s t a t u s ) ; // Clean up the mutex when we are finished with it . p t h r e a d m u t e x d e s t r o y (& l o c k ) ; return 0 ; } 9 1. No thread should attempt to lock or unlock a mutex that has not been initialized. 2. The thread that locks a mutex must be the thread that unlocks it. 3. No thread should have the mutex locked when you destroy the mutex. 4. Any mutex that is initialized should eventually be destroyed, but only after any thread that uses it has either terminated or is no longer interesting in using it. In practice it is sometimes the case that threads are blocked on mutex objects when the program wishes to terminate. In such a situation it might make sense to pthread cancel() those threads before destroying the mutex objects they are blocked on. Coordinating this properly can be tricky, however. Notice that it is possible to assign special “mutex attributes” to a mutex object when it is created. This is done by creating a mutex attributes object, assigning attributes to the object, and then passing a pointer to the attributes object into pthread mutex init(). The program in Listing 2 just calls for default attributes by providing a NULL pointer instead. In many cases this is perfectly adequate. The use of mutex attribute objects is beyond the scope of this document. Exercises 1. Enter the program in Listing 2 and try it out. Does it behave the way you expected? Try different values for the maximum loop index in the thread function and different sleep times in the main function. Try removing the call to sleep() entirely. Try the program on different machines. Can you explain what is happening? 2. Suppose you are building a C++ string class that you intend to use in a multi-threaded program. You are worried about your string objects possibly getting corrupted if they are updated by more than one thread at a time. You consider adding a mutex as a member of each string and locking that mutex whenever any string method is called. Discuss the implications of this design. Be careful: this question is considerably trickier than it may appear! 3.2 Condition Variables If you want one thread to signal an event to another thread, you need to use condition variables. The idea is that one thread waits until a certain condition is true. First it tests the condition and, if it is not yet true, calls 10 pthread cond wait() to block until it is. At some later time another thread makes the condition true and calls pthread cond signal() to unblock the first thread. Every call to pthread cond wait() should be done as part of a conditional statement. If you aren’t doing that, then you are most likely using condition variables incorrectly. For example i f ( f l a g == 0 ) p t h r e a d c o n d w a i t ( . . . ) ; Here I’m waiting until the flag is not zero. You can test conditions of any complexity. For example x = a + b − (2 ∗ c ) ; i f ( x < 0 | | x > 9) pthread cond wait ( . . . ) ; Here I’m waiting until x is in the range from zero to nine inclusive where x is computed in some complex way. Note that pthread cond wait() is only called if the condition is not yet true. If the condition is already true, pthread cond wait() is not called. This is necessary because condition variables do not remember that they have been signaled. If you look at my examples, you will see that there is a serious race condition in them. Suppose the condition is not true. Then suppose that after the condition is tested but before pthread cond wait() is called, the condition becomes true. The fact that the condition is signaled (by some other thread) will be missed by pthread cond wait(). The first thread will end up waiting on a condition that is already true. If the condition is never signaled again the thread will be stuck waiting forever. To deal with this problem, every time you use a condition variable you must also use a mutex to prevent the race condition. For example: p t h r e a d m u t e x l o c k (&mutex ) ; i f ( ) ; The thread that signals this condition will use the same mutex to gain exclusive access to the flag. Thus there is no way that the signaling could occur between the test of the flag and the waiting on the condition. For the above to work, pthread cond wait() needs to wait on the condition and unlock the mutex as an atomic action. It does this, but it needs to know which mutex to unlock. Hence the need for the second parameter of pthread cond wait(). When the condition is signaled, pthread cond wait() will lock the mutex again before returning so that the pthread mutex unlock() in the above example is appropriate regardless of which branch of the if is taken. Here is how the signaling thread might look 11 s i g n a l (& c o n d i t i o n ) ; Before setting the flag, and thus making the condition true, the signaling thread locks the mutex to make sure the waiting thread can’t get caught in a race condition. There is a further subtlety regarding the use of condition variables. Under certain conditions the wait function might return even though the condition variable has not actually been signaled. For example, if the Unix process in general receives a signal, the thread blocked in pthread cond wait() might be elected to process the signal handling function. If system calls are not restarting (the default in many cases) the pthread cond wait() call might return with an interrupted system call error code1 . This has nothing to do with the state of the condition so proceeding as if the condition is true would be inappropriate. The solution to this problem is to simply retest the condition after pthreadcond wait() returns. This is most easily done using a while loop. For example p t h r e a d m u t e x l o c k (&mutex ) ; while ( ) ; Of course this assumes you want to ignore any spurious returns from the wait function. In a more complex application you might want to process the error codes in various ways depending on the situation. The pthread cond signal function releases only one thread at a time. In some cases it is desirable to release all threads waiting on a condition. This can be accomplished using pthread cond broadcast. For example b r o a d c a s t (& c o n d i t i o n ) ; The example in listing 3 illustrates the use of condition variables in the context of a program. Although contrived, this example is at least complete and compilable. Notice that in this program the condition variables are also initialized and destroyed by calls to appropriate functions. As with mutex variables you can also initialize condition variables statically using a special symbol: PTHREAD COND INITIALIZER. 1 Of course this assumes you are dealing with an actual kernel thread. If the thread is purely a user mode thread such unexpected returns won’t occur. 12 Listing 3: Condition Variable Example #include <p t h r e a d . h> #include <u n i s t d . h> pthread cond t is zero ; p t h r e a d m u t e x t mutex ; // Condition variables needs a mutex . i n t s h a r e d d a t a = 3 2 7 6 7 ; // Or some other large number . void ∗ t h r e a d f u n c t i o n ( void ∗ a r g ) { // Imagine doing something useful . while ( s h a r e d d a t a > 0 ) { // The other thread sees the shared data consistently . p t h r e a d m u t e x l o c k (&mutex ) ; −−s h a r e d d a t a ; p t h r e a d m u t e x u n l o c k (&mutex ) ; } // Signal the condition . p t h r e a d c o n d s i g n a l (& i s z e r o ) ; return NULL; } i n t main ( void ) { pthread t thread ID ; void ∗ exit status ; int i; p t h r e a d c o n d i n i t (& i s z e r o , NULL ) ; p t h r e a d m u t e x i n i t (&mutex , NULL ) ; p t h r e a d c r e a t e (& t h r e ad I D , NULL, t h r e a d f u n c t i o n , NULL ) ; // Wait for the shared data to reach zero . p t h r e a d m u t e x l o c k (&mutex ) ; while ( s h a r e d d a t a != 0 ) p t h r e a d c o n d w a i t (& i s z e r o , &mutex ) ; p t h r e a d m u t e x u n l o c k (&mutex ) ; p t h r e a d j o i n ( t h r ea d I D , &e x i t s t a t u s ) ; p t h r e a d m u t e x d e s t r o y (&mutex ) ; p t h r e a d c o n d d e s t r o y (& i s z e r o ) ; return 0 ; } 13 Exercises 1. Modify the program in listing 3 to print messages and add delays (or wait for user input) at various places so you can verify that the thread is, in fact, waiting for the condition as appropriate. Verify that the thread does not wait if the condition is already true when it is first tested. 2. In the text above, when a condition is signaled the signaling thread releases the mutex before calling pthread cond signal(). However, it is also possible swap those operations as shown below. p t h r e a d m u t e x l o c k (&mutex ) ; flag = 1; p t h r e a d c o n d s i g n a l (& c o n d i t i o n ) ; p t h r e a d m u t e x u n l o c k (&mutex ) ; Does this result in the same behavior as before? Are any race conditions introduced (or fixed) by this change? How does this approach impact application performance? 3.3 Semaphores Semaphore are essentially glorified integer counters. They support two primary operations. One operation, called down or wait, attempts to decrement the counter. The other operation, called up or signal, attempts to increment the counter. What makes semaphores special is that if a thread tries to wait on a zero semaphore it is blocked instead. Later when another thread signals the semaphore the blocked thread is activated while the semaphore remains at zero. In effect, the signaling causes the semaphore to be incremented but then the thread that was blocked trying to do a wait is allowed to proceed, causing the semaphore to be immediately decremented again. If multiple threads are blocked waiting on a semaphore then the system chooses one to unblock. Exactly how this choice is made is generally system dependent. You can not assume that it will be in FIFO order2 . However, the order in which the threads are unblocked is not normally a concern. If it is, then your program may not be very well designed. A semaphore with an initial value of one can be used like a mutex. When a thread wishes to enter its critical section and access a shared data structure, it does a wait operation on the semaphore. If no other thread is in its critical section, the semaphore will have its initial value of one and the wait will return immediately. The semaphore will then be zero. If another thread tries to wait on the semaphore during this time it will be blocked. When the first thread is finished executing its critical section it does a signal operation on the 2 If threads have different priorities, normally the highest priority thread is allowed to go first. 14 semaphore. This will unblock one waiting thread or, if there are no waiting threads, increment the semaphore back to its initial value of one. A semaphore used in this way is called a binary semaphore because it has exactly two states. However, because semaphores are integers they can take on values larger than one. Thus they are often used to count scarce resources. For example a thread might wait on a semaphore to effective reserve one item of a resource. If there are no items left, the semaphore will be zero and the wait operation will block. When a thread is finished using an item of a resource it signals the semaphore to either increment the count of available items or to allow a blocked thread to access the now free item. A semaphore used in this way is called a counting semaphore. The POSIX semaphore API is not really part of the normal pthread API. Instead POSIX standardizes semaphores under a different API. Traditional Unix systems support shared memory, message queues, and semaphores as part of what is called “System V Interprocess Communication” (System V IPC). POSIX also provides shared memory, message queues, and semaphores as a package that competes with, or replaces, the older standard. The functionality of the two systems is similar although the details of the two APIs are different. Note that POSIX semaphores, like System V IPC semaphores, can be used to synchronize two or more separate processes. This is different than pthread mutexes. A mutex can only be used by threads in the same process. Because POSIX semaphores can be used for interprocess communication, they have the option of being named. One process can create a semaphore under a particular name and other processes can open that semaphore by name. In this tutorial, however, I will focus only on synchronizing threads in the same process. Thus here I will only go over what that requires and skip matters of semaphore naming. The skeleton program in Listing 4 shows how to initialize, clean up, and use a POSIX semaphore. For brevity the skeleton program does not show the threads being created or joined nor does it show any error handling. See the manual pages for the various functions for more information on error returns. Another difference between a pthread mutex and a semaphore is that, unlike a mutex, a semaphore can be signaled in a different thread than the thread that does the wait operation. This is necessary when using a semaphore to count instances of a scarce resource. The skeleton program in Listing 4 is using a semaphore like a mutex. I did this to simplify the listing so that the functions used to manipulate the semaphore would be clear. In a later version of this tutorial I may show an example of how to use a semaphore to count scarce resources. 15 Listing 4: Semaphore Example #include <semaphore . h> int shared ; sem t b i n a r y s e m ; // Used like a mutex . void ∗ t h r e a d f u n c t i o n ( void ∗ a r g ) { se m wa it (& b i n a r y s e m ) ; // Decrements count . // Used shared resource . s e m s i g n a l (& b i n a r y s e m ) ; // Increments count . } void main ( void ) { s e m i n i t (& binary sem , 1 ) ; // Give semaphore initial count . // Start threads here . se m wa it (& b i n a r y s e m ) ; // Use shared resource . s e m s i g n a l (& b i n a r y s e m ) ; // Join with threads here . s e m d e s t r o y (& b i n a r y s e m ) ; return 0 ; } Exercises 1. Using POSIX mutex and condition variables, implement a semaphore abstract type. For example, consider a header file containing the following. struct semaphore { // Fill in members as appropriate . }; void s e m a p h o r e i n i t ( struct semaphore ∗ s , i n t i n i t i a l c o u n t ) ; void s e m a p h o r e d e s t r o y ( struct semaphore ∗ s ) ; void s e m a p h o r e w a i t ( struct semaphore ∗ s ) ; void s e m a p h o r e s i g n a l ( struct semaphore ∗ s ) ; Implement the functions declared above. This shows that semaphores are not strictly necessary as part of a low level API. 2. Some semaphore APIs (such as the Win32 API) allow the signal operation 16 to advance the value of a semaphore by more than one. This can be implemented by executing a basic signal operation multiple times in a loop. However, such an approach is inefficient if the number to be added to the semaphore is large. Extend your solution for the question above so that semaphore signal takes an additional integer parameter specifying the how much the semaphore value is to be advanced. Try to use an efficient method of handling large advances. Make sure your solution works properly and does not suffer from any race conditions even when there are multiple threads waiting on the semaphore. 3.4 Reader/Writer Locks Mutex objects provide mutually exclusive access to a shared resource. But sometimes complete mutual exclusion is unnecessarily restrictive. If two threads are only interested in reading a shared resource, it should be possible to allow both to access the resource at the same time. If neither thread tries to modify the resource, the resource will never be in an inconsistent state and simultaneous access is safe. Indeed, it is common for there to be multiple threads trying to read a shared resource where updates to that resource are uncommon. For example a tree data structure might be used many times by multiple threads to look up information and yet updated only rarely by a single thread. To support this usage POSIX provides reader/writer locks. Multiple readers can lock such an object without blocking each other, but when a single writer acquires the lock it has exclusive access to the resource. All following readers or writers will block as long as a writer holds the lock. The skeleton program in Listing 5 shows the basic structure. By now the pattern of initialization, destruction, and use should look familiar. In a more typical program the thread function where the read lock is acquired might be executed by many threads while the main function where the write lock is needed might be executed by only one thread. Notice in this case that the same function is used to unlock both read locks and write locks. Depending on the implementation, a steady stream of readers might permanently lock out a writer. This situation is called writer starvation. On the other hand if the implementation favors writers in the sense of letting waiting writers obtain the lock as soon as possible, reader starvation may occur. The POSIX standard favors writers, depending on specific thread priorities. This behavior is reasonable because writers are presummed to be rare and the updates they want to do are presummed to be important. Exercises 1. I need something here. 17 Listing 5: Reader/Writer Lock Example #include <p t h r e a d . h> int shared ; pthread rwlock t lock ; void ∗ t h r e a d f u n c t i o n ( void ∗ a r g ) { p t h r e a d r w l o c k r d l o c k (& l o c k ) ; // Read from the shared resource . p t h r e a d r w l o c k u n l o c k (& l o c k ) ; } void main ( void ) { p t h r e a d r w l o c k i n i t (& l o c k , NULL ) ; // Start threads here . p t h r e a d r w l o c k w r l o c k (& l o c k ) ; // Write to the shared resource . p t h r e a d r w l o c k u n l o c k (& l o c k ) ; // Join with threads here . p t h r e a d r w l o c k d e s t r o y (& b i n a r y s e m ) ; return 0 ; } 4 Thead Models In this section I will describe some ways that threads can be used in real programs. The goal is to give you a feeling for the kind of design ideas that lend themselves to a threaded solution. It is usually possible to build a single threaded program that solves the same problem, but in some cases the single threaded solution is awkward and difficult to manage. Be aware, however, that single threaded solutions are often the most appropriate. There can be a significant amount of overhead associated with synchronizing threads; multiple threads, poorly applied, can easily result in a slower and more confusing program. 18 4.1 Boss/Worker Model Here the idea is to have a single boss thread that creates work and several worker threads that process the work. Typically the boss thread creates a certain number of workers right away—even before any work has arrived. The worker threads form a thread pool and are all programed to block immediately. When the boss thread generates some work, it arranges to have one worker thread unblock to handle it. Should all workers be busy the boss thread might 1. Queue up the work to be handled later as soon as a worker is free. 2. Create more worker threads. 3. Block until a worker is free to take the new work. If no work has arrived recently and there are an excessive number of worker threads in the thread pool, the boss thread might terminate a few of them to recover resources. In any case, since creating and terminate threads is relatively expensive (compared to, say, blocking on a mutex) it is generally better to avoid creating a thread for each unit of work produced. You have already seen this model in action many times. Consider a bank. When you arrive you have work that needs doing. You get in a queue and wait for a free teller (worker thread). When a teller is available that teller handles your work while other tellers are handling other work at the same time. Should someone in line have an unusually complicated transaction, it won’t hold up the line. Only one teller will be tied up dealing with the large work item. The other tellers will be available to handle other people’s work normally. Thus the response time is reasonable even when some work items are very time consuming. A web server is another excellent example of where the boss/worker model can be used. The boss thread listens to the network for incoming connections. When a connection is made, the boss thread directs a worker thread to handle that connection. The boss thread then returns to listening to the network again. In this way many connections can be handled at once. If a particularly time consuming connection is active, it won’t prevent the program for dealing with other connections as well. This model works the best when the work items are independent of each other. If the work items depend on each other or have to be processed in a particular sequence the worker threads have to talk to each other and the overall efficiency of this model is much reduced. Also, if you run a boss/worker program on a single processor machine it is important that servicing a work item involves a fair amount of blocking. If the work items are all 100% CPU bound then there won’t be any performance enhancement. A single thread servicing all the items in sequence would be just as fast as having multiple threads servicing several items at once. However, if servicing an item requires a lot of blocking, 19 then another thread can use the CPU while the first is blocked and the overall performance is better (often drastically so). 4.2 Pipeline Model Many programs take some input, transform it in several stages, and then output the result. Instead of having a single thread perform each step in sequence you could have a separate thread handling each stage. The result is much like an assembly line. The data flows from one worker to another and each worker performs their particular operation on the data. By the time the data reaches the end of the line it has been fully transformed into the desired output. Usually writing a single threaded program to process sequential data in stages is fairly straightforward. However, a multithreaded pipeline has the potential to outperform the single threaded solution. In general, if there are N stages to the pipeline there can be N items being operated on at once by the multithreaded program and the result will be N times faster. In practice it rarely works out this well. To obtain its full efficiency the time required for every stage must be identical and the processing of one stage can’t in any way slow down the processing of the others. If the program runs on a single processor the operations being done in each stage must block frequently so that the CPU can excute another stage while the blocked stages are waiting. To balance the load between the stages, the programmer might need to use profiling tools to find out which stages are taking shorter or longer amounts of time. Stages that are very short can be combined with the stage on either side while stages that are very long can be split into multiple stages (ideally with blocking operations divided evenly between the stages). Getting this balance just right is difficult yet without it the multithreaded solution to the pipeline model will hardly be any faster than the single threaded solution. In fact, because of locking overhead, it may even be slower3 . 4.3 Background Task Model Many programs have tasks that they would like to complete “in the background.” For example a program might want to backup its data files every 10 minutes or update a special status window every 5 seconds. It is awkward to program such things with only a single thread. The program must remember to check the time regularly and call the background function whenever an appropriate amount of time has elapsed. Since that might happen at any point in the program’s execution, the program’s logic must be littered with calls to functions that are largely unrelated to the main flow of the program. 3 The buffers between the stages must be careful to avoid race conditions and overflow/underflow conditions. This involves a significant amount of locking activity. 20 With multiple threads, however, this model is quite easy to program. A background thread can be created when the program initializes itself. That thread can sleep for a certain fixed time and then, when it wakes up, perform the necessary background operation. The thread would then just loop back and sleep again until the next time interval has expired. This can happen independently of the main program’s logic. The main complication involved with programming this model is in making sure that the background access is properly synchronized with the main access. In this approach the threads are used in a manner similar to the way interrupt service routines are used. They provide background services that the main program does not have to explicity invoke. Many useful tasks can be effectively handled in this way. 4.4 Interface/Implementation Model Most graphical environments are event driven. Each action taken by the user is a separate event that the program must handle. Examples of events include mouse clicks, menu selections, keystrokes, and so forth. Typically the program contains a single function that is called by the system whenever an event happens. That function must process the event and then return before the system calls the function with the next event. If the event handling function does not return quickly enough events will back up and the user will precieve the program as unresponsive and sluggish. In an extreme case the program will even appear to be dead. To avoid this the program can use multiple threads. If handling an event is going to be time consuming and difficult (and involve a lot of blocking), the event handling function can just create a thread to deal with it and then return at once. This gives the event handling function the opportunity to handle additional events while past events are being processed by other threads. The result is that the program’s interface remains responsive even if some of the operations requested are very time consuming. It is not necessary for an entire program to be organized this way. Internal modules in a program can use the same trick. When a function is called in such a module, the function might create a thread to carry out the requested operation and then return at once. The calling program will see the function as very quick and responsive even though the actual work requested hasn’t really been completed when the function returns. The difficulty with this model is that eventually the user of an interface will usually need know for sure when certain operations requested in the past have actually completed. Some way of coordinating that information must be provided. Also it is difficult for the program to report errors effectively with this model because an error might occur long after the operation was requested and apparently handled. 21 Many operating systems themselves use this model extensively. For example, when a program writes to a file, the file is typically not put onto the disk at once. Instead it is just put into a cache (faster) and written to disk latter when the system is less busy. In effect, the operating system writes to disk in a separate thread that is independent of the thread that actually requested the write operation in the first place. 4.5 General Comments In general, multithreaded programs work best if the threads are as independent as possible. The less the threads have to talk with each other the better. Whenever threads have to synchronize or share data there will be locking overhead and time spent waiting for other threads. Time blocked while waiting for another thread is time wasted. Such a thread is not doing anything useful. In contrast, if a thread is blocked waiting for I/O it is doing something that the program needs done. Such blocking is good because it allows other threads to get the CPU. But if a thread waits for another thread then it is not accomplishing anything that the program needs. The more threads interact with each other the more time they will spend waiting for each other and the more inefficient the program will be. It is easy to understand this idea when you think about working with another person. If you and your partner can do two largely independent activities you can both work without getting in each other’s way and you can get twice as much work done. But if you try to work too closely then one of you will simply be waiting for the other and the work won’t get done any more quickly than it would by a single person alone. Consider what would happen if you decided to type a paper with your partner but that you and your partner had to alternate keystrokes on the keyboard. To type “Hello” first you type ‘H’ then your partner types ‘e’ then you type ‘l’ and so on. Obviously this would be very inefficient. You would spend more time getting the alternation right than you would actually typing keys. The exact same issues arise in multithreaded programs. An improperly written multithreaded program can be slower—sometimes a lot slower—than its single threaded equivalent. If two tasks are very independent, they can often be handled by two entirely separate processes. Large software systems are often composed of many executable files, each taking care of a single aspect of the system. At this level the system is “multithreaded” even if the individual programs are not. However, multiple processes can find it difficult to share information effectively. Putting multiple threads into a single process makes the parallelism more fine grained and allows the threads to interact more closely and share more resources. This can be a good thing. But if taken to extreme it causes inefficiencies as I described above. A good multithreaded program will strike the right balance between sharing and independence. That balance is often difficult to find. 22 5 Thread Safety Typically when a complicated object is operated on, it goes through several intermediate, invalid states before the operation is complete. As an analogy consider what a surgeon does when he operates on a person. Although the purpose of the operation is to increase the patient’s health, the surgeon performs several steps that would greatly decrease the patient’s health if they were left incomplete. Imagine what would happen if a surgeon cut open a patient’s chest and then decided to go on vacation for three weeks! Similarly a function that operates on an object will often temporary put that object into an unusable state while it performs the update. Once the update is complete, the function (if written correctly) will leave the object is a fully functional state again. Should another thread try to use an object while it is in an unusable state (often called an inconsistent state) the object will not respond properly and the result will be undefined. Keeping this from happening is the essential problem of thread safety. The problem doesn’t come up in a single threaded program because there is no possibility of another thread trying to access the object while the first thread is updating it. (Unless exceptions are a possibility. In that case the updating thread might abort the update and then later try to access the incompletely updated object. This causes pretty much the same sort of problems to occur). 5.1 Levels of Thread Safety One of the problems people have discussing thread safety is that there are many different levels of safety one might want to talk about. Just saying that a piece of code is thread safe doesn’t really say all that much. Yet most people have certain natural expectations about thread safety. Sometimes those expectations are reasonable and valid, but sometimes they are not. Here are some of those expectations. • Reading an object’s value with multiple threads is not normally expected to be a problem. Problems only occur when an object is updated since it is only then that it has to be modified and run the risk of entering inconsistent states. However some objects have internal state that gets modified even when its value is read (think about an object that has an internal cache). If two threads try to read such an object there might be problems unless the read operations on that object have been designed to handle the multiple threads properly. • Updating two independent objects, even of the same type, is not normally expected to be a problem. It is usually assumed that objects that appear 23 to be independent are, in fact, independent and thus the inconsistent states of one such object have no impact on the other. However some objects share information behind the scenes (static class data, global data, etc) that causes them to be linked internally even when they do not appear to be linked from a logical point of view. In that case, modifying two “independent” objects might cause a problem anyway. Consider: void f ( ) { std : : s t r i n g x ; // Modify x. } } void g ( ) { std : : s t r i n g y ; // Modify y. If one thread is in function f() modifying the string x and another is in function g() modifing string y, will there be a problem? Most of the time you can assume that the two apparently independent objects can be simultaneously modified without a problem. But it is possible, depending on how std::string is implemented, that the two objects share some data internally and that simultaneous modifications will cause a problem. In fact, even if one of the functions merely reads the value of the string, there might be a problem if they share internal data that is being updated by the other function. • Functions that acquire resources, even if from a common pool of resources, are not normally exepected to be a problem. Consider: void f ( ) { char ∗p = new char [ 5 1 2 ] ; // Use the array p. } } void g ( ) { char ∗p = new char [ 5 1 2 ] ; // Use the array p. If one thread is in function f() and another thread is in function g(), both threads might try to allocate memory simultaneously by invoking the new operator. In a multi-threaded environment, it is safe to assume that new has been written to work correctly in this case even though both invocations of new are trying to take memory from the same pool of memory. Internally new will synchronize the threads so that each call will return a unique allocation and the internal memory pool will not be corrupted. Similar comments can be made about functions that open files, make network connections, and perform other resource allocation tasks. However if the resource allocation functions are not designed with threads in mind then they may well fail if invoked by multiple threads at once. What people typically expect to cause problems is when a program tries to access (update or read) an object while another thread is updating that same 24 object. Global objects are particularly prone to this problem. Local objects are much less so. For example: std : : s t r i n g x ; void f ( ) { std : : s t r i n g y ; // Modify x and y. } If two threads enter function f() at the same time, they will get different versions of the string y. This is because every thread has its own stack and local objects are allocated on the thread’s stack. Thus every thread has its own, independent copy of the local objects. As a result, manipulating y inside f() will not cause a problem (assuming that manipulating independent objects is safe). However, since there is only one copy of the global x that both threads will be touching, there could be a problem caused by those operations. Local objects are not immune to problems since any function can start a new thread and pass a pointer to a local object as a parameter to that thread. For example void f ( ) { std : : s t r i n g x ; s t a r t t h r e a d ( s o m e f u n c t i o n , &x ) ; s t a r t t h r e a d ( s o m e f u n c t i o n , &x ) ; } Here I assume there is a library function named start thread() that accepts a pointer to a thread function (defined elsewhere) and a pointer to a parameter for that function. In this case I start two threads executing some function(), giving both of them a pointer to the string x. If some function() tries to modify that string then two threads will be modifying the same object and problems are likely. Note that this case is particularly insidious because some function() has no particular reason to expect that it will be given the same parameter twice. Thus it is unlikely to have any protection to handle such a case. 5.2 Writing Thread Safe Code In theory the only way to control the actions of a thread is to use synchronization primitives such as mutexes or semaphores. In languages that provide threads as a part of the language, synchronization primitives of some kind are normally provided by the language itself. In other cases, such as with C, they are library functions, such as the Posix API, that interact with the operating system. 25 Normally you should write code that meets the usual expectations that people have about thread safe code. If you are implementing a class, make sure that multiple simultaneous reads on an object are safe. If you do update internal data behind the caller’s back, you will probably have to protect those updates yourself. Also make sure the simultaneous writes to independent objects are safe. If you do make use of shared data, you will probably have to protect updates to that shared data yourself. If you write a function that manages a shared resource for multiple threads from a common pool, you will probably have to protect that shared resource from corruption by multiple, simultaneous requests. However, in general, you probably don’t have to bother protecting every single object against simultaneous updates. Let the calling program worry about that case. Such total safety is usually very expensive in terms of runtime efficiency and not normally necessary or even appropriate. 5.3 Exception Safety vs Thread Safety Both thread and exception safety share a number of common issues. Both are concerned with objects that are in an inconsistent state. Both have to think about resources (although in different ways... exception safety is concerned with resource leaks, thread safety is concerned with resource corruption). Both have several levels of safety that could be defined along with some common expectations about what is and is not safe. However, there is one important difference between the exception safety and thread safety. Exceptions occur synchronously with the program’s execution while threads are asynchronous. In other words, exceptions occur, in theory, only at certain well defined times. Although it is not always clear which operations might throw an exception and which might not, in theory it is possible to precisely define exactly when an exception might happen and when it can’t happen. As a result it is often possible to make a function exception safe by just reorganizing it. In contrast there is no way to control when two threads might clash. Reorganzing a function is rarely helpful when it comes to making it thread safe. This difference makes thread related errors very difficult to reproduce and especially hard to manage. 6 Rules for Multithreaded Programming In this section I’ll try to summarize a few “rules of thumb” that one should keep in mind when building a multithreaded program. Although using multiple threads can provide elegant and natural solutions to some programming problems, they can also introduce race conditions and other subtle, difficult to debug problems. Many of these problems can be avoided by following a few simple rules. 26 6.1 Shared Data As I described in Section 3, when two threads try to access the same data object there is a potential for problems. Normally modifying an object requires several steps. While those steps are being carried out the object is typically not in a well formed state. If another thread tries to access the object during that time, it will likely get corrupt information. The entire program might have undefined behavior afterwards. This must be avoided. 6.1.1 What data is shared? 1. Static duration data (data that lasts as long as the program does). This includes global data and static local data. The case of static local data is only significant if two (or more) threads execute the function containing the static local at the same time. 2. Dynamically allocated data that has had its address put into a static variable. For example, if a function uses malloc() or new to allocate an object and then places the address of that object into a variable that is accessible by more than one thread, the dynamically allocated object will then be accessible by more than one thread. 3. The data members of a class object that has two (or more) of its member functions called by different threads at the same time. 6.1.2 What data is not shared? 1. Local variables. Even if two threads call the same function they will have different copies of the local variables in that function. This is because the local variables are kept on the stack and every thread has its own stack. 2. Function parameters. In languages like C the parameters to functions are also put on the stack and thus every thread will have its own copy of those as well. Since local variables and function parameters can’t be shared they are immune to race conditions. Thus you should use local variables and function parameters whenever possible. Avoid using global data. 6.1.3 What type of simultaneous access causes a problem? 1. Whenever one thread tries to update an object, no other threads should be allowed to touch the object (for either reading or writing). Mutual exclusion should be enforced with some sort of mutex-like object (or by some other suitable means). 27 6.1.4 What type of simultaneous access is safe? 1. If multiple threads only read the value of an object, there should be no problem. Be aware, however, that complicated objects often update internal information even when, from the outside, they are only being read. Some objects maintain a cache or keep track of usage statistics internally even for reads. Simultaneous reads on such an object might not be safe. 2. If one thread writes to one object while another thread touches a totally independent object, there should be no problem. Be aware, however, that many functions and objects do share some data internally. What appears to be two separate objects might really be using a shared data structure behind the scenes. 3. Certain types of objects are updated in an uninterruptable way. Thus simultaneous reads and writes to such objects are safe because it is impossible for the object to be in an inconsistent state during the update. Such updates are said to be atomic. The bad news is that the types that support atomic updates are usually very simple (for example: int) and there is no good way to know for sure exactly which types they are. The C standard provides the type sig atomic t for this purpose. It is defined in <signal.h> and is some kind of integer. Simultaneous updates to an object declared to be volatile sig atomic t are safe. Mutexes are not necessary in this case. 6.2 What can I count on? Unless a function is specifically documented as being thread-safe, you should assume that it is not. Many libraries make extensive use of static data internally and unless those libraries were designed with multiple threads in mind that static data is probably not being properly protected with mutexes. Similarly you should regard the member functions of a class as unsafe for multiple threads unless it has been specifically documented to be otherwise. It is easy to see that there might be problems if two threads try to manipulate the same object. However, even if two threads try to manipulate different objects there could still be problems. For various reasons, many classes use internal static data or try to share implementation details among objects that appear to be distinct from the outside. You can count on the following: 1. The API functions of the operating system are thread-safe. 2. The Posix thread standard requires that most functions in the C standard library be thread-safe. There are a few exceptions which are documented as part of the standard. 28 3. Under Windows the C standard library is totally thread safe provided you use the correct version of the library and you initialize it properly. 4. The thread safety of the C++ standard library is vauge and very much dependent on the compiler you are using. The SGI criteria for thread safety of the standard template library is gaining ground as the defacto standard. It is not universal. If you use a non thread-safe function in one of your functions, your function will be rendered non thread-safe as well. However, you are free to use a non thread-safe function in a multithreaded program provided it is never called by two or more threads at the same time. You can either arrange to use such functions in only one thread or protect calls to such functions with mutexes. Keep in mind that many functions share data internally with other functions. If you try to protect calls to a non thread-safe function with a mutex you must also protect calls to all the other related functions with the same mutex. This is often difficult. 29
https://www.scribd.com/document/14705905/Pthread-Tutorial-by-Peter-Good-One
CC-MAIN-2018-43
refinedweb
11,200
69.31
The primary goal of this glossary is to clarify meanings of selected terms and acronyms that appear frequently in the .NET documentation without definitions. AOT Ahead-of-time compiler. Similar to JIT, this compiler also translates IL to machine code. In contrast to JIT compilation, AOT compilation happens before the application is executed and is usually performed on a different machine. Because AOT tool chains don't compile at runtime, they don't have to minimize time spent compiling. That means they can spend more time optimizing. Since the context of AOT is the entire application, the AOT compiler also performs cross-module linking and whole-program analysis, which means that all references are followed and a single executable is produced. ASP.NET The original ASP.NET implementation that ships with the .NET Framework. Sometimes ASP.NET is an umbrella term that refers to both ASP.NET implementations including ASP.NET Core. The meaning that the term carries in any given instance is determined by context. ASP.NET Core A cross-platform, high-performance, open source implementation of ASP.NET built on .NET Core. See ASP.NET Core. assembly A .dll file that contains a collection of APIs that can be called by apps or other assemblies. A .NET assembly is a collection of types. An assembly includes interfaces, classes, structures, enumerations, and delegates. Assemblies in a project's bin folder are sometimes referred to as binaries. See also library. CLR Common Language Runtime. The exact meaning depends on the context, but this usually refers to the runtime of the .NET Framework. The CLR handles memory allocation and management. The CLR is also a virtual machine that not only executes apps but also generates and compiles code on-the-fly using a JIT compiler. The current Microsoft CLR implementation is Windows only. CoreCLR .NET Core Common Language Runtime. This CLR is built from the same code base as the CLR. Originally, CoreCLR was the runtime of Silverlight and was designed to run on multiple platforms, specifically Windows and OS X. CoreCLR is now part of .NET Core and represents a simplified version of the CLR. It's still a cross platform runtime, now including support for many Linux distributions. CoreCLR is also a virtual machine with JIT and code execution capabilities. CoreFX .NET Core Base Class Library (BCL) A set of libraries that comprise the System.* (and to a limited extent Microsoft.*) namespaces. The BCL is a general purpose, lower-level framework that higher-level application frameworks, such as ASP.NET Core, build on. The source code of the .NET Core BCL is contained in the CoreFX repository. However, the majority of the .NET Core APIs are also available in the .NET Framework, so you can think of CoreFX as a fork of the .NET Framework BCL. CoreRT .NET Core runtime. In contrast to the CLR/CoreCLR, CoreRT is not a virtual machine, which means it doesn't include the facilities to generate and run code on-the-fly because it doesn't include a JIT. It does, however, include the GC and the ability for runtime type identification (RTTI) and reflection. However, its type system is designed so that metadata for reflection isn't required. This enables having an AOT tool chain that can link away superfluous metadata and (more importantly) identify code that the app doesn't use. CoreRT is in development. See Intro to .NET Native and CoreRT ecosystem All of the runtime software, development tools, and community resources that are used to build and run applications for a given technology. The term ".NET ecosystem" differs from similar terms such as ".NET stack" in its inclusion of third-party apps and libraries. Here's an example in a sentence: - "The motivation behind the .NET Standard is to establish greater uniformity in the .NET ecosystem." framework In general, a comprehensive collection of APIs that facilitates development and deployment of applications that are based on a particular technology. In this general sense, ASP.NET Core and Windows Forms are examples of application frameworks. See also library. The word "framework" has a more specific technical meaning in the following terms: In the existing documentation, "framework" sometimes refers to an implementation of .NET. For example, an article may call .NET Core a framework. We plan to eliminate this confusing usage from the documentation. GC Garbage collector. The garbage collector is an implementation of automatic memory management. The GC frees memory occupied by objects that are no longer in use. See Garbage Collection. IL Intermediate language. Higher-level .NET languages, such as C#, compile down to a hardware-agnostic instruction set, which is called Intermediate Language (IL). IL is sometimes referred to as MSIL (Microsoft IL) or CIL (Common IL). JIT Just-in-time compiler. Similar to AOT, this compiler translates IL to machine code that the processor understands. Unlike AOT, JIT compilation happens on demand and is performed on the same machine that the code needs to run on. Since JIT compilation occurs during execution of the application, compile time is part of the run time. Thus, JIT compilers have to balance time spent optimizing code against the savings that the resulting code can produce. But a JIT knows the actual hardware and can free developers from having to ship different implementations. implementation of .NET An implementation of .NET includes the following: - One or more runtimes. Examples: CLR, CoreCLR, CoreRT. - A class library that implements a version of the .NET Standard and may include additional APIs. Examples: .NET Framework Base Class Library, .NET Core Base Class Library. - Optionally, one or more application frameworks. Examples: ASP.NET, Windows Forms, and WPF are included in the .NET Framework. - Optionally, development tools. Some development tools are shared among multiple implementations. Examples of .NET implementations: library A collection of APIs that can be called by apps or other libraries. A .NET library is composed of one or more assemblies. The words library and framework are often used synonymously. metapackage A NuGet package that has no library of its own but is only a list of dependencies. The included packages can optionally establish the API for a target framework. See Packages, Metapackages and Frameworks Mono An open source alternative to the .NET Framework. Mono started around the same time the .NET Framework was first released. Since the .NET Framework wasn't open source, Mono was forced to start from scratch and is thus a complete re-implementation of the .NET Framework with no shared code. When .NET Core was released under the MIT license, Microsoft also released large chunks of the .NET Framework under the MIT license as well. This enabled the Mono community to use the same code the .NET Framework uses in order to close gaps and avoid behavioral differences. Mono is primarily used to run .NET applications on Linux and macOS. There are ports of Mono to other platforms; see Mono's Supported Platforms. Mono has implementations (though not necessarily complete) of WinForms, ASP.NET, and System.Drawing. .NET The umbrella term for .NET Standard and all .NET implementations and workloads. Always capitalized, never ".Net". See the .NET Guide .NET Core A cross-platform, high-performance, open source implementation of .NET. Includes the Core Common Language Runtime (CoreCLR), the Core AOT Runtime (CoreRT, in development), the Core Base Class Library, and the Core SDK. .NET Core CLI A cross-platform toolchain for developing .NET Core applications. See .NET Core command-line interface (CLI) tools. .NET Core SDK A set of libraries and tools that allow developers to create .NET Core applications and libraries. Includes the .NET Core CLI for building apps, .NET Core libraries and runtime for building and running apps, and the dotnet executable (dotnet.exe) that runs CLI commands and runs applications. See .NET Core SDK Overview. .NET Framework An implementation of .NET that runs only on Windows. Includes the Common Language Runtime (CLR), the Base Class Library, and application framework libraries such as ASP.NET, Windows Forms, and WPF. See .NET Framework Guide. .NET Native A compiler tool chain that produces native code ahead-of-time (AOT), as opposed to just-in-time (JIT). Compilation happens on the developer's machine similar to the way a C++ compiler and linker works. It removes unused code and spends more time optimizing it. It extracts code from libraries and merges them into the executable. The result is a single module that represents the entire app. UWP was the first application framework supported by .NET Native. Now, we support building native console apps for Windows, macOS, and Linux. See Intro to .NET Native and CoreRT .NET Standard A formal specification of .NET APIs that are available in each .NET implementation. The .NET Standard specification is sometimes called a library in the documentation. Because a library includes API implementations, not only specifications (interfaces), it's misleading to call .NET Standard a "library." We plan to eliminate that usage from the documentation, except in reference to the name of the .NET Standard metapackage ( NETStandard.Library). See .NET Standard. NGEN Native (image) generation. You can think of this technology as a persistent JIT compiler. It usually compiles code on the machine where the code is executed, but compilation typically occurs at install time. package A NuGet package — or just a package — is a .zip file with one or more assemblies of the same name along with additional metadata such as the author name. The .zip file has a .nupkg extension and may contain assets, such as .dll files and .xml files, for use with multiple frameworks and versions. When installed in an app or library, the appropriate assets are selected based on the target framework specified by the app or library. The assets that define the interface are in the ref folder, and the assets that define the implementation are in the lib folder. platform An operating system and the hardware it runs on, such as Windows, macOS, Linux, iOS, and Android. Here are examples of usage in sentences: - ".NET Core is a cross-platform implementation of .NET." - "PCL profiles represent Microsoft platforms, while the .NET Standard is agnostic to platform." The .NET documentation frequently uses ".NET platform" to mean either an implementation of .NET or the .NET stack including all implementations. Both of these usages tend to get confused with the primary (OS/hardware) meaning, so we plan to eliminate these usages from the documentation. runtime The execution environment for a managed program. The OS is part of the runtime environment but is not part of the .NET runtime. Here are some examples of .NET runtimes: - Common Language Runtime (CLR) - Core Common Language Runtime (CoreCLR) - .NET Native (for UWP) - Mono runtime The .NET documentation sometimes uses "runtime" to mean an implementation of .NET. For example, in the following sentences "runtime" should be replaced with "implementation": - "The various .NET runtimes implement specific versions of .NET Standard." - "Libraries that are intended to run on multiple runtimes should target this framework." (referring to .NET Standard) - "The various .NET runtimes implement specific versions of .NET Standard. … Each .NET runtime version advertises the highest .NET Standard version it supports …" We plan to eliminate this inconsistent usage. stack A set of programming technologies that are used together to build and run applications. "The .NET stack" refers to the .NET Standard and all .NET implementations. The phrase "a .NET stack" may refer to one implementation of .NET. target framework. For some target frameworks (for example, the .NET Framework) the available APIs are defined by the assemblies that a .NET implementation installs on a system, which may include application framework APIs (for example, ASP.NET, WinForms). For package-based target frameworks (such as .NET Standard and .NET Core), the framework APIs are defined by the packages installed in the app or library. In that case, the target framework implicitly specifies a metapackage that references all the packages that together make up the framework. See Target Frameworks. TFM Target framework moniker. A standardized token format for specifying the target framework of a .NET app or library. Target frameworks are typically referenced by a short name, such as net462. Long-form TFMs (such as .NETFramework,Version=4.6.2) exist but are not generally used to specify a target framework. See Target Frameworks. UWP Universal Windows Platform.. UWP provides many services, such as a centralized app store, an execution environment (AppContainer), and a set of Windows APIs to use instead of Win32 (WinRT). Apps can be written in C++, C#, VB.NET, and JavaScript. When using C# and VB.NET, the .NET APIs are provided by .NET Core. See also .NET Guide .NET Framework Guide .NET Core ASP.NET Overview ASP.NET Core Overview
https://docs.microsoft.com/en-us/dotnet/standard/glossary
CC-MAIN-2017-34
refinedweb
2,109
61.33
How to compile the example "facerec_video.cpp"? Hello. I got some problems to compile the example "Face Recognition in Videos with OpenCV" (problem with facerec_video.cpp). The problem is that i don't understand where is the "include files" #include "opencv2/core.hpp" #include "opencv2/face.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/objdetect.hpp" I installed opencv-2.4.9. Is this the problem? In /usr/local/include i found the opencv2 folder with all the header files. Really there was some differences: core.hpp was in opencv2/core/core.hpp, highgui.hpp in opencv2/highgui/highgui.hpp and so on but can't find face.hpp. Help me please! hi andrei, put you entire code once then easy to found where is problem, and in your question there is ambiquity too..
https://answers.opencv.org/question/43615/how-to-compile-the-example-facerec_videocpp/
CC-MAIN-2021-43
refinedweb
137
64.57
Wednesday 9 March 2011 The Django development server is great: it comes in the box, serves Django, auto-restarts on source code changes, and now even color-codes the log lines based on the status returns. But it isn't multi-threaded, which normally wouldn't be a problem for a development server, unless you're writing Ajax interactions, and these days, who isn't? The Django team has declared that they will not offer a multi-threaded development server, for good or bad, so we are left to our own devices. James Aylett wrote django_concurrent_test_server which offers multi-threading and forking, though I haven't tried it. David Cramer offers django-devserver which seems to offer a number of interesting new logging options also. Many developers simply use other "real" web servers, like Apache or gunicorn, but those don't detect code changes, and often don't provide stdout for debugging with. I wanted multi-threading on a project but I didn't want to use a big real web server, and didn't want to install a new Django app and modify settings.py, so I adapted the patch from the closed Django bug ticket to create threadedmanage.py: #!/usr/bin/env python# # A clone of manage.py, with multi-threadedness monkeypatched in.import os, sysfrom django.core.management import execute_managertry: import settings # Assumed to be in the same directory.except ImportError: sys.stderr.write( "Error: Can't find the file 'settings.py' in the directory containing %r. " "It appears you've customized things.\n" "You'll have to run django-admin.py, passing it your settings module.\n" "(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__ ) sys.exit(1)def monkey_patch_for_multi_threaded(): # This monkey-patches BaseHTTPServer to create a base HTTPServer class that # supports multithreading import BaseHTTPServer, SocketServer OriginalHTTPServer = BaseHTTPServer.HTTPServer class ThreadedHTTPServer(SocketServer.ThreadingMixIn, OriginalHTTPServer): def __init__(self, server_address, RequestHandlerClass=None): OriginalHTTPServer.__init__(self, server_address, RequestHandlerClass) BaseHTTPServer.HTTPServer = ThreadedHTTPServerif __name__ == "__main__": monkey_patch_for_multi_threaded() execute_manager(settings) Now I can run "./threadedmanage.py runserver .." and get the standard development server, but with multiple threads. The usual caveats apply: This isn't a real web server, don't use it in production. Your code likely has threading issues, please fix them. I'm pretty sure there are good reasons not to use this code, but it's working well for me. A couple of your comments about inability to do certain things seem to perhaps be aimed squarely at Apache/mod_wsgi. Neither of them though is necessarily accurate or not telling the full story. Prior to mod_wsgi version 3.0, it did indeed by default block writing to stdout for logging. This was because doing so breaks WSGI application portability. Okay, it was only CGI/WSGI bridges that were the problem, but the intent was to still try and get people not to include debugging statements which would effectively preclude use of CGI. This restriction could be disabled in a number of ways, but all the same, overall people seemed not to care or were lazy and instead just complained about the restriction rather than fix their code. As such the restriction was removed in mod_wsgi 3.0 and you can write as much non portable code as you want. See: As to code reloading, this doesn't apply just to Apache/mod_wsgi, but for Apache/mod_wsgi, although it is not the default, it is possible to enable code reloading on all code changes. Thus it can be used during development, with either multithreaded or multiprocess configurations. The only restriction here is that you must use daemon mode on UNIX systems and cant use embedded mode. You also need to hook in a bit of monitoring code to enable this ability. See: Doing development inside of Apache/mod_wsgi using this feature not only allows you to make use of multithreaded or multiprocess configurations, it also avoids problems where stuff works in the development server and not in production due to the fact that the development server preloads a lot of stuf where as real WSGI servers, because of how the Django WSGI interface works, lazily loads stuff. This time and time again seems to cause problems for people around order of Python module imports and import cycles. Thus there is quite a bit of sense to the argument of using Apache/mod_wsgi during development and not just in production or a staging/test environment. See: The stderr message about settings.py always bites me. Django tends to import the whole world so an ImportError anywhere gives the settings.py message. I'd rather see the actual ImportError. We assume people arent idiots, and our standard manage.py looks something like this: try: import settings # Assumed to be in the same directory. except ImportError, exc: import sys import traceback.stderr.write("\nFor debugging purposes, the exception was:\n\n") traceback.print_exc() sys.exit(1) 2011, Ned Batchelder
http://nedbatchelder.com/blog/201103/quick_and_dirty_multithreaded_django_dev_server.html
CC-MAIN-2015-11
refinedweb
823
57.77
微软Office的源代码样式规范(上) —— 绝对机密文档!!! Office Source Code Style Guide Dave Parker, 6/30/95 Abstract This document outlines a general style guide for C and C++ source code in Office Development. The main purpose here is to list features of C++ which we will use and which we will avoid, along with the basic rationale for doing so. There are also standards for basic coding issues for the sake of consistency within the code and robust constructs. This is not a complete list of C/C++ language features with commentary. Rather, it mentions only the issues we consider important. Knowledge of C++ is assumed. Contents 1. GENERAL GOALS 3 2. CLASSES 3 2.1 CLASS VS. STRUCT 4 2.2 PUBLIC, PRIVATE, AND PROTECTED MEMBERS 4 2.3 DATA MEMBERS 4 2.4 VIRTUAL FUNCTIONS 5 2.5 CONSTRUCTORS 5 2.6 DESTRUCTORS 6 2.7 NEW AND DELETE 7 2.8 OPERATORS 7 2.9 INHERITANCE 8 2.9.1 Inheritance of Interface vs. Implementation 8 2.9.2 Inheritance vs. Containment 10 2.9.3 Multiple Inheritance 11 3. OTHER C++ FEATURES 11 3.1 CONSTANTS AND ENUMERATIONS 12 3.2 REFERENCES 12 3.3 CONST PARAMETERS AND FUNCTIONS 13 3.4 DEFAULT ARGUMENTS 13 3.5 FUNCTION OVERLOADING 14 3.6 OPERATOR OVERLOADING 14 4. COMMON C/C++ ISSUES 14 4.1 #IFDEFS 14 4.2 GLOBAL VARIABLES 15 4.3 MACROS AND INLINE FUNCTIONS 16 4.4 OPTIMIZATION 16 4.5 WARNINGS 17 4.6 PRIVATE DATA AND FUNCTIONS 17 4.7 TYPEDEFS 17 4.8 BASIC DATA TYPES 17 4.9 POINTERS 18 4.10 SWITCH STATEMENTS 19 4.11 ASSERTS 19 4.12 ERRORS AND EXCEPTIONS 19 5. FORMATTING CONVENTIONS 20 5.1 NAMING CONVENTIONS 20 5.2 FUNCTION PROTOTYPES 21 5.3 VARIABLE DECLARATIONS 22 5.4 CLASS DECLARATIONS 22 5.5 COMMENTS 23 5.5.1 File Headers and Section Separators 23 5.5.2 Function Headers 24 5.5.3 In-Code Comments 25 5.5.4 Attention Markers 25 5.6 MISC. FORMATTING CONVENTIONS 26 5.7 SOURCE FILE ORGANIZATION 27 5.7.1 Public Interface Files 27 5.7.2 Private Interface Files 28 5.7.3 Implementation Files 28 5.7.4 Base Filenames 29 6. INTERFACES TO DLLS 29 6.1 C FUNCTIONS AND GLOBAL VARIABLES 29 6.2 COMMON C/C++ PUBLIC HEADER FILES 29 6.3 LIGHTWEIGHT COM OBJECTS AND ISIMPLEUNKNOWN 30 7. APPENDIX A: BASIC HUNGARIAN REFERENCE 33 7.1 MAKING HUNGARIAN NAMES 33 7.2 STANDARD BASE TAGS 33 7.3 STANDARD PREFIXES 34 7.4 STANDARD QUALIFIERS 35 1. General Goals C++ is a complex language that provides many ways to do things, and going 搘hole hog” on all of its features can lead to confusion, inefficiency, or maintenance problems. All Office developers need to become experts on the features we will use, and avoid the others in order to form solid conventions within the group that we are all comfortable with. Our use of C++ features will be fairly conservative. We抎 much rather err on the side of just dealing with C, which we抮e all used to, then screwing up our app with a new concept that not all of us are used to. Underlying the choice of all of the style decisions are a few basic goals, as listed below. When in doubt about a particular issue, always think about the spirit of these goals. Sometimes these goals will conflict, of course, and in these cases we try to either prioritize the tradeoffs or use experience (either our own or from other groups that have used C++ extensively). 1. Simplicity. When in doubt, keep it simple. Bugs are related mostly to complexity, not code. 2. Clarity. The code should do what it looks like it抯 doing. Other people need to be able to understand your code. 3. Efficiency. Speed and size are important. Using C++ does not imply big and slow. There are plenty of perfectly reasonable ways to make things as fast or faster than the normal C way. Speed and size often trade off, and most people probably err on the side of choosing speed too often. Remember that 20% of the code is responsible for 80% of the time. In most cases, we抮e more concerned about fitting comfortably in less RAM. 4. Appropriateness. Use the language construct that is appropriate for the abstraction or operation you are trying to do. Do not abuse the language. Don抰 use a construct just because it happens to work. Definitely don抰 use a strange construct to amaze and confuse your friends to try to show how smart you are. 5. Natural transition from C to C++. We all used to be C programmers. Others that look at our code are still C programmers (e.g. Word and Excel). When possible, avoid C++ constructs where a C programmer抯 instinct causes a wrong assumption. 6. Catch Errors Early. Having the compiler catch an error is ideal. Having debug code (e.g. Asserts) catch it is the next best thing, etc. Declare things in such as way as to give the compiler the best chance at catching errors. 7. Fast builds. Total generality and modularity can cause lots of inter-dependencies between files, which can have a dramatic impact on build times. This is a constant time sink for everyone. It is often worth rearranging things a little to make incremental builds faster. 8. Consistency. The whole point of having a style guide is that programmers are never totally autonomous, even when the group has strong code ownership. Other people need to read and understand your code. Everyone has to give a little to have a consistent style guide, but everyone gains it back when they read or debug other people抯 code. 2. Classes C++ classes are a nice way to encapsulate code and data into a single unit, which provides a good paradigm for object-oriented implementations as well other features such as flexible access control, convenient and type-safe polymorphism, and the possibility of code reuse via inheritance. At the most general, classes are an extension to the built-in typing of C which allows you to define your own types along with the operations on that type. Taken to the extreme, every piece of data in a program could be an instance of a class. However, we will not go nearly this far in Office. We will use classes when there is a good reason to, such as the concept being implemented is inherently object-oriented or polymorphism is required. It has been the experience of many people that programs that use classes for everything evolve into systems that are complex and inefficient. Although this may not be the fault of any particular class, complex class hierarchies can lead to needless complexity, and overly abstracted concepts can easily lead to inefficiency. In general, we will avoid allocating classes on the stack and passing classes by value, because this is where the use of constructors and destructors gets you into the most trouble. Most classes should be allocated via new, freed by delete, and passed by pointer. In addition, we will never declare a global variable which is an instance of a class that has a constructor, because this causes a bunch of C runtime stuff to get linked in and stuff to happen at boot time to construct the thing, which is a big performance hit. Using only heap-allocated classes implies we抣l probably use classes only for relatively complex objects that you would normally have in the heap anyway, not simple things like basic data types. Beyond this, it is a judgment call when to use a class. Use one if there is a good reason, but not if a more straightforward solution is just as good. Summary: Use classes to encapsulate the implementation of an object-oriented concept. Use classes to implement polymorphism. Avoid allocating class instances on the stack and passing them by value. Use new and delete, and pass them by pointer. This implies not using classes for simple data types. Never declare a global instance of a class that has a constructor. Not everything is as class. Use them only when you gain something. 2.1 Class vs. Struct In C++, a struct can also have member functions and operators and everything else that a class can have. In fact, the only difference between a class and a struct is that all members default to public access in a struct but private access in a class. However, we will not use this as the deciding point between using a class vs. a struct. To match the normal intuition, we will use a class if and only if there are member functions included. Summary: Use a class instead of a struct if and only if there are member functions. 2.2 Public, Private, and Protected members As stated above, structs default to public access and classes default to private access. However, we will depend on the default only in the case of structs (where we leave all the data implicitly public). For a class, we will declare all members (both data and code) explicitly as public, protected, or private, and group them into sections in that order. For example: class Foo { public: Foo(); ~Foo(); void Hey(int I); void Ack(); protected: int m_iValue; private: int m_iStuff; void LocalHelperSub(); }; Summary: Declare all class members explicitly as public, protected, or private, in groups in that order. 2.3 Data Members Data members should use the naming convention m_name where name is a normal Hungarian local variable name. This makes member function implementations easier to read (no confusion about member vs. local data), and allows the use of the same Hungarian name for, e.g., parameters and members. See the example below. Data members should normally not be declared public because this usually defeats the purpose of the class abstraction. To efficiently export a data member, declare inline get and set member functions. This will get optimized into the same code as a public data member. For example: class Counter { public: int CItems() const { return m_cItems; } void SetCItems(int cItems) { m_cItems = cItems; } private: int m_cItems; }; Summary: Data members use the naming convention m_name. Do not declare public data members. Use inline accessor functions for performance. 2.4 Virtual Functions Virtual functions are used to allow derived classes to override a method in a base class by providing their own implementation in a way that always causes the most-derived version to be called whenever a method is called through an object pointer, even if that pointer is declared as a pointer to the base class. This is usually done to implement polymorphism, and that抯 when we抣l use them. For example, all COM interface methods are virtual because you are always going for polymorphism via a standard interface. Unlike simple member functions, virtual functions incur some overhead due to need to call through the vtable. If a class contains at least one virtual function then the data size of each instantiated object will be 4 bytes larger than the combined size of the declared data in order to hold the vtable pointer. After the first virtual function, each additional one only adds another entry to the class vtable, which is static and per-class (nothing per object), so the main concern here is whether a class has any virtual functions at all. In addition to the memory overhead, there is the overhead to indirect a pointer twice before calling the function. This is fairly fast and compact in 32-bit code, but affects speed and size nevertheless. Perhaps the worst part is that virtual functions cannot be inlined, so there will always be a function call, even when the work is trivial. Because they have overhead, you should not use virtual functions in a class unless you need to. However, make sure you do use them when it makes sense. In particular, if you have a base class which requires a destructor, then the destructor should definitely be virtual to allow derived classes to destruct any added members properly. If the destructor were not virtual, then in a context where polymorphism is being used (so the object pointer is declared as a pointer to the base class), the base class destructor will always get called, even for an object of a derived class that added data members and declared its own destructor in an attempt to free them. The derived class抯 destructor will only get called if the base class destructor is declared virtual. This scenario applies to many other kinds of methods that you will add to your classes. In fact, most of the methods in a base class might be this way if polymorphism is intended. This issues is discussed in more detail in the Inheritance section below. Note that although virtual functions have a performance penalty over regular member functions, they are often the most efficient way to implement a concept such as polymorphism where the alternative would be large switch statements (not to mention the benefits of the object-oriented encapsulation). Summary: Use virtual functions to implement polymorphism. Virtual functions have overhead, so don抰 use them unless you really should. A destructor in a base class should always be virtual if polymorphism is intended. 2.5 Constructors Ah, constructors. Every new C++ programmer抯 nightmare. This is one reason to try to minimize the use of constructors -- C programmers aren抰 used to them and will get confused. Another reason is the infamous performance overhead of calling a function (unless it抯 inline) and doing work at possibly unexpected and/or redundant times. However, using constructors can eliminate the dangers of uninitialized data and can also made the code simpler to read (if you抮e used to it). Judicious use of destructors (see below) which match the constructors can also help prevent memory leaks and other resource management problems. Fortunately, the issue is mainly one when classes are declared on the stack or passed by value, both of which we will avoid. Most of our classes should be dynamic memory objects which will be passed around by pointer. In this case, the constructor is essentially just a helper function for the functions that create these dynamic objects. Using a constructor for this purpose is reasonable to ensure a clean and consistent initialization (if you make sure to initialize all data members), but to prevent potential performance problems due to redundant initialization the constructor should not do anything expensive. Simply assigning a constant or a parameter value to each data field is about right. Very simple constructors can be made inline. Most importantly, a constructor should never be able to fail, because lacking a fancy exception handling mechanism, the caller has no way to handle this in some cases. Any initialization that can fail (e.g. memory allocations) should be put in a separate initialization member function (called, e.g., FInit). When this is the case, it is often useful to encapsulate the creation of an object in a function (a global function or a member of another class) that calls new and then FInit for the object, and returns the result of FInit. For example: class Foo { public: Foo(int cLines) { m_hwnd = NULL; m_cLines = cLines} virtual ~Foo(); BOOL FInit(); void DoSomething(); private: HWND m_hwnd; int m_cLines; }; BOOL FCreateFoo(int cLines, Foo **ppfoo) { if ((*ppfoo = new Foo(cLines)) == NULL) return FALSE; if (*ppFoo->FInit()) return TRUE; delete *ppFoo; *ppFoo = NULL; return FALSE; } BOOL Foo::FInit() { m_hwnd = CreateWindow(...); return (m_hwnd != NULL); } Summary: Do not do expensive work in a constructor. If you do make a constructor, make sure to initialize all data members. Very simple constructors can be made inline A constructor should never fail. Do memory allocations and other potential failures in an FInit method. Consider making a creation function that encapsulates the new and FInit operations. 2.6 Destructors If a class has resources that need to be freed, then the destructor is a convenient place to put this. The normal case for us will be that this is just the central place to free resources for an object that is freed via delete (see below). The trickier use of destructors is for stack-allocated classes, but we抮e going to avoid that by not using classes on the stack. A destructor should be careful to destroy an object properly regardless of how it was created or used. Furthermore, if you choose to implement a method that frees any resources before the actual destruction, make sure to reset those fields (e.g. set pointers to NULL) so that a destructor will not try to free them twice. It is not necessary for the destructor to reset any fields, though, because the object cannot be used after it is destructed. Like a constructor, a destructor can never fail. Also, as stated above, a destructor in a base class should always be declared virtual to make polymorphism work. The destructor for the above example would be defined as: Foo:~Foo() { if (m_hwnd != NULL) DestroyWindow(m_hwnd); } Summary: Use a destructor to centralize the resource cleanup of a class which is freed via delete. If resources are freed before destruction, make sure the fields are reset (e.g. set pointers to NULL) so that a destructor will not try to free them again. A destructor should never fail. A destructor in a base class should always be declared virtual if polymorphism might be used. 2.7 New and The operators new and delete should be used to allocate and free classes (instead of the low-level malloc-like function in your app) so that the constructor and destructor, if any are called properly. We will implement our own global new and delete so that they in turn call our favorite low-level memory manager, so the only difference is really that new does the sizeof automatically and also calls a constructor, and delete calls the destructor. Note that there must be some mechanism for detecting failed memory allocations. For new, the calling code is responsible for checking. Our memory manager simply returns 0 for a failed allocation, and this will in turn be returned from new (and the constructor will not be called). It is therefore up to the caller of new to check for a 0 return value, as in the example above in the Constructors section. You should avoid defining any other new and delete (i.e. class-level) operators and stick to the global one to avoid mixed memory models, which complicates things like help optimization and memory leak checking and makes it risky to have the routines that allocate and free a block be different (although this is normally bad structure anyway). Summary: Use new and delete to allocate and free classes. We will implement our own global new and delete in terms of the Office infrastructure memory manager. Check the return value of new for failure. Avoid defining any other new and delete operators (use the global ones defined by Office). 2.8 Operators Ideally, you will never need to define an operator for a class. If you did one, it might be operator=, but don抰 define one unless you really think you want this capability. Next might be operator== and operator!=, but the same applies here, only define them if really needed. We抮e not in the business of providing a general class library that might be used in a certain way, we抮e just implementing code that we actually expect to use ourselves (as explained in a later section, we will not export a real C++ class to anyone). And if you do define these operators, make sure they are efficient so that you are not hiding an expensive operation. By all means, never define standard operators such as operator+ to do anything other than the standard semantics for built-in objects. Don抰 even push it by doing things like defining, say, operator+ to do a union or concatenation operation. In addition to causing confusion, this hides potentially expensive work behind an innocent-looking operator. Summary: Ideally, classes shouldn抰 need to define any operators. Define 搑easonable” operators such as =, ==, and != only if you really want and use this capability yourself, and if you do they should be super-efficient (ideally inline). Never define an operator to do anything other than the standard semantics for built-in types. Never hide expensive work behind an operator. If it抯 not super efficient then make it an explicit method call. When in doubt, just make a member function to do the work so that the operation is explicit. 2.9 Inheritance Inheritance is a powerful technique, but it is often misused and can lead to complex class hierarchies that are hard to understand and hard to change. The following sections describe the various uses of inheritance, compare them to other techniques and try to provide rules of thumb about when to use it. Beyond being appropriate in a particular case, however, just because inheritance can be appropriate does not mean it should be used everywhere. A deep or wide inheritance tree gets hard to understand, hard to browse, and eventually hard to maintain. Keep inheritance limited to a few 搒ilver bullets” where you really win from it. Summary: Don抰 use inheritance just because it will work. Use it sparingly and judiciously. 2.9.1 Inheritance of Interface vs. Implementation Most people think about inheritance as a way to share code. However, one of the most useful ways to use it is simply as a way to ensure working polymorphism by inheriting interface only. The classic example is to have an interface class which is entirely abstract (all methods are pure virtual), and then one or more implementation classes that inherit the interface and implement it in different ways. The OLE COM model is an example of this. A COM interface is expressed in C++ as an abstract base class, and then a separate implementation class inherits from the interface class and implements the interface methods for that object. Here the inheritance is simply a convenient way to ensure that the object speaks the exact interface it is supposed to (has the right methods in the right order in the vtable with the right parameters and the right return types). This is ensured by having each implementation class inherit from the same interface class, which is only declared once in a common header file. Note than when an interface class implements an inherited pure virtual method, it must redeclare it because from a language point of view, it is still considered to 搊verride” the base method. For example: // The interface base class provides interface only class FooInterface { public: virtual void DoThis() = 0; // pure virtual virtual void DoThat(int i) = 0; // pure virtual }; // The implementation class implements the FooInterface interface class FooImplementation: public FooInterface { public: virtual void DoThis(); virtual void DoThat(); } void FooImplementation::DoThis() { ... } ... The above example shows the case where the entire base class is interface only. However, inheritance of interface only can also happen at the level of an individual member function in a base class which also includes some implementation. This is the case when any member function is declared pure virtual. An example of this is shown below with the DrawObj::Draw method. The above example does not use inheritance to share code. However, inheritance can also be used for this, and this is done by providing implementations of methods in a base class that inherited classes can use. There are two interesting cases here. If the base class defines an implementation of a method which can either be used or overridden, then the base method is defining an interface with a default implementation. In this case, the method should be defined as virtual so that any class which overrides the method will get the right result when polymorphism is used. Alternately, if the base class method provides an implementation of a method which is not meant to be overridden (because it does a standard action on data which is private to the base class), then the base method is defining an interface and a required implementation. In this case, the method should not be declared virtual. The converse of this is that when inheriting from a class, do not override any non-virtual functions because this could lead to maintenance problems when the base class is changed. In general, the two cases of inheritance of implementation outlined above as well as the case of inheritance of interface only can all be combined in a single class by having different methods do different things. The key is to decide, for each method, whether the goal of the base method is to provide interface only, interface plus default implementation, or interface plus required implementation. For example: // A base class for drawing objects class DrawObj { public: virtual void Draw() = 0; // interface only virtual BOOL FHitTest(POINT pt); // default implementation void GetBounds(RECT *pr); // required implementation private: Rect m_rBounds; // bounding rectangle }; BOOL DrawObj::FHitTest() { return PtInRect(pt, m_rBounds); } void DrawObj::GetBounds(RECT *pr) { *pr = m_rBounds; } In this example, the Draw method is pure virtual because it is only specifying an interface for polymorphic use. Any derived class that can be instantiated must define the Draw method. The FHitTest method is defining interface (for polymorphism) as well as a default implementation. Any derived classes that don't need non-rectangular hit-testing can just use the default implementation (no code or declaration required), but other classes can simply override this method and do special hit-testing. The GetBounds method is an example of a required implementation. The base class requires that "bounds" be defined in the same way for all objects, and it doesn't make sense for anyone to change it. In this case, the member does not need to be virtual (and should not be for clarity and efficiency) because the base class implementation is always used. Summary: Inheritance of interface can be used for ensuring a consistent (e.g. polymorphic) interface. An implementation class can inherit its interface from an interface class where the interface class has only pure virtual methods. When using inheritance of implementation to share code in a base class, Use pure virtual functions to provide interface only. Use virtual functions to provide interface and a default implementation. Use non-virtual functions to provide interface and a required implementation. 2.9.2 Inheritance vs. Containment The most common misuse of inheritance is to view inheritance as a way to share code among 搒imilar” objects and to use it in a context where there is no real 搃s a” relationship. There are several ways to share code, and the simpler technique of containment and delegation (one class contains another and delegates the relevant functionality to it), which we抮e all used to from traditional structured programming, works fine in most cases. In this case, the relationship is described as 揾as a”. The primary reason to use inheritance instead of containment is to achieve polymorphism (in conjunction with the use of virtual functions). The easiest way to test for an 搃s a” relationship is to think whether polymorphism is what is desired. If so, then inheritance could be appropriate (assuming any other practical concerns are met). Another way to test 搃s a” vs. 揾as a” is to ask yourself if it could make sense to have more than one of the base class in the derived class. If so, then 揾as a” (containment) is the right model. For example, if you were implementing a scrolling window and you already have a scrollbar class, you would notice that a window could have two scrollbars (horizontal and vertical) even if you weren抰 planning on that feature in the first version, so a window should contain (揾as”) a scrollbar, not inherit from (搃s”) one. Even when you do decide to use inheritance from another class, it is often the case that you should split the original class into a base class and a derived class and inherit only from the base class. This allows you to split off only the stuff that is really shared. For example, say you had a Rectangle drawing object, and now you want an 揙val” object. You convince yourself that polymorphism is desired (e.g. drawing and hit-testing code in the caller wants to treat all objects the same), and that an Oval would never want two Rectangles. Now you might decide to have the Oval inherit from the Rectangle, but probably what you really want is to split the Rectangle class into a base DrawingObject class and a separated derived Rectangle class, and then Oval would inherit from DrawingObject, not Rectangle. This allows later changes to the Rectangle object that are specific only to it, even if this isn抰 needed now. As in the example from the previous section, the DrawingObject base class will probably have a combination of pure virtual methods to enforce the polymorphic interface, virtual methods to provide a standard interface as well as a default implementation for all 搒imple objects”, and non-virtual methods to provide required implementation of stuff that is common to all objects and assumed to be constant in the common code. Note that containment forces you to use the contained object抯 public interface, whereas inheritance allows use of protected members also. This is another way of saying that containment is more encapsulated than inheritance. In fact, it is often said that inheritance breaks encapsulation because it can create dependencies on the implementation of the base class. This is particularly true in the case of overridden functions, where a change to the base class might not have the right effect on all derived classes. Summary: Be careful with inheritance vs. containment. When in doubt, use containment. Inheritance is an 搃s a” relationship, whereas containment is a 揾as a” relationship. Test for 搃s a” by seeing if polymorphism is desired or makes sense. Test for 揾as a” by asking yourself if one class could ever use more than one of the other class. 2.9.3 Multiple Inheritance We will avoid multiple inheritance altogether. Multiple inheritance has a number of problems including resolution of name conflicts, efficiency concerns of some operations (functionality is hidden from you), maintenance problems, and general confusion about what the heck is going on. If you are building a large and complex inheritance hierarchy (to be avoided as noted above), you might find yourself wanting multiple inheritance to share code from two different places. In the case of literally sharing code from two different places, this is the most dangerous form of multiple inheritance because it leads to the trickiest dependencies. There are other forms of multiple inheritance, though. The safest is multiple inheritance of only interfaces (no code from any base class), but even this has problems with things like name conflicts. So, we will avoid it altogether. Every time you think you need multiple inheritance, you should consider that maybe you are over-using inheritance and you should switch to containment in some cases. Inheritance is a silver bullet that you have only one of. Once you抳e used it for a given class, you need to use containment to get anything else. Note that you can use containment as much as you want within a given class with no problems. Summary: Don抰 use multiple inheritance. Given only single inheritance, inheritance is a 搒ilver bullet” which you have only one of, so use it sparingly and judiciously. 3. Other C++ Features The following sections comment on various new features of C++ that aren抰 directly related to classes. 3.1 Constants and Enumerations C++ adds the concept of true constants to C. In C, you had the choice of using a #define or declaring a "const" global variable. However, the #define will not be type safe, and the const variable takes up real memory and isn't optimized. For example: // C alternatives: #define dxMin 0 // not type safe const DX dxMin = 0; // just a real global variable In C++, the const syntax declares a real constant of the specified type that the compiler will type-check, and then substitute the actual value in-line and optimize (fold constants, etc). As a bonus, the debugger will even know about this symbol. For example, // C++ solution: const DX dxMin = 0; // type safe, optimized, and debug symbol So true C++ constants are preferred to the traditional C++ #define. Note that they cannot be used in shared C/C++ header files, though, because a C compiler will just allocate memory for them. C++ also makes the existing C concept of an enum type safe. An enum in C++ defines a type and declares constants of that type. You can then use that type as, say, a parameter to a function, and the compiler can then enforce that you pass one of the symbols defined in the enumeration (or you can type cast to get around this if you need to). An enum can also be made local to a class so that its scope is limited. For example, class Foo { public: enum GMODE { gmNo = 0, gmYes = 1, gmMaybe = -1 }; void InsertGNode(GMODE gm); }; Summary: Use const or enum instead of #define for constants that are only used in C++. 3.2 References C++ adds the ability to express references to objects, and the primary use of them is to pass classes as parameters without the overhead of the copy constructor being called. This is a worthy goal, but a more straightforward method to do this is to just to pass classes by pointer, which is what we抮e all used to from C. For someone used to C, seeing something being passed by reference looks like it抯 being passed by value, so you might wonder if the constructor is being called, or whatever. Furthermore, when using a reference, the illusion is that you have a local copy of the object that you can reference cheaply, but in fact you just have a pointer to the object (this is how the compiler does it), and every access is an indirection. We should just make this indirection explicit by actually using pointers. Typing “*” or “->“ instead of “.” is not a big deal, and it makes it more clear what is going on. The one real advantage of references over pointers is that they are guaranteed to be initialized (they cannot be NULL or point to garbage). But this advantage is not worth the above problems for us. Also note that when you do pass objects by pointer, use const to mark formal parameters that are read-only (see the "Const" section below). This is related to references because some C++ programmers will use the convention that read-only objects are passed by references and other objects are passed by pointer (to make this safe you still need to the declare the reference const because C++ will let you change a parameter through a reference). This is a reasonable convention, but it still has the problem of looking foreign and confusing to programmers with a C background. So, we will use const to get the safety but pass every object by pointer. There are other more exotic uses of references, such as being able to return an lvalue from an operator function, and sometimes this is necessary if you've defined such an operator. But since we don抰 plan to use operators much if at all (because we won抰 use stack-based classes), we should be able to avoid references in most cases. Summary: Avoid references. Pass objects that are larger than an 搃nt” by pointer. 3.3 Const Parameters and Functions As mentioned above, you should use const to mark formal parameters that are read-only. This allows the compiler to check that you actually obey this, serves as a form of documentation to users of your function, and also allows the compiler to produce better code in some cases. For example: /* Copy the contents of 'fooSrc' into 'fooDst'. */ void CopyFoo(const FOO *fooSrc, FOO *fooDst); You can also declare non-pointer formal parameters as const (as well as the actual pointer portion of a pointer parameter, rather than what it points at, in which case the word "const" may appear twice for that parameter), but this is not as much of a win and it can make the prototype harder to read, so it's optional. This just makes sure that you don't reuse the parameter itself as a local variable and change its value. Of course, sometimes a function will do this as a way of avoiding declaring and setting up a local variable, so in this case you can't use const (not that this is not great programming style, but we're not going to disallow it). On the other hand, if you don't change the value of the parameter within the function, declaring it as const may allow the compiler to generate better code. Note that doing this does not give any useful documentation to the caller, though. For example: /* Copy 'cb' bytes of the contents of 'fooSrc' into 'fooDst'. In addition to not changing what 'fooSrc' points at, my implementation promises not to change the values of any of the local parameters within the function (like you care...). */ void CopyFooCb(const FOO *const fooSrc, FOO *const fooDst, const int cb); In addition to declaring parameters const, you can also declare a member function const to indicate that the function does not modify the object. Again, this allows compiler checks and possible optimization as well as a form of documentation. For example: class Counter { public: int CItems() const { return m_cItems; } void SetCItems(int cItems) { m_cItems = cItems; } private: int m_cItems; }; Summary: Use const to mark read-only pointer parameters (what the pointer points at, not the pointer itself). Use const to mark member functions that don't change the object Use const to mark parameters themselves only if you care about the possible performance gains in the implementation. 3.4 Default Arguments Having default arguments seems like a cool feature. It seems like a way to add a parameter which only some calls to a function will need to pass, so that the simple cases will be kept simple. Well unfortunately, there is no efficiency gain here, and instead the compiler is just hiding work from you. If you have a function with one required argument and four optional arguments, every call to this function will push all five arguments, so you are getting the code size and time hit in every case. Furthermore, you can抰 even use default arguments just to try something new without bothering with the old calls because you still have to find all the old calls in order to rebuild those files (if you do an incremental build of just one use after adding a default argument, the other calls will screw up). Finally, default arguments can be easily confused with overloading (which we抣l also avoid). There are cases, however, where a certain parameter is totally irrelevant in a call (because, for example, the value of another parameter tells you all you need to know). Note that this is somewhat different from a default argument because there is no real default value for this parameter. In these cases, it is nice to have the untyped constant "NA" , #defined to be 0, to stand for "Not applicable" which can be passed to indicate this for any actual parameter. This is better than passing, say, NULL for a pointer or FALSE for a Boolean because it makes it clear that the value is not important at all. For example: #define NA 0 // universal "not applicable" parameter value /* If fShow then show the object, else hide it. If showing then redraw it only if fRedraw. void Show(BOOL fShow, BOOL fRedraw); void Ack() { Show(TRUE, TRUE); ... Show(FALSE, NA); } Summary: Don't use default arguments. Use "NA" (#defined to be 0) for "not applicable" parameters in a call. 3.5 Function Overloading Overloading functions is just a lazy naming scheme. It seems like a form of polymorphism, but it shouldn抰 be confused with real polymorphism because all the decisions must be made staticly at compile time. It抯 just a way to keep 搒imple” function names and reuse them for different cases. Such a lazy naming scheme just causes more confusion than it抯 worth (trying to determine which function is relevant, changing the wrong one by accident, etc.) and can also interfere with proper use of Hungarian in some cases. Finally, the combination of function overloading and type coercion can be quite confusing indeed. Summary: Don抰 overload functions 3.6 Operator Overloading The main use of operators is in classes. This is discussed in a previous section. Operators can also be overloaded at global scope. For example, you can define what operator+ should do when it finds a Foo on the left side and a Bar on the right side. Unlike the use within a class, this allows control over the left-hand side operand. Anyway, all the same problems apply and more (due to the larger scope). Functionality is hidden (a possible efficiency problem) and confusion can result, so we will avoid this. Summary: Don抰 overload operators, especially at global scope. 4. Common C/C++ Issues The following sections comment of features of regular C that we also try to maintain a consistent use of. 4.1 #ifdefs First and foremost, everyone should try really hard to minimize the use of #ifdefs. Programs with lots of #ifdefs are really hard to read. It is often possible to either invent the right abstraction or to isolate the #ifdefs to small places in header files, or make the right definitions in target-specific headers so as to make #ifdefs unnecessary in the main code. The main argument for #ifdefs (over, say, a regular 搃f”) is to minimize the code size. However, everyone should be aware that the optimizer is perfectly capable of simplifying statements that evaluate to a constant. For example, // Wrong: #ifdef MAC if (x == 3 || Foo() || FSomeMacMode()) #else if (x == 3 || Foo()) #endif // Right: // In a header file for each non-Mac platform, there is #define FSomeMacMode() FALSE // Then the using code can just be if (x == 3 || Foo() || FSomeMacMode()) In this example, the compiler is perfectly capable of eliminating what amounts to (搢| FALSE”) at compile-time. Furthermore, if the entire "if" were to always evaluate to FALSE at compile time, then the optimizer will also remove all of the code inside the "if" and remove the test. If you must use an #ifdef, we prefer to use #if instead because it's shorter and allows logical operations, as in: int Foo() { int x = 3 #if MAC && !DEBUG x = 0; #endif return x; } Note that we will still leave flags such as DEBUG undefined when false, but the compiler does the right thing here (treats it the same as being defined to be 0). Leaving these flags undefined means that #ifdef will also work, in case this is used by accident anywhere. Also, as this example shows, #ifs should be properly indented so that they read easily when nested. Yes, this works; C Compilers have accepted this for years. Aside from the standard identifiers defined by our build process (e.g. DEBUG, MAC), we will also use the identifiers UNUSED and LATER, which are never defined, to mark code which is currently unused but kept in for some reason, and code which cannot be activated yet but will eventually, respectively. Summary: Minimize #ifdefs by defining good abstractions, partitioning files better, or defining appropriate constants or macros in header files for the compiler to figure out. Prefer #if over #ifdef. Indent an #if with the code so that it reads better when nested within others. Use #if UNUSED for code that is on longer used but kept in for some reason. Use #if LATER for code that cannot be used yet but will eventually. 4.2 Global Variables Global variables are usually bad programming style. More specifically, they are often trouble when used to cache 揷urrent” state because it is so easy to get them out of sync. Everybody knows this from their past experience, so there抯 no point in going into gory detail. In addition to these problems, globals make things such as multiple uses of a DLL in the same process, reentrancy, and multi-threading very hard to achieve, and we need to worry about all of these in Office. Due to the DLL/process/thread problem (all instances of the same DLL in a process as well as all threads share the same copy of the globals), most things that you might normally of as global should go in an instance data structure. In Office, this structure is the MSOINST struct, which is allocated and returned for each caller of MsoFInitOffice. When you do use a global (e.g. for data which is truly shared among all uses in a given process), use the Hungarian 搗” prefix before the type tag to make the global clear. Summary: Minimize global variables. Most per-client read/write storage should go in the MSOINST structure. Use the Hungarian 搗” prefix at the beginning of global variables. 4.3 Macros and Inline Functions In C++, what would be a functional or procedural macro in C is usually better expressed as an inline function because this makes it type safe and avoids problems with multiple evaluation of macro parameters. For example: #define XOutset(x) ((x) + 1) #define XMin(x1, x2) ((x1) < (x2) ? (x1) : (x2)) inline XY XOutset(XY x) { return x + 1; } inline XY XMin(XY x1, XY x2) { return x1 < x2 ? x1 : x2; } In addition, inline functions can be limited to the scope of a class if appropriate in order to make them more specific. Note that #define must still be used in public header files that are exported to C clients. Actually, some C compilers do implement inline functions (via __inline), though, so this may be possible in C also if all of your relevant compilers support it. When you do use #define to write functional macros with arguments, be sure to remember to enclose each instance of an argument in parentheses, and also the entire expression if necessary, to avoid precedence problems. Summary: Use inline functions instead of #define macros when possible. In functional macros, enclose all argument instances in parentheses as well as the entire expression if necessary. 4.4 Optimization Always know what code the compiler generates for your favorite constructs, and what things typically get optimized. Trying to hand-optimize your code can cause bugs and can also actually make the generated code worse. For example, introducing temporary variables may cause something that would have been pre-computed and cached in a register to be moved into a stack variable. It is worth it for everyone to play around with sample constructs, compile with /Fc, and look at the .cod file to see what gets generated. Finally, remember that the expanded code you see when debugging is not the optimized code; it is totally unoptimized for debugging purposes (e.g. to make it line up exactly with the source statements). Another issue to be aware of is that in order to get maximum benefit from our optimizer, we want to enable lots of different kinds of optimization. Some coding constructs can confuse the optimizer and cause bugs (for example, depending on subtle aliasing behavior). The rule of thumb here is that the more straightforward your code is, the better the optimizer will be able to improve it and the less chance of an optimization bug. This is always good practice anyway, because it makes your code easier for people too. Summary:
http://blog.csdn.net/silver/article/details/5461
CC-MAIN-2018-09
refinedweb
7,974
62.07
Getting started with OpenFaaS on minikube This is a guide on how to setup OpenFaaS — Serverless Functions Made Simple on Kubernetes 1.8 or later with minikube. minikube is a Kubernetes distribution which lets you run a Kubernetes cluster on your laptop — it’s available for Mac and Linux, but is most commonly used with MacOS. OpenFaaS in 2021: Quite a lot has changed since this blog post was written. KinD, Multipass and K3d all provide light-weight alternatives to local Kubernetes. Minikube is no longer the only option. Please try one of the following: Getting set up with Minikube on MacOS brew is a package manager for MacOS, you can use it to make installing packages quicker and easier. - Install minikube if you don’t already have it on your system. - Install the xhyve driver or VirtualBox which will be used to create a Linux VM for minikube. I find the VirtualBox option to be the most reliable. - Setup minikube using the official docs — make sure that you enable RBAC, too. - Install faas-cliusing curl -sL cli.openfaas.com | sudo shor brew - Install the helmCLI via brew: brew install kubernetes-helm - Start a local cluster: minikube start Docker Captain’s tip: get a more native experience with your Kubernetes development by using Docker for Mac and Kubernetes, read my first impressions here. Deploy OpenFaaS to minikube - Create namespaces for OpenFaaS core components and OpenFaaS Functions: kubectl apply -f - Add the OpenFaaS helm repository: helm repo add openfaas - Update all the charts for helm: helm repo update - Generate a random password: export PASSWORD=$(head -c 12 /dev/urandom | shasum| cut -d' ' -f1) - You may want to take a note of your password with echo $PASSWORDbefore continuing. - Create a secret for the password kubectl -n openfaas create secret generic basic-auth --from-literal=basic-auth-user=admin --from-literal=basic-auth-password="$PASSWORD" - Install OpenFaaS using the chart: helm upgrade openfaas --install openfaas/openfaas --namespace openfaas --set functionNamespace=openfaas-fn --set basic_auth=true - Set the OPENFAAS_URLenv-var export OPENFAAS_URL=$(minikube ip):31112 - Finally once all the Pods are started you can login using the CLI: echo -n $PASSWORD | faas-cli login -g -u admin — password-stdin You’ll now see the OpenFaaS pods being installed on your minikube cluster. Type in kubectl get pods -n openfaas to see them: NAME READY STATUS RESTARTS AGEalertmanager-6dbdcddfc4-fjmrf 1/1 Running 0 1mfaas-netesd-7b5b7d9d4-h9ftx 1/1 Running 0 1mgateway-965d6676d-7xcv9 1/1 Running 0 1mprometheus-64f9844488-t2mvn 1/1 Running 0 1m If you run into any issues you can follow the troubleshooting guide for Kubernetes with OpenFaaS or the helm installation guide. 30,000ft: The API Gateway contains a minimal UI for testing functions and exposes a RESTful API for function management. The faas-netesd daemon is a Kubernetes controller which connects to the Kubernetes API server to manage Services, Deployments and Secrets. Prometheus and AlertManager work in tandem to enable auto-scaling of functions to match demand. Prometheus metrics give you operational oversight and allow you to build powerful dashboards. Prometheus dashboard example: To get your own Grafana dashboard, see the OpenFaaS workshop at the end of the post. Build/ship/run OpenFaaS uses the Docker image format for the creation and versioning of functions which means that unlike many other FaaS projects you can use this in production to do: - vulnerability scanning - CI/CD - rolling upgrades You can also deploy OpenFaaS to your existing production cluster and make use of spare capacity. The core services require around 10–30MB of RAM each. A key advantage of OpenFaaS is that it works with the container orchestration platform’s API, which means we integrate natively with both Kubernetes and Docker Swarm. Also, since our functions are properly versioned within a Docker registry, we can scale our functions on demand without any additional latency associated with frameworks that build functions on demand. Scaffold a new function faas-cli new --lang python3 hello This will create hello.yml along with a handler folder containing your handler.py file and requirements.txt for any pip modules you may need. You can edit these at any time without worrying about maintaining a Dockerfile — we do that and use best practices: - multi-stage builds - non-root users - Official Docker Alpine Linux builds for the base (this is swappable) Build your function Your function will be built on your local machine and then pushed to a Docker registry. Let’s use the Docker Hub — just edit the hello.yml file and enter your user account name: provider: name: faas gateway:: hello: lang: python3 handler: ./hello image: alexellis2/hello Now invoke a build. You will need Docker on your local system. faas-cli build -f hello.yml Push the versioned Docker image which contains your function up to the Docker Hub. If you’ve not logged into the Docker hub then type in docker login before carrying on. faas-cli push -f hello.yml Once you have multiple functions you can use the --parallel=N flag to build or push with multiple cores at once. The CLI also supports options such as --no-cache and --squash. To save on typing you can also run faas-cli upwhich combines the build, pushand deploysteps in one single command. Deploy and test your function Now you can deploy your function, see it listed and invoke it. Each time you invoke the function we collect metrics which are made available through Prometheus. $ export gw=(minikube ip):31112$ faas-cli deploy -f hello.yml --gateway $gw Deploying: hello.No existing function to removeDeployed.URL: You are given a standard route for invoking the function in the deployment message, but can also use the CLI to save on typing: $ echo test | faas-cli invoke hello --gateway $gw Now list the functions deployed and you will see the invocation count has gone up. $ faas-cli list --gateway $gw Function Invocations Replicashello 1 1 Note: this command also accepts a --verbose flag for more information. Since we are running OpenFaaS on a remote cluster (a Linux VM) we set up a --gateway override environmental variable. This could also be a remote host on a cloud platform. The alternative is to update the gateway value in your .yml file. Moving beyond minikube Once you are familiar with OpenFaaS on minikube you can deploy to any Kubernetes cluster running on Linux hosts. Here’s an example of OpenFaaS running on Kubernetes on Google’s GKE platform by Stefan Prodan of WeaveWorks demonstrating the built-in auto-scaling capabilities: We’ve tested OpenFaaS with many different managed Kubernetes services — you can find instructions in the Kubernetes Deployment Guide. Keep learning We have dozens of guides and blog available to get you up and running on the “FaaS Train” — head over to GitHub and bookmark our guides: I’ve included a short 15min video from Dockercon 2017 in Copenhagen where I gave an overview of Serverless and OpenFaaS at the Moby Summit. - For all the latest hacks, demos and news follow OpenFaaS on Twitter - To go deeper with Serverless Functions — try the OpenFaaS Workshop — a dozen self-paced hands-on labs to help you master functions. - Having problems with Minikube? Try OpenFaaS with KinD — a new lighter-weight alternative that will run anywhere you have Docker. Written by Alex Ellis, the founder of OpenFaaS. Thanks to Richard Gee for proof-reading this post. Join our community Slack and read our weekly Faun topics ⬇ Join a Community of Aspiring Developers.Get must-read articles, learn new technologies for free… Join thousands of developers and IT experts, get must-read articles, chat with like-minded people, get job offers and…
https://medium.com/faun/getting-started-with-openfaas-on-minikube-634502c7acdf
CC-MAIN-2021-10
refinedweb
1,280
60.14
. We also recommend some additional tags below, for a better podcast experience. - You must provide an image for your podcast. - The feed and audio files should not require any authentication or be blocked to Google in any way. Google will use. - Use either HTTP or HTTPS, but not both. The RSS feed and all episodes should be located either on HTTP or HTTPS. Google strongly recommends using HTTPS. If your feed or homepage is hosted at one protocol (HTTPS) but the linked resources are hosted at another protocol (HTTP), Google Chrome will display a click-through warning to users before loading those resources, or possibly not allow them to be loaded at all. This includes episode audio files. Therefore you should be sure that, at minimum, the feed and the homepage, plus all audio file URLs in <enclosure>tags be using the same protocol (ideally HTTPS). -> <googleplay:owner>dafna@example.com</googleplay:owner> Google-specific RSS tags Here are the required and recommended RSS tags used by Google to display your podcast: Tag namespaces You will need one or both of the following RSS extensions to define your podcast, depending on which tags you use in your RSS feed. Be sure to include the appropriate RSS extensions in the <rss> tag at the top of your feed. Here is how you would include both extensions in a feed: . Episode-level RSS tags To be eligible to appear in Google Podcasts platforms, you must include the required episode-level tags. You can also include the recommended tags to add more information about your content, which could provide a better user experience. Required episode tags You must define these RSS tags at the episode level in order to be eligible to appear in Google Search. Use the appropriate namespace for your tag. Recommended episode tags These RSS tags are not required, but providing them can provide a better user experience in search, as well as providing more information for users to help find your episode in Google.
https://support.google.com/podcast-publishers/answer/9889544
CC-MAIN-2021-17
refinedweb
335
61.67
Introduction to Python Type Function In Python, every value in the Python program has a data type as everything is an object in the program, whereas data types are classes and variables are the object of these classes. Examples of data types are int, float, string, tuple, etc. To determine what type of object declared in the program there is a built-in function in Python known as type(). The function type(), when used on any object, returns what type of the specified object it is. This type() method is usually used for debugging of the program. There are two types of parameters passed to these type() function one is with a single parameter and the second is with three parameters. How Python type() Function Work? In Python, there are many built-in functions whereas we declare variables without specifying its data type before it as we do in other languages. So there is a function or method to determine the data type of the variable or object to make it easier for programming. The type() function has two types of parameters single and three parameters. If a single argument is passed it gives the type of the object whereas for three arguments are passed then it returns a new type object. Syntax: type( object) type( name, bases, dict) Parameters in Python Type Function - object: A single parameter to the type() function returns only the type of the specified object. - name: It has the __name__ attribute of the given name of the class. - bases: It also has __bases__ attribute which returns the tuple of classes from which the current class is driven - dict: This has namespaces for the class which returns a dictionary and have the attribute __dict__. Examples of Python Type Function The following are the examples of Python Type Function: Example #1 The example below is code to determine the type of the given variable ‘n’. Code: n = [1, 2] print(type(n)) Output: Example #2 The below example gives you all the data types with the output: Code: n = 2 print(type(n)) f = 2.9 print(type(f)) a = 'educab' print(type(a)) d = {1: 'one', 2: 'two'} print(type(d)) t = ('apple', 'banana', 'cherry') print(type(t)) Output: - In the above example, we have taken a number that contains value as 2, and in return, it prints the type of the variable ‘n’ which is ‘int’. - In the second case, we have taken a float number that contains the value 2.9 and it returns the type by printing the type of variable ‘f’ as the float. - In the third case, we have taken a string ‘educab’ and it returns the type of the variable ‘a’ as string ‘str’. - In the fourth case, we have taken dictionary type which contains some value and it returns the type by printing the type of the variable ‘d’ which is dictionary type ‘dict’. - In the fifth case, we have taken tuple type with the variable‘t’ which contains some value and it returns the type as ‘tuple’. Example #3 Now as type() function has two different types of arguments, will now see type() function with 3 parameters. Code: new = type('New', (object, ), dict(var1 = 'Educab', b = 2020)) print(type(new)) print(vars(new)) Output: Example #4 Another example that will clearly show you the use type() function with three arguments. Code: t1 = type('A', (object,), dict(p='Foo', x=43)) print(type(t1)) print(vars(t1)) class test: p = 'Foo' x = 12 t2 = type('B', (test,), dict(p='Foo', x=12)) print(type(t2)) print(vars(t2)) Output: - In the above program, we have taken type() function with three parameters in this program we have used vars() function, in Python vars() function returns dictionaries attribute like __dict__attribut. This dictionary is used to store the object’s writable attribute in the __dict__ attribute. - As we saw type() function has two different types of stating arguments one with identifying the type of the object in single parameter and other it has three arguments which will give us the tuple with name, type of the variable and in the dictionary form. So using this built-in function helps to debug the programs to know the correct data types of the initialized variable. Sometimes this function may not be used on string data type but in very few cases which yields some errors which will be very difficult to handle such errors so to avoid such difficulties we can use type() function and as the requirement, we can convert the given string into required string to execute the program with error-free. - Another use of this type() function in which we can register the tables in the database using SQL and we can also dynamically initialize classes along with their attributes. Conclusion In Python, there are many data types which you can determine using a built-in function of Python known as type(). In other programming languages, we declare data type before declaring or initializing the variable, but in Python, we don’t declare any data type we just write the variable with its values it takes the data type of its own. If we want to know the data type of the variable, we can use this built-in function. This function is useful when we are having the confusion of the data type declared in other program and this function is also useful while debugging any program. Recommended Articles This is a guide to Python Type Function. Here we discuss how it works, parameters and examples of python type function with code implementation. You can also go through our other related articles to learn more –
https://www.educba.com/python-type-function/
CC-MAIN-2020-24
refinedweb
945
63.73
Visual Note : This article is also Published @ CodeProject? Visual.. You can start debugging from the Debug menu of VS IDE. From the Debug Menu, you can select “Start Debugging” or just press F5 to start the program. If you have placed breakpoints in your code, then execution will begin automatically. There is another way to start the debugging by “Attach Process”. Attach process will start a debug session for the application. Mainly we are very much familiar with the attach process debugging for ASP.NET Web Application. I have published two different articles on the same on CodeProject. You may have a look into this. We generally start debugging any application just by putting breakpoint on code where we think the problem may occur. So, let’s start with breakpoints. Breakpoint is used to notify debugger where and when to pause the execution of program. You can put a breakpoint in code by clicking on the side bar of code or by just pressing F9 at the front of the line. So before keeping a breakpoint, you should know what is going wrong in your code and where it has to be stopped. When the debugger reaches the breakpoint, you can check out what’s going wrong within the code by using a different debugging tool. You have already set a breakpoint in your code where you want to pause the execution. And now start the program by pressing “F5″. When the program reaches the breakpoint, execution will automatically pause. Now you have several options to check your code. After hitting the breakpoint, breakpoint line will show as yellow color which indicates that this is the line which will execute Now you have several commands available in break mode, using which you can proceed for further debugging. After debugger hits the breakpoint, you may need to execute the code line by line. “Step Over” [ F10 ] command is used to execute the code line by line. This will execute the currently highlighted line and then pause. If you select F10 while a method call statement is highlighted, the execution will stop after the next line of the calling statement. Step Over will execute the entire method at a time. This is similar to Step Over. The only difference is, if the current highlighted section is any methods call, the debugger will go inside the method. Shortcut key for Step Into is “F11″. This is related when you are debugging inside a method. If you press the Shift – F11 within the current method, then the execution will complete the execution of the method and will pause at the next statement from where it called. It’s like run your application again. It will continue the program flow unless it reaches the next breakpoint. The shortcut key for continue is “F5″. This is quite an interesting feature. Set Next Statement allows you to change the path of execution of program while debugging. If your program paused in a particular line and you want to change the execution path, go to the particular line, Right click on the line and select “Set Next Statement” from the context menu. You will see, execution comes to that line without executing the previous lines of code. This is quite useful when you found some line of code may causing breaking your application and you don’t want to break at that time. Shortcut key for Set Next Statement is Ctrl + Shit + F10. This line is marked as a yellow arrow. These lines indicate that it will be executed next when we continue the program. This is the new feature in VS 2010. This is used for better managing breakpoints. It enables us to better group and filter breakpoints. It’s kind of categorization of breakpoints. If you are having different types of breakpoints which are related with a particular functionality, you can give their name and can enable, disable, filter based on the requirements. To understand the whole functionality, let’s assume that you have the below code block which you want to debug. class Program{static void Main(string[] args){string[] strNames = { "Name1", "Name2", "Name3", "Name4", "Name5", "Name6" }; foreach (string name in strNames){Console.WriteLine(name); // BreakPoint}int temp = 4;for (int i = 1; i <= 10; i++){if (i > 6)temp = 5;}} public static void Method1(){Console.WriteLine("Break Point in Method1"); // BreakPoint} public static void Method2(){Console.WriteLine("Break Point in Method2"); // BreakPointConsole.WriteLine("Break Point in Method2"); // BreakPoint} public static void Method3(){Console.WriteLine("Break Point in Method3"); // Breakpoint}} If you run the program, execution will pause on the first breakpoint. Now see the below picture, where you have the list of breakpoints. In the given picture label column in blank. Now, see how you can set the label on break point and what is the use of it. To set label for any breakpoint, you just need to right click on the breakpoint symbol on the particular line or you can set it directly from breakpoint window. Right Click on Breakpoint, Click on the Edit Labels link, you can add the label for each and every breakpoints. As per the sample code, I have given very simple understandable names for all the breakpoints. Let’s have a look at how this labeling helps us during debugging. At this time, all the break points are enabled. Now if you don’t want to debug the method2, in a general case you need to go to the particular method and need to disable the breakpoints one by one, here you can filter/search them by label name and can disable easily by selecting them together. method2 This is all about the Breakpoint labeling. The example I have shown to you is very basic, but it is very much useful when you have huge lines of code, multiple projects, etc. Suppose you are iterating through a large amount of data and you want to debug a few of them. It means you want to pause your program on some specific condition. Visual Studio Breakpoints allow you to put conditional breakpoint. So if and only if that condition is satisfied, the debugger will pause the execution. To do this, first of all you need to put the breakpoint on a particular line where you want to pause execution. Then just “Right Click” on the “Red” breakpoint icon. From there you just click on “Condition” . By clicking on the “Condition” link from context menu, the below screen will come where you can set the condition for breakpoints. Let’s assume that you have the following code block: class Program{static void Main(string[] args){string [] strNames = { "Name1","Name2", "Name3", "Name4", "Name5", "Name6"}; foreach(string name in strNames){Console.WriteLine(name); // Breakpoint is here}}} You have a breakpoint on onsole.WriteLine() statement. On running of the program, execution will stop every time inside that for-each statement. Now if you want your code to break only when name=”Name3″What needs to be done? This is very simple, you need to give the condition like name.Equals("Name3"). for each name.Equals("Name3") Check the Breakpoint Symbol. It should look like a plus (+) symbol inside the breakpoint circle which indicates the conditional breakpoints. After setup of the condition of your breakpoint, if you run the application to debug it, you will see execution of program is only paused when it satisfied the given condition with breakpoint. In this case when name="Name3". name="Name3" intellisense In Condition Text Box: The breakpoint condition which I have demonstrated here is very simple and can be written easily inside condition textbox. Sometimes, you may need to specify too big or complex conditions also. For that, you do not need to worry, VS IDE provide the intellisense within the condition textbox also. So whenever you are going to type anything inside the condition box, you will feel like typing inside the editor itself. Have a look into the below picture. I have almost covered all about the conditional breakpoints except one thing. In condition window you have seen that there are two options available: We have already seen what is the use of “Is True” option. “Has changed” is used when you want to break the code if some value has changed for some particular value. This is another interesting feature where you can save breakpoints and can use them in future. Visual Studio saves breakpoints in an XML Format. To save the breakpoints, you just need to click on the “Export” button in breakpoint window. You can use the saved XML file for the future and you can pass the same to other developers. You can also save breakpoints based on the search on labels. Let’s have a quick look inside the content of the XML File. The XML file is collection of BreakPoints tag within BreakpointCollection. Each breakpoints tag contains information about the particular breakpoint like line number, is enabled, etc. BreakPoints BreakpointCollection If you delete all the breakpoints from your code at any time, you can easily import them by just clicking on the “Import“ breakpoints button. This will restore all of your saved breakpoints. Import Note: Breakpoint Import depends on the line number where you have set your breakpoint earlier. If your line number changed, breakpoint will set on the previous line number only, so you will get breakpoints on unexpected lines. Breakpoint Hit Count is used to keep track of how many times the debugger has paused at some particular breakpoint. You also have some option like to choose when the debugger will stop. “Breakpoint Hit Count” window having the following: By default, it’s set to always. So, whenever the breakpoints hits, hit count will increase automatically. Now we can set some condition as earlier mentioned. So based on that condition, breakpoint will hit and counter will be increased. Let’s explore it with the sample code block below: for (int i = 0; i <= 10; i++){ Console.WriteLine(i.ToString()); // Breakpoint} If you want your code to break when hit count is a multiple of 2, you need to select the third option from the dropdown list. After that, your code line should break only when the hit count is 2,4,6,… etc. Till now, I hope you are very much clear about breakpoints, labeling, hit count, etc. Now have a look at what is “Breakpoint When Hit” option. This is apart from your normal debug steps, you want to do something else while breakpoint is hit, like print a message or run some macros. For those type of scenarios, you may go for this option. You can open this window by just right clicking on breakpoint. The first thing that you need to notice is the symbol of breakpoint. Breakpoint symbol has changed to a diamond and you can also check out the tool tip message which indicates what it is going to do when execution reaches here. You can restrict the breakpoint to hit for certain processes or threads. This is extremely helpful while you are dealing with multithreading program. To open the filter window, you need to right click on the breakpoint and select “Filter”. In the filter criteria, you can set the process name, Id, Machine name, Thread ID, etc. I have described it in detailed uses in Multithreading debugging section. Data tip is kind of an advanced tool tip message which is used to inspect the objects or variable during the debugging of the application. When debugger hits the breakpoint, if you mouse over to any of the objects or variables, you can see their current values. Even you can get the details of some complex object like dataset, datatable, etc. There is a “+” sign associated with the dataTip which is used to expand its child objects or variables. dataset datatable Few months ago, I published one article on VS 2010 DataTip Debugging Tips. Here are a few cool features that you can use during debugging of your application. pinned. Unless you manually close these pinned items, they will be visible in the IDE. You can easily Drag and Drop the data tip inside the Visual Studio IDE. This is quite helpful when you need to see some object value list in the bottom section of code. You can easily drag those pinned data tips over there. You can add comments on the pinned data tip. For providing comments, you need to click on “Expand to see the comments” button. This will brings up an additional textbox to add comments. Below is some demonstration of Adding comments on pinned inspect value: This is another great feature of Visual Studio 2010 debugging. feature is quite similar to the import/Export breakpoints. Like Breakpoints, you can import and export pinned data tips values in an XML file. These saved data tips can be imported during any point of time for further debugging. The XML file looks like below: You can further explore the XML file if you want to know more details about it. DataTips is also used to changed the value while debugging. This means it can be used like a watch window. From the list of Pinned objects, you can change their value to see the impact on the program. You can clear the data Tips by selecting “Clear Data Tips” from Debug menu. There are two options: So if you want to clear all the Data Tips from all over your project / solution, just select the first option. But if you want to delete the pinned data tips from a particular file, then you need to open that particular file, there you have the second option to select. You can even delete particular pinned data tips by just right clicking on it and clicking “Clear”. You can say it is an investigation window. After breakpoint has been hit, the next thing you want to do is to investigate the current object and variables values. When you mouse hover on the variable, it shows the information as a data tip which you can expand, pin, import which I have already explained. There are various types of watch windows like Autos, Local, etc. Let’s have a look into their details. It automatically displays the list of variables within the scope of current methods. If your debugger currently hits a particular breakpoint and if you open the “Autos” window, it will show you the current scope object variable along with the value. These variables are automatically detect by the VS debugger during the debugging. Visual Studio determines which objects or variables are important for the current code statement and based on that, it lists down the “Autos” variable. Shortcut key for the Autos Variable is “Ctrl + D + A”. Watch windows are used for adding variables as per requirement. It displays variables that you have added. You can add as many variables as you want into the watch window. To add variables in the watch window, you need to “Right Click” on variable and then select “Add To Watch”. You can also use Drag and Drop to add variables in watch windows. If you want to delete any variable from watch window, just right click on that variable and select “Delete Watch”. From the debug window, you can also edit the variable value at run time. There are 4 different watch windows available which you can use parallelly. If any of the row variables of the above window holds the object instance, you can have a “+” symbol with the variable to explore the properties and member of that object variable. Visual Studio Debugger has another great functionality where you can create an object ID for any particular instance of object. This is very much helpful when you want to monitor any object at any point of time even if it goes out of scope. To create Object Id, from watch window you need to right click on a particular object variable and then need to click on “Make Object ID”. After adding Object Id with a particular object variable, Visual Studio adds a numeric number with “#” with that object to indicate that one Object ID has been created. Immediate window is very much common and a favorite with all developers. It’s very much helpful in debug mode of the application if you want to change the variable values or execute some statement without impacting your current debugging steps. You can open the Immediate window from menu Debug > Window > Immediate Window { Ctrl + D, I / Alt + Ctrl – I }. Immediate window has a set of commands which can be executed any time during debugging. It also supports Intellisense. During Debug mode, you can execute any command or execute any code statement from here. These are very much common features for all the developers, so I am not going into details of each and every command of Immediate window. These features also improve the productivity during debugging. If you have multiple method calling or nested calling all over your application and during debugging, you want to check from where this method has invoked, “Call Stack” comes into the picture. The Call Stack Window shows that current method call nesting. In Call Stack window if you clicked on any of the rows, it will point you to the actual code of line of Visual Studio Code Editor. You can also customize the call stack row view by selecting different types of columns. To customize, Right Click on the “Call Stack” window, and from the context menu, you can select or deselect the option. Call stack is very much important when you have multiple methods call all across the application and one particular method throwing an exception on some particular case. At that time, you can use call stack to see from where this method is getting invoked, based on that you can fix the defect. As of now, what I have discussed is all about fundamentals of debugging, knowing debugging tools and their uses. Now let’s have a look into the multithreaded scenarios. Here you will see how to work with multithreaded program debugging, where is your current thread, what is the thread execution sequence, what is the state of thread. Before continuing with the demo, sample code,″ and see what are the changes in thread window.: The sample code which I have explained for the thread debugging is very simple. What will happen if you have a huge code block with multiple number of threads. Then it will be very difficult for you to identify which thread is part of your code or which ones are not related. Thread window gives you very easy features to set the “Flag” for all the threads which are part of your code. For that, you need to just flag your thread by option “Flag Just My Code“. While discussing about breakpoint filter in breakpoint section, I said that breakpoint filter is very much helpful for Multithreaded debugging mode. Now this is the time to explore it. In our current example, we have three threads Main Thread, Thread1 and Thread 2. Now what if you want breakpoint to hit only for “Thread 2″. What will you do ? Here is the use of breakpoint filter. Right click on the breakpoint, select “Filter” from the context menu. Now in breakpoint filter window, you need to fill the filter criteria. As per your requirement, you need to specify “ThreadName="Thread 2" . ThreadName="Thread 2" Here ThreadName was one of the criteria by which you can filter, but you can filter on multiple clauses like ThreadID, ProcessName, ProcessID, etc. After setting the breakpoint filter, run the application and open the “Threads” window. ThreadName ThreadID ProcessName ProcessID You will find your program execution has only paused during the execution of “Thread 2″ . This is all about the debugging with multithreaded application. Hope you have learned something from it. Let’s start with another most important topic “Parallel Debugging”. This is another great feature added to Visual Studio 2010 to debug parallel program. Parallel programming is the new feature coming with .NET 4.0. If you want to learn more about parallel programming, please check here. Now Debugging the parallel program is also a big topic. Here I will give you a basic overview to know about the debugging of parallel program. To discuss about it, let’s consider you have the following piece of code: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks; namespace ParalleTaskDebugging{ class Program { static void Main(string[] args) { var task_a = Task.Factory.StartNew(() => DoSomeWork(10000)); var task_b = Task.Factory.StartNew(() => DoSomeWork(5000)); var task_c = Task.Factory.StartNew(() => DoSomeWork(1000)); Task.WaitAll(task_a, task_b, task_c); } static void DoSomeWork(int time) { Thread.Sleep(time); } }} To understand the parallel program debugging, we need to be aware about two window options: Before continuing with parallel tasks and parallel stacks, you have to know about Threads Window which I have already covered. In the given code, you have three different tasks which are doing something and after sometime, all the tasks are put on hold. This is done intentionally to check the status of each task. To test, put a breakpoint on DoSomeWork() method and run the application. You will see your program execution paused on the breakpoint. After the program break, you can go to Debug > Window > Open Parallel Tasks and Parallel Stacks window. I asked to open both at the same time only because you can visualize what is going on. DoSomeWork() Parallel Task window will show you what are the different tasks that have been created for the program and what is their current status. On the other hand, Parallel Stacks will show you the graphical view of all thread creation, containing tasks, how they are related. If you click on the thread from the Parallel Stacks, it will show you the code line related with the thread (as shown in the picture with a Green Arrow). To move ahead, press F5. Let’s see what comes In the above diagram, you can find one of the tasks has been executed and the other two are remaining. Current execution point is set to AsyncMethod_1, so if you continue, this method will execute first and next time the others. When you are working with parallel programming, there are many scenarios which will come like Deadlock, Dependency problem, etc. These topics is very interesting and long to discuss. Please check further study section of the article to know more details. AsyncMethod_1 This is another great feature of Visual Studio 2010 IDE. IntelliTrace Debugging is sometimes called as historical Debugging. IntelliTrace operates in the background, records what you are doing during debugging. When you want the information of previous event or some particular event, you can easily get it from intelliTrace information, a past state of your application. In this mode, you can navigate to various events, steps that are recorded. In this section, I will give you a basic overview of how to use IntelliTrace. Here I am using one sample program by which I will show you what IntelliTrace does. Below is the sample code block: [/sourcecode] class Program{static void Main(string[] args){Console.WriteLine("IntelliTrackerTest");CallTestMethod(5);} public static void CallTestMethod(int TestValue){Console.WriteLine("In CallTestMethod : " + TestValue.ToString());Console.WriteLine("Last Statement....");}} [sourcecode language="csharp"] Run the program and Open IntelliTrace window from Debug menu, you will find the below screen added in the right hand side of Visual Studio. Did you find any relationship with your code and with the IntelliTracker List view? I guess you should. If not, let me explain about it. Let’s have a look into the below picture: From the picture, I am sure you have got the idea what IntelliTrace is doing. Yes, exactly its records/capture what your code is doing. If you call a method, it will capture. If code fired an event, it will trap. Yes at a single statement, I will capture each and everything. Now from the IntelliTrace window, you can navigate your code with any part and see what’s happened internally. If you can get the call stack, Local variables information are recorded. To navigate, just click any of the events that you want to explore, that block will automatically expand. When you will select any block, it will expand automatically and that line will be highlighted. As per the given picture, I have highlighted the first console section and you can see the corresponding code block has also been highlight. You can now easily map them. In the expanded block (Light Orange), there are two Related View Sections Locals and Stack Call. I have already explained Locals and Stack Calls. But can you imagine what is the use of Locals and Call Stack over here. Yes, you guessed it correctly, it will show you the Locals and Call Stack status for that time period when the selected block has been executed. What a nice feature this is. If you have a lot of recorded information in the intellitrace window, you can easily filter them out. You can filter data based on the Categories or Thread. As for example suppose you want to see only the data that is related with Console Related, you just need to check the “Console” From categories list. Note: By default, Visual Studio stored IntelliTrace information in “\Microsoft Visual Studio\10.0\TraceDebugging” Location in a iTrace file. You may change the location. Debugging with IntelliTrace is itself a big topic. So it is very much difficult for me to cover them up within this article. I just give you the basic overview so that you can at least explore it by yourself now. Please check the further study section to know more about it. I am stopping here. Hope you have enjoyed the full article. Please share your feedback and suggestions. This article covers basic fundamentals of debugging procedure. It describes how to debug an application using VS IDE. I have explained almost all important tools and their uses. For Parallel program debugging, I have covered only basics. In further study section, there is a great article on Parallel debugging procedure. If you are interested, please go through the link. My main objective was to cover almost all utilities that are available in Visual Studio debugging. Hope you have learned something new from this article. Tags: Visual Studio, ASP.NET, .NET, VS2010, BRH,
http://beyondrelational.com/modules/2/blogs/37/posts/13508/mastering-in-visual-studio-2010-debugging.aspx
CC-MAIN-2015-18
refinedweb
4,415
64.91
Senate Bill Raises Possibility of Withdrawl From ITER As Science Cuts Loom 180 ananyo writes "Are the knives coming out for ITER? A Senate Department of Energy ... voted to boost ITER funding and to support the domestic program at almost 2012 levels on 6 June. U.S. 'sequester', a pre-programmed budget cut scheduled to take effect on 2 January, could cut 7.8% or more off science and other federal budgets unless Congress can enact last-minute legislation to reduce the deficit without starving U.S. science-funding agencies." Gotta love politicans (Score:5, Insightful). Re:Gotta love politicans (Score:5, Interesting) Re: (Score:2). Re:Gotta love politicans (Score:4). It's not just administrator pay, it's also the sheer size of administration. And pork projects (yes, schools have those too) as well. The education budget for the most part is bloated, with little to show for it. Re: (Score:3) And pork projects (yes, schools have those too) as well. Oh boy do they ever. The local school district is cutting everything they can and still in danger of going under for lack of funds. Part of that is because no one wants to raise property taxes but largely it's because every year or three for as long as I can remember they've basically been digging ditches just to fill them back in again. Repave a parking lot then almost immediately tear it up to build a new extension, destroy and remake 3 or 4 perfectly good tennis courts in less than a decade (despite not Re: (Score:2) With activities like that, why would anyone want to pay increased property taxes? Besides, those taxes were enough in the past, they should be enough now. Tax revenues aren't a fixed amount, since they're a percentage of some activity, they rise and fall with that activity (in this case, property values). Just because local governements were fat and happy during the real estate bubble due to massively inflated property values doesn't mean they're entitled to those giant revenues forevermore. They're alway Re: (Score:2) Re:Gotta love politicans (Score:4, Insightful) Yeah, this. My mother taught at a ghetto school for quite a while at the end of her career. I worked there for a semester, and volunteered quite a bit in addition to that. They had gobs and gobs of "technology" (computers, teleconferencing equipment) lying around that wasn't being used, paid for by federal grants -- and that nobody there really knew *how* to turn into actual student learning. They maintain an "aerospace science" magnet program in name only which (for a while) was there in name only and existed just to qualify for federal funding. What we need to do to fix education is: 1) Pay teachers a salary that is commensurate with highly-trained competent professionals 2) Demand that they actually be highly-trained competent professionals 3) Get the hell out of their way and stop micromanaging them Re:Gotta love politicans (Score:4) .) Re:Gotta love politicans (Score:5, Insightful) .) First, you're right, in K-12, we have the highest spending in the world, and you're correct: you'd hardly know it from the results. Second, our university system is at the edge of a precipice. Our colleges have been living off of their reputations for years, and other institutions across the world are catching up, or have caught up with us. Harvard and Yale... like Oxford and Cambridge... will always have a brand to sell, but our higher education bubble is going to burst soon, and it's going to make the housing bubble look small by comparison. We have too many colleges with too many students that shouldn't be their learning too much fluff and paying too much for it. If something can't last forever, it wont. Re: (Score:2) Why, it's almost as if throwing money at the problem doesn't solve it! Re:Gotta love politicans (Score:4) Re: (Score:2) It's approximately the same ($1171/$1253B) [cbo.gov] (depending on whether you use the baseline or proposed budget), and only that bad because of the economy. Projections for the future are $612B/$977B in 2013 down to $175B/$510B in 2018. Re: (Score:2) If you go back to Reagan and zero out military spending since then, you also zero out the debt (to about 5%). This calculation was based on looking up year-to-year military spending and year-to-year interest on the debt. Re: (Score:2) The funny thing is, even if the US cut 100% of that spending overnight, it still wouldn't make up the deficit. Military spending, while it certainly doesn't help, is not the biggest problem with US spending. Not even close. Right now, yields on government bonds are negative out to 20 years. People are paying to lend the US government money. Given high unemployment, decaying infrastructure and free money, the most sensible thing to do right now is borrow and build. The deficit is not the problem. Paying the interest on government debt is what matters. Re:Gotta love politicans (Score:5, Insightful) Re:Gotta love politicans (Score:5, Interesting) Take a guess as to who said this in. You might think it's some liberal peace activist type speaking to a bunch of hippie protesters. But you'd be wrong: it's Dwight D Eisenhower. Re: (Score:2) You might think it's some liberal peace activist type speaking to a bunch of hippie protesters. But you'd be wrong: it's Dwight D Eisenhower. I wouldn't be surprised, but today, Nixon is to the left of the "socialist" Obama. From this perspective, Eisenhower was a stinking hippy. Re: (Score:2) Eisenhower was brilliant, in this regard. He predicted and warned against the military-industrial complex more or less taking over the country. His military experience didn't make him a warmonger, it let him see the dark underbelly of the military that normal people would not have even imagined. Re: (Score:2) Yes, and look what happened: The American public elected one warmonger after another, going into Vietnam, Iraq (twice), Afghanistan, plus countless smaller campaigns all during that time. Re: (Score:2) It should also be pointed out that Ike got elected primarily on the promise to fight the Commies in Korea. His attitude towards war seems to have been seeing it as necessary when faced with opponents like the Nazis and the USSR. His opponent Adlai Stevenson, on the other hand, really did advocate peaceful foreign relations. He lost handily to Ike in 1952 and 1956. Re: (Score:3) Yes, and that's a perfectly reasonable attitude towards war IMO. Unfortunately, Korea was well before my time, and also seems to be "the forgotten war" as when we study American history we mostly skip over WWI except maybe for mentioning archduke Ferdinand and the Red Baron, study WWII thoroughly, then briefly mention Korea and give it about as much time as the Bay of Pigs, and then jump right into Vietnam. But Korea was mostly successful, in that even though it was largely a civil war and a proxy war lik Re: (Score:3) Look -- absolutely ALL of these issues we've got with "dumb government moves" has to do with how politicians get elected. Term limits are dumb because we already have Congress campaigning every two years, so they are on a money train, and then if you kick them out (after 5 years they get retirement benefits thanks to Republican lawmakers), you only empower the lobbyists and unelected experts who groom them to get elected. I'm sure Exxon was happy to step in and fund candidates and that's how you've still got Re: (Score:2) (I hate .mil spending diatribe removed) Lets not make it too complicated here. There's an easy enough solution. Fund ITER out of the navy black ops budget. Just like happened historically with fission reactors, I guarantee some admiral is going to be waterski-ing behind a reactor powered aircraft carrier, decades before my kitchen oven is powered by reactor generated electricity. Now with fusion instead of fission. Whatever. I don't think the US Navy wants to be left behind as the only world power navy who doesn't have fusion reactors in the eng Re: (Score:2) The military typically only funds research of something that could be built within the next 20 years, usually much less. Fusion is nowhere near that close. The military, despite what you may think of it, is interested in stuff that can produce practical results in the foreseeable future, not theoretical research (and never have been). Fusion research is currently very much theoretical. If you wanted DoD funding for fusion research, you'd have to go to DARPA or something, and they aren't likely to be interes Re: (Score:2) So greater knowledge and understanding are not practical results? Huh. Karma Burn (Score:2, Troll) So greater knowledge and understanding are not practical results? Huh. Ask a member of the Tea Party and see what they say. Re: (Score:2) Honestly, DOD/DARPA are the only segment of American society, other than erstwhile Bond villians [wikipedia.org], investing in any sort of long-term research. Re: (Score:2) There is no Polywell funding. Yes there is [recovery.gov] This has always been some internet myth. Polywell will never produce a viable power source because you will always need to put more energy into it than you will get out. That remains to be seen, but in any case it's not relevant to whether or not they're receiving government funding. Re: (Score:2) Subs get fission reactors for two reasons: 1) it lets them hide out underwater indefinitely (especially useful for the "boomer" ballistic missle subs), and 2) they're almost always underwater, so it's not like they have to worry a lot about anyone boarding the ship and taking it over. I'm guessing they probably don't have platoons of marines on board; they don't have the space for it anyway. Aircraft carriers, OTOH, have plenty of space for extra people. But even there, they almost never travel without e Re: (Score:3). While I heartily agree that both the military budget and government employee pay is too high, you're intentionally ignoring the elephant in the room: entitlements. We could completely abolish the military, and entitlements are still going to bankrupt us. Re:Gotta love politicans (Score:5, Insightful). Re: (Score:3). First off, what I call entitlements are just that: entitlement spending programs, and they're the most massive chunks in the budget pie. Second, medicare and SS will remain a problem regardless because cost growth is outstripping income from new generations of workers. Third, it is simply a falsehood that repealing those tax cuts will make up for entitlement growth. Not even close, especially in the long run. We have several problems in our budget, but when you look for the biggest ones, entitlements are th Re: (Score:2) Yes, the entire government spending problem would go away if the bush tax cuts were elimenated. Everything was just hunky dory and everything was paid for before him. Re: (Score:2) Instead of cutting where its needed (*entitlements*), they cut everything else instead. FTFY - and I'm soon to be eligible for Social Security. The standard practice for all political administrations since forever has been to always propose to cut whatever is most desirable, popular and necessary, rather than what is least important, most expensive and biggest boondoggle. This assures an outcry about "Don't cut X", setting the debate about the wrong topic and leaving the politicians in charge of ever more money. It has worked since the first democracy (read about Pericles, who invented 'bre Historical fusion budget (Score:2) Fusion scientists often get criticized for making unrealistic promises ("Fusion has been thirty years away, for fifty years!" or some variation on that). But take a look at the graph here [wikimedia.org]. The graph shows the funding estimates from a 1976 fusion development plan, with various paths to a reactor. The black curve way at the bottom is the actual funding profile. You forgot about bankers. (Score:2) Re: (Score:2) The problem with the Federal budget isn't military spending. Yes defense can be cut, but it's already the one budget item which has been cut the most in the last 50 years [npr.org]. Right now, our annual budget deficit exceeds the defense budget, so we could drop defense spending to zero and we'd still have a budget crisis. And FWIW, defense spending is on the chopping block as well [nationalde...gazine.org] if the Budget Control Act [wikipedia.org] Re: (Score:2) The military cannot be cut because they'll need the military to put down the insurrection in the States when martial law is declared. Frankly, I don't think it will do them any good. There are so many gun toting civilians and many will step up their game to more powerful methods once the martial law police start coming for their families to cull the population. It's gonna be messy. LOL! Japan (Score:2, Insightful). Re:Japan (Score:5, Interesting). I think you're rewriting history a bit as the USA bailed completely out of the project in the 90s until the canadians pouted and quit in the 00s because they didn't get the construction site and we joined sorta in their place, kinda, at about the same time Japan agreed to stop arguing about where to build it if they got extra job slot quotas. So if anything interest picked up when Japan stopped fighting, not reduced. I suppose "interest decreased" in a sort of prime time reality TV drama sense in that it got less dramatic and more boring once Canada stopped pouting and got evicted from the island or whatever mixed metaphor and Japan stopped picking fights with everyone. On the other hand, after the prime time TV drama ended, they actually started working on stuff and there's dirt being dug up and things being built right now... It won't be the first time we've bailed, it'll probably happen again. Kazakhstan wants to join (yeah, Kazakhstan, no kidding) ... I suppose as a point of national pride they are a rising country instead of a declining one like the US. They even have a superior medical system. Its embarrassing that replacing us with them will, overall, be an upgrade to the ITER project. To some extent this is just a larger scale version of what happens every time a school district budget is squeezed. Don't lower mahogany row salaries from $250K to "only" $200K per year because then we wouldn't attract the "leadership" of the best and brightest who are currently running us into the ground, nahh, just threaten to cut something cool and popular like drivers ed or high school football until the taxpayers are beaten into submission and meekly accept higher tax rates. Re: (Score:2) I'm not rewriting history at all, I remember the massive pressure from the US to give it to Japan and the scramble to find "compensation" so both the US and Japan would back down. I also remember an implicit threat that the US would back out if it didn't go to Japan. Re: (Score:3) Yeah well sorry maybe that was a little harsh phrase selection. I checked wikipedia and the order is as I recall, the opposite of the order of events you recall. We bailed out, came back momentarily, were not exactly negotiating from a position of strength. If we were planning on taking one for the team and ally with Japan, we wouldn't have bailed out to begin with. I'm confused why the US and japan were supposedly allied as you'd think we'd have pushed harder for the Canadians who bailed out, maybe its If this is all because of "The Dark Knight Rises" (Score:2) ...then I might have to run for office myself. Next article up, shortage of scientists (Score:5, Insightful) Next article up, some manager whining about how there's a shortage of scientists because he wants to pay almost nothing and the domestic eggheads think they're worth more than $7.25/hr so we'll have to crank open the H1B floodgates until Physicists can only dare to daydream of having the career opportunities of a mcdonalds fry cook. I'm glad I didn't go into science. Would have loved to, but hate grinding poverty even more and don't want to spend my middle age as a taxi driver like happened to all the rocket scientists I know after Apollo. Next article after that will be some washed up town patting themselves on the back for rolling out a new STEM program for grade school kids, to handle the massive future shortage of STEM employees. You know, the kind of town where 2000 STEM employees just got the axe because one of the STEM educational initiative corporations just moved their HQ from that heartland town to China, and another 200 person foundry just went bankrupt and a 200 person cement factory just closed (this is my home town... I'm not directly affected but it still sucks) As long as the rich get richer I guess we're on the right path... Re:Next article up, shortage of scientists (Score:4, Interesting) Re: (Score:2) The problem is that China actually cares about how many immigrants it admits and is selective. Doesn't sound like a country we all know well and most slashdotters live in. Re: (Score:3) The problem is that China actually cares about how many immigrants it admits and is selective. Doesn't sound like a country we all know well and most slashdotters live in. Sounds exactly like Canada. Re: (Score:2) Ah, the old it's only racist if white people do it. Didn't you get the memo? Everybody has a god given right to move and occupy whatever land/country they want to move to. Re: (Score:2) Interestingly, this is already old thinking. Chinese manufacturing will form a dwindling part of their economy and service their own market more and more. Now of course they will keep doing manufacturing, but automation will increase the relative costs of transport, and Chinese workers cost (or will cost within 5 years) as much as Eastern Europeans. So, although those manufacturing jobs are not coming back (they have evaporated due to robotics), the engineering jobs attendant to local (automated) plants are Re: (Score:2) And innovation requires well-paid engineers Why? You sound all optimistic and kool aid drinky which is fine in a mass media group think way, but... why? I've eaten great food from innovative and creative and hardworking chefs who aren't paid squat. I've admired innovative and creative artwork from artists who live in comparative poverty. Ditto music. Music and fine art clowns sometimes Demand that poverty is a mandatory ingredient in good product. Same story with architecture and landscaping/formal gardens. I can design and implement a microwave RF am Re: (Score:2) Of course, great many things are done for the love of it. But as a company, if you rely on your employees to work for the sake of love, you are in for a big surprise. Good engineers are hard to come by. Good mathematicians, physicists are rare. Because not so many students get masters in technical and scientific fields. And indeed the unemployment figures are this... So there is in reality almost no unemployment for people with higher education degrees. [bls.gov] The salaries are however low because of the pressure of Re: (Score:2) Good engineers are hard to come by. Good mathematicians, physicists are rare. My advice is is someone says you sound kool-aid drinky the most effective response is likely not to repeat yourself and quote some made up for political motivation .gov stats. Do what you want, do what works for you, do it well, it just doesn't work for me. And that's OK, as long as we're having fun. But you're not convincing me. Good chefs, artists, musicians, landscapers, textile workers, poets, and tool and die makers are equally rare. Yet very poorly paid. There is no magic connection where having s Re: (Score:2) Your waitress friend isn't unemployed, she's employed... as a waitress. So according to the government, everything's hunky-dorey for her. The government doesn't recognize the state of "underemployment". You're right though; in this day and age, you really need to ponder whether it's even worth it to get a degree. For a lot of people, it doesn't seem to be. However, your anecdotal examples are a little telling: math, education, and special ed are not exactly fields with lots of openings. Re: (Score:2) The stats are not that there is no unemployment in general (there is, a lot of it), just that there is very little employments amongst folk with higher education degrees. This does not mean that they are doing a job corresponding to their degree or that they are well paid. I am not responsible for you not understanding what is written. Of course a bachelor of maths or a bachelor of education is going to have a hard time finding a job! Their degrees are worthless. That being said, their degrees still prov Re: (Score:2) Of course, great many things are done for the love of it. But as a company, if you rely on your employees to work for the sake of love, you are in for a big surprise. Exactly. You end up with extremely disloyal employees who will abandon your company for the next job offer that's only slightly higher. And you end up with a shortage of qualified workers, because not many people will bother going into that field, especially when it requires a massive investment in education (and money) to become qualified, a unlikely place to find savings (Score:2) Considering the size of the U.S. federal budget, it always seems to be smallish programs that are symbolically put on the chopping block when these political debates come up. This one isn't as ridiculous as, say, spending lots of time arguing over NPR's paltry budget, but it's still a pretty small budget, and comes with quid-pro-quos that make the net cost even less. The U.S. contributes 1/11th of the ITER construction costs, and in return American companies get 1/11th of the construction contracts, and U.S Re: (Score:2) The U.S. contributes 1/11th of the ITER construction costs, and in return American companies get 1/11th of the construction contracts, and U.S. scientists make up 1/11th of the staffing. So it's quite possible they withdrawn from ITER then go ahead and make their own ITER in the USA. For an AC that's actually a pretty good idea, you should proudly sign your name to that. Seriously. The problem with the ITER is there are 535 congress members and "most" of the ITER money as currently budgeted is probably going to come from a small minority of members districts... for example probably more scientists will be hired out of Caltech and MIT than, for example, Wyoming (does WY even have a research university as opposed to a teaching U?). Bringing it in-house like NASA means it'll cost more, b science funding is not a significant % of budget (Score:2, Insightful) The entire US science funding - for EVERYTHING - is a drop in the bucket. You want to make a difference in the budget? Here's what you have to do: (1) Trim entitlement spending (2) Trim military spending. Shit, there's enough graft, corruption, and incompetence in both that you could probably cut their budgets in half and end up with the same effectiveness at the end. Nothing else besides entitlements and military spending matters to any significant degree, and eating your seed corn is always a bad idea. Re: (Score:3) Yes, let's cut 'entitlement' spending. I'm sure all the (wildly overexaggerated) problems with those programs will simply disappear overnight if we take money away from them. Or, you know, the ACTUAL result will be that benefits will be cut to people who have paid into the system for decades. Yeah, that's fair. I'm all for improving efficiency in government. But you don't cure cancer by shooting yourself in the head. Re: (Score:2) Or, you know, the ACTUAL result will be that benefits will be cut to people who have paid into the system for decades. Yeah, that's fair. That sounds unfair until you realize that historical taxes for some big entitlements were lower than they are today: [ssa.gov] People starting jobs today are paying 300% more than someone who started their career in the 60s. It's unfair NOT to cut benefits for people who are about to retire. They didn't pay their fair share into the system for most of their careers. Re: (Score:2) Fine, so we need to cut 'entitlements'. What's your plan? Re: (Score:2) before we talk about entitlements I think we need to create a proper bar graph where one bar is entitlements and the other is military. Then we can talk entitlement cut. It's not that there is nothing there to cut, it's just that the entitlement discussion is entirely out of proportion. Re:science funding is not a significant % of budge (Score:5, Informative) From the 2012 budget... MIlitary budget, including overseas contingency operations: $716.3 Billion. Note that the above doesn't count the VA, which can adds in another $129.6 Billion. If you assume that the VA is part of "military spending", that makes the total $845.9 Billion. If you assume VA is NOT part of "military spending", then it probably should be added to "entitlement spending".... Entitlement spending... Social Security: $778.6 Billion. Medicare: $484.4 Billion "Income Security": $579.5 Billion. Total: $1842.5 Billion Not sure if that's all the entitlements, but looks reasonable. Note that Medicaid may or may not be included in "Income Security". If it's not, then add a hundred billion or so more onto the entitlement pile. Note that payment on the National Debt amounted to $225 Billion. So about 6% of our federal spending vanishes to pay for overspending in previous years.... So, "entitlements" amount to rather more than twice "military spending" if you count VA as "military spending", and 2.75x "military spending" if you count the VA as "entitlement spending".... Note, by the by, that those two chunks of money ("entitlements" and "military spending" amount to considerably more than we take in in tax revenue. So we could ZERO the rest of the government, and still have a large deficit with those untouched. Re: (Score:2) One issue I've always had with a military budget - why ever would the US government publish the true dollar amount of the military budget? Wouldn't it be a national security concern that foreign nations could estimate force and equipment strength based on an accurate dollar amount? Somehow, I have my doubts that the published dollar amount is anywhere close to the real amount. Re: (Score:2) Re: (Score:3) To sum up your post: Deficit (more being spent than taken in) is too high, so the only possible solution is to cut spending (in two categories you list). Do you notice the gap in this logic? Here, I'll highlight it: Deficit (more being spent than taken in) The current US deficit crisis isn't due to a spike in spending but a collapse in income. Re: (Score:2) Good theory, but not true. 2005 Federal tax revenues - $2.152 trillion 2012 Federal tax revenues - $2.469 trillion. That works out to about 1.9% annual increase in revenues, which is a bit below inflation (2.3% per year on average). Of course, the economy has well and truly sucked for the last four years, but even so, tax revenues are only about $60 billion below what would be expected from inflation. And the annual defi Re: (Score:2) You can't get blood from a turnip. People are already suffering under the tax burden they already have. Heck, half the workers in the country pay no income tax because they can't *afford* to. They need every penny they can get for basic needs like shelter and food. And when grandpa's monthly retirement check is cut as an "entitlement" and their uncle bob who can only work 3 days a week due to disease gets kicked off disability and can't make rent on the 1-room basement "apartment" anymore, this makes them better off how? I have this CRAZY idea on how to cut the deficit.. (Score:5, Insightful) How about... 1. We pull back all of our military forces except at a few major naval bases, end the occupations of Iraq and Afghanistan and tell Europe, Japan and Korea to pick up 100% of their defense budget from now on. Then cut the defense budget by 25%-30%. 2. We reduce unemployment benefits to six months instead of two years. Sorry, if you haven't worked in your field for about two years you don't have a career in it anymore. Unemployment benefits I believe are right now about $500B-$600B of the current federal budget. 3. We means test the hell out of Social Security and Medicare. 4. Release all non-violent drug offenders (including dealers) from prison, end the War on Drugs and send the enforcement personnel DEA and ATF to work for another federal law enforcement agency. 5. Privatize TSA, repeal 90% of the legislation behind Homeland Security and just admit that the only sensible reform we really needed post 9/11 was letting the FBI and CIA coordinate on terrorism cases. But nope, we can't stop bombing foreign backwaters where some jihadi is rattling his sabre and AK47 impotently at the Great Satan(tm) or tell someone they need to back away from the federal trough. Re: (Score:2) Interesting that you left Israel out of your first bullet point... Re: (Score:2) Israel can do a perfectly fine job of taking care of itself. It has nukes and some of the most modern arms on the planet. Why should we, the American taxpayers, pay for a squabble between Judaism Mk. I and Judaism Mk. III? (Probably because Judaism Mk. II has some ideological stake in it...) Re:I have this CRAZY idea on how to cut the defici (Score:5, Informative) Unemployment benefits I believe are right now about $500B-$600B of the current federal budget. Combined state and federal unemployment benefits peaked in 2010 at $160 billion, 2010 was about $120 billion. Re: (Score:2) Typo, 2011 was about $120 billion. Re: (Score:2) We do all those things, and we'll reduce our deficit to maybe three quarters of a trillion per year. Which will make it the fifth highest in history.... Re: (Score:2) reduce unemployment benefits to six months instead of two years. Sorry, if you haven't worked in your field for about two years you don't have a career in it anymore. So if someone can't find a job in six months - screw them? Or are you suggesting to replace the other 18 months by government-sponsored courses to re-train the unemployed into another career? Anyway, as I understand it, unemployment benefits go right back into economy since 100% of them are actually spent right away. Re: (Score:2) MikeRT, I totally agree with you. Run for office please! Re: (Score:2) Ron Paul ran on a platform like this, but he was ahead of his time. When world and domestic circumstances finally force the USA's hand into doing major things like what you're suggesting (probably due to unavoidable debt constraints), then your suggestions will be (involuntarily) implemented. Until then, your ideas are untouchable, politically because people don't want to give up the American cake while eating it too. BTW - I'm for legalizing and taxing/regulating marijuana comparable to alcohol, but other dr The government can borrow for free (Score:3) I'm looking forward to someone explaing to me why the government needs to save money now, when it can borrow for free? That is to say that the US government can borrow money for zero or even negative interest rates. To me, this seems to say that people have so little faith in the economy that they rather take a little loss but a guaranteed return (even if only via the mythical printing press) than invest their money in the economy. Now, if the government can have money so cheaply, and if my analysis of the reason is correct, then it should be an immediate logical consequence that government should make up the lack of investment in the private sector by spending itself. So, why should the government save money? Re: (Score:2) from Krugman's blog [nytimes.com], 5- 7- and 10-year bonds have negative yields [treasury.gov]. Investors are paying the government to buy these things instead of going into stocks. Re: (Score:2) Re: (Score:2) Your assumption is that the government has 100% faith in the economy, so if people don't invest in the economy it does on their behalf. What if there is really something wrong with the economy? Why should the government automatically dump money into it? Some things don't need lots of money to fix. Say hypothetically there are too many environmental regulations so nobody wants to build factories that pump out cheap widgets. Just change the laws. I think it would be interesting if the US had a sovereign wealth Re: (Score:2) I think you're misreading me. I'm not talking about government investing, I'm talking about government spending. And really, government can't act as an investor in the way a company can: if the government invests, then it gets its investment back in the form of greater welfare of the populace, not by selling more products as a private manufacturer would. To me it appears that right now people would rather give their money to the government than to private institutions. Why? Because they know they'll get Science and education (Score:5, Insightful) are investments in the future. Our politics has been infested with the corporate tendency to think short term, just as long as the next quarterly results. Which makes sense, since our representatives answer to the agendas of the corporations that fund them, certainly not the people who elected them. The result of which is that the USA is declaring its intent to be a declining power in the world. You invest in science and education, or you head towards second rate status in the world. It's that simple. Yet another reason why the corporate infection of our democracy basically means our doom. We almost never write our votes (Score:2) "Short term" means "next campaign." The problem with science and education investment, is that it NEVER pays off, even in the very long term. If you vote to increase that spending, it will never result in you getting an advertising budget advantage over your opponent. It might help the country, but nobody ever votes for people who help the country; they only vote for people who buy ads. Ad budgets are voters' primary means of If the money was directed to Thorium... (Score:5, Interesting) and/or nuclear plants with passive safety systems and a rational waste storage facilities, it would be a good idea. Instead, well'l use the savings to pay down debt caused by military spending, bail out banks and making sure very wealthy people stay wealthy and get wealthier. We are almost the definition of a culture in decline. Re: (Score:2) We are almost the definition of a culture in decline. Almost? Very well (Score:2) More free energy for us! There are better places to cut spending (Score:2) Considering % taxes used in defense of one form or another and considering that developing cheap or free energy also solves many conflicts... its easy to see where cuts should be happening. "Starving"? Really? (Score:2) Re: (Score:2) If they had any idea what the private sector was going through they would be spending even more. When governments can borrow at negative rates they should do so and use that money to build infrastructure. We don't fund new means of producing energy.. (Score:2) .. because RIGHT NOW it's not profitable for Big Energy. If ExxonMobil figured out a way to make billions on it, you can bet your ass the government would be funding it. Big Energy likes us right where they have us: under their collective thumb. And they'll spend billions to keep us there. So?? (Score:2) This is an ongoing debate (Score:5, Informative) Ph.D student in fusion here. (I was one of the authors of this Ask Slashdot [slashdot.org].) It's important to note that there are a range of opinions on this. Everyone thinks ITER is a good idea, at the right price. That price was originally quoted at $5-billion (with the U.S. picking up 9% of that) when the U.S. made the decision to join in 2003; today the construction cost is estimated at somewhere north of $20-billion. Hopefully now with Motojima as Director-General, this cost will stop rising. (From what I hear, he's being very rigorous about cost and schedule control and pushing the team hard on these fronts.) The problem for the U.S. is that participation in ITER doesn't make sense without a strong domestic program in place to take advantage of the results that come out of it. And without a (temporary) surge in U.S. fusion funding to get over the ITER construction "hump", the entire domestic program might be "squeezed" out of existence. Check out the graph here: [pppl.gov] So it's not so much a matter of "is ITER good science?" (it is!). The question is: "is ITER the right path for the U.S. at a cost of 9% of $20-billion or $25-billion, without a commitment to sustain the domestic program through the ITER construction phase?" I urge everyone here to go to our website that we set up at fusionfuture.org [fusionfuture.org], which has a lot of information about this issue. We still need your help - the House has restored funding for the domestic fusion program [fusionfuture.org], but the current Senate version of the bill still has the domestic fusion budget slashed (and the fusion experiment at MIT entirely closed down). There is still work to do! Go cull yourself (Score:3) Go cull yourself first. Re: (Score:2) Re: (Score:2) Re: (Score:2) Re: (Score:2) You should also note that these F-22's can't fly far from bases, since the pilots have been getting hypoxic: their oxygen systems don't work. Re: (Score:2)
https://news.slashdot.org/story/12/07/25/136210/senate-bill-raises-possibility-of-withdrawl-from-iter-as-science-cuts-loom?sdsrc=rel
CC-MAIN-2016-36
refinedweb
6,634
62.38
The @now/node Builder takes an entrypoint of a Node.js function, builds its dependencies (if any) and bundles them into a Lambda. When to Use It This Builder is the recommended way to introduce any Node.js-based dynamic request handling into your codebases. It can be used directly (as a single file, like my-function.js), or you can define an index.js file inside a directory. How to Use It: module.exports = (req, res) => { const { name = 'World' } = req.query res.send(`Hello ${name}!`) } An example serverless Node.js function. @now/nodeBuilder also supports asynchronous functions, an example of which can be found in the Request and Response Objects section.: The example deployment above is open-source and you can view the code for it here: You can pass query parameters to make the name change: The lambda using the name query parameter to change the text using Node.js. Request and Response Objects For each invocation of a Node.js lambda, two objects, request and response, are passed to the function. These objects are the standard HTTP request and response objects given and used by Node.js. Helpers In addition to the standard Node.js request and response methods, we provide a set of helper properties and methods to make it even easier for you to build a new lambda function: The following lambda(`hi ${who}, what's up?`) } Example Node.js lambda using the req.query, req.cookies and req.body helpers. It returns greetings for the user specified using req.send(). helpersto falsein the configuration of the builder. If you opt-out, request objects will be replaced by the standard HTTP request and response. { "builds": [ { "src": "my-file.js", "use": "@now/node", "config": { "helpers": "false" } } ] } You can opt-out of helpers by setting helpers to false in the configuration. lambda using the req.body helper that returns pong when you send ping. Typescript support We provide types for the request and response objects. To install these types, use the following command: yarn add @now/node --dev Or, if you're using npm: npm install @now/node --save-dev Once the types have been installed, import NowRequest and NowResponse from @now/node, to type the request and response objects: import { NowRequest, NowResponse } from '@now/node' export default function(req: NowRequest, res: NowResponse) { const { name = 'World' } = req.query res.send(`Hello ${name}!`) } An example "Hello World" Typescript lambda using the req.query helper. Async support We support asynchronous functions out-of-the-box. In this example, we use the package asciify-image to create ascii art from a person's avatar on github. First, we need to install the package: yarn add. Deploying with Static Content You can upload static content alongside on including static files in your project, read the documentation for @now/static: Technical Details Entrypoint The entrypoint of this Builder is always a JavaScript file that exposes a function. If you want to expose a server, you should read the documentation for the @now/node-server Builder, although this is not recommended. @now/nodewill automatically detect a `package.json` file to install dependencies at the entrypoint level or higher. Dependencies Installation The installation algorithm of dependencies works as follows: - If a package-lock.jsonis present, npm installis used - Otherwise, yarnis used. Private npm modules To install private npm modules, define NPM_TOKEN as a build environment variable in now.json. Build Step, const fs = require('fs');.send(` This Lambda was built at ${new Date(BuiltTime)}. The current time is ${new Date()} `) } now.jsonfile: { "version": 2, "builds": [ { "src": "index.js", "use": "@now/node" } ] } The resulting lambda contains both the build and current time: Node.js Version The Node.js version used is the v8.10. Maximum Lambda Bundle Size" } } ] }
https://docs-560461g10.zeit.sh/docs/v2/deployments/official-builders/node-js-now-node/
CC-MAIN-2019-35
refinedweb
623
59.4
USING ECLIPSE XML TOOLS FOR WEBSPHERE COMMUNITY EDITION 2.0 TUTORIAL INTRODUCTION When using WebSphere Application Server Community Edition there may be several XML files that you need to create as part of deploying an application. WAS-CE has the concept of “deployment plans” which describe how to deploy a Java Enterprise application to WAS-CE. Since these files may be complex any errors in syntax can cause wasted time and effort trying to deploy an application to WAS-CE. In this article you will learn how to use the XML tools built into the Eclipse Web Tools Platform to help create these files to avoid syntax errors. Since the WAS-CE Eclipse plug-in does not naturally know how to create these files you will be using an XML tool called the XML Catalog to add the definitions for the WAS-CE related XML schemas. After doing this you can easily create XML files for WAS-CE, even using some of the visual XML editor capabilities to simplify the process. SETUP This article assumes you have an environment setup as described in the Getting Started with WebSphere Community Edition 2.0 and Eclipse article. If you do not yet have WAS-CE and Eclipse installed follow the steps in that article to configure the environment. IMPORT WAS-CE SCHEMAS The easiest way to use the WAS-CE XML schemas from Eclipse is to import them into your Eclipse workspace. This section will do that so the next section can add entries in the XML Catalog that point to the local schema files. Start Eclipse if it is not already running. Generally this is done by executing the ‘eclipse.exe’ program or double-clicking a shortcut that points to it. When Eclipse starts it will likely ask for a “workspace”. Use the workspace from the last article if you have one. If you don’t use an empty folder. Make sure you are in the ‘Java EE’ perspective by selecting ‘Window -> Open Perspective -> Other’, selecting Java EE from the list and clicking OK. To simplify the setup a file will be provided with an Eclipse project that includes the WAS-CE schemas and another file you will need for the XML Catalog in the next step. To start, click on this link and download the file. You can save it anywhere as you will import it into Eclipse in the next step. In the menus of Eclipse select ‘File -> Import…‘. Expand the General group and select Existing Projects into Workspace. Press the Next button. /> Select the radio button next to the Select archive file option. Use the Browse button to find the location where you saved the downloaded file from earlier. Press the Finish button once your options match that below to import the project. /> If you expand the project in the ‘Project Explorer’ view you should see all of the schema files that were added. If you see two ‘WAS-CE-Schema’ projects listed in the ‘Project Explorer’ view you might want to restart Eclipse to refresh so only one is listed. /> Note: You may notice that many of the file names start with ‘geronimo-xxx’. This is because WAS-CE is based on Apache Geronimo and uses the same schema definitions. ADD XML CATALOG ENTRIES The “XML Catalog” is a tool you can use to provide Eclipse with additional XML schema definitions. Although you can add entries to this catalog manually this section will show you how to import a file that can add them automatically. From the main Eclipse menus select ‘Window -> Preferences‘. Expand the ‘Web and XML‘ group of preferences and select ‘XMLCatalog‘. /> On the right click the Advanced button. On the dialog that appears click the Import button. On the next dialog that pops up expand the ‘WAS-CE-Schema‘ project, select the ‘WTP2.catalog‘ file, and click the OK button to complete the import. /> In the upper section of the XML Catalog preferences expand the section for “User Specified Entries”. If you select the various entires, notice that these are the schemas for Geronimo (and WAS-CE) XML files and they link to the various schema files in the ‘WAS-CE-Schema‘ project in your workspace. /> Click the OK button to close the preferences dialog. Congratulations! You have just provided Eclipse with the definition of about 20 Geronimo/WAS-CE XML schemas simply by importing a few files. In the next sections you will learn how to use these definitions. CREATE XML FILE FROM SCHEMAS Now that you have imported Apache Geronimo/WAS-CE XML Schema definitions into the XML Catalog you can use them to create XML files. The easiest way to associate the schema with an XML file is to do it when the XML file is created. First create a project to place your XML files in. You can do this by selecting ‘File -> New -> Project‘. You can use the “Genral” project type and the name of the project can be anything. Once you have a project, right click the project in one of the Eclipse views that shows the project contents and select ‘New -> Other‘. Expand the ‘XML‘ group in the list and select the ‘XML‘ entry. Press the Next button. /> Change the name of the XML file to anything you want it to be, as long as the file extension is still .xml. If you are creating Geronimo specific XML files like deployment plans that must be a certain name you must change the name manually as Eclipse will be unaware of what the name of the file should be. Make sure that the project you created to hold the XML file is selected as the location and press the Next button. /> On the next page select the ‘Create XML file from an XML schema file‘ option and press the Next button. /> On the next page select the option for ‘Select XML Catalog entry‘ and choose the XML schema you need to use for the file from the list. Refer to the Geronimo or WAS-CE documentation for which schema is appropriate for your usage. In this example we are using the schema for a Geronimo/WAS-CE 2.0 web deployment descriptor. /> The final screen of the wizard will give you options for how to create the XML file. Check that the element selected as the “root element” is correct as a choice that is different than the one you might want may be selected if there are multiple options. You might also want to select the various entries in the “Namespace Information” list and edit the details. You can change the prefix if you want and fill in a value for the “location hint” to get the full benefit of the XML editor in the next step. To edit the location hint browse and find the matching entry for each namespace in the XML Catalog entries. Press the Finish button when the options for creating the XML file are filled in. /> Your XML file will open with the XML editor. Initially there will probably just be a root element and a number of XML namespace definitions. You will edit this file in the next section. /> Note: If you are working with Geronimo/WAS-CE 2.0 XML files like deployment plans you will have to manually open them with the XML editor. You can do this by right-clicking a file and selecting ‘Open With -> XMLEditor‘. There is a “Deployment Plan Editor” that comes with the WAS-CE Eclipse plug-in but it is not currently able to edit 2.0 deployment plans. Importing the schemas to the XML Catalog will help make using the XML editor easier as shown next. /> EDIT XML FILE CONTENT The XML tools available in Eclipse are most powerful when used in conjunction with the syntax defined in a schema. Since you have imported the WAS-CE XML schemas into your workspace and added them to the XML Catalog you can now use these tools to greatly simplify editing XML files. If you do not already have the file open from the last section open it now with the XML editor. Remember that as described in the note at the end of the last section you may need to manually open the file with the XML editor if Eclipse wants to open the file with the “deployment plan editor”. Although the XML editor has a source view where you could type the file out you can also use the visual “design” view to edit your file. Switch to the “Design” tab along the bottom if it is not open already. Most likely your XML file currently only has a root element and a few namespace definitions. Right click on the root element and select ‘Add Child‘. Select one of the entries from the list depending on what element you wish to add. All of the choices on the list are legal elements defined by the various schemas that are in use. This helps greatly in avoiding syntax errors. /> Once other elements are added as children of the root element you can continue to right-click additional elements and add other children to create the structure of the file. /> You can also right click and select ‘Add Before‘ and ‘Add After‘ to add elements at the same level as the currently selected element. You can see how the visual “Design” view makes it much easier to see the structure of the XML file. /> To edit the values associated with the various elements, click in the right column next to the element value to edit. Type a new value and hit <Enter> to accept the new value. Continue to do this for all the elements you have added. /> Note: Make sure that you hit <Enter> to accept the last value you have changed before saving the file, otherwise you will not save all of your changes. You should also be aware that when you add an element the default value is usually the same as the name of the element. Besides this creating potential for confusion it is likely that this default value would not be a legal value for the XML element at runtime. You can switch to the “Source” view tab along the bottom to see the XML syntax you have created in the Design view. /> REVIEW By following the steps of this article you can now use the XML tools that are part of Eclipse to create and edit WAS-CE/Geronimo XML files, including deployment plans. You did this by first importing the WAS-CE schemas as part of a project into your Eclipse workspace. You then imported a file into the XML Catalog that defined these schemas for Eclipse. Although you could have manually added all of the required XML Catalog entries this file made it much easier. You then saw how to create and edit XML files using the syntax in the various schemas. You saw how to visually edit the XML files using the “Design” view of the XML editor which makes it easy to see and change the structure of the file. RESOURCES Getting Started with WebSphere Community Edition 2.0 and Eclipse WAS-CE XML Catalog entries for Eclipse WTP 2 WAS-CE Deployment Plan reference WASKB-034 USING ECLIPSE XML TOOLS FOR WEBSPHERE COMMUNITY EDITION 2.0 TUTORIAL was last modified: October 30th, 2018 by admin
https://www.webagesolutions.com/knowledgebase/waskb/waskb034
CC-MAIN-2021-39
refinedweb
1,902
70.63
DtSearchReinit(library call) DtSearchReinit(library call) NAME [Toc] [Back] DtSearchReinit - Reinitialize the DtSearch online API SYNOPSIS [Toc] [Back] #include <Dt/Search.h> int DtSearchReinit( char ***dbnames, int *dbcount); DESCRIPTION [Toc] [Back] DtSearchReinit closes and reopens databases and other files as necessary, and reinitializes the search engine API. It is typically used after either databases or the ocf file have been externally changed to force the search engine to reinitialize itself, and to acquire the new database names if any. It can also be used after any function returns DtSrREINIT to acquire the new database names. ARGUMENTS [Toc] [Back] dbnames Specifies the address where a pointer to an array of static database name string pointers will be placed. The dbnames pointer from a previous DtSearchInit or DtSearchReinit may no longer be valid. Each string identifies a single successfully opened database. A database name string from this array is required for most other API function calls. The dbn member in DtSrResult is an index into this array. dbcount Specifies a pointer where the size of the dbnames array will be stored. RETURN VALUE [Toc] [Back] DtSearchReinit returns DtSrOK and the current dbnames array if the reinitialization was successful or if reinitialization was not necessary. It returns DtSrERROR and messages on the MessageList on any other condition. SEE ALSO [Toc] [Back] DtSrAPI(3), DtSearchInit(3), DtSearchGetMessages(3), dtsrocffile(4), DtSearch(5) - 1 - Formatted: January 24, 2005
http://nixdoc.net/man-pages/HP-UX/man3/DtSearchReinit.3.html
CC-MAIN-2019-26
refinedweb
233
54.02
Using a singleton without importing it? - nbigaouette Hi all, I want to create a QML singleton with some properties in it (for example some colors to reuse). I'd like that singleton to be usable both when launching my QML application with qmlsceneand from C++ (through a QApplicationand QQmlApplicationEngine). The only way I've found was to create a qmldirbeside my Main.qmland MySingleton.qmlwith singleton MySingleton 0.1 MySingleton.qmlin it and importing it using import "."in Main.qml. Is there a way to prevent having to import "."wherever I want to use my singleton? I find that import statement confusing as it's not explicit that I'm importing the current directory to get access to the singleton. Normally, I can create a component, say MyComponentand save it to MyComponent.qml. I can then automatically use this component in other qml files through its filename (without extension). Why can't I do this with the singleton? Thanks! I believe the import "." requirement is a bug that's in the bug database. - nbigaouette Just for completeness, the bug is this one:
https://forum.qt.io/topic/63051/using-a-singleton-without-importing-it
CC-MAIN-2018-09
refinedweb
182
51.55
Before we begin programming, there are two simple steps required to get everything ready for some amazing 3D graphics demos. Step 1 is to obtain the Flash 11 plugin and the Stage3D API. Step 2 is to create a template as3 project and test that it compiles to create a working Flash SWF file. Once you have followed these two steps, you will have properly "equipped" yourself. You will truly be ready for the battle. You will have ensured that your tool-chain is set up properly. You will be ready to start programming a 3D game. Step 1: Downloading Flash 11 (Molehill) from Adobe Depending on the work environment you are using, setting things up will be slightly different. The basic steps are the same regardless of which tool you are using but in some cases, you will need to copy files to a particular folder and set a few program options to get everything running smoothly. If you are using tools that came out before Flash 11 went live, you will need to download some files from Adobe which instruct your tools how to handle the new Stage3D functions. The directions to do so are outlined below in Step 1. In the near future, of course, Flash will be upgraded to include Stage3D. If you are using CS5.5 or another new tool that is compatible with the Flash 11 plugin, you may not need to perform the steps below. If this is the case, then simply skip to Step 2. Assuming that your development tool-chain does not yet come with Stage3D built in, you will need to gather a few things before we can start programming. Let's assemble all the equipment we need in order to embark on this grand adventure, shall we? Time for action - getting the plugin It is very useful to be running the debug version of Flash 11, so that your trace statements and error messages are displayed during development. Download Flash 11 (content debugger) for your web browser of choice. At the time of writing, Flash 11 is in beta and you can get it from the following URL: Naturally, you will eventually be able to obtain it from the regular Flash download page: On this page, you will be able to install either the Active-X (IE) version or the Plugin (Firefox, and so on) version of the Flash player. This page also has links to an uninstaller if you wish to go back to the old version of Flash, so feel free to have some fun and don't worry about the consequences for now. Finally, if you want to use Chrome for debugging, you need to install the plugin version and then turn off the built-in version of Flash by typing about:plugins in your Chrome address bar and clicking on Disable on the old Flash plugin, so that the new one you just downloaded will run. We will make sure that you installed the proper version of Flash before we continue. To test that your browser of choice has the Stage3D-capable incubator build of the Flash plugin installed, simply right-click on any Flash content and ensure that the bottom of the pop-up menu lists Version 11,0,1,60 or greater, as shown in the following screenshot. If you don't see a version number in the menu, you are running the old Flash 10 plugin. Additionally, in some browsers, the 3D acceleration is not turned on by default. In most cases, this option will already be checked. However, just to make sure that you get the best frame rate, right-click on the Flash file and go to options, and then enable hardware acceleration, as shown in the following screenshot: You can read more about how to set up Flash 11 at the following URL: Time for action - getting the Flash 11 profile for CS5 Now that you have the Stage3D-capable Flash plugin installed, you need to get Stage3D working in your development tools. If you are using a tool that came out after this book was written that includes built-in support for Flash 11, you don't need to do anything--skip to Step 2. If you are going to use Flash IDE to compile your source code and you are using Flash CS5, then you need to download a special .XML file that instructs it how to handle the newer Stage3D functionality. The file can be downloaded from the following URL: If the preceding link no longer works, do not worry. The files you need are included in the source code that accompanies this book. Once you have obtained and unzipped this file, you need to copy some files into your CS5 installation. - FlashPlayer11.xml goes in: Adobe Flash CS5\Common\Configuration\Players - playerglobal.swc goes in: Adobe Flash CS5\Common\Configuration\ActionScript 3.0\FP11 Restart Flash Professional after that and then select 'Flash Player 11' in the publish settings. It will publish to a SWF13 file. As you are not using Flex to compile, you can skip all of the following sections regarding Flex. Simple as it can be! Time for action - upgrading Flex If you are going to use pure AS3 (by using FlashDevelop or Flash Builder), or even basic Flex without any IDE, then you need to compile your source code with a newer version of Flex that can handle Stage3D. At the time of writing, the best version to use is build 19786. You can download it from the following URL: Remember to change your IDE's compilation settings to use the new version of Flex you just downloaded. For example, if you are using Flash Builder as part of the Abode Flex SDK, create a new ActionScript project: File | New | ActionScript project. Open the project Properties panel (right-click and select Properties). Select ActionScript Compiler from the list on the left. Use the Configure Flex SDK's option in the upper-right hand corner to point the project to Flex build 19786 and then click on OK. Alternately, if you are using FlashDevelop, you need to instruct it to use this new version of Flex by going into Tools | Program Settings | AS3 Context | Flex SDK Location and browsing to your new Flex installation folder. Time for action - upgrading the Flex playerglobal.swc If you use FlashDevelop, Flash Builder, or another tool such as FDT, all ActionScript compiling is done by Flex. In order to instruct Flex about the Stage3D-specific code, you need a small file that contains definitions of all the new AS3 that is available to you. It will eventually come with the latest version of these tools and you won't need to manually install it as described in the following section. During the Flash 11 beta period, you can download the Stage3D-enabled playerglobal.swc file from the following URL: Rename this file to playerglobal.swc and place it into an appropriate folder. Instruct your compiler to include it in your project. For example, you may wish to copy it to your Flex installation folder, in the flex/frameworks/libs/player/11 folder. In some code editors, there is no option to target Flash 11 (yet). By the time you read this book, upgrades may have enabled it. However, at the time of writing, the only way to get FlashDevelop to use the SWC is to copy it over the top of the one in the flex/frameworks/libs/player/10.1 folder and target this new "fake" Flash 10.1 version. Once you have unzipped Flex to your preferred location and copied playerglobal.swc to the preceding folder, fire up your code editor. Target Flash 11 in your IDE--or whatever version number that is associated with the folder, which you used as the location for playerglobal.swc. Be sure that your IDE will compile this particular SWC along with your source code. In order to do so in Flash Builder, for example, simply select "Flash Player 11" in the Publish Settings. If you use FlashDevelop, then open a new project and go into the Project--->Properties--->Output Platform Target drop-down list. Time for action - using SWF Version 13 when compiling in Flex Finally, Stage3D is considered part of the future "Version 13" of Flash and therefore, you need to set your compiler options to compile for this version. You will need to target SWF Version 13 by passing in an extra compiler argument to the Flex compiler: -swf-version=13. 1. If you are using Adobe Flash CS5, then you already copied an XML file which has all the changes, as outlined below and this is done automatically for you. 2. If you are using Flex on the command line, then simply add the preceding setting to your compilation build script command-line parameters. 3. If you are using Flash Builder to compile Flex, open the project Properties panel (right-click and choose Properties). Select ActionScript Compiler from the list on the left. Add to the Additional compiler arguments input: -swf-version=13. This ensures the outputted SWF targets SWF Version 13. If you compile on the command line and not in Flash Builder, then you need to add the same compiler argument. 4. If you are using FlashDevelop, then click on Project | Properties | Compiler Options | Additional Compiler Options, and add -swf-version=13 in this field. Time for action - updating your template HTML file You probably already have a basic HTML template for including Flash SWF files in your web pages. You need to make one tiny change to enable hardware 3D. Flash will not use hardware 3D acceleration if you don't update your HTML file to instruct it to do so. All you need to do is to always remember to set wmode=direct in your HTML parameters. For example, if you use JavaScript to inject Flash into your HTML (such as SWFObject.js), then just remember to add this parameter in your source. Alternately, if you include SWFs using basic HTML object and embed tags, your HTML will look similar to the following: The only really important parameter is wmode=direct (and the name of your swf file)-- everything else about how you put Flash into your HTML pages remains the same. In the future, if you are running 3D demos and the frame rate seems really choppy, you might not be using hardware 3D acceleration. Be sure to view-source of the HTML file that contains your SWF and check that all mentions of the wmode parameter are set to direct. Stage3D is now set up! That is it! You have officially gone to the weapons store and equipped yourself with everything you require to explore the depths of Flash 11 3D graphics. That was the hard part. Now we can dive in and get to some coding, which turns out to be the easy part. Step 2: Start coding In Step 1, you downloaded and installed everything you need to get the Stage3D source code to compile. Whether you use Adobe CS5, Flash Builder, FlashDevelop, or you compile Flex from the command line, the actual AS3 source code required to get Stage3D working is exactly the same. This is the demo that you will program in this article: If you are the impatient type, then you can download the final source code project that you would create if you followed the steps below from the following URL: For the sake of learning, however, why not go through the following steps, so that you actually understand what each line does? It is a poor warrior who expects to hone their skills without training. Time for action - creating an empty project Your next quest is simply to prepare an empty project in whatever tool-set you like. For the sake of matching the following source code, create a class named Stage3dGame that extends Sprite, which is defined in an as3 file named Stage3dGame.as. How you do so depends on your tool of choice. Flash veterans and artists often prefer to work within the comfortable Adobe Flash IDE environment, surrounded by their old friends, the timeline, and the library palette. Create a brand new .FLA file, and prepare your project and stage as you see fit. Don't use any built-in Flash MovieClips for now. Simply create an empty .FLA that links to an external .AS3 file, as shown in the following screenshot: Some game developers prefer to stick with pure AS3 projects, free of any bloat related to the Flash IDE or Flex that uses MXML files. This technique results in the smallest source files, and typically involves use of open source (free) code editors such as FlashDevelop. If this is your weapon of choice, then all you need to do is set up a blank project with a basic as3 file that is set to compile by default. No matter what tool you are using, once you have set up a blank project, your ultra-simplistic as3 source code should look something like the following: package { [SWF(width="640", height="480", frameRate="60", backgroundColor="#FFFFFF")] public class Stage3dGame extends Sprite { } } What just happened? As you might imagine, the preceding source code does almost nothing. It is simply a good start, an empty class, ready for you to fill in with all sorts of 3D game goodness. Once you have a "blank" Flash file that uses the preceding class and compiles without any errors, you are ready to begin adding the Stage3D API to it. Time for action - importing Stage3D-specific classes In order to use vertex and fragment programs (shaders), you will need some source code from Adobe. The files AGALMiniAssembler.as and PerspectiveMatrix3D.as are included in the project source code that comes with this book. They belong in your project's source code folder in the subdirectory com/adobe/utils/, so they can be included in your project. Once you have these new .as files in your source code folder, add the following lines of code which import various handy functions immediately before the line that reads "public class Stage3dGame extends Sprite". import com.adobe.utils.*; import flash.display.*; import flash.display3D.*; import flash.display3D.textures.*; import flash.events.*; import flash.geom.*; import flash.utils.*; What just happened? In the lines of the preceding code, you instruct Flash to import various utility classes and functions that you will be using shortly. They include 3D vector math, Stage3D initializations, and the assembler used to compile fragment and vertex programs used by shaders. Try to compile the source. If you get all sorts of errors that mention unknown Molehill-related classes (such as display3D), then your compiler is most likely not set up to include the playerglobal.swc we downloaded earlier. You will need to check your compiler settings or Flex installation to ensure that the brand new Stage3D-capable playerglobal.swc is being used as opposed to an older version. If you get errors complaining about missing com.adobe.utils, then you may not have unzipped the AGALMiniAssembler.as andPerspectiveMatrix3D.as code into the correct location. Ensure these files are in a subfolder of your source directory called com/adobe/utils/. If your code compiles without errors, you are ready to move on. Time for action - initializing Molehill The next step is to actually get the Stage3D API up and running. Add the following lines of code to your project inside the empty class you created by updating the empty Stage3dGame function and adding the init function below it as follows: public function Stage3dGame() { if (stage != null) init(); else addEventListener(Event.ADDED_TO_STAGE, init) } private function init(e:Event = null):void { if (hasEventListener(Event.ADDED_TO_STAGE)) removeEventListener(Event.ADDED_TO_STAGE, init); // class constructor - sets up the stage stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; // and request a context3D from Stage3d stage.stage3Ds[0].addEventListener( Event.CONTEXT3D_CREATE, onContext3DCreate); stage.stage3Ds[0].requestContext3D(); } What just happened? This is the constructor for your Stage3dGame class, followed by a simple init function that is run once the game has been added to the stage. The init function instructs Flash how to handle the stage size and then requests a Context3D to be created. As this can take a moment, an event is set up to instruct your program when Flash has finished setting up your 3D graphics. Time for action - defining some variables Next, your demo is going to need to store a few variables. Therefore, we will define these at the very top of your class definition, above any of the functions, as follows: // constants used during inits private const swfWidth:int = 640; private const swfHeight:int = 480; private const textureSize:int = 512; // the 3d graphics window on the stage private var context3D:Context3D; // the compiled shader used to render our mesh private var shaderProgram:Program3D; // the uploaded vertexes used by our mesh private var vertexBuffer:VertexBuffer3D; // the uploaded indexes of each vertex of the mesh private var indexBuffer:IndexBuffer3D; // the data that defines our 3d mesh model private var meshVertexData:Vector. ; // the indexes that define what data is used by each vertex private var meshIndexData:Vector. ; // matrices that affect the mesh location and camera angles private var projectionMatrix:PerspectiveMatrix3D =new PerspectiveMatrix3D(); private var modelMatrix:Matrix3D = new Matrix3D(); private var viewMatrix:Matrix3D = new Matrix3D(); private var modelViewProjection:Matrix3D = new Matrix3D(); // a simple frame counter used for animation private var t:Number = 0; What just happened? The demo you are writing needs to store things such as the current camera angle, the vertex, and fragment programs that we are about to create, and more. By defining them here, each of the functions we are about to write can access them. Time for action - embedding a texture Before we start creating the functions that perform all the work, let's also define a texture. Copy any 512x512 jpeg image into your source folder where you are putting all the files for this demo. If you are using Flex or a pure AS3 programming environment such as Flash Builder or FlashDevelop, then you don't need to do anything further. If you are using Adobe Flash CS5, then you will need to open the Library palette (F11) and drag-and-drop the jpg file, so that the image is part of your .FLA file's library, as shown in the following screenshot: Once this texture is in the library, right-click on it and open properties. Click on the Advanced button to view more options and turn on the check mark that enables Export for ActionScript and give the new class the name myTextureBitmapData. This will be used below. If you are using Flash CS5, then add the following code just after the other variables you recently defined: private var myBitmapDataObject:myTextureBitmapData = new myTextureBitmapData(texture_size, texture_size); private var myTextureData:Bitmap = new Bitmap(myBitmapDataObject); // The Molehill Texture that uses the above myTextureData private var myTexture:Texture; If you are using Flex or a pure AS3 environment, you do not have a "library" and instead, can embed assets using a line of code. Instead of the preceding code, define your texture in the following way: [Embed (source = "texture.jpg")] private var myTextureBitmap:Class; private var myTextureData:Bitmap = new myTextureBitmap(); // The Molehill Texture that uses the above myTextureData private var myTexture:Texture; What just happened? The code you just entered embeds the JPG image you selected for use as a texture. This texture will eventually be drawn on the mesh we are about to define. Time for action - defining the geometry of your 3D mesh For the purposes of this simple demo, all we need to define is a "quad" (a square). We will define it now as follows: private function initData():void { // Defines which vertex is used for each polygon // In this example a square is made from two triangles meshIndexData = Vector. ([ 0, 1, 2, 0, 2, 3, ]); // Raw data used for each of the 4 vertexes // Position XYZ, texture coordinate UV, normal XYZ meshVertexData = Vector. ( [ //X, Y, Z, U, V, nX, nY, nZ -1, -1, 1, 0, 0, 0, 0, 1, 1, -1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, -1, 1, 1, 0, 1, 0, 0, 1 ]); } What just happened? The preceding function fills a couple of variables with numerical data. This data is eventually sent to the video card and is used to define the locations of each vertex in your 3D mesh. For now, all we have defined is a simple square, which is made up of two triangles that use a total of four vertexes. Eventually, your models will be complex sculptures, made up of thousands of polies. Anything from a sword to an entire city can be constructed by listing the x,y,z locations in space for each of a mesh's vertexes. For now, a simple square will be proof-of-concept. Once we can get a square spinning around in 3D, adding more detail is a trivial process. Time for action - starting your engines Recall that the init() function requests a Context3D object. An event handler was set up that Flash will run when your video card has prepared itself and is ready to receive data. Let's define this event handler. The perfect place for this new snippet of code is just below the init() function: private function onContext3DCreate(event:Event):void { // in case it is not the first time this event fired removeEventListener(Event.ENTER_FRAME,enterFrame); // Obtain the current context var t:Stage3D = event.target as Stage3D; context3D = t.context3D; if (context3D == null) { // Currently no 3d context is available (error!) return; } // Disabling error checking will drastically improve performance. // If set to true, Flash will send helpful error messages regarding // AGAL compilation errors, uninitialized program constants, etc. context3D.enableErrorChecking = true; // Initialize our mesh data initData(); What just happened? Inside the onContext3DCreate event handler, all your Stage3D inits are performed. This is the proper moment for your game to upload all the graphics that will be used during play. The reasons you cannot upload data during the constructor you already wrote are: . It can take a fraction of a second before your device drivers, 3D card, operating system, and Flash have prepared themselves for action. . Occasionally, in the middle of your game, the Context3D can become invalidated. . This can happen, for example, if the user's computer goes to "sleep", or if they hit Ctrl-Alt-Delete. For this reason, it is entirely possible that during the play, the mesh and texture data will need to be re-sent to your video RAM. As it can happen more than once, this event handler will take care of everything whenever it is needed. If you read the comments, you will be able to follow along. Firstly, as the event might fire more than once, any animation is turned off until all data has been re-sent to the video card. A Context3D object is obtained and so we remember it by assigning it to one of the variables we defined earlier. We turn on error checking, which is handy during development. Once we are finished with our our game, we will turn this off in order to get a better frame rate. Time for action - adding to the onContext3DCreate function The next thing we need to do in our onContext3DCreate function is to define the size of the area we want to draw to and create a simple shader that instructs Stage3D how to draw our mesh. Continue adding to the function as follows: // The 3d back buffer size is in pixels context3D.configureBackBuffer(swfWidth, swfHeight, 0, true); // A simple vertex shader which does a 3D transformation var vertexShaderAssembler:AGALMiniAssembler = new AGALMiniAssembler(); vertexShaderAssembler.assemble ( Context3DProgramType.VERTEX, // 4x4 matrix multiply to get camera angle "m44 op, va0, vc0\n" + // tell fragment shader about XYZ "mov v0, va0\n" + // tell fragment shader about UV "mov v1, va1\n" ); // A simple fragment shader which will use // the vertex position as a color var fragmentShaderAssembler:AGALMiniAssembler = new AGALMiniAssembler(); fragmentShaderAssembler.assemble ( Context3DProgramType.FRAGMENT, // grab the texture color from texture fs0 // using the UV coordinates stored in v1 "tex ft0, v1, fs0 <2d,repeat,miplinear>\n" + // move this value to the output color "mov oc, ft0\n" ); // combine shaders into a program which we then upload to the GPU shaderProgram = context3D.createProgram(); shaderProgram.upload(vertexShaderAssembler.agalcode, fragmentShaderAssembler.agalcode); What just happened? A back-buffer is set up, which is a temporary bitmap in the video RAM where all the drawing takes place. As each polygon is rendered, this back-buffer slowly becomes the entire scene, which when completed is presented to the user. Two AGALMiniAssembler objects are created and a string containing AGAL (Adobe Graphics Assembly Language) is turned into compiled byte code. Don't worry too much about the specific AGAL code for now, we will dive into fragment and vertex programs later. Essentially, these AGAL commands instruct your video card exactly how to draw your mesh. We will continue working with the Context3DCreate function. Time for action - uploading our data In order to render the mesh, Stage3D needs to upload the mesh and texture data straight to your video card. This way, they can be accessed repeatedly by your 3D hardware without having to make Flash do any of the "heavy lifting". // upload the mesh indexes indexBuffer = context3D.createIndexBuffer(meshIndexData.length); indexBuffer.uploadFromVector(meshIndexData, 0, meshIndexData.length); // upload the mesh vertex data // since our particular data is // x, y, z, u, v, nx, ny, nz // each vertex uses 8 array elements vertexBuffer = context3D.createVertexBuffer( meshVertexData.length/8, 8); vertexBuffer.uploadFromVector(meshVertexData, 0, meshVertexData.length/8); // Generate mipmaps myTexture = context3D.createTexture(textureSize, textureSize, Context3DTextureFormat.BGRA, false); var ws:int = myTextureData.bitmapData.width; var hs:int = myTextureData.bitmapData.height; var level:int = 0; var tmp:BitmapData; var transform:Matrix = new Matrix(); tmp = new BitmapData(ws, hs, true, 0x00000000); while ( ws >= 1 && hs >= 1 ) { tmp.draw(myTextureData.bitmapData, transform, null, null, null, true); myTexture.uploadFromBitmapData(tmp, level); transform.scale(0.5, 0.5); level++; ws >>= 1; hs >>= 1; if (hs && ws) { tmp.dispose(); tmp = new BitmapData(ws, hs, true, 0x00000000); } } tmp.dispose(); What just happened? In the preceding code, our mesh data is uploaded to the video card. A vertex buffer and an index buffer are sent, followed by your texture data. There is a short loop that creates similar, but smaller versions of your texture and uploads for each one. This technique is called MIP mapping. By uploading a 512x512 image, followed by the one that is 256x256, then 128x128, and so on down to 1x1, the video card has a set of textures that can be used depending on how far away or acutely angled the texture is to the camera. MIP mapping ensures that you don't get any "jaggies" or "moiree patterns" and increases the quality of the visuals. Time for action - setting up the camera There is one final bit of code to add in our onContext3DCreate() function. We simply need to set up the camera angle and instruct Flash to start the animation. We do this as follows: // create projection matrix for our 3D scene projectionMatrix.identity(); // 45 degrees FOV, 640/480 aspect ratio, 0.1=near, 100=far projectionMatrix.perspectiveFieldOfViewRH( 45.0, swfWidth / swfHeight, 0.01, 100.0); // create a matrix that defines the camera location viewMatrix.identity(); // move the camera back a little so we can see the mesh viewMatrix.appendTranslation(0,0,-4); // start animating addEventListener(Event.ENTER_FRAME,enterFrame); } What just happened? A set of matrices are defined that are used by your shader to calculate the proper viewing angle of your mesh, as well as the specifics related to the camera, such as the field of a view (how zoomed in the camera is) and the aspect ratio of the scene. Last but not the least; now that everything is set up, an event listener is created that runs the enterFrame function every single frame. This is where our animation will take place. That is it for the Stage3D setup. We are done programming the onContext3DCreate function. Time for action - let's animate The enterFrame function is run every frame, over and over, during the course of your game. This is the perfect place to change the location of your meshes, trigger sounds, and perform all game logic. private function enterFrame(e:Event):void { // clear scene before rendering is mandatory context3D.clear(0,0,0); context3D.setProgram ( shaderProgram ); // create the various transformation matrices modelMatrix.identity(); modelMatrix.appendRotation(t*0.7, Vector3D.Y_AXIS); modelMatrix.appendRotation(t*0.6, Vector3D.X_AXIS); modelMatrix.appendRotation(t*1.0, Vector3D.Y_AXIS); modelMatrix.appendTranslation(0.0, 0.0, 0.0); modelMatrix.appendRotation(90.0, Vector3D.X_AXIS); // rotate more next frame t += 2.0; // clear the matrix and append new angles modelViewProjection.identity(); modelViewProjection.append(modelMatrix); modelViewProjection.append(viewMatrix); modelViewProjection.append(projectionMatrix); // pass our matrix data to the shader program context3D.setProgramConstantsFromMatrix( Context3DProgramType.VERTEX, 0, modelViewProjection, true ); What just happened? In the preceding code, we first clear the previous frame from the screen. We then select the shader (program) that we defined in the previous function, and set up a new modelMatrix. The modelMatrix defines the location in our scene of the mesh. By changing the position (using the appendTranslation function), as well as the rotation, we can move our mesh around and spin it to our heart's content. Time for action - setting the render state and drawing the mesh Continue adding to the enterFrame() function by instructing Stage3D which mesh we want to work with and which texture to use. // associate the vertex data with current shader program // position context3D.setVertexBufferAt(0, vertexBuffer, 0, Context3DVertexBufferFormat.FLOAT_3); // tex coord context3D.setVertexBufferAt(1, vertexBuffer, 3, Context3DVertexBufferFormat.FLOAT_3); // which texture should we use? context3D.setTextureAt(0, myTexture); // finally draw the triangles context3D.drawTriangles(indexBuffer, 0, meshIndexData.length/3); // present/flip back buffer context3D.present(); } What just happened? Once you have moved objects around and prepared everything for the next frame (by instructing Stage3D which vertex buffer to draw and what texture to use), the new scene is rendered by calling drawTriangles and is finally presented on the screen. In the future, when we have a more complex game, there will be more than one mesh, with multiple calls to drawTriangles and with many different textures being used. For now, in this simple demo, all we do each frame is spin the mesh around a little and then draw it. Quest complete - time to reap the rewards Now that the entire source code is complete, publish your .SWF file. Use your web browser to view the published HTML file. You should see something similar to the following: If you see nothing on the screen when you view the HTML file that contains your new SWF, then your Flash incubator plugin is probably not being used. With fingers crossed, you will see a fully 3D textured square spinning around in space. Not much to look at yet, but it proves that you are running in the hardware accelerated 3D mode. Congratulations! You have just programmed your first Flash 11 Stage3D (Molehill) demo! It does not do much, but already you can see the vast possibilities that lay ahead of you. Instead of a simple square spinning around, you could be rendering castles, monsters, racing cars, or spaceships, along with all the particle systems, eye-candy, and special effects you could imagine. For now, be very proud that you have overcome the hardest part--getting a working 3D demo that compiles. Many before you have tried and failed, either because they did not have the proper version of Flash, or did not have the correct tools setup, or finally could not handle the complex AS3 source code required. The fact that you made it this far is a testament to your skill and coding prowess. You deserve a break for now. Rest easy in the satisfaction, as you just reached a major milestone toward the goal of creating an amazing 3D game. The entire source code All the code that you entered earlier should go in a file named Stage3dGame.as alongside your other project files. For reference, or to save typing, all source and support files are available at the following URL: The final demo can be run from the following URL: Your folder structure should look similar to the one shown in the following screenshot. You might have used different file names for your html files or texture, but this screenshot may be helpful to ensure you are on the right track: Have a go hero - a fun side quest In order to really hone your skills, it can be a good idea to challenge yourself for some extra experience.There is a side quest with which you can experiment. It is completely optional. Just like grinding in an RPG game, challenges such as these are designed to make you stronger, so that when you forge ahead, you are more than ready for the next step in your main quest. Your side quest this time is to experiment with the mesh data. Doing so will help you understand what each number stored in the meshVertexData variable (which is defined in the initData function) means. Play with all these numbers. Notice that each line of eight numbers is the data used for one vertex. See what happens if you give them crazy values. For example, if you change the first vertex position to -3, your square will change shape and will become lopsided with one corner sticking out: meshVertexData = Vector. ( [ //X, Y, Z, U, V, nX, nY, nZ -3, -1, 1, 0, 0, 0, 0, 1, 1, -1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, -1, 1, 1, 0, 1, 0, 0, 1 ]); If you tweak the U or V texture coordinates, then you can make the rock texture more zoomed in or tiled multiple times. If you change the vertex normals (the last three numbers of each line above), then nothing will happen. Why? The reason is that the ultra-simplistic shader that we are using does not use normal data. If all this seems a bit low level, then do not worry. Eventually, you won't be defining mesh data by hand using lists of numbers entered in the code: in the near future, we will upgrade our game engine to parse the model data that we can export from a 3D art program, such as 3D Studio Max, Maya, or Blender. For now, however, this simple "side quest" is a great way to start becoming familiar with what a vertex buffer really is. Summary We were victorious in our first "boss battle" along the way to the creation of our own 3D video game in Flash. It was tricky, but somehow we managed to achieve the following milestones: we learned how to obtain Flash 11 for our browser, we got all the tools ready to compile Stage3D games, we learned how to initialize the Stage3D API, how to upload mesh and texture data to the video card, and how to animate a simple 3D scene. Now that we have created a simple template 3D demo, we are ready to add more complexity to our project. What was merely a tech demo will soon grow into a fully-fledged video game.
https://www.gamedev.net/articles/programming/general-and-gameplay-programming/adobe-flash-11-stage3d-setting-up-our-tools-r2850?md=viewrev&rva=0&rvb=0
CC-MAIN-2017-30
refinedweb
5,902
61.36
MS property subscript expression. More... #include "clang/AST/ExprCXX.h" MS property subscript expression. MSVC supports 'property' attribute and allows to apply it to the declaration of an empty array in a class or structure definition. For example: The above statement indicates that x[] can be used with one or more array indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), and p->x[a][b] = i will be turned into p->PutX(a, b, i). This is a syntactic pseudo-object expression. Definition at line 818 of file ExprCXX.h. Definition at line 863 of file ExprCXX.h. References clang::Stmt::getStmtClass().
https://clang.llvm.org/doxygen/classclang_1_1MSPropertySubscriptExpr.html
CC-MAIN-2018-39
refinedweb
112
59.8
[001] Create WPF Projects Like a PRO erkn ・2 min read TL;DR; Read only bold ones you fat. I bet, you didn't know you can do like this. [1] A purpose to open a WPF project [2] JetBrains Rider (No Tonny, Visual Studio is bad for your health.) [3] Open Rider ♥ [4] Click New Solution [5] Select .Net Core (But sir I don't want dotnet core, I want my project in normal regular NetFramework X.Y bla bla bla...) Just select the fucking DotNet Core Desktop Application I will get there alright. [6] Check Create .git and thank me now. [7] Finally, hit the Create button (Do not forget to give a name to your $0.0F project.) [8] Open the [projectname].csproj file. We have work to do. [9] Change <TargetFramework> to <TargetFrameworks> for supporting more customer and earn more money and do more writing of course. [10] Since you don't want to write with .Net Core remove netcoreapp3.1 and write net48 [11] For now, you should be able to Build and Run your project and see the worthless Window. Well done! You might want to add multiple projects for your Business or Core or BLL for your garbage code. [12] Guess next step. When you are creating new project you will always use .NetCore alrigt. To understand the reasion you can create a regular project and compare *.csproj files. [13] Go create a .NetCore ClassLibrary and repeat [8], [9] and [10] [14] When you are create a class library on Rider, it does not automatically adds <UseWPF>true</UseWPF> like it adds on DesktopApplication so add it. [15] Also same goes for Sdk="Microsoft.NET.Sdk.WindowsDesktop" too. [16] As last step before write your own code create a class named AssemblyInfo.cs with filled with code: using System.Windows; [assembly: ThemeInfo( ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly )] Now you are good to go. If you do not do step [14] or [15] or [16] Rider cannot build and complain that you suck and do not deserve to use JetBrains Rider so you should go back to use Visual Studio like every regular boring developers do. (When Rider fixes this problem, this paragraph will destroy itself.). 🎩 JavaScript Enhanced Scss mixins! 🎩 concepts explained In the next post we are going to explore CSS @apply to supercharge what we talk about here....
https://practicaldev-herokuapp-com.global.ssl.fastly.net/erkantaylan/001-create-wpf-projects-like-a-pro-12ba
CC-MAIN-2020-24
refinedweb
395
76.01
Question 1 : Is there any difference between the following two statements? char *p=0; char *t=NULL; NULL is #defined as 0 in the 'stdio.h' file. Thus, both p and t are NULL pointers. Question 2 : Is this a correct way for NULL pointer assignment? int i=0; char *q=(char*)i; The correct way is char *q=0 (or) char *q=(char*)0 Question 3 : Is the NULL pointer same as an uninitialised pointer? Question 4 : Will the program compile in Turbo C? #include < stdio.h > int main() { int a=10, *j; void *k; j=k=&a; j++; k++; printf("%u %u\n", j, k); return 0; } Error in statement k++. We cannot perform arithmetic on void pointers. The following error will be displayed while compiling above program in TurboC. Compiling PROGRAM.C: Error PROGRAM.C 8: Size of the type is unknown or zero. Question 5 : Will the following program give any warning on compilation in TurboC (under DOS)? #include < stdio.h > int main() { int *p1, i=25; void *p2; p1=&i; p2=&i; p1=p2; p2=p1; return 0; }
http://www.indiaparinam.com/c-programming-language-question-answer-pointers/yes-no-questions
CC-MAIN-2019-22
refinedweb
183
75.91
In Hour 4, "The Building Blocks," we looked at defining global constants. Remember that constants hold values that cannot be changed during script execution. You define global constants using the define() function. As of PHP 5, you can define constants within classes. You declare a constant using the const keyword at the top of your class: class MyClass { const PI = 3.14; //... Constants are available via the class rather than an object: print MyClass::PI; This aspect makes a class constant useful when the value it contains applies equally to all objects of the type and when the value should be fixed and unchangeable. Let's work through a simple example. In Listing 17.1, we present a fragment of an Item class. An Item in this example is an item of stock in a shop. We want to store an integer $status property for every Item. This single integer will combine multiple flags. We want the flags to be available globally, and we need them to be read-only. 1: <?php 2: 3: class Item { 4: const DISCONTINUED = 1; 5: const PROMOTIONAL = 2; 6: const STOCKED_OFFSITE = 4; 7: private $status = 0; 8: 9: public function addStatus( $num ) { 10: $this->status | = $num; 11: } 12: 13: public function isPromotional() { 14: return ( Item::PROMOTIONAL & $this->status )?true:false; 15: } 16: 17: public function isDiscontinued() { 18: return ( Item::DISCONTINUED & $this->status )?true:false; 19: } 20: 21: public function isOffsiteItem() { 22: return ( Item::STOCKED_OFFSITE & $this->status )?true:false; 23: } 24: } 25: 26: $item = new Item(); 27: $item->addStatus( Item::STOCKED_OFFSITE ); 28: $item->addStatus( Item::PROMOTIONAL ); 29: $item->addStatus( Item::DISCONTINUED ); 30: 31: if ( $item->isOffsiteItem() ) { 32: print "This item is stocked at our warehouse. Delivery within 4 days"; 33: } 34: ?> We define three class constant flags on lines 4 to 6. It's easiest to think of these flags in binary terms: 001 = 1 010 = 2 100 = 4 The idea is that we can combine each of those numbers in a single $status property by using the binary or (|) operator. This process sets the bits that are set in either one operand or the other: 1 | 2 == 3 001 or 010 equals 011 We perform the operation to combine flags in the addStatus() method on line 9. We call addStatus() on lines 27 to 29, setting all the available bits. Notice how we access the status flags using the class name and not the object handle. The rest of the class consists of methods to check the $status array. Let's look at isDiscontinued() on line 17. We use the binary and (&) operator to compare $status with the constant flag Item::DISCONTINUED. This test compares the bits in the two operands and resolves to a new number that contains only the bits that the two numbers have in common: 111 $status 001 DISCONTINUED 001 result of 'and' operation The effect of this operation is that isDiscontinued() will only return true if Item::DISCONTINUED has been passed to addStatus(). Another common use for class constants is to store error codes that can be set and tested when an object fails in an operation.
http://books.gigatux.nl/mirror/php24hours/0672326191_ch17lev1sec1.html
CC-MAIN-2018-09
refinedweb
518
62.07
Checks and fixups¶ Automatic fixups¶ In addition to Quality checks, Weblate can also automatically fix some common errors in translated strings. This can be quite powerful feature to prevent common mistakes in translations, however use it with caution as it can cause silent corruption as well. See also Quality checks¶ Weblate does wide range of quality checks on messages. The following section describes them in more detail. The checks take account also special rules for different languages, so if you think the result is wrong, please report a bug. See also CHECK_LIST, Customizing checks Translation checks¶ These are executed on every translation change and help translators to keep good quality of translations. Unchanged translation¶ The source and translated strings are the same at least in one of the plural forms. This check ignores some strings which are quite usually same in all languages and strips various markup, which can occur in the string, to reduce number of false positives. This check can help finding strings which were mistakenly not translated . Starting or trailing newline¶ Source and translated do not both start (or end) with a newline. Newlines usually appear in source string for a good reason, so omitting or adding it can lead to formatting problems when the translated text is used in the application. Starting spaces¶ Source and translation do not both start with same number of spaces. Space in beginning is usually used for indentation in the interface and thus is important to keep. Trailing space¶ Source and translated do not both end with a space. Trailing space is usually used to give space between neighbouring elements, so removing it might break application layout. Trailing stop¶ Source and translated do not both end with a full stop. Full stop is also checked in various language variants (Chinese, Japanese, Devanagari or Urdu). When the original string is a sentence, the translated one should be a sentence as well to be consistent within the translated content. Trailing colon¶ Source and translated do not both end with a colon or the colon is not correctly spaced. This includes spacing rules for languages like French or Breton. Colon is also checked in various language variants (Chinese or Japanese). Colon is part of a label and should be kept to provide consistent translation. Weblate also checks for various typographic conventions for colon, for example in some languages it should be preceded with space. Trailing question¶ Source and translated do not both end with a question mark or it is not correctly spaced. This includes spacing rules for languages like French or Breton. Question mark is also checked in various language variants (Armenian, Arabic, Chinese, Korean, Japanese, Ethiopic, Vai or Coptic). Question mark indicates question and this semantics should be kept in translated string as well. Weblate also checks for various typographic conventions for question mark, for example in some languages it should be preceded with space. Trailing exclamation¶ Source and translated do not both end with an exclamation mark or it is not correctly spaced. This includes spacing rules for languages like French or Breton. Exclamation mark is also checked in various language variants (Chinese, Japanese, Korean, Armenian, Limbu, Myanmar or Nko). Exclamation mark indicates some important statement and this semantics should be kept in translated string as well. Weblate also checks for various typographic conventions for exclamation mark, for example in some languages it should be preceded with space. Trailing ellipsis¶ Source and translation do not both end with an ellipsis. This only checks for real ellipsis ( …) not for three dots ( ...). Ellipsis is usually rendered nicer than three dots, so it’s good to keep it when the original string was using that as well. See also Trailing semicolon¶ Source and translation do not both end with a semicolon. This can be useful to keep formatting of entries such as desktop files. Maximum Length¶ Translation is too long to accept. This only checks for the length of translation characters. Source and translation usually do not have same amount of characters, but if translation is too long, it can be affect a rendered shape. For example, in some UI widget, it should be kept in a specific length of characters in order to show complete translation within limited space. Unlike the other checks, the flag should be set as a key:value pair like max-length:100. Format strings¶ Format string does not match source. Weblate supports following formats: - Python format - Python brace format - PHP format - C format - Perl format - Javascript format - AngularJS interpolation string Omitting format string from translation usually cause severe problems, so you should really keep the format string matching the original one. Missing plurals¶ Some plural forms are not translated. Check plural form definition to see for which counts each plural form is being used. Not filling in some plural forms will lead to showing no text in the application in case this plural would be displayed. Same plurals¶ Some plural forms are translated same. In most languages the plural forms have to be different, that’s why this feature is actually used. Inconsistent¶ More different translations of one string in a project. This can also lead to inconsistencies in displayed checks. You can find other translations of this string on All locations tab. Weblate checks translations of the same string across all translation within a project to help you keep consistent translations. Has been translated¶ This string has been translated in the past. This can happen when the translations have been reverted in VCS or otherwise lost. Mismatched \n¶ Number of \n in translation does not match source. Usually escaped newlines are important for formatting program output, so this should match to source. Mismatched BBcode¶ BBcode in translation does not match source. This code is used as a simple markup to highlight important parts of a message, so it is usually a good idea to keep them. Note The method for detecting BBcode is currently quite simple so this check might produce false positives. Zero-width space¶ Translation contains extra zero-width space (<U+200B>) character. This character is usually inserted by mistake, though it might have legitimate use. Some programs might have problems when this character is used. See also Zero width space on wikipedia Source checks¶ Source checks can help developers to improve quality of source strings. Optional plural¶ The string is optionally used as plural, but not using plural forms. In case your translation system supports this, you should use plural aware variant of it. For example with Gettext in Python it could be: from gettext import ngettext print ngettext('Selected %d file', 'Selected %d files', files) % files Ellipsis¶ The string uses three dots ( ...) instead of an ellipsis character ( …). Using Unicode character is in most cases the better approach and looks better when rendered. See also Multiple failing checks¶ More translations of this string have some failed quality checks. This is usually an indication that something could be done about improving the source string. This check can quite often be caused by a missing full stop at the end of a sentence or similar minor issues which translators tend to fix in translations, while it would be better to fix it in a source string.
https://docs.weblate.org/en/weblate-2.16/user/checks.html
CC-MAIN-2018-34
refinedweb
1,200
63.39
How to Calculate Investment Returns By: Lane Kawaoka (Simple Passive Cash Flow) Note: Article originally published on Simple Passive Cash Flow. Article re-posted with permission. To view the original article, click here. There are potentially better investments (risk divided by reward) backed up by a hard asset, however, those deals are not obtainable by the average individual who does not have access to a rich and powerful network of people and who does not have a net worth exceeding $1-million. The simple rental property is something that is accessible to everyone and today we are talking about the math behind it. So put on your propeller hats, because we’re about to talk numbers. As a rental investor you make money four ways: - Cash Flow - Appreciation - Tax Benefits - Principal Reduction/Debt Paydown Cashflow Cashflow is your income (rents), minus your expenses and mortgage. For example, if your tenant pays you $1,000 a month and if your monthly expenses including principal, interest, taxes, insurance, and maintenance/occupancy reserve are $800 a month, then the $200 difference is now income in your pocket. The goal is to keep acquiring rentals that will increase your passive cashflow. It is this cashflow that is the money that you will live off of to be able to quit your day job. In the board game ‘Cashflow,’ you win when your cashflow is greater than your expenses. When this happens you have “escaped the rat race” and able to spend your time doing things that are more meaningful to you. I recognize that in the Real Estate investing community there are two camps: - Cashflow focused - Appreciation focused Folks in the appreciation focused group feel that buying homes in the Midwest is silly because those “fly over States” never appreciate, and they fail to see the hidden benefits of real estate. I underwrite my deals to look at the bigger picture, knowing that it is the cashflow that will eventually replace my income from my day job. I admit that this will widely depend on what you use as the assumed average appreciation for the purchases in markets with more rapid appreciation, but appreciation is not constant — it is cyclical, and I prefer to see a steady rise. By purchasing in cashflow markets, the highs aren’t as high, but corrections aren’t as painful. I run a passive investor Meet-Up in Seattle, and there is always an old-school investor who is investing for appreciation and was one of the unlucky folks. Basically, what happened is that they bought during the wrong time in hopes that the market would go up 5–10% every year, but instead, they are underwater. And to add insult to injury, they bought it with negative cashflow and are still losing money every month. Now that investor/gambler is in the doldrums for nearly a decade unable to do anything in terms of building his/her portfolio. Appreciation This is the famous topic of dinner/cocktail parties where people brag that they bought their home for 200k and now it’s worth 400k and how they had incredible foresight. Well congratulations, appreciation “floats all boats — even ones with holes.” Despite how cool it sounds, appreciation is a hidden benefit that you only realize when you sell your investment property for greater than what you bought it for — it’s a paper gain. Even though you can’t live off appreciation like cashflow (unless you use a HELOC or refinance). Example: If you bought a home for 100k and it went up by 5% which is a pretty good year, your property would be worth 105K… but wait…your initial investment was 30k so now you have 35K. Here is the math. $30K initial investment creates $5,000 this year in equity gain 5,000/30,000=16%, is the appreciation return (3x on a 5% market gain) I’m not a fan of including this in my underwriting because I believe it is gambling, but I just wanted to show you the math behind it so you can see how your leverage is at work with government subsidized loans. It’s interesting to note that when the market goes down, more people can’t afford homeownership and turn to renting, which is good for the landlords. While an economic downtown is generally bad for those banking on appreciation, my monthly cashflow is more resistant to economic changes. Tax Benefits Your rental is a business, and if your expenses are tracking ~50% of your income, then you will be running at a near zero profit business on paper and will not have any taxable income. If you are super-sneaky, you can also pass expenses through this business of yours, but work with your CPA first and don’t get greedy. Taking illegal shortcuts will definitely cost you in the long run. But wait… the cool thing about real estate is that you can take a depreciation deduction off your taxable income. This amount is dictated by taking 1/27.5th the building value of your property for the first 27.5 years of ownership. With the expenses negating your income this depreciation incentive is taking that amount off your W-2 day job income. (Side note — unlike stocks/other assets when there is a capital gain you pay taxes on the gain you can defer capital gains tax when you sell by using a 1031 tax exchange.) Example: 100K home has a typical building value of ~$70k $70k/27.5=$2,600 per year that you are able to write-off $2,600 at the 25% tax rate is savings of $650 per year Going back to the original investment: 650/30,000=2% is the tax benefits. Not bad but I’ll take it. Principal Reduction When you rent out your home, your tenants are paying down your mortgage a little bit each month with their hard earned money — not you. You can download a great mortgage/amortization spreadsheet by signing up with your email on the sidebar menu. In the beginning of a mortgage, most of the payment is going toward the interest payment side as opposed to the principal pay down/equity for you. Just know that you don’t realize any of these gains until you sell/refinance the property but it’s there. 100K home (with 25% downpayment) has a typical PITI payment of around $550/month. Of that 550 only ~$150/month or ~$1800/year is going to principal paydown as equity gain. Example: 1,800/30,000=6% is the Principal Reduction benefits Congratulations on sticking with the article. The summary of the numbers are below: - Cash Flow = 12% - Appreciation = 16% - Tax Benefits = 2% - Principal Reduction/Debt Paydown = 6% - Total = 36% In this conservative example, (although there is no guarantee in anything) the total is 36% return. Pretty dang good when you compare with that mutual funds. The problem is the average person overlooks the hidden ways you can make money. Love Hate Relationship with Appreciation When I purchase investments I define my goal as cashflow over appreciation. Like many things in life, you can’t have it all, such as both strong appreciation and strong cashflow. I invest in the boring “cashflow markets” because I define my endgame as needing passive cashflow that I can live off of. Appreciation is something I can’t live off of since it does not appear in my bank account each month. I see appreciation as the icing on the cake or the dessert with the meal. Therefore, I remove the appreciation from my calculation/underwriting and plan for those projections. For the above example the total return without appreciation would be 20% which is not bad and still greater than the stock market. I recognize appreciation has the potential to be a very large part of this return in terms of a colossal windfall in a good market (10% equals 40% gain with typical leverage) however there is also the potential for large downswings. Frankly, I try to simplify my life and therefore I am not cool with the volatility and is another reason I don’t use stocks/mutual funds. I tell a lot of investors who purchase homes with negative cashflow such as a $500k rental in Seattle that rents for $3,000 per month that they need to be conscious of what the numbers are telling them. If they can look me in the face and say they are investing for appreciation then I am cool with that — that is their goal. However, most people in this situation (Mom & Pops who were taught to just buy a property despite if it made fiscal sense) are clueless that they are losing money to the tune of a few hundred dollars each month in cashflow. If you every played Paigow Poker, investing for appreciation is like the “fortune bet” where you keep paying into the side bet in hopes of hitting it big one. For those stock-centric folks look at it this way. Appreciation in your home is similar to the gain in the price of a stock like Apple. The price of the stock goes up and down, however, the volatility is much less with rentals. There are some stocks like AT&T that produce dividends and those are similar to the cashflow from a rental. However, I don’t see many dividend stocks producing more than 4% compare with the double-digit cashflow returns from rentals. Other hidden ways you make money that I do not consider: Equity Capture This is when you buy a house for less than the market value. Many people say “you make your money when you buy” and this is what they are talking able. Personally, I pretty much buy at market value. I don’t have the time to do any work to find any deals which involve the arduous tasks of doing the direct marketing, tracking down leads, fix properties, or any of these active real estate investor past-times. Another example of this is if you bought a house for $50K, put $30K into rehab (all in for $80K) and now the property is worth 100K on the open market (disregarding transaction costs) — you just created $20K of equity capture. This is a great way to acquire assets, but it requires money, time, and effort (that might have a higher and best use at your day job). Other hidden ways you make money that I do not consider: Inflation Hedging When your parents bought a home back in 1985, they spent about $30K on the property. Their mortgage payments were ~$100-$125 dollars per month and at that time that made up a noticeable portion of their family budget. Now fast forward to today and they are still paying the same payment (taxes and insurance have gone up). This illustrates how by having a mortgage you are locking in and hedging yourself from the inflations. Here are other reasons supporting inflation is going to be greater in the future: I’m not saying that it’s going to be a total new world order but the best day to buy (and lock up 30-year mortgages) was yesterday and the 2nd best is today. Don’t use the excuse “Oh, I’m waiting for the next crash or evaluations are too high”. Instead, buy on fundamentals with healthy spreads in cashflow so when that next correction comes you are above water in terms of cashflow. The Skinny Rental real estate is the most time-tested wealth-building tool available to the average person. If you weren’t paying attention earlier, here is an acronym for you to explain to your naysayers who think you are crazy: Real estate (not particularly your primary residence) is I.D.E.A.L. I stands for Income The property produces income after it pays for expenses. This is called sash flow and it is what puts food on the table. This is a concept that most investors and regular people never understand… because most invest for appreciation or capital gain which is sort of like gambling. Rule 1 of investing is don’t lost money! consider. I am not a lawyer but, consider another view of risk. The risk we don’t think about is having equity in your property. If there is a lawsuit, you can bet you are a bigger target if you have a bunch of equity in the property. If you have prudently leveraged your investment, it’s going to be a smaller target to go after. A lot of experienced investors and non-experienced investors use large sums of cash to obtain properties at great discounts (70–80 cents on the dollar) via direct sales of pocket listings or auctions. Paying cash commands respect and is seen as a more reliable deal which is the reason for the discount on the property. The following will analyze the numbers behind this strategy and compare it to a typical 20% down payment conventional deal. Scenario A: All Cash Market Value: $100,000 Purchase Price = Money in the Deal: $75,000 Annual Cash Flow: $12,000 (assuming 1% rule) Cash on Cash Return: 12k/75k = 16% Scenario B: Typical 20% conventional deal Market Value = Purchase Price: $100,000 Money in the Deal (20%): $20,000 + $3000 for closing costs above and beyond Scenario A Annual Cash Flow: 12 months x ($1,000–540(PITI)) = $5,520 (assuming 1% rule) Cash on Cash Return: 5520/23,000 = 24% Under these circumstances, purchasing all in cash would yield 8% less in returns on your principal investment. While the cash-on-cash return will vary between properties (and is only one part of the total sum of ways you are making money as discussed in this article), using leverage will allow your money to go further. However, do the math for yourself. About: Lane Kawaoka, PE is an ex-engineer and real estate investor, currently with over 1 billion dollars assets under management. He is the founder of Simple Passive Cash Flow, where he teaches individuals how to successfully invest in real estate.
https://drchrisloomdphd.medium.com/how-to-calculate-investment-returns-f1d8fd13e915?source=read_next_recirc---------1---------------------d12cb89e_5614_4360_9c5a_a2b8548d3846-------
CC-MAIN-2022-40
refinedweb
2,368
56.89
From: Bronek Kozicki (brok_at_[hidden]) Date: 2004-01-17 11:21:19 Dear Boosters I want to ask you to take a look at file ext_auto_ptr_07.zip (size 3KB) , which is available in files section of boost YahooGroup . If you are not happy downloading file from Yahoo, you may get it from my own WWW : . Actually ext_auto_ptr_07.zip contains two files: T191.hpp and T191.cpp (both files are available standalone under ) . File T191.hpp contains improved auto_ptr (placed in namespace boost::ext), file T191.cpp is simple application using its new features (tested under MSVC71 and MINGW - GCC 3.3.1). This auto_ptr is based on Rani Sharoni proposal to improve standard std::auto_ptr. Rani's idea is to use SFINAE in smart way and remove auto_ptr_ref from standard (as there is no longer need for it). Whole story can be found here: Preliminary FAQ: Why improve auto_ptr? There are few reasons: * shared_ptr has support for deleters, while current std::auto_ptr does not. * shared_ptr can be safely used to store pointers to derived classes, without using virtual destructor. Currently auto_ptr cannot be safely used this way * support for conversion to bool which could be used in "if (my_pointer)" Because shared_ptr will possibly be included in future versions of C++ standard, I wanted to improve auto_ptr , to make it compatible with features available in shared_ptr . What does it cost? Very little. There is no additional heap allocation (as in shared_ptr), and on special CPU overhead. There is however memory overhead: smarter auto_ptr stores 3 pointers instead of 1. Added pointers are: pointer to deleter function (ie. function called to release owned pointer) and pointer to owned pointer cast to void * (this pointer will be passed to deleter function). As first pointer is actually using template function (ie. trampoline), there is also potential for code bloat and slightly longer compilation time. Is it compatible with std::auto_ptr ? You may use it safely whenever you used std::auto_ptr. There is one case when you may encounter compilation error, as a result of adding conversion to bool. This problem was best described by Rani Sharoni: > Nevertheless since it's a relaxation we must be careful about backward > compatibility issues. > Consider the following: > char* f(auto_ptr<B>); > long* f(bool); > > auto_ptr<D> dp; > char* p = f(dp); > > Without the implicit conversions to bool the above code is (read suppose to > be) well formed. The relaxed auto_ptr will yield ambiguity since there are > two user defined conversions with the same rank. Notice that this problem is > only related to bool parameters (i.e. change bool to int in the above code > and the problem will disappear). > Adding additional tie break parameters (e.g. char and int) will lead to > well-formed code with different meaning. same problem with template vs > non-template. Does it accept deleters as used in shared_ptr? Yes, but with one important limitation: there is no separate instance of deleter object for each instance of auto_ptr. Basicaly smarter auto_ptr is using static function (class function) named "free" which takes pointer being released. There are two template classes "del_functor" and "del_bind" which allow use of functor object: first one will create single (static) instance of this object and call it whenever pointer has to be released, the other one will use object with external linkage you point to (ie. pointer to deleter object is second parameter of template class). Really no support for deleters as used in shared_ptr? This support is possible, I just want to discuss it with you before I add it. The one solution that comes to my mind is to use multiple inheritance: your class deleter class ^ ^ object managed by auto_ptr this way deleter object is contained within managed pointer. It's possible to store pointer to deleter class (as fourth pointer) in auto_ptr, thus allowing access to it, but I do not know how to make it type-safe (without extra CPU cost). Why it's named auto_ptr ? Becasue it's improved auto_ptr. If you do not like this name, we can discuss some other name for this template class, like "smart_auto_ptr" or "auto_ptr_ext" . In the meantime feel free to rename it (just search&replace in T191.hpp will do). BTW: you are invited to rename T191.hpp to something else, and share this new name with others :) I hope you enjoy it, and I'm eagerly awaiting your opinion. B. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2004/01/59352.php
CC-MAIN-2021-31
refinedweb
755
66.03
Paul Malherbe <paul_AT_tartan.co.za> writes: > Thanks for you input, it has really helped me!! Glad I could help. > What I was trying to do was write an event script which would raise the > client which received focus. > > I have done it but the response is slow (acceptable), however I have had > to write a bash script calling a python script as my bash is not very good. > Could you maybe help me simplify it by using only one (python) script? Take a look at, if you want. My (python) wmiirc is there, as well as modwmii.py. In modwmii.py I have this (Popen is from subprocess, in python 2.4): class wmii_event(Popen): def read(self): return string.rstrip(self.stdout.readline()) def close(self): # If wmii is exiting the wmiir process may already be dead. if not self.poll(): os.kill(self.pid, signal.SIGTERM) return(self.wait()) So you could do (again, PIPE is from subprocess): events = wmii_event(("wmiir", "read", "/event"), stdout = PIPE) And loop with events.read(). -- Jeremy Hankins <nowan_AT_nowan.org> PGP fingerprint: 748F 4D16 538E 75D6 8333 9E10 D212 B5ED 37D0 0A03Received on Mon Jul 03 2006 - 01:02:26 UTC This archive was generated by hypermail 2.2.0 : Sun Jul 13 2008 - 16:10:27 UTC
http://lists.suckless.org/wmii/0607/2368.html
CC-MAIN-2019-43
refinedweb
214
76.62
Re: [bolger] Duckworks Charging for Subscriptions Expand Messages - MAIB doesn't pay anything to its contributors either, and I'm sure they don't mind (I don't) that Bob Hicks makes a living off the magazine. But $25 a year for a Web based magazine seems a bit much to me for the market to bear. If Chuck was asking for $10, or even $15 a year I don't think we'd be hearing so many complaints, and he would probably end up doing better. As someone who spends a lot of time publishing something on the Web for little in return (it started out "for fun" but turned into a monster...) I wish Chuck well in his attempt to get a little something back for his efforts. On Sun, 30 Mar 2003 18:22:37 +0100, you wrote: > As a journalist myself and a good journalist's union member, I'm > nevertheless happy to write for free to support something I enjoy and which > is used by a limited market, so long as I have no reason to believe the > proprieter is making a fortune while ripping off the contributors. > ... -- John <jkohnen@...> In this world of sin and sorrow there is always something to be thankful for; as for me, I rejoice that I am not a Republican. <H. L. Mencken> - As I read the last two MAIB's it became instantly apparent to me that Bolger was writing them. I laid out several past articles and those two for my 17 year old son to do a composition comparison. He's at the stage where he can recognize good and bad writing, but he's not sure why it's good or bad. Bolger as a teaching tool for English, is there no end to the usefulness of his work? HJ I don't think I could stomach a whole book full of Susanne's writing! :oP I hope she has lots of other virtues, because her prose will never get her past the pearly gates. It was a pleasant surprise to open up the last two issues of MAIB and find that Phil himself had written the articles! :o) -------------------------------------------------------------------- mail2web - Check your email from the web at . Your message has been successfully submitted and would be delivered to recipients shortly.
https://groups.yahoo.com/neo/groups/bolger/conversations/topics/27137?xm=1&m=e&l=1
CC-MAIN-2017-30
refinedweb
385
73.41
The Vaadin Wiki is temporarily in read only mode due to large recent spam attacks. Implementing Enterprise Web applications with Vaadin Part I - Setting up the development environment and project structure # What is an enterprise web application? # Enterprise web applications written in Java are mostly layered, component based applications that exist in the server side and are run in Application Server such as JBoss or GlassFish. Application Servers provide containers to host different components such as EJB Container for EJB Beans and Web Container for Servlets. In this tutorial I'll present ways to bind Vaadin together with other Java technologies used to build modern web applications. This first part of the tutorial is about setting up the development environment and project structure to support enterprise application development. As mentioned, and as you probably knew, Vaadin is Servlet based User Interface framework that provides developer with User Interface components such as layouts, text fields, buttons and tables to implement the required UI to perform business operations. When saying backend, I mean everything below the User Interface layer. As Vaadin application is Servlet also the UI logic is run in the web container of an application server and only the representation of the application state is shown for the user in the browser window. This is sometimes called a thin client approach as Vaadin is fully Ajax based. Enterprise web application is layered and component based application that has clear separation between User Interface, Business logic and data storage layers. On top of the application is the User Interface that can be seen as user’s window to the application. Right beneath it is usually the Facade layer that provides User Interface with ways to interact with the Business Logic. Facades are service provides that work as aggregates for Business EJB Beans. Business Beans are components that provide functionality to perform certain business operations, such as adding and updating product information to the storage system, handling product purchases from the cash register system and providing reports for management about sold products for example. As with regular classes in every Object Oriented programming language, each class should serve only one purpose and have only one reason to change. Same applies to EJBs where one bean provides clean and simple API to serve single functionality. Of course one bean can have multiple methods to perform different business operations which are tightly related together but same EJB should not generate reports and handle updating storage amounts. What EJBs mostly do is that they modify data within the system by certain business rules. This data is stored to the persistency layer with Java Persistence API (JPA). From developer point of view JPA manages entity instances that can be used as regular objects by the EJBs. One instance of certain entity represents a single row in one database table that can have relations to other tables. Theory of JPA is basically out of the scope of this tutorial but is mentioned as background information. What makes an enterprise application so enterprisey is usually the usage of multiple technologies and specifications and modular structure. I hope to show you that even with more complex project structure you can easily create and maintain complex applications. Couple of simple design patterns and modular structure makes testing components and services easy and allows possibility to change things as requirements change during the development process. Now let’s start with setting up the development environment. After that we’ll create basic enterprise application project structure “manually” without using dependency management tools like Maven. Such tools greatly help creating project structures but it’s also good to understand the basic before using such automated tools. Setting up the development environment # Let’s start by setting up the development environment. In this tutorial I'll be using Java EE version of Eclipse Indigo as development IDE and JBoss 7.1.1 as the Application Server that hosts my enterprise application. I’ve chosen JBoss 7 because we want to have Java EE 6 support. Other options like GlassFish 3 are also available so this is only personal preference. If you have clean Java EE Eclipse and workspace with no JBoss 7 installed. Start off by first downloading the Community edition of JBoss 7.1.1. JBoss can be downloaded from: JBoss download site After download extract the package to some folder. No other installation process or configuration is required at this time. Start Eclipse and create new workspace. The purpose of new workspace is to have projects and JBoss runtime configured only to that workspace so you don’t clutter up your existing workspaces if something goes wrong. It's also good idea to have separate projects in their own workspaces. Now that you have Eclipse running and JBoss nicely extracted, let’s attach the JBoss to Eclipse. This can be done using the JBoss Application Server tools that can be downloaded to Eclipse as plug-in from the Eclipse Marketplace. From Eclipse click Help menu item -> Eclipse Marketplace and type jboss as search term to the find dialog. From the results you should see JBoss Tools (Indigo) and have install button on the right bottom corner. Click it. After some dependency calculation and downloading Eclipse will present you a list of plug-in options. Deselect everything except ‘JBossAS Tools’. Click next to install the selected plug-in. After installation Eclipse will prompt you with restart. Do it. Now that you have JBoss integration plug-in installed, you can configure new server runtime. From Eclipse’s Window menu item select preferences. Dialog will open. You can type ‘runtime’ to the search box and select the runtime environment item from the list under the Server item. There you should have an empty list of server runtimes. Click add button. From the JBoss Community folder select JBoss 7.1 Runtime. You will not see this item if you have not installed the JBossAS Tools in the previous step. New Server Runtime Environment dialog will open. Click on the Browse button on the Home Directory and select the folder where you extracted the JBoss. Make sure that JRE option points to JDK, not JRE. If you don’t have JDK in the dropdown list, click on the JRE button and add JDK to the list of installed JRE’s. Then select it from the JRE dropdown. After selecting JDK as your JRE click Finish. JBoss 7.1 Runtime will appear to the list of server runtimes. From Eclipses Window menu item, select “Show View -> Other. From the dialog select Servers item under the Server folder. Servers view will open to your Eclipse perspective. If the view is empty, right click it and select New -> Server. From ‘Define a New Server’ dialog select JBoss AS 7.1. Make sure that the Server runtime environment dropdown has the Runtime you configured in the previous step. If you did not configure the runtime, you can click the Add… link to open the runtime dialog. Now you’re done with attaching JBoss to your Eclipse installation. It’s now possible to start the JBoss Application Server from the Eclipse and it will run the JBoss that you downloaded and extracted during the first steps. As we’re building enterprise web application with Vaadin UI, it’s good idea to install the Vaadin plug-in to your Eclipse just as you did with JBoss plug-in. From the Eclipse Marketplace type ‘vaadin’ as search parameter. You should see Vaadin Plug-in for Eclipse. Click Install button on the right corner just as you did with the JBoss plug-in. After installation completes, restart Eclipse once more. Setting up the Enterprise project # Enterprise Application Project consists of several sub modules such as EJB module, Vaadin UI Web Project module, Common Utility Project module and Enterprise Application EAR project. From these four projects the EAR project is the main project for application server deployment. You’ll deploy only the EAR project and have it manage the other projects. It’s important that all the modules are deployed within the EAR project; otherwise class loading issues will occur during runtime. We’re going to create four separate Eclipse projects to your Eclipse workspace. First let’s create the simplest Utility Project. The purpose of the utility project is to have classes that are required by both, the UI and the backend. These classes are for example the entities of the system as well as some general helper and support classes. Utility project # From you workspace navigator or project explorer or whatever you have in your Eclipse perspective, Right click it and select New -> Other. A Dialog will open. From the Select a Wizard dialog type in to the filter text ‘utility’ and select Utility Project under the Java EE folder. In the New Utility Module dialog name the project as ‘common’. Select JBoss 7.1 as Target runtime. Select Default configuration. At this point discard the EAR membership selections and press Finish. New empty Utility project called ‘common’ will appear in your workspace. EJB project # As with the Utility Project, right click the workspace view and select New -> Other. To the search box type ‘ejb’ and from the EJB folder select EJB Project. Name the project as ‘backend’. Select JBoss 7.1 Runtime as Target runtime and Default configuration. Discard the EAR membership and click Finish. New empty EJB project will appear in your workspace. Vaadin project # Now that you have the Utility and EJB projects created, create new Vaadin project. Click the workspace again with right mouse button and select New -> Other and type ‘vaadin’ to the search box. From the Vaadin folder select Vaadin Project. You will not see this option if you have not installed the Vaadin Eclipse Plug-in in the setting up the development environment chapter. Click Next. Name your Vaadin project as ‘ui’. Set target runtime to JBoss 7.1 and for the configuration select Vaadin, Java 6, Servlet 3.0. From the deployment configuration select Servlet (default) and from the Vaadin version dropdown select latest version. If version dropdown is empty, click Download button to get the latest version. Vaadin Eclipse plug-in will setup all the required Vaadin libraries and configuration for you. Click next. Accept default source and output folder by clicking Next in the following dialog page. In Web Module configuration dialog, make sure that ‘Generate web.xml deployment descriptor’ is NOT checked, accept otherwise the default configuration and click Next. In Vaadin project dialog uncheck the ‘Create project template’ and make sure that Portlet version is set to ‘no portlet’ and Vaadin version is the latest one that you selected. Click Finish. New empty Vaadin project is created to your workspace. JBoss 7 class loading issue # As we’re using JBoss 7 there is a class loader issue when using Vaadin because JBoss tries to load classes related to the Vaadin client side implementation that you don’t directly need but which are related to compiling the widget set. JBoss’ class loader will end up throwing class not found exception unless you copy gwt-user.jar to your Vaadin projects WebContent/WEB-INF/lib/ folder. You can get the gwt-user.jar from eclipse/configuration/com.vaadin.integration.eclipse/download/gwt-user/2.3.0/ folder where Vaadin Eclipse plug-in downloaded it or you can download the GWT package version 2.3.0 and extract the gwt-user.jar from it. This step is not necessary if you’re using GlassFish application server or if you’re using Vaadin version 7 which at this point is still in alpha phase. This issue is not directly related to Vaadin but instead to the way the JBoss class loading mechanism handles the class references. For the enterprise application project this is all unnecessary information and all you need to know in order to get the project set up correctly is to copy the gwt-user.jar to web project’s WEB-INF/lib/ folder mentioned above. Enterprise Application Project (EAR) # After creating all the enterprise application modules, create the Enterprise Application Project that will bundle together all the modules. To do this, once more right click the workspace and select New -> Other. From the dialog search ‘enterprise’ and from Java EE folder, select Enterprise Application Project. Name your project as ‘ear’, select target runtime as JBoss 7.1 and EAR version as 6.0. Use default configuration. Click next. From the following dialog select all three projects you created in the previous steps as Java EE Module dependencies for the EAR project. This means that EAR will contain all the project and when it’s deployed also the contained projects will be deployed to the Application Server. You can also check the ‘Generate application.xml deployment descriptor’ to have the xml file that manages the ear content. This is not necessary but might be helpful in some situations. Click Finish. New Enterprise application project is created with references to module projects. Project hierarchy in Eclipse # At this point you should have four separate projects in your Eclipse Workspace: EJB Project called backend, Utility Project called common, Vaadin Project called ui and Enterprise Application Project called ear. You should have copied the gwt-user.jar to your Vaadin Project’s WEB-INF/lib/ folder and you should have application.xml file in your Enterprise Application Project’s META-INF/ folder. You should not have web.xml in your Vaadin Projects WEB-INF folder. Project structure should look like the following: Setting up the project dependencies # As we’re building layered enterprise application we want to have dependencies between the projects. It’s important to understand the direction of dependencies. Just as the users use the software from the UI, we want to have similar dependency structure from UI layer to backend and not the other way around. Right click your Vaadin UI project and from the properties select ‘Java Build Path’. Add backend and common projects to the Projects tab in the build path window. This means that UI project depends on Common and Backend Projects. Click ok. Next open the same project dependency dialog for the Backend Project. As we never call UI from the backend, add just the common project as backend’s dependency. Don’t attempt to create circular dependencies. Eclipse will warn you about this if you do. Setting up the Context and Dependency Injection (CDI) for Vaadin Project # At this point we’re going to insert utility library that handles Context and Dependency Injection mechanism for the Vaadin project. CDI is used by the Application Server to inject references to backend functionality to the Vaadin application. Start by downloading CDI Utils Add-on by Tomi Virkki from the Vaadin Directory at: Directory From the Directory you’ll get .jar package that contains CDI utility that makes it much easier to enable CDI in your Vaadin Application. Copy the jar file you downloaded to Vaadin Projects WEB-INF/lib/ folder, right next to the vaadin.jar package. To tell your Application Container that we want to use its CDI mechanism, we’ll have to enable it manually. To do this insert EMPTY 0 byte in size file called ‘beans.xml’ to Vaadin projects WEB-INF/ folder. After adding the CDI related files, your project structure should look like as in above picture. Implementing basic CDI enabled Vaadin Application # After configuring the Vaadin project with proper CDI related files and libraries in the previous step we can write our first classes which will be the foundation of our UI. First we’ll create CDI aware application servlet class. As we’re using Servlet 3.0 API creating this class will be really easy. To your ui projects source folder, create new class called UIApplication and extend it from AbstractCdiApplication. Put the class to some reasonable package like: com.company.application.ui for example. #!java package com.company.application.ui; import org.vaadin.virkki.cdiutils.application.AbstractCdiApplication; import com.vaadin.ui.Window; public class UIApplication extends AbstractCdiApplication { @Override public void init() { Window window = new Window("Vaadin Application"); addWindow(window); } } To your ui projects source folder and to the same package in which you created the UIApplication class, create new class called UIApplicationServlet and extend it from AbstractCdiApplicationServlet. Leave the class empty but annotate it with two annotations @WebServlet(urlPatterns =”/”) and @ApplicationClass(UIApplication.class). #!java package com.company.application.ui; import javax.servlet.annotation.WebServlet; import org.vaadin.virkki.cdiutils.application.AbstractCdiApplicationServlet; import org.vaadin.virkki.cdiutils.application.AbstractCdiApplicationServlet.ApplicationClass; @WebServlet(urlPatterns = "/*") @ApplicationClass(UIApplication.class) public class UIApplicationServlet extends AbstractCdiApplicationServlet { } The above class will work as ApplicationServlet that is capable of injecting references to application instance with CDI. WebServlet annotation is used to define the URL to which your application responds to. ApplicationClass annotation is used to tell the application servlet which application class it should instantiate. Deploying the project to JBoss # Now that you have the development environment and the project structure set up and CDI enabled Vaadin Application stub defined you can test that it’s deployable to the Application Server. To do this first open the servers view in your Eclipse if it’s not open. In the first steps related to setting up the development environment you added the JBoss runtime to Eclipse and added the server instance to Servers view in Eclipse. If Servers view is not visible you can open it from Window -> Show View -> Other. Type ‘servers’ to the dialog’s field. Select Server in Servers folder. In the servers view you should see your JBoss 7.1 Runtime Server. Right click the server and Select ‘Add and Remove…’ In the Available column you should see your ‘ear’ project. Click the small arrow on the left side of the project icon to open the project hierarchy. Under the ear project you should have the three modules listed you created and added to the EAR in previous steps. If all three modules are in place move the ear project to Configured column with the Add button. Click Finish. You have now deployed the multi module enterprise application stub project to the JBoss application server. Try running your JBoss by clicking the green “play” button in the Servers view. As application server starts it automatically deploys the EAR and makes it available for you. If you have disabled automatic deployment, right click the server and from the menu select publish. During deployment process that usually takes couple of seconds for “empty” projects you should see lines like following in the Eclipse log: JBAS015876: Starting deployment of "ear.ear" JBAS015876: Starting deployment of "ui.war" JBAS015876: Starting deployment of "backend.jar" JBAS018210: Registering web context: /ui JBAS018559: Deployed "ear.ear" If log indicates no errors you’re good to go and try viewing the UI project with your web browser. Enter localhost:8080/ui to your web browser. You should see grey color background in your browser with ‘Vaadin Application’ title. This indicates that the deployment has succeeded and Vaadin application is deployed with /ui web context. If you chose different name for you Vaadin project during the project setup the web context name may be different. Use it to access your application. Notice that common.jar will not be directly deployed as EJB and web projects were because it does not contain deployable components but it works just as library for other modules. That’s why it’s not listed in the deployed items logs. At the moment the web application part is still completely separate from other modules. Only thing that links them together is that they’re all present in the same EAR package. Next we’ll take a look how to create few EJB beans and bind them to Vaadin application with Model View Presenter (MVP) Pattern. To accomplish this we'll be building our implementation on top of the CDI stub we deployed above.
https://vaadin.com/wiki/-/wiki/Main/Implementing+Enterprise+Web+applications+with+Vaadin
CC-MAIN-2016-50
refinedweb
3,319
56.86
Search: Search took 0.02 seconds. - 4 Feb 2010 12:39 PM Yep, it is working with chart listener now, thx. So, is it bug or sth else? - 3 Feb 2010 12:38 PM Here is the full sample code: import java.util.ArrayList; import java.util.List; import com.extjs.gxt.charts.client.Chart; import com.extjs.gxt.charts.client.event.ChartEvent; import... - 3 Feb 2010 7:24 AM Anyone has a idea about this? - 1 Feb 2010 3:22 AM barChart.addChartListener(new ChartListener() { public void chartClick(ChartEvent ce) { Info.display("Chart Clicked", "Yes"); ... - 28 Jan 2010 3:18 AM Hi, I tried to add chart listener to the stacked bar chart as shown in following codes: StackedBarChart barChart = new StackedBarChart(); ... Results 1 to 5 of 5
https://www.sencha.com/forum/search.php?s=e63dba11df882e4f454b94444f6d0086&searchid=11510568
CC-MAIN-2015-22
refinedweb
129
80.38
Django FormMail Clone Here’s a little nugget I just posted to Django Snippets. It emulates the behavior of an old Perl script I used way back when, FormMail.pl. I often find myself needing to build a form whose contents get emailed to the site owner(s). This class let’s you call form.notify() on any form that is a subclass of it to have the fields ordered and sent in a plain text email to all users that are flagged as staff. from django import newforms as forms from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.core.mail import send_mail class FormMail(forms.Form): def notify(self): """ Sends an email to all members of the staff with ordered list of fields and values for any form that subclasses FormMail """ site_name = Site.objects.get_current().name form_name = self.__class__.__name__ subject = '%s %s Submission' % (site_name, form_name) user_list = [u.email for u in User.objects.filter(is_staff=True).exclude(email="").order_by('id')] message = "" for k in self.base_fields.keyOrder: message = message + '%s: %s\n\n' % (self[k].label, self.cleaned_data[k]) send_mail(subject, message, user_list[0], user_list) ## Example form class ContactForm(FormMail): name = forms.CharField() phone = forms.CharField(required=False) email = forms.EmailField() comment = forms.CharField(widget=forms.Textarea()) ## Example view code form = ContactForm(request.POST) if form.is_valid(): form.notify() Got something to say? This was written on March, 13 2008 and is filed in code,, 15 hours ago - Basecamp 500 Internal Server Error Pete, 1 day, 15 See also Thanks James, I didn’t notice your project until after I had already written my code. I haven’t dug into django-comment-form, what extra goodies does yours offer? I’m just a user of James’ contact-form, but what drew me to it was akismet. It’s a subclass(?) of the default ContactForm class. Just need to add your akismet key to settings.py and point the contact form to AkismetContactForm and voila. Whoops – I just broke out the contact form on my site into a separate app… based on a comment by James during his talk at PyCon… not realizing that this existed. He probably mentioned it but I was typing away. I like this implementation as well – very slick! Thanks for sharing.
http://lincolnloop.com/blog/2008/mar/13/django-formmail-clone/
crawl-002
refinedweb
385
61.53
This is the mail archive of the libc-help@sourceware.org mailing list for the glibc project. On 03/26/2014 02:21 PM, Jan Kratochvil wrote: > Hi, > > Reproducer: > gcc -g -o tlsvar tlsvar.c -pthread -static; gdb ./tlsvar -ex 'b 12' -ex r -ex 'info thread' -ex 'p *thread_local_p' > > Actual output: > Cannot find executable file `.../tlsvar' in dynamic linker's load module list > > Expected output: > $1 = 10 (or 20 or 30) > > With -static there is no _r_debug, no link_map, no '.dynamic' section so there > is nothing to pass as 'psaddr_t __map_address' for td_thr_tls_get_addr. There is _r_debug for a static link, it comes from libc.a (dl-debug.o), but the r_map is going to be NULL because we never set it. There is a valid internal link_map for static executables as of 2.18, see bug 15022 and bug 16046 for some followup fixes. However, this isn't exposed in any way to the user. It would require additional patches to make _r_debug work for static binaries and that would make the dependency 2.20 or later. > Attached GDB fix that uses td_thr_tlsbase() instead of td_thr_tls_get_addr() > and pass 'modid' as value 1. But I haven't found it documented anywhere. It's an internal implementation detail that rtld sets the module ID to 1 for the application. The loader also starts as module ID 1 and eventually selects it's own module ID. The module ID of 1 for the executable might change at some point, but I doubt it. Your use of td_thr_tlsbase() is exactly what td_thr_tls_get_addr() does, but the latter looks up the module ID in the link map, which is what you'd like to do, but can't because we didn't provide one. > Is such patch acceptable for upstream GDB or is there some better way with > glibc? The best way forward would be to ensure you can get a link map even for static executables, and then use that with td_thr_tls_get_addr(). This would allow gdb to avoid doing two different things for static and dynamic executables. It also helps all other applications using libthread_db interfaces. Would you mind testing something like this in fedora rawhide? diff --git a/csu/libc-start.c b/csu/libc-start.c index 3b7092b..d571a1a 100644 --- a/csu/libc-start.c +++ b/csu/libc-start.c @@ -264,6 +264,9 @@ LIBC_START_MAIN (int (*main) (int, char **, char ** MAIN_AUXVEC_DECL), GLRO(dl_debug_printf) ("\ntransferring control: %s\n\n", argv[0]); #endif +#ifndef SHARED + _dl_debug_initialize (0, LM_ID_BASE); +#endif #ifdef HAVE_CLEANUP_JMP_BUF /* Memory for the cancellation buffer. */ struct pthread_unwind_buf unwind_buf; --- [carlos@koi ~]$ cat test.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <link.h> int main (int argc, char **argv) { printf ("%p\n", &_r_debug); printf ("%p\n", _r_debug.r_map); return 0; } [carlos@koi ~]$ gcc -Wl,--build-id=none -nostdlib -nostartfiles -static -o ./test-static /home/carlos/build/glibc/csu/crt1.o /home/carlos/build/glibc/csu/crti.o `gcc -Wl,--build-id=none --print-file-name=crtbeginT.o` ./test-static.o -Wl,--start-group /home/carlos/build/glibc/libc.a -lgcc -lgcc_eh -Wl,--end-group `gcc -Wl,--build-id=none --print-file-name=crtend.o` /home/carlos/build/glibc/csu/crtn.o -Wl,-Map,linkmap.txt [carlos@koi ~]$ ./test-static 0x6b4b40 0x6b2260 That link map has l_tls_modid set to 1 as expected, and is the new _dl_main_map added in 2.18 by Maciej's work. No matter what solution I propose you'll still have to support an older glibc and the static executable won't have a link map in _r_debug's r_map. In summary: * Assuming modid of 1 for the executable is OK for now. * glibc should be exposing a link map for the executable even when static via _r_debug's r_map for use with td_thr_tls_get_addr(). Comments? Cheers, Carlos.
https://sourceware.org/ml/libc-help/2014-03/msg00026.html
CC-MAIN-2017-26
refinedweb
629
59.5
4.10. Predicting House Prices on Kaggle¶ In the previous sections, we introduced the basic tools for building deep networks and performing capacity control via dimensionality-reduction, weight decay and dropout. You are now ready to put all this knowledge into practice by participating in a Kaggle competition. Predicting house prices is a great place to start: the data is reasonably generic and doesn’t have the kind of rigid structure that might require specialized models the way images or audio might. This dataset, collected by Bart de Cock in 2011, is considerably larger than the famous the Boston housing dataset of Harrison and Rubinfeld (1978). It boasts both more examples and more features, covering house prices in Ames, IA from the period of 2006-2010. In this section, we will walk you through details of data preprocessing, model design, hyperparameter selection and tuning. We hope that through a hands-on approach, you will be able to observe the effects of capacity control, feature extraction, etc. in practice. This experience is vital to gaining intuition as a data scientist. 4.10.1. Kaggle¶ Kaggle is a popular platform for machine learning competitions. It combines data, code and users in a way to allow for both collaboration and competition. While leaderboard chasing can sometimes get out of control, there’s also a lot to be said for the objectivity in a platform that provides fair and direct quantitative comparisons between your approaches and those devised by your competitors. Moreover, you can checkout the code from (some) other competitors’ submissions and pick apart their methods to learn new techniques. If you want to participate in one of the competitions, you need to register for an account (do this now!). On the House Prices Prediction page, you can find the data set (under the data tab), submit predictions, see your ranking, etc., The URL is right here: 4.10.2. Accessing and Reading Data Sets¶ Note that the competition data is separated into training and test sets. Each record includes the property value of the house and attributes such as street type, year of construction, roof type, basement condition, etc. The features represent multiple datatypes. Year of construction, for example, is represented with integers roof type is a discrete categorical feature, other features are represented with floating point numbers. And here is where reality comes in: for some exampels, some data is altogether missing with the missing value marked simply as ‘na’. The price of each house is included for the training set only (it’s a competition after all). You can partition the training set to create a validation set, but you’ll only find out how you perform on the official test set when you upload your predictions and receive your score. The ‘Data’ tab on the competition tab has links to download the data. We will read and process the data using pandas, an efficient data analysis toolkit, so you will want to make sure that you have pandas installed before proceeding further. Fortunately, if you’re reading in Jupyter, we can install pandas without even leaving the notebook. # If pandas is not installed, please uncomment the following line: # !pip install pandas %matplotlib inline import d2. print(train_data.shape) print(test_data.shape) (1460, 81) (1459, 80) Let’s take a look at the first 4 and last 2 features as well as the label (SalePrice) from the first 4 examples: train_data.iloc[0:4, [0, 1, 2, 3, -3, -2, -1]] We can see that in each example, the first feature is the ID. This helps the model identify each training example. While this is convenient, it doesn’t carry any information for prediction purposes. Hence we remove it from the dataset before feeding the data into the network. all_features = pd.concat((train_data.iloc[:, 1:-1], test_data.iloc[:, 1:])) 4.10. numeric_features = all_features.dtypes[all_features.dtypes != 'object'].index all_features[numeric_features] = all_features[numeric_features].apply( lambda x: (x - x.mean()) / (x.std())) # After standardizing the data all means vanish, hence we can set missing # values to 0 all_features[numeric_features] = all_features[numeric. # Dummy_na=True refers to a missing value being a legal eigenvalue, and # creates an indicative feature for it all_features = pd.get_dummies(all_features, dummy_na=True) all_features.shape (2919, 331) You can see that this conversion increases the number of features from 79 to 331. Finally, via the values attribute, we can extract the NumPy format from the Pandas dataframe and convert it into MXNet’s native NDArray representation for training. n_train = train_data.shape[0] train_features = nd.array(all_features[:n_train].values) test_features = nd.array(all_features[n_train:].values) train_labels = nd.array(train_data.SalePrice.values).reshape((-1, 1)) 4.10.4. Training¶ To get started we train a linear model with squared loss. Not surprisingly, our linear model will not lead to a competition winning submission but it provides a sanity check to see whether there’s meaningful information in the data. If we can’t do better than random guessing here, then there might be a good chance that we have a data processing bug. And if things work, the linear model will serve as a baseline giving us some intuition about how close the simple model gets to the best reported models, giving us a sense of how much gain we should expect from fanicer models. loss = gloss.L2Loss() def get_net(): net = nn.Sequential() net.add(nn.Dense(1)) net.initialize() return net With house prices, as with stock prices, we care about relative quantities more than absolute quantities. More concretely, we tend to care more about the relative error \(\frac{y - \hat{y}}{y}\) than about the absolute error \(y - \hat{y}\). For instance, if our prediction is off by USD 100,000 when estimating the price of a house in Rural Ohio, where the value of a typical house is 125,000 USD, then we are probably doing a horrible job. On the other hand, if we err by this amount in Los Altos Hills, California, this might represent a stunningly accurate prediction (their, the median house price exceeds 4 million USD). One way to address this problem is to measure the discrepancy in the logarithm of the price estimates. In fact, this is also the official error metric used by the compeitition to measure the quality of submissions. After all, a small value \(\delta\) of \(\log y - \log \hat{y}\) translates into \(e^{-\delta} \leq \frac{\hat{y}}{y} \leq e^\delta\). This leads to the following loss function: previous sections, our training functions here will rely on the Adam optimizer (a slight variant on SGD that we will describe in greater detail later). The main appeal of Adam vs vanilla SGD is that the Adam optimizer, despite doing no better (and sometimes worse) given unlimited resources for hyperparameter optimization, people tend to find that it is significantly less sensitive to the initial learning rate. This will be covered in further detail later on when we discuss the details in Section 10. 4.10.5. k-Fold Cross-Validation¶ If you are reading in a linear fashion, you might recall that we intorduced k-fold cross-validation in the section where we discussed how to deal with model section (Section 4.4). that this is not the most efficient way of handling data and we would definitely do something much smarter if our dataset wasconsiderably larger. But this added complexity might obfuscate our code unnecessarily so we can safely omit here owing to the simplicity of our problem.: d2l.plot(list(range(1, num_epochs+1)), [train_ls, valid_ls], xlabel='epoch', ylabel='rmse', legend=['train', 'valid'], yscale='log') print('fold %d, train rmse: %f, valid rmse: %f' % ( i, train_ls[-1], valid_ls[-1])) return train_l_sum / k, valid_l_sum / k 4.10.6. Model Selection¶ In this example, we pick an un-tuned set of hyperparameters and leave it up to the reader to improve the model. Finding a good choice can take quite some time, depending on how many things one wants to optimize over. Within reason, the k-fold cross-validation approach is resilient against multiple testing. However, if we were to try out an unreasonably large number of options it might fail since we might just get lucky on the validation split with a particular set of hyperparameters..170231, valid rmse: 0.157110 fold 1, train rmse: 0.162145, valid rmse: 0.189155 fold 2, train rmse: 0.163622, valid rmse: 0.168052 fold 3, train rmse: 0.167955, valid rmse: 0.154912 fold 4, train rmse: 0.162626, valid rmse: 0.182833 5-fold validation: avg train rmse: 0.165316, avg valid rmse: 0.170413 You will notice that sometimes the number of training errors for a set of hyper-parameters can be very low, while the number of errors for the \(K\)-fold cross-validation may be higher. This is an indicator that we are overfitting. Therefore, when we reduce the amount of training errors, we need to check whether the amount of errors in the k-fold cross-validation have also been reduced accordingly. 4.10. def train_and_pred(train_features, test_feature, train_labels, test_data, num_epochs, lr, weight_decay, batch_size): net = get_net() train_ls, _ = train(net, train_features, train_labels, None, None, num_epochs, lr, weight_decay, batch_size) d2l.plot(range(1, num_epochs+1), train_ls, xlabel='epoch', ylabel='rmse', yscale='log') our model. One nice sanity check is to see whether the predictions on the test set resemble those of the k-fold cross-validation process. If they do, it’s time to upload them to Kaggle. The following code will generate a file called submission.csv (CSV is one of the file formats accepted by Kaggle): train_and_pred(train_features, test_features, train_labels, test_data, num_epochs, lr, weight_decay, batch_size) train rmse 0.162429 Next, we can submit our predictions on Kaggle and see how they compare to the actual house prices (labels) on the test set. The steps are quite simple: Log in to the Kaggle website and visit the House Price Prediction Competition page. Click the “Submit Predictions” or “Late Submission” button (as of this writing, the button is located on the right). Click the “Upload Submission File” button in the dashed box at the bottom of the page and select the prediction file you wish to upload. Click the “Make Submission” button at the bottom of the page to view your results. 4.10. 4.10.9. Exercises?
http://classic.d2l.ai/chapter_multilayer-perceptrons/kaggle-house-price.html
CC-MAIN-2020-16
refinedweb
1,720
54.32
Pipes.Parse.Tutorial Description pipes-parse builds upon pipes to add several missing features necessary to implement Parsers: Synopsis Overview pipes-parse centers on three abstractions: Producers, unchanged from pipes Parsers, which play a role analogous to Consumers Lens'es between Producers, which play a role analogous to Pipes There are four ways to connect these three abstractions: - Connect Parsers to Producers) zoom :: Lens' (Producer a m x) (Producer b m y) -> Parser b m r -> Parser a m r (^.) :: Producer a m x -> Lens' (Producer a m x) (Producer b m y) -> Producer b m y (.) :: Lens' (Producer a m x) (Producer b m y) -> Lens' (Producer b m y) (Producer c m z) -> Lens' (Producer a m x) (Producer c m z) You can obtain the necessary lens utilities from either: - The lens-family-corelibrary, importing Lens.Family(for ( ^.) / viewand over) and Lens.Family.State.Strict(for zoom), or: - The lenslibrary, importing Control.Lens(for ( ^.) / view, overand zoom) This tutorial uses Lens.Family since it has fewer dependencies and simpler types. Parsers ParsPink zoom lets you delimit a Parser using a Lens'. The above code says to limit drawAll to a subset of the input, in this case the first three elements: >>> evalStateT drawThree (each [1..])[1,2,3] splitAt is a Parsers, using zoom. When we combine zoom with (splitAt 3) we limit a parser to the the first three elements of the stream. When the parser is done zooms, Pipes can only be modeled as functions between Producers. However, Pipes are preferable to functions between Producers when possible because Pipes can transform both Producers and Consumers. If you prefer, you can use lens-like syntax for functions between Producers by promoting them to Getters using to: import Lens.Family example :: Monad m => Producer Int m () example = each [1..3] ^. to (map' (*2)) However, a function of Producers (or the equivalent Getter) cannot be used transform Parsers (using zoom or otherwise) . This reflects the fact that such a transformation cannot be applied in reversed. Building Lenses Lenses are very easy to write if you are willing to depend on either the lens-family or lens library. Both of these libraries provide an iso function that you can use to assemble your own lenses. You only need two functions which reversibly transform back and forth between a stream of as and a stream of bs: -- "Forward" fw :: Producer a m x -> Producer b m y -- "Backward" bw :: Producer b m y -> Producer a m x ... such that: fw . bw = id bw . fw = id You can then convert them to a Lens' using Producers, but introduce two new abstractions: Lens'es and Parsvalues pipes-attoparsec: Converts attoparsecparsers to pipespars
http://hackage.haskell.org/package/pipes-parse-3.0.1/docs/Pipes-Parse-Tutorial.html
CC-MAIN-2016-30
refinedweb
450
52.7
what Widget / tools should I use to create this type of list? I need to create a list of Qstrings that I read in from a file. I then need to be able to click each one and have an "on Clicked" slot that I can use to do something with the text. The last part is that I need to have a little clickable "x" or icon next to each list item that does something different with that text. My idea is to create a widget with a clickable text and a small button at the end of the x and just add them to a page as i read in each line of the text file. However I have no idea how to even start this. I'm decent with c++ but need to get something up and running in qt as fast as I can. Any tips, pointers, or suggestions are welcome! Hi and welcome you could use a QListWidget and use the void QListWidget::setItemWidget ( QListWidgetItem * item, QWidget * widget ) to insert the button. This becomes very heavy if you have many rows, but should qualify as up and running fast. If you right click on the QListWidget you can add a slot for "on Clicked" for the button, you have the issue that it has no information on the selected row, but you could cheat and just QListWidgetItem * QListWidget::currentItem() const in the "On click" function of the button. you would create the buttons on the go so would have to hook up its "Clicked" ala (main window) QPushButton* m_button = new QPushButton ( "X", this ); bool c = connect ( m_button, SIGNAL ( released() ), this, SLOT ( buttonPressed() ) ); void MainWindow::buttonPressed() { // } Just a fast suggestion.many ways to do this :) @mrjj thank you!!! You are the first person to point me in at least some kind of direction. Can I ask how I would get the x button to appear next to each list item? @mrjj said: Sad I never found a way to place it to the right as I wanted. On same line as the text. Also, this has a flaw. If user Click directly on the button, the row is not selected since the button got the focus. So I inherited a Button and added a variable to it , so i can know which row (index) a button belonged to. How many lines do you got ? @mrjj Wait you have this working? I'm still trying to figure it out haha. Its going to be dynamic. Every time you start the application its going to read from text file that has on average 10-20 lines of text (short lines, 24 char max). If i could just get the text clickable I would be happy. I'm having trouble just adding text to it. - mrjj Lifetime Qt Champion last edited by mrjj You create QListWidgetItem using new and insert into list. List owns them and will delete. The text as such is not clickable as such. its the whole row/QListWidgetItem. If you use the visual editor, you can just right click the List and "Goto Slot" and select the "Clicked" slot. This gives you a function that get called when clicking on Item. So you have some lines you load into a list and the user can do something to the text by clicking the text or clicking the button to do something different? Hi Something like this could work, using a place holder for a label and a button will get you this you still need to hook up button&label for it to do something :) #include "mainwindow.h" #include <QApplication> #include <QCheckBox> #include <QRadioButton> #include <QPushButton> #include <QVBoxLayout> #include <QLabel> #include <QFile> #include <QMessageBox> #include <QTextStream> void CreateItem ( QListWidget * TheList , QString& TheText ) { QListWidgetItem * item = new QListWidgetItem ( "" ); TheList->addItem ( item ); // add a place hodler for label and button QWidget * w = new QWidget(); w->setLayout ( new QHBoxLayout() ); QPushButton *but = new QPushButton ( "Do it" ); QLabel *lab = new QLabel ( TheText ); // make row a bit bigger item->setSizeHint ( QSize ( item->sizeHint().width(), 30 ) ); // add the label and button to the layout w->layout()->addWidget ( lab ); w->layout()->addWidget ( but ); // reduce the space around it abit w->layout()->setContentsMargins ( 1, 1, 1, 1 ); // set this combined widget for the row TheList->setItemWidget ( item, w ); } int main ( int argc, char ** argv ) { QApplication app ( argc, argv ); QListWidget * list = new QListWidget(); list->setGeometry(50,50,400,200); QFile file ( "e:/mylist.txt" ); if ( !file.open ( QIODevice::ReadOnly ) ) { QMessageBox::information ( 0, "error", file.errorString() ); } QTextStream in ( &file ); while ( !in.atEnd() ) { QString line = in.readLine(); CreateItem ( list, line ); } file.close(); list->show(); return app.exec(); };
https://forum.qt.io/topic/56630/what-widget-tools-should-i-use-to-create-this-type-of-list/5
CC-MAIN-2020-05
refinedweb
769
70.73
Okay, I don't think I understand definitions, really. How does this work? With this def travel_cost function, can't I just call hotel_cost, plane_cost and rental_cost? I don't understand. Please help! def hotel_cost(nights): return 140 * nights def plane_ride_cost (city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 else: return "I'm sorry, that city is not in our database. Please choose from the following: Charlotte, Tampa, Pittsbugh or Los Angeles. Thank you" def rental_car_cost(days): if days >= 7: return days * 40 - 50 elif not days >= 7 and days >= 3: return days * 40 - 20 else: return days * 40 def trip_cost(city, days): return hotel_cost + plane_ride_cost + rental_car_cost
https://discuss.codecademy.com/t/i-dont-think-i-understand-definitions/81527
CC-MAIN-2018-39
refinedweb
121
63.39
Hi all, would anyone know of a way to query the usage statistics in hosted feature services through any of the APIs to find items that haven't been used in 30, 90 days, etc? To my knowledge there isn't an easy way to do this. You can create usage reports on how much content is being created but usage on individual services is not straightforward, though Portal or ArcGIS Online. There is an Esri idea where people are asking for something similar: Create Detailed AGOL Usage Report for Every Item If this is for an ArcGIS Enteprise deployment, rather than AGOL then you can get access to ArcGIS Server statistics in Server Manager. There you can view the number of requests for given services. It's not exactly what you are after but it allows you to see which services are getting requests and which are not. Thanks for sharing that, Mark Donnelly! It would be SO helpful for organization administrators to be able to generate reports like that! I did notice in the comments of that Idea that item.usage() from the Python API will produce similar results....maybe something that would be worth it to look into in the meantime. However, making this functionality available for all org admins, even those without programming experience, is essential! Good link, Mark. I'm definitely upvoting that. I'm playing around with the .usage() function that Katherine mentioned, looks like it could be promising. I'm definitely not familiar with the API so there's probably better ways to do this but plugging into a Notebook is giving good results so far. from arcgis.gis import GIS from IPython.display import display gis = GIS("home") items = gis.content.search(query="type:Feature Service") for item in items: try: itemHistory = item.usage(date_range='1Y', as_df=True) # <--- Looking in the past 12 months total = itemHistory['Usage'].sum() if total <20: # <--- Less than 20 total views display(item) except: pass Wow, thanks for posting the code! I'll need to give that a try as well! Nice bit of code Jason. I wasn't aware of the item.usage object, so thanks for sharing!
https://community.esri.com/t5/arcgis-online-questions/finding-unused-feature-services/m-p/733511
CC-MAIN-2021-10
refinedweb
362
66.84
PyRSS2Gen 1.1 Generate RSS2 using a Python data structurePyRSS2Gen-1.1 A Python library for generating RSS 2.0 feeds. Requires at least Python 2.3. (Uses the datetime module for timestamps.) Also works under Python 3.x To install: % python setup.py install This uses the standard Python installer. For more details, read (And there's only one file, so you could just copy it wherever you need it.) The documentation was written in 2003 which is why the examples are a bit dated. Don't let that dissuade you! It's now 2012 and many people are still using the package. There have been (minor) bug fixes during the time, and even a port to Python3. ====== ====== ====== ====== ====== ====== ====== ======. (And I want bug-eyed monsters from Alpha Centauri to be *real* bug-eyed monsters from Alpha Centauri - is that too much I ask you?). So I messed around a bit with the spec from The result looks like this:")) The output does not contain newlines, so if you want to read it, you'll need to use your favorite XML tools to reformat it. RSS is not a fixed format. People are free to add various metadata, like Dublin Core elements. The RSS objects are converted to XML using the 'publish' method, which takes a SAX2 ContentHandler. If you want different output, implement your own 'publish'. The "simple" data types which takes a string, int, or date, can be replaced with a publishable object, so you can add metadata to, say, the "description" field. To support new elements for RSS and RSSItem, derive from them and use the 'publish_extensions" hook. To add your own attributes (needed for namespace declarations), redefine 'element_attrs' or 'rss_attrs' in your subclass. To use a different encoding, create your own ContentHandler instead of using the helper methods 'to_xml' and 'write_xml.' You'll need to make sure the 'characters' method in the handler does the appropriate translation. The "categories" list is somewhat special. It needs to be a list and doesn't have a publish method. That's because the RSS spec doesn't have an explicit concept for the set of categories -- an RSS2 channel can have 0 or more 'category' elements, but doesn't have a "list of categories" -- my "categories" attribute is an API fiction. BUGS: Several people have used this package since its first release in September of 2003 and reported a couple of bugs. All those are fixed. There are no known bugs. The name PyRSS2Gen is a mouthful. It didn't think it was useful to come up with a cute name. You might consider having import PyRSS2Gen as RSS2 in any code which uses this module. I'm not changing the name because anyone who reads "RSS2" will likely think it's a parser and not a generator. Plus, the current name is very easy to find via a web search. LICENSE: This is copyright (c) by Andrew Dalke Scientific, AB (previously 'Dalke Scientific Software, LLC') and released under the BSD license. See the file LICENSE in the distribution, or for details. CHANGES for 1.1: Released August 25, 2012 - Ported to Python 3.x. Thanks to Graham Bell for the initial patch. CHANGES for 1.0: Released November 6, 2005 - Many people (Richard Chamberlain, Daniel Hsu, Leonart Richardson and Daniel Holth) pointed out that Guid sets "isPermaLink" (with a "L" not "l"). Fixed, and changed it so the isPermaLink RSS attribute is always either "true" or "false" instead of assuming empty means false. - Added patches from Erik de Jonge and MATSUNO Tokuhiro to set the output encoding. - Implemented a suggestion by Daniel Hoth to convert the enclosure length to a string. CHANGES for 0.1.1: Released in September 2003 - retroactively renamed "0.0" to "0.1" - fixed bug in Image height. Patch thanks to Edward Dale. - Downloads (All Versions): - 279 downloads in the last day - 2074 downloads in the last week - 2232 downloads in the last month - Author: Andrew Dalke - License: BSD - Categories - Package Index Owner: btbytes, dalke - DOAP record: PyRSS2Gen-1.1.xml
https://pypi.python.org/pypi/PyRSS2Gen/1.1
CC-MAIN-2015-11
refinedweb
676
75.3
On 12/12/05, Joel Reymont <joelr1 at gmail.com> wrote: > Folks, > > I love the Erlang multi-processing experience and think that a lot of > the mistakes that I made could be avoided. What I want to have is > > 1) Processes, aka threads with single-slot in/out mailboxes > 2) A facility to keep a list of such processes and send events to > them using their process id > 3) A socket reader/writer abstraction that communicates with the > outside world using using its mailboxes > > Probably some other things but I would start with the above. I also > want to use STM for this. > > One particular thing that bugs me is that I cannot really use TChan > for thread mailboxes. I don't think I experienced this problem with > Erlang but using a TChan with a logger thread quickly overwhelms the > logger and fills the TChan and a lot (hundreds? thousands) of other > threads are logging to it. Someone said it's because the scheduler > would give ther other threads proportionally more attention. You could use a bounded TChan. Chans are good because the smooth out "noise".. Ie a sudden surge of messages can be handled without stalling the senders, but sustained heavy traffic will cause a stall (preventing the TChan from growing too big). Here's an untested, off-the-top-of-my-head, implementation.. I may have gotten some names wrong but it should be quite straightforward to write a "real" implementation.. -- may want a newtype here? type BoundedTChan a = (TVar Int, Int, TChan a) -- (current size, max, chan) newBoundedTChan n = do sz <- newTVar 0 ch <- newTChan return (sz,n,ch) writeBoundedTChan (sz,mx,ch) x = do s <- readTVar sz when (s >= mx) retry writeTVar sz (s+1) writeChan ch x readBoundedTChan (sz,mx,ch) = do modifyTVar sz (-1) readTChan ch (s+1) /S -- Sebastian Sylvan +46(0)736-818655 UIN: 44640862
http://www.haskell.org/pipermail/haskell-cafe/2005-December/012880.html
CC-MAIN-2014-35
refinedweb
313
69.01
View Questions and Answers by Category Advertisements java program using transient variable Hi Friend, A transient variable is a variable that may not be serialized.The transient keyword indicates that the variable is not the part of the persistent state of the object. Variables that are part of the persistent state of an object must be saved when the object is archived. Here is an example: public class TransientVariable{ String name; transient String pass; public TransientVariable(String n, String p) { this.name = n; this.pass = p; } public String toString() { return "Name=" + name + "\n Password=" + pass; } public static void main(String[] args) { TransientVariable v=new TransientVariable("rose","roseindia"); String st= v.toString(); System.out.println(st); } } For more information, visit the following link: Thanks
http://www.roseindia.net/answers/viewqa/Java-Beginners/15195-core-java.html
CC-MAIN-2014-52
refinedweb
123
55.34
I had the chance, at an Intel IoT Hackaton taking place at Usine.io in Paris, beside an Intel Edison Arduino board and a bunch of Grove sensors/actuators, to also get the new Akene board from Snootlab. Thanks to the Intel IoT guys, Nicolas from SigFox and all the staff of BeMyApp for this Hackaton… Step 1: The Project... I decided to build a small light sensor station, with the Intel Edison board, the Grove shield, the SigFox Akene Shield, and an I2C Grove TSL2561. This station will upload, through the SigFox network about every 10 minutes, 3 different values (in lux) relating to that 10 minutes period: the arithmetic average light, the minimum and maximum light. That will allow to know how the light fluctuate around its average value for this period of time, and therefore to get the big picture on how the sky could be cloudy (if some wind at least to push the clouds…). I will use Python for that project. Step 2: a Friendly Development Environment I assume that the Intel Edison environment is ready for Python, and a password is set on the Edison in order to open SSH sessions and also SFTP to upload the python code. I am using OS X, and will use CoolTerm for communication, and the excellent TextWrangler as code editor and code uploader (SFTP). Step 3: The Framework: Sensor.py There is no difficulty to mention at that step. Step 4: What You Get With Sensor.py >python sensor.py Step 5: SigFox and the Akene Shield The Akene board is an experimentation Arduino shield from SnootLab with the TD1208 SoC (System on Chip) on it. The TD1208 is a SigFox-certified radio transceiver combined with an ARM Cortex M3, which implements the telecommunication modem stack for sending values to the SigFox operated telecommunication network, and also includes I2C capabilities for IoT sensors, beside its serial modem link. SIgFox services rely on a LPWA (Low-Power Wide-Area) network currently deployed in Western Europe, San Francisco, as well as other countries or cities. The SigFox protocol is designed for small messages and its technology is focusing on energy efficiency for devices clients and large area coverage for each infrastructure base station. The SigFox network allows each device to send up to 140 messages per day (i.e. every 10mn), each of them up to 12 available bytes i.e. 6 short integer values (the timestamp and the unique device ID are also transmitted in addition). More informations: Step 6: Let's Make Sure the Akene Shield and Its Modem Is Functional The Akene shield can be used as a modem, so we will first connect it to the Edison that way: • Ground to Ground (Black wire) • 3.3v to 3.3v (Red wire) • serial Rx (pin 0) of Edison to Tx of Akene (pin D4) - Blue wire • serial Tx (pin 1) of Edison to Rx of Akene (pin D5) - White wire Step 7: Sending Direct Commands Through a Terminal to the TD1208 of the Akene Shield We can consider the TD1208 as a modem. The PySerial package has to installed. >python -m serial.tools.miniterm We use miniterm (part of PySerial) - and specify the serial port: /dev/ttyMFD1 - to send direct commands, like: • AT which should reply OK (otherwise there is a problem) • AT&V which reply by the TD1208 identification • AT$SS01234567 which send the 01234567 message to the SigFox network (the maximum hexadecimal digits is 24, i.e. 12 bytes) • AT? which return the list of commands available To exit miniterm, on OS X with a french keyboard: CTRL 6 Step 8: A Simple Python Command to Send a Message to the SigFox Network This is a fast adaptation of a python command dedicated for another TD1208 board (RPISIGFOX from SNOC) and found on internet. Just to mention that, for using serial with Intel Edison, • it is prior necessary to initialise the port / pins which will be used, in our case /dev/ttyMFD1 (pins 0 and 1): import libmraa x=Uart(0) • the port is automatically open when calling serial.Serial(...... You can use the command that way: > python sendsigfox.py 01234567 which will send the message 01234567 to the SigFox network Step 9: What You Get With Sendsigfox.py >python sendsigfox.py 346723 Step 10: The Full Program: Sensor2sigfox.py No special difficulty there also, just to mention: • Each data sent is a short integer of 2 bytes. the valueAvg, valueMin and valueMax are therefore 6 bytes, i.e. 12 hexadecimal chars string. As the setup from SigFox in the case I am using is done in order that data are resent to actoboard.com, and that actoboard.com currently accept data in LittleEndian byte order, each data is, prior to be sent, transformed accordingly... • the Akene shield is fully plugged on top of the Grove shield, and in order to fit the wiring of the serial of Edison on pins 0 and 1 and the serial of Akene on pins D4 and D5, straps has been used (0 to D4: White strap) and (1 to D5: Yellow strap), see first picture... That mean a clean wiring but no possibility to use Pin 4 and 5 of the Edison... Step 11: What You Get With Sensor2sigfox.py >python sensor2sigfox.py 2 Discussions 3 years ago Thank you very much for your tutorial. We will share it on our forum. You could put the SeeedStudio base shield on top of Akene () to access all Grove connectors. Once the Edison library will be available, you'll won't need the two jumpers to connect Rx-Tx. 3 years ago on Introduction Very nicely done, thanks for sharing this!
https://www.instructables.com/id/Simple-as-sending-IoT-sensor-values-through-SigFox/
CC-MAIN-2019-26
refinedweb
952
60.55
LINQ to SQL support for Windows Phone 8 [ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ] Starting with Windows Phone OS 7.1, apps can use LINQ to SQL to store relational data in a local database. While Windows Phone supports most LINQ to SQL features, there are some limitations. This topic describes those limitations. For more information about using a local database, see Local database for Windows Phone 8. Note New features have been added to LINQ to SQL specifically for Windows Phone apps. For example, on a local database you can have multiple indexes and programmatically update the schema. For the API reference for these features, see Microsoft.Phone.Data.Linq and Microsoft.Phone.Data.Linq.Mapping. This topic contains the following sections. - LINQ to SQL support - LINQ to SQL API support - Related Topics LINQ to SQL support Windows Phone supports most LINQ to SQL features; there are some limitations. The following list describes aspects of LINQ to SQL support that should be considered when working with a local database in your. LINQ to SQL API support The following tables list the LINQ to SQL APIs that are partially supported and not supported on Windows Phone compared to other platforms. Partial supported means that the API was modified to work with Windows Phone. For complete details about the LINQ to SQL API for Windows Phone, see the class library reference for the following namespaces. Note The Microsoft.Phone LINQ to SQL APIs are applicable only to Windows Phone. Because Microsoft.Phone.Data.Linq and Microsoft.Phone.Data.Linq.Mapping are available only on Windows Phone, they are not listed in the following tables. System.Data.Linq The following members of System.Data.Linq are partially supported or not supported on Windows Phone. System.Data.Linq.Mapping The following members of System.Data.Linq.Mapping are partially supported or not supported on Windows Phone. See Also Other Resources Windows Phone Training Kit LINQ to SQL Documentation Query Examples (LINQ to SQL) How to use the Isolated Storage Explorer tool for Windows Phone 8
https://docs.microsoft.com/en-us/previous-versions/windows/apps/hh202872(v=vs.105)
CC-MAIN-2019-22
refinedweb
355
58.69
On the 0x511 day of Apache Harmony Naveen Neelakantam wrote: >> on first implementation we checked BidirectionalBubbleSort with the >> current ABCD. It removed all checks. IMHO, this is a good argument to >> prove that the issue is fixable without introducing principially new >> concepts. >> > > I disagree with your assessment. I believe that although ABCD did > work once, it is actually quite fragile. My fix removes a major > source of this fragility. > > And as for introducing new concepts, I believe that has already > happened when you decided to introduce an e-SSA that has enhanced pi > nodes and that is used for both the upper bound and lower bound > problems simultaneously. I think those were good changes based on > sound understanding. I believe my change also falls into this > category. Please take the time to understand what I am proposing. Naveen, sorry for the very late reply. It is not only me very busy, but also there had to be a lot of experimentation to find out what is happening. The short story is: "Your patch in HARMONY-6007 is great, awesome, it's operation is absolutely correct, it reveals a bunch of serious existing problems. I am very thankful for these. Fixing these problems covers all issues and adds extra benefits. So, I am going to stay with the new version." Now the full story, take a good seat, have a nice drink and leesen carefully :) I would be really glad to see comments, objections, advice, counterexamples, etc. Preface. I attached my patch to HARMONY-6007, please, take a look (the solver contains a lot of trailing space removal, sorry for that). Chapter 1. Passes. Optimization passed preceding to "classic_abcd" are: "memopt,dce,uce,simplify,dce,uce". I removed "hvn" since I did not find cases, where it becomes useful in presence of "memopt". "simplify" is required immediately before "classic_abcd" (modulo "dce,uce") because the latter relies on constants being folded, you can see it by running DaCapo pmd benchmark in debug mode using server_static pass. Chapter 2. Revealed problems. Naveen, your patch does a great job at termination stage at finding arraylength operands even if they are unconnected (i.e. unconstrained). Array length operand being unconstrained is a bug in "classic_abcd", so I jumped in at fixing this. The problem appeared in this pseudocoded situation: "call A() -> int x; newarray(size=x);". The fix contains two parts: (1) handling more load operations that can produce arraylength operands (Op_LdStatic, Op_TauLdInd, Op_DirectCall, Op_TauVirtualCall, etc.) and (2) not renaming array length operands in chkbounds instructions so that there is a single instance of this arraylen to find in the solver. Meanwhile I spotted another problem with our approach. Consider the code: int arr[] = new int[limit]; if (i < limit) { if (0 <= i) { arr[i] = 5; } } both original version and your patched version failed to eliminate the check here. Just because pi renaming logic was incorrect (in fact I never looked into it before and relied on many assumptions about what in fact it does not do). And there was a bug that relied on the fact that Pi instructions always start the block. This is no longer the case when we insert tauedge() (this was probably why it broke, not sure). Weird, we have a lot of such crap in JIT. So, I fixed, cleaned that up a little. I was lazy to verify that it works right with nontrivial code structures. Small examples like the above worked. If you spot something weird with a relatively small test, I would very much appreciate and will fix that faster than this time. Chapter 3. Results. I ran DaCapo with both patches in server_static mode with debug build (all I could, not everything works, dammit). Original patch in HARMONY-6007 ate 9.5% checks, while the new patch ate 9.9555%. Among the whole run I found only 2 methods, where original patch outperformed the new one, but again I was lazy to spot the problem since the methods were quite big. Almost forgot, regression tests passed with both patches. I should commit them into the codebase as real regression tests. TODO. Chapter 4. Problems remaining. My solution is still "more fragile" in terms of being resistant to adding new opcodes. Whoever adds new opcodes should be careful about setting the constrained/unconstrained status on them in the inequality graph. I'd like to stick with this solution though, as I said, to minimize the amount of levels of abstraction. Another problem: memopt sucks .. at finding aliases of arraylen loads if we are working with fields and not with arrays on stack. Example: public class field { public Object ss = new Object(); public Object[] objs = null; private Object[] run(int l) { objs = new Object[l]; for (int i = l-1; i >= 0; i--) { objs[i] = ss; } return objs; } public static void main(String[] args) { field t = new field(); System.out.println(t.run(10)[0]); } } this is probably not killing performance in real cases because there is usually some external call in the loop that can potentially rewrite the field (using reflection, argh). If anyone finds more problems with bounds checks removal, please, report with tests. To find out how many bounds checks was detected/eliminated for each method, this DRLVM option is useful: -XX:jit.arg.dump_abcd_stats=true, this dumps the info in the ./bounds_checks.log (Though do not forget that other optimizations can also eliminate bounds checks as hvn,dabce,fastArrayFill). Chapter 5. Conclusions. Naveen, thank you thank you thank you for the great work! Without it I would have been clueless about important problem sources for a much longer while. Great job! -- Egor Pasko
http://mail-archives.apache.org/mod_mbox/harmony-dev/200903.mbox/%3C0vqab7tg4yl.fsf@gmail.com%3E
CC-MAIN-2017-34
refinedweb
940
63.29
Hello - I've just installed Semantic MediaWiki, and all seems to have gone smoothly (i.e., the Special:version page shows that 0.7 of the software was installed.) But when I run the 'Testing your Installation' checks (from ), I run into a problem. Specifically - this is not working for me: *~*~*~*~*~*~*~* Create a regular wiki page named "TestSMW", and in it enter the wiki text).*~*~*~*~*~*~*~*~* Rather, I simply get a classic 'The page cannot be displayed' error. Does anyone have any suggestions as to what the fix might be here ? I'm wondering about the following install note: *~*~*~*~* If you have your own custom namespaces, you have to set the parameter $smwgNamespaceIndex beforeincluding SMW_Settings.php. *~*~*~*~*~* ... and whether that using Template: pages means that I need to take this step. Any advice is most appreciated. Thanks !
http://sourceforge.net/p/semediawiki/mailman/attachment/6671f7d50705212109q4e574050q55293e98101f8059@mail.gmail.com/1/
CC-MAIN-2016-07
refinedweb
135
66.84
How to sleep() a thread in C++ I'm making a simple program that creates a thread, sleeps for 20 seconds, then terminates the thread. The code below compiles, but fails to sleep and crashes at runtime (after all cout lines are run). I'm not sure what is wrong, I've tried to emulate other threads (ha) on this topic as best I can. Is there a different approach I should be using? Using Windows 10 #include "stdafx.h" #include <iostream> #include <thread> #include <Windows.h> using namespace std; void t1(int x) { cout << "Child greeting!\n"; Sleep(20000); cout << "Child terminating!\n"; std::terminate(); } int main() { cout << "Parent greeting!\n"; thread first(t1,0); cout << "Parent terminating!\n"; return 0; } 2 answers - answered 2018-02-13 02:57 Some programmer dude The problem isn't with your sleeping (which you really should do using std::this_thread::sleep_for()), but that your process ends before the thread ends. That happens when the main()function returns. That means the thread object will be destructed in an invalid state leading to std::terminate()being called, and your process appears to crash. You can solve this very easily by waiting for the thread to end. Which you do with the std::thread::join()method. On the other hand, you yourself call std::terminate()in your thread, so even if you wait for the thread to end, your program will still "crash". If you want the thread to end, just let the t1()function exit the normal and usual way. - answered 2018-02-13 03:00 zooropa Change your main to be: int main() { cout << "Parent greeting!\n"; thread first(t1,0); first.join(); // ADD THIS!!! cout << "Parent terminating!\n"; return 0; } and remove the terminate call from your thread function. void t1(int x) { cout << "Child greeting!\n"; Sleep(20000); cout << "Child terminating!\n"; // REMOVE THIS!!! std::terminate(); }
http://quabr.com/48758714/how-to-sleep-a-thread-in-c
CC-MAIN-2018-34
refinedweb
315
77.33
Content count419 Joined Last visited Posts posted by -TDRR- Nice! Glad to know that Vanilla compat. is really, really close. The new flame bringer sprites look pretty good as well as the new HUD face, looks less strangely thin. All in all a pretty good update, haven't checked out the new FreeDM maps and the new music but i'm sure i'll like them a lot! Congrats to everyone involved, great work as always. EDIT: I think a link to the manual would be nice to have in the home page. I don't know if i'm going bonkers, but apparently hiding behind a wall moments before a Pain Elemental spits a Lost Soul, makes it not come out at all. Doesn't seem to work at all in ZDoom though, so do this only in stuff that's not a ZDoom derivative or K8Vavoom. Alternatively, if you have the chance, hug the Pain Elemental and it won't do anything. When chainsawing a Pinky, it's usually smart to backpedal while doing so, to avoid getting harmed. Make sure you do this if you are using the -fast parameter, because they will get the bite on you most of the time if you don't! Revenants can be tricked by running into melee range and backing out before he hits you. Repeat as many times as needed. Strafing in circles (Not circle strafing) is helpful when facing a crowd of Pinkies that have you surrounded, it's not a perfect strat but a lot of the time it will save you some health. Using the SSG for these situations will be helpful too, or the Plasma Rifle if that's available. EDIT: I forgot this one! Never, NEVER, NEVER grab an invisibility sphere unless you are in a room chock full of hitscanners, because it's not going to be fun running straight into your enemies' projectiles. Yes, those GUI surfaces were a chore to get working. I don't have the manual at hand, but IIRC it said that there are 3.000+ lines of code for the GUI surfaces alone. I also hated how boring it made everything. GUI surfaces are a really cool idea, but they put so many of them that it gets tiring real quick. TBH I think Doom 2016 did it fine. 2 hours ago, GoatLord said: Let me try to make this more clear: You know how you can just literally load a resource texture wad into Doom Builder, and use the "save map into" function to make it a single .wad containing the new textures? I want to do that for thing entities; specifically new monsters and especially props (such as trees, traffic cones, office chairs, etc.). Is there an equivalent for this or is it only possible through manual editing, even with a format like UDMF? UDMF doesn't matter here, it's just something to store map data (originally separated in LINEDEFS, SECTORS, THINGS and a few others AFAIR), but stuff like custom monsters and props is definitely out of the scope of what it can do. This could be done, but the editor needs to support it, and anyways adding new things is so easy that it's not needed at all. Literally all you need is like 5 minutes, something like SLADE/XWE and your required files, and that's it. Not like it takes a 5000 IQ and years of learning. Actually, you can even do it without any of that, just Windows' integrated .zip file handler. Create a new .zip file, then drop all Realm667 .wad files here (Yeah i know waste of RAM bla bla bla, but this is meant to be super simple so...) and then just rename the file to have a .pk3 extension, and that's it. Whenever you want to pack it up for release, drop your map .wad in the .pk3 too. 6 minutes ago, tempdecal.wad said: Are you sure? This makes it sound like he wants to insert it directly into the map without using a map editor -10 for reading comprehension, i thought you wrote ways that an actor could drop something, my bad. In that case, using a RandomSpawner that replaces whatever monster you want with whichever other random selection of other monsters would work here. In a DECORATE lump, use this: ACTOR RandomZombieman : RandomSpawner replaces Zombieman { DropItem "TypeActorNameOfOtherVariant" } And keep adding more "dropitem" lines for more replacements. By the way, have you tried Scalliano's 667 Shuffle? That might be what you are looking for, and it has many Realm 667 guns and monsters. 1 hour ago, tempdecal.wad said: A few ways I can think of to do this: That's not at all what he meant. He means a way you can put custom monsters and stuff in your map without editing it in SLADE. No, there's no such way to do this. You have to either use SLADE or XWE if you seriously, seriously don't want to go through the hassle of installing SLADE. You grab all the stuff that the Realm667 downloaded WAD has, and you put it in your wad in any place before the "MAPXX" markers. I still recommend using SLADE much more than XWE, but if you haven't used SLADE because it's comparatively heavy or requires those stupid Visual C runtimes that force you to update Windows to the latest update, then it's an """okay""" alternative.. Man, this would be awesome for classic Doom. Not as much Doom 3 as it already has pretty cool shadowing, but this is great for outdoor areas since spamming lights is a lil bit laggy outdoors. Only issue with classic Doom is that you'd have to make a map for every single wall, but it would be really cool anyways. (yeah i know K8Vavoom does this but it's nice to have full control over the end result, like editing it in Paint or something) Anyways, this is neat. Interested to see whatever comes out of this. (Doom 2016 in Doom 3 amirite?) 2 hours ago, ketmar said: ah, that was fun! ;-) your map spots aren't marked to spawn on UV skill. and k8vavoom's default skill is "UV", not "HMP". so no map spots were spawned, and no monsters were placed. run it with UV skill in any other sourceport, and you'll see the same effect (or on HMP in k8vavoom, and the monsters will appear). Oh, i'm stoopid! Well sorry for that waste of time :) Thanks anyway. @ketmar I have a small issue with one of my mods: Randomized Roguelike map generates the map just fine, but it's completely devoid of monsters. Monsters spawn just fine in the whole ZDoom family so it seems i haven't done anything wrong. What's weird, is that MAP02 spawns everything just fine, but MAP01 doesn't. Any chance you can fix this or tell me what's wrong? As for the TDBots, i have updated my K8V version but the A_LookEx bug persists. The good news is that it's the last thing left to get the TDBots (v14 at least) fully working in K8Vavoom, as everything else works just fine. Could you show the whole ACS source code? I can't tell you what's wrong with it if you only show me that one line. No reason to keep it private anyways. Also, here's how the .pk3 file should be: My sad and slow laptop (Celeron 1.4GHz + Intel HD Baytrail + 2GB RAM) is far too garbage to run Windows 10 well. Also, no proper drivers are available to run Win10 with all of this laptop's features, so i really doubt i'm upgrading. Not only that, but many of the programs i use don't work properly in Windows 10. And this Windows 7 is actually Windows 7 Lite so i pretty much stopped recieving updates a while ago (This is Service Pack 1 AFAIR) I also have Linux, but i very rarely use it because GL performance absolutely sucks there (Playing Counter-Strike 1.6 at 120fps? Too bad! Enjoy these 20fps :) I don't care at all about modern games, since i can't run them in here anyways. Though if they manage to get Doom 2016 running in GL 3.3 with at minimum 2fps then i'll upgrade, if only to play the best slideshow of my life! The most modern not-indie game i can play here at high settings is Modern Warfare 2, and that's from like 2009. Still a good game though, but it shows the kind of trash PC i'm stuck with right now. On 7/27/2019 at 11:21 PM, Nevander said: Hey guys, if Doom 64 is actually being re-released or officially ported, it's possible I may be given a C&D. I certainly hope not though. I don't know if they would also go after Absolution TC, Brutal Doom 64, GZDoom64, or GEC Master Edition as well. Mine and BD64 are certainly the most well known so there's no doubt we would be targeted first (and possibly only us). EX is most likely safe, since you need the ROM anyway. It's literally only an executable. No data is included with EX. I hope they will view my project and others as "fan recreations" or something similar, instead of as an actual "remake." The former may allow them to stay up, since they are not really the original game in that sense. Regardless, I would advise you download it now while you still can. I love my work and I hope I can continue to make updates. If anything happens, i'll try to spread the .pk3 in as many, many pages i can get it so at least your work is preserved. I would hate to see this only be played by the people who got the chance of getting it before it got taken down. Also, i'm making a Zandronum version (yeah i always say this on many projects and a lot of the time nothing happens) but is it fine if i release it on this thread? It would be pretty cool to see Retribution being played online. EDIT: Nevermind this was already done. Another question that had me curious for a while, how were Breakdown's sliding doors done in the original? 16 hours ago, Hekksy said: The obvious answer is Zandronum because its easier for you to port and the most widely played client server port. However, I personally would love to see this in Odamex because it currently lacks bot support at all and desperately needs them. Both :) Ackshually, i went back to working in bots for Odamex. They are the ZCajun bots so expect them to be garbage at first, though they really aren't that hard to improve. Just takes a little bit of patience and a couple hours. In Odamex, it would be rather hard to use the bots since you would have to open multiple instances, i imagine having them all visible on-screen at the same time. Which is obviously very impractical and not really comfortable at all. 21 hours ago, Thfpjct said: Ok for some reason when i Summon the Weapon pickup the game just crashes, maybe i did something wrong? Here the "pk3" file to take less time. COLT EXPERIMENTATION GUN.zip Well, looking at the zip, you organized everything wrong. Make your project a .pk3 instead, and organize it like this: Sprites go in a directory of the .pk3 called "sprites", Make sure to not include SS_XXXX markers in this folder. Compiled ACS goes in "acs" (Not LOADACS, only the compiled file, which in this case is named "PICKUP") After doing this, i got no crashes at all in ZDoom LE or LZDoom, so you just organized everything incorrectly and that was the cause of the crash. 56 minutes ago, Thfpjct said: thanks alot! btw do you know any way that i can make the weapon pickup not instant? like a need to press E on them to pick it up? You can do this by expanding on the method i gave you above. You will need an ACS script for this, but i'm going to write it for you. Though, you will need to compile it and put it into your mod. //=====CODE STARTS HERE======== #library "PUTTHENAMEOFTHISFILEWITHOUTEXTENSIONHERE" #include "zcommon.acs" Script "Use_Button_Stuff" ENTER { int use; = GetPlayerInput(-1, INPUT_BUTTONS); while(GetActorProperty(0, APROP_HEALTH) > 0) { delay(2); use = GetPlayerInput(-1, INPUT_BUTTONS); TakeInventory("PickupWeapons",1); if(use & BT_USE) {GiveInventory("PickupWeapons",1);} } } Script "Use_Button_Stuff2" RESPAWN {ACS_NamedExecuteAlways("Use_Button_Stuff", 0);} //=====CODE ENDS HERE======== Make a new item called "PickupWeapons" (You can name it whatever you want, but change the name above too) And on the code of the CustomInventory item do this: //=====CODE STARTS HERE======== Actor insertsomenamehere : CustomInventory replaces insertreplacedweaponnamehere { states { Spawn: //show a sprite here or something Pickup: //New state, old pickup state was moved to DoPickup TNT1 A 0 A_JumpIfInventory("PickupWeapons", 1, "DoPickup") Fail DoPickup: TNT1 A 0 A_JumpIfInventory("WeaponLimitCount", 3, "DontPickup") //if the limit has been reached, don't do anything TNT1 A 0 A_GiveInventory("WeaponLimitCount", 1) //if not, just give the weapon and add to the counter TNT1 A 0 A_GiveInventory("ActualWeaponNameHere") Stop DontPickup: TNT1 A 0 A_RailWait //does nothing, just stays there Fail } } //=====CODE ENDS HERE======== 8 hours ago, Graf Zahl said: It depends on how you look at it. Doom.exe renders directly to video memory, but the texture in its raw form will remain in the regular RAM. I know that, but that's pretty much useless in the way xttl said it could be used.7 hours ago, Jon said: Yeah, i wonder how could it be worked around editing the .exe itself? 8 hours ago, Jon said: You can definitely crash hexen with bad ACS, it's easy to do evne if you aren't trying to. Whether that can be turned into something useful is perhaps worthy of investigation, yep. If this ever happens, we could maybe get ZDoom ACS power in Vanilla Hexen, which would be extremely cool.8 hours ago, Jon said: That's almost certainly enough. One just needs to bootstrap enough code so you can load in another lump and read more code from there. 1KB is a lot of machine code for that. This means that we can basically run entirely different programs using Vanilla Hexen as a startup method? Would be funny to run Doom on it, if nothing else.8 hours ago, Jon said: But we have the source code for the ports. We can do *anything* in the ports, by changing the source code. We don't need to artificially restrict ourselves to hacks and exploits. The only circumstance where that's interesting, IMHO, is where it's necessary, and that's pushing the boundaries of the original binaries. I guess. But my issue is that implementing this in a playable manner for both Vanilla and Chocolate is going to be pretty tough, since you would have to recompile Chocolate and put that along your .wad distribution, all of this while making sure it's at least somewhat close behavior between the two. So it's rather impractical. 8 hours ago, Jon said: I saw these and thought "uh oh" but your message was actually interesting. Yeah, i'm unexpert on all this stuff but i like reading up on hacking console games via exploits, just find it pretty cool. Maybe that's why not everything i said was completely nonsensical stuff. On 6/26/2019 at 11:36 AM, xttl said: Personally, I think the ultimate vanilla mapping/modding trick would actually be finding a way to get arbitrary code execution from any loaded WAD. Preferably early in the game startup, but at map load time, at time of running the first tic, or while rendering the first frame wouldn't be bad either. I've tried a bit to look into getting this working, but unfortunately I am no hacker extraordinaire after all. ;__; The only thing I've found so far is that the code which handles DMXGUS lumps (inside libDMX) allows you to overwrite stack contents with data from this lump, but obviously this only works if the user has GUS selected as the music card and the game must be able to detect it too. In addition, the first zero byte in the data will always terminate the copying of data from the lump since this is a string function (strcat) copying data to a fixed size buffer, and this zero byte will be replaced by a '.' (0x2E) from ".pat" which is further strcat'ed to the string to form a path to a GUS patch file on disk, which makes it difficult to write any good pointer values (they tend to have zeroes as the most significant byte) to the stack. Exploitation of any possibly usable overflows or other bugs is also made difficult by the "ASLR" which is in effect. As probably everyone who's interested in Watcom binary hacking/reversing knows by now: you can't really trust DOS4GW to load the sections to same addresses every time... (though this wasn't really meant as a security feature like ASLR nowadays so depending on hardware and software config the addresses aren't guaranteed to always change either) Perhaps Hexen could be a better candidate for this due to the multiple text-based game definition lumps it loads from WADs and parses, plus the ACS bytecode interpreter? ...now that I think of it, can the CPU execute code from VGA memory in DOS era PCs and DOSBox? Doesn't matter if it's slow as long as it works. That would always be guaranteed to be at the same address (0xA0000) no matter where DOS4GW relocates the LE sections. You could write code there by crafting special graphic patches and textures for the game to draw, then try to trigger a jump to 0xA0000 somehow! **warning: unexpert talk follows** I think restricting ourselves to the original .exe is just way too hard and restrictive like to do anything at all with arbitrary code execution. I'm no programmer, but i think it would be much easier to set up some way to make the .exe just blindly accept whatever the DMXGUS lump says, and if possible force it to load every time. I think this allows for code execution directly when the game starts since music playback is needed since the title screen appears, and most likely DMXGUS is parsed some time before that. Maybe you could also change the name of the DMXGUS lump to EXCODE or something, so normal DMXGUS lumps don't cause crashes. Then distribute the .exe modifications as patches, using whatever file patching program is available for DOS. But Hexen could be interesting, and probably possible without modifying anything. What if you just put complete garbage into a compiled ACS file? I'm pretty sure there's no safeguards since at first it was only intended to be used with the in-house ACC and only by the team. Though, less than 1KB is given to ACS in Vanilla Hexen so not sure how feasible that is either. But, we have to remember: This would only work in DOS or DOSBox, both of which are rarely used for Doom-ing nowadays. Shame it's impossible to do something like this in Chocolate Doom. Also, correct me if i'm wrong but, do the textures ever go through the VGA card? I thought it was all stored in RAM and stuff is rendered by the CPU and then the whole screen is sent to the card. You could make a DECORATE file in your wad with these contents: //========COPY STARTS HERE=============== Actor IceyPinky : Demon replaces Demon {Translation Ice} Actor IceyImp : DoomImp replaces DoomImp {Translation Ice} Actor IceyCacodemon : Cacodemon replaces Cacodemon {Translation Ice} Actor IceyHellKnight : HellKnight replaces HellKnight {Translation Ice} //========COPY ENDS HERE================= And that would make Pinkies, Imps, Cacodemons and Hell knights have an icey color. Sorry if it's not that great, but it's something at least. Would it be worth playing through doom 3? in Doom 3 Posted Depends, do you like repetitive corridors and ambushes? If so, then do give it a shot. Never finished it either, got way too bored. But i think the best way to decide is booting it up and playing for 10-30 minutes and then decide if you really want to continue.
https://www.doomworld.com/profile/22845-tdrr/?do=content&type=forums_topic_post&change_section=1
CC-MAIN-2019-43
refinedweb
3,447
70.43
#1 Posted 27 February 2011 - 11:18 PM i was jus wondering if i should use boost regexp to ease my parsing of the bsp entities text i think in quake3 they are just using regular c string functions to parse this but that is just simply way too much code and could be done way faster with reg exp help but installing boost c++ libs to get reg exp is like 240mb why is boost asking for that much room? how should i parse this? #2 Posted 27 February 2011 - 11:41 PM #3 Posted 28 February 2011 - 12:46 AM { "name" "value" "name2" "value2" } so w preg_match i would just do entities[] = preg_match(/{.*?}/) entities[i].lines[] = explode(entities[i], "\n") preg_match(/(\".*?\")\s+?(\".*?\")/, entities[i].lines[i], entities[i].nameandvaluearray) #4 Posted 28 February 2011 - 02:45 AM #5 Posted 28 February 2011 - 05:45 AM its just that quake source is using only using c string function and logic i guess so i thot it be way less code to do it with regex #6 Posted 28 February 2011 - 06:22 AM #7 Posted 28 February 2011 - 11:04 AM - Currently working on: the 3D engine for Tomb Raider. #8 Posted 28 February 2011 - 11:09 AM and no i dont need error detection the less code the better ill add that stuff later #9 Posted 28 February 2011 - 11:28 AM #10 Posted 28 February 2011 - 01:32 PM My plan to make things simpler is to do a precompile to reduce everything in the typed code to simple 2 variable + one operator instructions, then interpreting after that will be really simple. Just like .oisyn says, little more than scanf is all you need. :) #11 Posted 01 March 2011 - 02:09 AM this is a perfect place to use it and i would like to have it anyways i also mad at c++ strings because i cant printf them it tells me that printf is expecting a string and my string is an int, wtfff so i tried converting string to char and it wont let me do that either what is wrong with u c++ lol c++ is acting like c-- maybe even an f+ #12 Posted 01 March 2011 - 05:10 AM By the way, C-- is an actual language, although one designed more as an intermediate language for compilers than a language for humans. #13 Posted 01 March 2011 - 07:23 AM enjoycrf said: In C++, you shouldn't even use the C I/O functions, but the STL counterpart, like 'cout << str;'. See here for more info, and here for why you should avoid printf and the likes. enjoycrf said: #14 Posted 01 March 2011 - 08:29 AM hmm this looks very familiar lets try this again #15 Posted 01 March 2011 - 08:37 AM could that possibly be windows code? i migrated from windows plus i get code from dif sources #16 Posted 01 March 2011 - 08:40 AM wow i am a total nuub i guess i just found that i am doing c style file handling too? #include <fstream> // Include this to use ifstream #include <vector> // Include this to use STL vectors #17 Posted 01 March 2011 - 08:41 AM - Currently working on: the 3D engine for Tomb Raider. #18 Posted 01 March 2011 - 08:50 AM g++ %f -o nice -lGLU -lGL -lglut -lfmodex -std=c++0x slim, mean and lean cuisine lol let me kno if theres something beter or i should be using 1 user(s) are reading this topic 0 members, 1 guests, 0 anonymous users
http://devmaster.net/forums/topic/14260-parsing-text/page__p__76242
CC-MAIN-2013-20
refinedweb
600
55.75
Storage remobve the static storage specifier from variable p in prog1.c. You should be able to compile prog1.c and prog2.c together. Compiler will not give any error Register variables indicate the compiler to store the variable in CPU register instead of memory. The register storage class specifier is typically specified for frequently used variables, such as a loop control variable, to enhance performance by reducing access time. But compiler is not required to commit this request. Because of the limited size and number of registers available on most systems, only few variables can actually be put in CPU registers. If the compiler does not allocate a CPU register for a register variable, the variable is treated as having the storage class specifier auto.The following are the rules of use for register variables: #include <stdio.h> register int r; /* Wrong declaration */ int main() { register int var; int *b = &var; /* Not allowed */ return 0; } An external variable is a variable declared as global in another file and is extracted from that file for using in the current file.The following are the rules of use for extern variables: Above program will produce the following output.Above program will produce the following output. /* File ext1.c */ #include <stdio.h> void call_fun(); int val2 = 90; int main() { call_fun(); return 0; } /* File ext2.c */ #include <stdio.h> extern int val2; void call_fun() { printf("The value of val2 is %d\n",val2); } $ gcc ext1.c ext2.c $ ./a.out The value of val2 is 90 $
https://www.mbed.in/c/storage-classes-in-c/
CC-MAIN-2020-45
refinedweb
253
57.37
Dynamically typed code¶ As mentioned earlier, bodies of functions that don’t have have any explicit types in their function annotation are dynamically typed (operations are checked at runtime). Code outside functions is statically typed by default, and types of variables are inferred. This does usually the right thing, but you can also make any variable dynamically typed by defining it explicitly with the type Any: from typing import Any s = 1 # Statically typed (type int) d = 1 # type: Any # Dynamically typed (type Any) s = 'x' # Type check error d = 'x' # OK Operations on Any values¶ You can do anything using a value with type Any, and type checker does not complain: def f(x: Any) -> int: # All of these are valid! x.foobar(1, y=2) print(x[3] + 'f') if x: x.z = x(2) open(x).read() return x Values derived from an Any value also often have the type Any implicitly, as mypy can’t infer a more precise result type. For example, if you get the attribute of an Any value or call a Any value the result is Any: def f(x: Any) -> None: y = x.foo() # y has type Any y.bar() # Okay as well! Any types may propagate through your program, making type checking less effective, unless you are careful. Any vs. object¶ The type object is another type that can have an instance of arbitrary type as a value. Unlike Any, object is an ordinary static type (it is similar to Object in Java), and only operations valid for all types are accepted for object values. These are all valid: def f(o: object) -> None: if o: print(o) print(isinstance(o, int)) o = 2 o = 'foo' These are, however, flagged as errors, since not all objects support these operations: def f(o: object) -> None: o.foo() # Error! o + 2 # Error! open(o) # Error! n = 1 # type: int n = o # Error! You can use cast() (see chapter Casts) or isinstance to go from a general type such as object to a more specific type (subtype) such as int. cast() is not needed with dynamically typed values (values with type Any).
https://mypy.readthedocs.io/en/latest/dynamic_typing.html
CC-MAIN-2017-13
refinedweb
359
68.3
Issues ZF-2802: Allow Zend_Loader to load classes with real namespaces Description PHP 5.3 introduces real namespaces (Namespace::Class). With the following small patch Zend_Loader can handle them too. PHP 5.3 introduces real namespaces (Namespace::Class). With the following small patch Zend_Loader can handle them too. Posted by Lars Strojny (lars) on 2008-03-04T07:46:01.000+0000 Allow Zend_Loader to handle classes with real namespaces Posted by Wil Sinclair (wil) on 2008-03-25T21:30:49.000+0000 Please categorize/fix as needed. Posted by Matthew Weier O'Phinney (matthew) on 2008-11-22T09:15:06.000+0000 Until 5.3 has a stable API, there is no sense in changing this functionality. Posted by Keith Pope (mute) on 2009-11-01T03:14:55.000+0000 Now that 5.3 has been released could this be applied in a 1.x release? I am just looking at doctrine 2 integration with the 1.x series and this would be a helpful addition, though this can be achieved by adding a custom autoloader into the stack as a workaround. Posted by Benjamin Eberlei (beberlei) on 2009-11-01T08:29:35.000+0000 @Keith I have exactly the same problem while writing a Doctrine 2 resource plugin, I'll reopen the issue and put it to very high priority. Posted by Benjamin Eberlei (beberlei) on 2009-11-01T08:30:23.000+0000 Hm issue is not reopenable. I'll add a new one.
http://framework.zend.com/issues/browse/ZF-2802
CC-MAIN-2015-32
refinedweb
245
70.5
On 11-12-07 13:08, David Newall wrote: > Rene Herman wrote: >> On 11-12-07 08:40, Paul Rolland wrote: >> >>> Well, if the delay is so much unspecified, what about _reading_ port >>> 0x80 ? >>> Will the delay be shorter ? >> >> The delay is completely and fully specified in terms of the ISA/LPC clock > > That would be the delay on the i386 (sic) architecture. In general, > though, the delay is: This particular discussion isn't about anything in general but solely about the delay an outb_p gives you on x86 since what is under discussion is not using an output to port 0x80 on that platform to generate it. > Thinking that _p gives a pause is perhaps too PC-centric. Why, if a delay > is needed, wouldn't you use a real delay; one that says how long it > should be? Because any possible outb_p delay should be synced to the bus-clock, not to any wall-clock. Drivers that want to sync to wall-clock need to use an outb, delay pair as you'd expect.. The delay it gives is very close to 1 us on a spec ISA/LPC bus (*) and as such, even though it may not be the right thing to do from an theoretical standpoint, generally a udelay(1) is going to be a fine replacement from a practical one -- as soon as we _can_ use udelay(), as I also wrote. Rene. (*). #include <stdlib.h> #include <stdio.h> #include <sys/io.h> int main(void) { unsigned long cycles; if (iopl(3) < 0) { perror("iopl"); return EXIT_FAILURE; } asm ( "cli \n\t" "rdtsc \n\t" "movl %%eax, %%ecx \n\t" "outb %%al, $0x80 \n\t" "rdtsc \n\t" "subl %%ecx, %%eax \n\t" "sti " : "=a" (cycles) : : "ecx", "edx"); printf("out = %lu\n", cycles); asm ( "cli \n\t" "rdtsc \n\t" "movl %%eax, %%ecx \n\t" "inb $0x80, %%al \n\t" "rdtsc \n\t" "subl %%ecx, %%eax \n\t" "sti " : "=a" (cycles) : : "ecx", "edx"); printf("in = %lu\n", cycles); return EXIT_FAILURE; }
http://lkml.org/lkml/2007/12/11/55
crawl-002
refinedweb
333
63.53
See also: IRC log <Nilo> scribe:Nilo <Jonathan> agenda approved, with test status update included Feb 20 minutes approval postponed to tomorrow test results from Jonathan: 5 implementations tested, results shown, basically a sea of green a few optional features have no implementations; so they are at risk Bob would like to get PR text completed today and wants everyoe to work towards that AI review - all AIs completed Umit concerned about lack of WSDL implementations affecting the WSDL binding Bob says that we have a choice re WSDL binding - choice of 1) making doc a Note or 2) changing the number of implementations needed to progress it <hugo> DH thinks this is a potentially editorial change and can be done after we have agreed to the other changes to this text. He proposes discussion be deferred until later Umit: how is SOAP1.1 text affected? <Jonathan> jonathan: two action values - one for addressing-specific faults, another for application-level ones Hugo: concern with the term "generic SOAP faults" general consensus re the action value for the addressing-specific faults with one addition: add a reference to the section on the Faults section <bob> The [action] property below designates WS-Addressing fault messages: <bob> <bob> *This action SHOULD NOT be used as an action value in messages other <bob> than those carrying WS-Addressing faults.* section 6.4 <bob> SOAP modules, extensions and applications SHOULD define custom [action] values for <bob> the <bob> faults they describe but MAY designate use of the following [action] <bob> value <bob> instead: Katy: change "generic faults" to "such as..." DaveO: call them "SOAP defined faults" instead of "generic SOAP faults" <dorchard> SOAP defined SOAP faults. Marc: seems a bit contradictory Glen: may want to have infrastructure choose the appropriate action value consenusus building around closing the second part with no action Umit: what's the reason for the second part Jonathan: it would be nice to know if it was a generic SOAP fault as opposed to a app level fault. Glen: it almost seems like over-riding SOAP fault codes Anish: still need to change the para between the two action value. <anish> in section 6 This will be marked as CR24 Resolution: CR24 as above, accepted without objection <bob> The above [action] value SHOULD be used for SOAP defined faults <bob> including <bob> version mismatch, must understand, and data encoding unknown. *This <bob> action SHOULD NOT be used as an action value in messages other than <bob> those carrying SOAP defined faults or those of SOAP modules and <bob> extensions.* <bob> <bob> I use SHOULD because this is a hard thing to test, seems like the <bob> appropriate level of guidance, and doesn't force a breaking change in <bob> implementations at this point. <bob> <bob> Original thread that sparked this follows... <bob> <bob> This SOAP 1.1 request optional response HTTP binding, in conjunction <bob> with the SOAP 1.1 binding, can be used for sending request messages with <bob> an optional SOAP response. This binding augments the SOAP 1.1 binding <bob> by allowing that the HTTP [RFC 2616] response MAY have a 202 status code <bob> and the response body MAY be empty. Note that the HTTP [RFC 2616] <bob> specification states "the 202 response is intentionally non-committal". <bob> As such, any content in the response body, including a SOAP body, MAY or <bob>". <dorchard> As such, any content in the response body, including a SOAP body, MAY or Umit: can the last sentnce be reworded? Anish: this is an op response, so you could also get back 202 with and without a SOAP env, as well as a 200 with a SOAP env Bob: we need new text starting from "As such..." <marc> At the risk of prolonging the discussion I note that SOAP 1.1 doesn't preclude a HTTP 202 without a SOAP entity body: Anish: propose striking sentence starting "As such..." Jonathan: how does this affect the test suite Glen: the 202 is used in the test suite <dorchard> Another slight wording mod of the last 2 sentence.. <dorchard> Note that the HTTP [RFC 2616] specification states "the 202 response is intentionally non-committal" and so any content in the response body, including a SOAP Envelope, MAY not be an expected SOAP response. Text above agreed RESOLUTION: Out-optional-in MEP is accepted and will be published as a WG NOTE Break until 10:45 <bob> above resolution is to clean up and publish the note: <bob> N.B. <bob> Bob- talk to hugo about how to publish resuming meeting again <bob> <anish> alternate proposal: Anish: has an alternative proposal and suggests that this isuue be closed with no action umit: it is WS_RX's choice to use our anon URI or mint their own Glen: agrees with Anish ... we don't need to encourage WS-RX to use this URI in ways that may not be these semantics Katy: the semantics is that it depends on the underlying SOAP transport binding ... It allows RX to go either way - use this URI as we define it or define their own URI for acksTo <uyalcina> I am very uncomfortable in reverting a request that came from RX and forcing a particular decision on them, <uyalcina> we should give them the choice Anish: not comfortable with making its meaning context sensitive Jonathan: there is value in making this URI mean that it depends on the infrastructure ... in short, agreeing with Katy DH: if you are using anon, you need to understand the context it is to be used <Zakim> GlenD, you wanted to indicate that using a different URI is more comprehensible than looking up a namespace for an EPR header such as <wsrx:AcksTo> Tom: could go either way, but does not see why a spec can't define its own EPR's semantics Glen: in summary would prefer WS-RX to mint its own URI DOR provides an analogy to java abstract vs concrete classes anish: we don't disallow use of anon in any other context. we simply define its use for reply/failtTo <GlenD> Tom just made an interesting point - when you see a URI, you tend to want to deference it to see what it means... umit: there is an abstract/concrete analogy. abstract is "any back channel" while concrete is specific back channels in specifc contexts <GlenD> If it's RX's "sequenceBackchannel" URI, that's clearer than "W3C's no-real-meaning-anonymous URI" anish: the current text encourages you to use this URI in a different context <Zakim> TonyR, you wanted to addressing RX minting their own URI Tony: RX should define their own URI because it has a different meaning <Zakim> dhull, you wanted to point out that RX is not the only potential reuser of anon <uyalcina> Please folks, WS-RX ASKED us to loosen up the definition of the URI for them. <uyalcina> This is why we are discussing this <anish> the issue about implementations changing is a red herring, imho, it does not change the impl much. There are a whole lot of changes that are currently taking place in wsrx which are huge compared to this tiny 'if' stmt change <uyalcina> +1 to DH. DH: we should leave the door open for future SOAP bindings which have back channels; so we should provide guidance for what anon might mean for them > Hugo: support Anish's proposal <Katy> Additional text does not force rx to use anon URI - just states that, if it is used, the behaviour must be specified in RX context. DO: in either case, the RX spec implementers will have to look at their spec to see how the anon value is used Jonathan: wants to allow anon to be used with AcksTo as used today <Zakim> GlenD, you wanted to call the question (let's vote!) Tom: happier with Anish's proposal, but could edit Katy's proposal to meet concerns <dorchard> Is it almost the straw poll of "do you want anon re-used or not"? Glen: want to get a sense of the group Katy: RX implementations are using the anon URI Marc/Anish: they are not using this CR anon URI <pauld> has no sympathy for WS-RX, they're referencing a moving target Anish: RX uses the old anon URI Umit: the semantics of the old anon URI was "any back channel" which is what Katy's proposal is trying to capture <GlenD> Umit - it doesn't matter that it's the SAME anonymous URI as addressing uses, though, does it? <GlenD> If they need to change anyway, is it that big a deal? <uyalcina> it does matter to RX. <uyalcina> They asked us to define it for them <pauld> what implementations are using our freshly minted URI?! <GlenD> I'm asking Umit the architect/developer, not Umit the politician. :) <uyalcina> i was the one who raised CR4 on behalf of WS-RX poll to adopt katy's proposal straw poll: for 6 against 8 Tom: the input WS-RX did not use "anon" Bob: can we live with no action? <dorchard> And, can we live with Katy's proposals? Umit: I was given the AI by WS-RX TC to define the use of "anon" Bob: I have an ongoing AI with WS-RX to keep tabs on movement to cr4, thus I will communicate to WS-RX what has changed ... What needs to change in the proposal to make it acceptable? DO: I thought we voted for the intent, not the exact text Glen: Minting URIs is easy and there does not seem to be a benefit to use the same URI with different meaning DH: WS-RX found the "back channel"semantics of anon to be useful to reuse <Zakim> dorchard, you wanted to ask more people Vikas: For a non synchronous transport, you do not want somebody to specify what the back channel is Anish: does not achive the reuse objective. WS-RX sequence can make use of many differnt binding fora given sequence; so this text may not be able to describe the RX scenarios. <dorchard> anish, this only doesn't work if there's a non-soap binding.. Bob: anon means "knows what to do" <anish> dave, or another soap/http binding Hugo: I do not understand why people care about this so much as it's not clear that any of the option will change anything; let's change find an option that everybody can live with and move on <anish> dave, or if you use soap 1.1 and smtp or another transport protocol <dorchard> anish, if somebody else defines soap/http then they would have to do anon.. <anish> right, and they would not be using our soap addressing binding, so any text we put it in there cannot be used by wsrx <dorchard> jeff, aren't we defining extensible semantics though? That is the semantics are of re-use... <uyalcina> The URI's semantic is the same=back channel Jeff: if you use a URI defined in a spec you are confined to its semantics. If anyone wants to use a differnt semantics, define a different URI. Problem if different specs continue to use anaon with different semantics <anish> can we do a can-live-with poll <uyalcina> what we are debating is the semantics of the EPRs that use the URI <pauld> wakes up for what sounds like a versioning and extensibilty discussion <bob> ? Bob: can anyone not live with closing with no action? Tom: I don't want to suggest reuse in the text, becasue if you do you have to put in all sorts of caveats. ... katy's text needs worsmithing. <uyalcina> +1 To Jonathan <pauld> anonymous means "do the right thing" <anish> jonathan, do u think we need to say that or is it enuf for wsrx to say that? <anish> i.e., with status quo wsrx can do exactly what u are suggesting <Jonathan> I think we've overconstrained anonymous already. <Zakim> TonyR, you wanted to point out that jonathan's point is valid, but that's not what the words SAY at the moment <anish> how? <anish> we in fact only say right now what it means in replyTo and faultTo <anish> we don't say anything beyond that Tony: At this point it does not say "knows what to do" <dorchard> I assert that the anon is a special value and it means that a user will have to look at context, and the good part of Katy's proposal is to highlight that people need to describe their use.. <Katy> Additional text clarifies what is required by those who want to reuse anonymous - i.e. it must be defined when used outside ws-a context Anish: we do not say what anon means outside replyTo/FaultTo Jonathan: we constrain what it means at the SOAP level and the HTTP level <pauld> Katy's text is simply "caveat emptor" .. I puzzle how to write test cases for it .. <anish> section 5.1.2 says: ]. Bob: Does the spec overly constrain the use of anon? Tony: heading of 5.1 needs to be changed. Add some text to say that this section defines the use of anon in the ctx of WSA. Anish: apart from the section heading, text does not constrian you in any way. Bob: over lunch, small group will work on new text DH: pending c18 will also affect this text bob: anish and katy will work on text over lunch, followed by formal vote LUNCH BREAK resume 1:15PM <Katy> Katy: explains the proposal prepared over lunch <Katy> The precise <Katy> meaning of this URI ** within the context of Addressing ** is defined by the binding of Addressing to a <Katy> specific protocol.. <Katy> The precise <Katy> meaning of this URI ** within the context of Addressing ** is defined by the binding of Addressing to a <Katy> specific protocol.. Katy: is katy's suggested alternative text to the proposal <scribe> Scribe: Anish Bob: how do folks feel about this? Tony: s/in SOAP Response/for SOAP Response/ Umit: i think the heading is still incorrect ... it is a general stmt ... s/SOAP// RESOLUTION: resolve issue CR23 with proposal at no objections Marc explains the issue jonathan: i feel that we made a bunch of changes in Vancouver and looks like we have issues about it. ... our solution introduced more problems. Revert back to what we had, but open to fixing this however we can Discussion on what CR17 resolution did Marc: I would rather just define a default which is not context sensitive Glen: there are usecases where people can't use this Umit: in that case the property is no longer optional ... it makes the header optional but not the property optional glen: u can fix it either way ... if i care about one-way messages only then i don't care about it <dhull> can everyone still hear on the phone anish: don't make premature optimizations, no default. if the property is there, it is there. Else it isn't. glen: instead of saying syntactic default, we can specify in the 'how to sent the reply' section ... why do we need to specify that in the wsdl doc anish: how important is the default? glen: it is important as there are cases where the reply can be large % of the message. umit: in the wsdl doc, we have described using abstract message props ... the reply endpoint should be there. But that does not mean that the header is there. <marc>;%20charset=utf-8#WSDLMEPS Marc: we can just delete section 5 in wsdl binding anish: i don't think we should do it glen: i don't think section 5 should be removed <dorchard> Glen suggestion: change "in message" to "used by communicating nodes". <dhull> +1 to "hands off the core" davidh: what we are trying to say that this is actually used in message exchange jonathan: i think we can revert CR17 and make the property required More discussion on various solution katy: my concern is that if we undo cr17, we have to make sure that it all works ... can we fix it syntactically in the wsdl spec ... under the MEPs, it says "this section describes whether properties are required or optional" <dhull> s/Mandatory/Required by MEP/? katy: we can change it to : this section says which core MAPs are rquried by MEPs of WSDL 1.1 ... and the top of the table change mandatory to requried dhull: i don't think change from mandatory to required does anything. we need to say that the requireness is for the MEP ... the important part is "for MEP" umit: how does it solve the current problem ... the MAP reply-to will always have a value Marc: u are mixing the abstract and serialized one ... if u come up with another way to serialize this then it won't fly Glen: agree with katy's suggestion ... we say there is no syntactic defaults ... from the MEP there may be defaults Marc: i want to write a lib which can query soap message and get the abstract properties ... if i have to default based on the context, i don't like it umit: we can't put any case (where it has to fault if a value is not present) in our test case glen: that is a different issue marc: in this case, for our mapping, there will always be a value for [reply to] umit: without all the context you can never figure this out marc: we can add another note to make this clear ... proposal -- core section 3.4 note that for the serialization [fault to] and [reply to] is always present Tony: rather than saying that the processor will never fault, I would say that the MAP would never be empty ... instead of talking about the behavior of the processor we should talk about the properties Marc: proposal -- reopen CR17, close with clarification to the existing note and revert decision on CR17 Umit: i prefer saying explicitly that we allow other serializations bob: we have marc's proposal and see if we can converge ... is this the approach to take to resolve this? ... can we leave the wordsmithing to the editors? Umit: I'll work with marc on this Tony's proposed text: The [reply endpoint] messaging property is defaulted to "ANONYMOUS" by the current serialisation, so this MAP will not be empty. RESOLUTION: cr21 Revert cr17, new text proposed by Tony and close issue CR21 with reversal of cr17 umit: there will be clarification of the note <scribe> ACTION: umit/tony/marc to figure out the wordsmithing for clarification to the note (CR17/CR21) [recorded in] jonathan/paul: can we do that later but still discuss the issue coming out of the tests? Jonathan explains the issue Issue explained at: Jonathan: these features were marked at risk ... MS's position is we are not going to implement it, we would like it to be gone. We don't mind having it in, as long as we have 2 implementations hugo: we did not mark those things at risk ... we put in a note saying that the section may change paul: from my POV i feel strongly about it. it has minimal with no value but requires lot of testing ... my recollection from Boston was that it was at risk Hugo: i don't think removing something like that would change the reviewer/implementers experience jonathan: we are not going to implement it, unless you hold a gun to our head and then we would do something, but not ship dhull: if this is not useful then i'm not going push on it jonathan: not a security expert, but i have heard that passing just a Qname is better dhull: u would send a message and the person receiving the message may not have the context bob: We have not heard anyone speaking strongly for this ... do we have agreement that we redact the problemheader ... it is the Team's opinion that it would not change the implementation experience RESOLUTION: redact problemHeader Jonathan: not sure how to test it ... no motivation ... i don't want this fault code hold up CR ... this isn't as clear cut as the last one ... we could make it an informative test case rather than optional test case dhull: feel differently about it ... the idea behind this is to deal with hop-by-hop or gateway situations ... if we want to do a test, we can create an endpoint that always throws a fault jonathan: we might have to work on it. move it to informative will not help wrt result this week. but could be helpful in the long run dhull: don't want to derail this. if we want to do it now or later that is fine ... the fact that no one has implemented doens ... n't tell us much ... would like to keep it, will help with test cases <more discussion on various fault codes and what they mean> dhull: we should be able to make the box turn green bob: if status-quo means we need to have 4 imples then it is a problem jonathan: this is a more advanced feature and we can agrue that we don't need this now paul: i look at this fault and think it is not interoperable ... no benefit of this katy: agree with paul dhull: this is not an advanced feature it is a simple feature tony: davidh your position would be more defensible if you had an impl jonathan: two different perspective, say it is more adv. feature bob: what do we have to do here to move on? davidIh: there is no must here bob: does the resolution mean just removing the testcase hugo: we have an agreement that if we can't test it we'll remove it jonathan: we can say that we failed to get implementations of this particular error condition ... advanced impl. can use this ... we can't have every class of implementations bob: could be useful for say 'tcp/ip' ... nothing to do with addressing dhull: in the gateway case not necessarily a transport failure ... jabber case is another one ... not going to lie on the road jeff: the reason to set a criteria before you are under pressure is to create one that is reasonable ... hard to believe justification given now ... don't believe any arguements about things happening in the future ... this is supposed to be widely implemented spec and easy ... we should stick with it and carry on with the program hugo: but nobody is using it jonathan: what are you suggesting? jeff: don't move on till we have an implementation hugo: i don't understand that -- we have 3 (or 5) impl. and no one is using it jeff: either yank it out or implement it jonathan: i've a positioin that is compatible with that paul: test cases haven't been written dhull: lets be consistent <uyalcina> It appears that there are no test cases for section 6.4.1 dhull: i don't want to cherry-pick paul: we have a number of testcases bound to contributions from MS/IBM/myself/Hugo/Philippe -- we don't give good coverage to this area (faulting) ... it could be one fault or multiple fault ... don't know the reasons for test cases for a few faults and not all ... each fault code implies a processing model ... each of these has a high cost ... my company position to yank it out dhull: in that case we have to yank out other things too ... are there test cases for actionnotsupported and endpointunavailable <pauld> dhull: how do u know that the implementation is behaving properly daveo: is it a question of creating testcases or impl. just don't support it ... lets have the WG members write tests <pauld> daveo: standardized fault is important <BREAK> <scribe> Scribe: anish bob: we are trying to figure out appropriate way to move forward on the fault codes ... one suggestion is to take all of non-tested/unimplemented faultcodes and to remove them from the normative spec and put it in a non-normative note ... all of the faults in section 6 that are not tested dhull: actually all the optional faults (with no MUST) umit: why not create a non-normative fault codes jeff: need faultcodes for interop ... helps to have std codes dhull: that is the idea ... but nothing normative paul: i favor note, non-normative appendix has a cost ... wrt errata ... expectation is that it will grow ... these are soap fault that are useful tom: non-Required faults are still normative for the clients <uyalcina> I do not prefer a note, one spec is enough for implementors as a reference. All of our implementors are confused how many specifications docs are out there, what their status is, etc. jeff: i don't understand the packaging argument paul: i can pick up the ws-addr spec with 2 pages as opposed to 6 pages jeff: there should be normative in the sense that they are defined by the rec paul: endpointnotavailable can be catch for a lot of things jeff: is helpful so that one can have a switch <uyalcina> we seem to be mixing the concept of whether we can test the error generating conditions and whether the codes may be useful for users. paul: want more of vendor specific codes ... if the semantics can be nailed down -- which is a lot of work jeff: u don't have to test them bob: if the spec were to include the other non-must faults, those may be impossible/hard to test jeff: we could write a test for that bob: we might dhull: fault is not the feature hugo: we are talking about section 5 and it is useless, times time, helps interop etc ... put them on the whiteboard and find out which are releated to MUST, whether there is a test, implemented etc umit: where are we going with the classification? ... i'm worried that eliminating subcodes. Would like to compare their use how XML schema codes were useful with XML Schema implementations schema. Would like to keep most of the codes <hugo draws a chart with various faultcodes and associated attributes: Must, Test and Implemented> jonathan: one of the difficulties with testing is that it is hard to create bad messages paul: not people writing test cases <dhull> section 6 says "[Details] The detail elements, use of the specified detail elements is REQUIRED. If absent, no detail elements are defined for the fault.", but I don't think any of the faults really gives any REQUIRED detail elements. They either say nothing or say MAY. paul: my understanding was that implementations don't implement features in time, they are gone <uyalcina> Lets be fair here. WSDL binding just went to LC and some of the fault codes were added recently after Japan at Vancouver. Hugo's table: Problem hdr - Must:N Test:Y Impl:N Problem Hdr QN - Must:N Test:Y Impl:Y Problem IRI - Must:N Test:Y Impl:N Problem Action - Must:N Test:N Impl:N Retry After - Must:N Test:N Impl:N Invalid Addr Hdr - Must:Y Test:Y Impl:Y Inv Addr - Must:Y Test:N Impl:N Inv EPR - Must:Y Test:N Impl: Inv. Cardinality - Must:Y Test:Y Impl:Y Miss Addr in EPR - Must:Y Test:N Impl: Dup MID - Must:N Test:N Impl: Action Mismatch - Must:Y Test:N Impl: Only Anon - Must:Y Test:N Impl: Only Non-Anon - Must:Y Test:N Impl: Message Adr Hdr Req - Must:Y Test:Y Impl:N Dest. Unreachable - Must:N Test:N Impl:N Action Not Supported - Must:N Test:N Impl:N Endpoint Unavailable - Must:N Test:N Impl:N bob: we do not specify behavior hugo: my proposal is to keep the ones with 'Must' and they seem to be implemented and figure out what to do with the rest katy: we should be able to look and them and remove if not needed umit: i pushed 2 error codes cause they are related to WSDL <dorchard> agenda question, what else is after the test cases? jonathan: if we can have a written proposal that can be reviewed by our engineers that would be good ... and look at it tomorrow <uyalcina> those two error codes came in late in Vancouver, they are relevant for the WSDL binding. <pauld> I do not believe we have two implementations who have implemented each of these faults in the same way <pauld> WSDL Binding can develop its own faults <Zakim> dhull, you wanted to reconsider whether a standard spelling with no standard semantics is helpful or harmful daveh: the reason for have the last three fault codes in hugo's table was to not to have a must around it, but having the spelling available for interop ... we could just pull the 3 out bob: proposal -- ... Define normatively two faults that MUST be implemented ... 1)Invalid Adr Header; subfaults move to note ... 2) message Adr Hdr req ... 3) move all other non-MUST fualts to a note ... 0) drop Dest unreachable, Action not supported and Endpoint unavailble faults <dorchard> For the record, I'll be in and out tomorrow AM then absent in the PM for other WG/TAG meetings.. dhull: 0 is separate decision bob: any opposition none RESOLUTION: accepted (0) in bob's proposal (subsequently nullified the following day) jeff: don't agree that it should be in the note umit: what if there are in a non-normative appendix jeff: i want to be able to be count on these codes as a client katy: David Illsley thinks that we can remove more codes bob: there are a lot of flavor of Invalid Addr Hdr jeff: normativeness means we reserve this slot in the NS hugo: we have done the generic category of Invalid Addr Hdr ... don't find the necessity to test the details bob: we have tested at least one detail paul: unhappy camper ... i went with the consensus in Boston with the assumption that based on implementors experience we'll rip it out if needed ... would like to express my objection and get it on record ... i would like to remove all rows that are optional ... it is half-baked, we slapped it in there ... it should not be in there jeff: in corba there were predefined codes which were hints to users paul: this will come back an bite us umit: we have two fault codes related to WSDL. WSDL isn't even in CR paul: i feel strongly about remove these codes, but i'm willing to move on cause we need to get done ... error codes need to be machine processable jeff: other reasons to have error codes too <discussion on error codes> dhull: intellence systems can go thru logs and do interesting things. So this is helpful ... i do agree that our processing model is weak (wrt codes) katy: in response to Paul, agree with what he is saying, but we are down to only two faults ... we got these subcodes/details, they will just fall out depending on what we decide ... we have 6.4.1.1 - 6.4.1.8 subcodes instead of throwing them into a note we should step thru them and see if they are needed ... why not move the anon/non-anon faults to wsdl umit: we tell people when they are required but they are valid independent of that katy: problem action is not a fault, it is a detail bob: ah, it is part of invalid header hdr Bob's new proposal: 1) invalid Adr header; tested one detial, leave the rest of the details (internal rationalization) 2) message Adr Hdr req kept 3) move all other non-MUST faults to a note dhull: i don't want to revisit closed issues Bob's new new proposal: 1) invalid Adr header; tested one detail, leave the rest of the details (internal rationalization, induction proof) 2) message Adr Hdr req kept bob: we will close this tomorrow morning ... immediatly after which we will continue with the test report jonathan: our report is looking better, but will be better to have more vendors online bob: we also have to discuss wsa:From and source endpoint which have been ... identified as "at risk" features <Recessed for the day >
http://www.w3.org/2002/ws/addr/6/03/02-ws-addr-minutes.html
CC-MAIN-2015-40
refinedweb
5,440
62.21
Sep 18, 2007 02:16 PM|Frank Phillps|LINK Hi all. Tried to do a search on this one, but didnt know exactly how to word it so I wasn't able to find much info on what I wanted to do. Overview of what I'm trying to do. Version: asp.net 1.1 I have a crystal report that takes a long time to run and impatient users click the submit button over and over mucking up the system. I've been trying to create a "processing your request" type progress bar that will pretty much inform the user to chill out and let the report run its course. (I'm also going to disable the buttons when I get that far). I've gotten the bar to run, but for the life of me cannot call the ProcessReport() from the javascript and its driving me nuts. Javascript: function html_Submit_Progress(pThis) { if(pThis.nodeName=='INPUT') { pThis.value='...Loading...' } else { pThis.innerHTML='...Loading...' }; html_ShowElement('AjaxLoading'); // There's another function to show the element, thats not an issue, so I didnt include it // window.setTimeout('$x("AjaxLoading").innerHTML = $x("AjaxLoading").innerHTML', 100); } ???? Here's where I'm hitting the ceiling. What do I call here to run the ProcessReport() c# function in the code behind? I've tried __doPostBack and <% ProcessReport(); %> (which unfortunately runs the process as soon as it's encountered so thats not good) and neither have seemed to run it for some reason. my Form info: <form id="wwv_flow" action="wwv_flow.accept" method="post" name="wwv_flow" runat="server"> Any help would be greatly appreciated. Thanks Frank Sep 18, 2007 02:24 PM|NC01|LINK There is really no way to do that, as client-side processing and server-side processing are 2 different things. I posted this little control a while back that works asynchroneously and might help you out: Or you might take a look here for an AJAX solution: NC... Sep 19, 2007 05:27 PM|Frank Phillps|LINK Looking at the control I have one question before I try it. I think i've tried something similar to this, but not sure. When the "process report" button is clicked, a crystal report is generated and saved to the server as a PDF. Then the process redirects the user to that file which loads into an adobe acrobat reader that is displayed outside of the browser (in browser display is turned off). So I'm not sure if this will work for what I'm trying. Right now what happens is that the progress bar pops up when the button is clicked, but after the redirect I can't seem to get it to stop. What I've thought to do is create the file, store the value in a hidden field and on the post back, if that field is populated, turn off the progress bar and then do a javascript redirect. Which, I would expect, would do the same thing. Not sure how well that would work though, im not as familar with javascript, so not sure how well that would work. Frank Sep 19, 2007 06:08 PM|NC01|LINK I doubt if the control will work for that, as it works asynchroneously on a page object. While the Page object is doing the server-side processing, the control is visible. As soon as the server-side processing is completed, the control is hidden. You'd have to have to place it into the PDF doc that you are redirecting to. This might work however. Instead of redirecting to the PDF doc, redirect to this dummy page which only contains an IFrame to display the PDF doc. Call by: Response.Redirect("PdfDisplayer.aspx?PdfDoc=" + pdfDocUrl); /////////////////////////// // aspx file: /////////////////////////// <%@ Page language="c#" Codebehind="PdfDisplayer.aspx.cs" AutoEventWireup="false" Inherits="Tester.PdfDisplayer" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>PDF Displayer</title> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> <meta content="JavaScript" name="vs_defaultClientScript"> <meta content="" name="vs_targetSchema"> <base target="_self"> </HEAD> <body bottommargin="0" topmargin="0"> <form id="Form1" method="post" runat="server"> <iframe id="displayIFrame" frameborder="0" height="100%" runat="server" src="" width="100%"> </iframe> </form> </body> </HTML> /////////////////////////// // aspx.cs file: /////////////////////////// protected System.Web.UI.HtmlControls.HtmlGenericControl displayIFrame; private void Page_Load(object sender, System.EventArgs e) { string frameSource = this.Request["PdfDoc"]; this.displayIFrame.Attributes.Add("src", frameSource); } NC... Sep 19, 2007 07:30 PM|jamezw|LINK Here is an old .NET 1.1 function I wrote a while back which disables a Button after it is clicked (only if it passes client-side validation). The server-side code for the button will still run though and the button will re-enable after the postback completes. It is overloaded to allow the passing of a message which will override the message that exists on the button. Here is the function:); } Just call this function on each page load for any button you want it attached to like this: DisableButtonOnClientClick(ref this.Button1, "...Loading..."); Sep 19, 2007 07:45 PM|jamezw|LINK Normally it does. That is why I came up with this solution awhile back. It will disable the button client-side after it is clicked (ONLY if client-side validation passes) but it will still fire the server-side button event. It will remain disabled until the button's server side code completes and the page completes its post back. Sep 19, 2007 07:48 PM|jamezw|LINK I wrote a similar function in .NET 2.0 which accounts for validation groups. If someone wants it I will dig it up and post it as well. Sep 19, 2007 08:01 PM|jamezw|LINK The button is only disabled if client-side validation passes. If client-side validation passes then the button is disabled and the server-side button click event is fired. The disabled status (along with the textual change on the button's value property) will go away after the server-side code runs and the page finishes its postback. Sep 19, 2007 08:09 PM|jamezw|LINK Unfortunately I cannot provide links to my company's internal systems [:)] Sep 20, 2007 12:04 AM|NC01|LINK James, I can't see how that will work as 1. You're disabling it AFTER the server-side button event, so it is not going to take affect until AFTER the next button click. 2. What is the use of checking for client-side validation AFTER the server-side event has happened, as it would have already happened for the server-side event to fire. This will work, though I agree with Josh that disabling buttons could cause problems. private void Page_Load(object sender, System.EventArgs e) { StringBuilder javaScript = new StringBuilder(); javaScript.Append("if ( typeof(Page_ClientValidate) == 'function' )"); javaScript.Append("{ "); javaScript.Append(" if ( Page_ClientValidate() == false )"); javaScript.Append(" return false;"); javaScript.Append("} "); javaScript.Append("this.value = 'Please wait...';"); javaScript.Append("this.disabled = true;"); javaScript.Append(Page.GetPostBackEventReference(Button1, string.Empty)); javaScript.Append(";"); Button1.Attributes.Add("onclick", javaScript.ToString()); } private void Button1_Click(object sender, System.EventArgs e) { // Emulate a lengthy process... TimeSpan waitTime = new TimeSpan(0, 0, 0, 10); System.Threading.Thread.Sleep(waitTime); Response.Write("Button1_Click fired<br>"); } NC... Sep 20, 2007 01:08 PM|jamezw|LINK The button is not disabled AFTER the server-side button event. It is disabled BEFORE the server-side button event. When the button is clicked, here is the order of operation for this function: The button will remain disabled until the server-side code post back is complete. I've included a very basis .NET 1.1 example below. You can test it out easily. I put a 2.5 second sleep in the button server-side code to demonstrate the temporary disabling. You can keep or remove the RequiredFieldValidator on the page as it works with or without client-side validation.ASPX <" /> </form> </body> </HTML> using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace TestSolution { /// <summary> /// Summary description for WebForm1. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.WebControls.Button Button1; private void Page_Load(object sender, System.EventArgs e) { DisableButtonOnClientClick(ref this.Button1, "...Loading..."); }) { if (Page.IsValid) { System.Threading.Thread.Sleep(2500); } } } } Sep 20, 2007 02:06 PM|jamezw|LINK Ho hum. Here is the same example page with a custom validator on it. If custom validation fails it does not leave the button disabled. Whether the custom validation is client-side or server-side it doesn't matter. Are you even testing the code or should I just stop providing examples? <=""> <script type="text/javascript"> function doCustomValidation(sender,args) { args.IsValid = (document.getElementById('<%=TextBox1.ClientID%>').value != ''); } </script> <" /> <asp:CustomValidator </form> </body> </HTML> Sep 20, 2007 02:10 PM|JoshStodola|LINK Dude, I don't need to test the code becuase, as mentioned before, I have already been down this path! I am not talking about this CustomValidator bullcrap. I am talking about hard coding your own form onsubmit validation. Not with any .NET validators or anything like that, that is all rubbish. In several of my web apps, I have my own validation that I put on the form onsubmit that does many different things. Your code will break that, guaranteed. I can say that with confidence withotu testing. Perhaps you should test your code with that and see for yourself! I am done arguing with you about this. It is a bad idea to disable the submit button. Period. Regards... Sep 20, 2007 02:35 PM|jamezw|LINK The OP did not mention anything about any custom form OnSubmit validation, so therefore I feel the solution I provided (along with NC's which is almost exactly the same) are valid. If you can provide a code example for your custom OnSubmit validation breaking this technique that is all fine and dandy. I'd like to see it. Then maybe I could find a solution for that scenario as well. Sep 20, 2007 02:42 PM|JoshStodola|LINK Surely... untested of course... <form onsubmit="if(document.getElementById('TextBox1').value.length == 0) { alert('Awww, shucks'); return false; }"> Do that, remove your validators and your button is now disabled and the form is useless. I understand that this example is unbelievably basic and primitive, but some of my validation in my applications is ungodly long and tedious (because of form complexity). And certain choices/selections mean a whole different set of validation rules. I just looked at one of my validation functions in-production for where I work and it is 640 lines of javascript code (so you can understand why .NET validators just don't cut it for me). Nevertheless, even something as simple as above won't work with your example. Regards... Sep 20, 2007 03:02 PM|jamezw|LINK <form onsubmit="document.getElementById('Button1').disabled=true;if(document.getElementById('TextBox1').value.length == 0) { alert('Awww, shucks'); document.getElementById('Button1').disabled=false; return false; }"> The button is disabled immediately. If validation fails, the button is re-enabled along with the alert call. If validation does not fail, the button will revert back to being enabled after the post back completes because the button control does not maintain the disabled attribute which was set client-side prior to the postback. Sep 20, 2007 03:06 PM|jamezw|LINK Ok. I see what you are saying. The button code does not execute in this scenario. I think I have a solution for that as well though, let me work through it and I will post my results. Sep 20, 2007 03:21 PM|jamezw|LINK Ok. The key to this example is setting the form OnSubmit server-side at page load. Doing it this way allows you to call the GetPostBackEventReference method which will ensure that the __doPostBack javascript function gets registered to the page: private void Page_Load(object sender, System.EventArgs e) { // run this code every page load not just on first load StringBuilder onSubmit = new StringBuilder(); onSubmit .Append("document.getElementById('" + this.Button1.ClientID + "').disabled=true;") .Append("if(document.getElementById('" + this.TextBox1.ClientID + "').value.length == 0) { ") .Append("alert('Awww, shucks');") .Append("document.getElementById('" + this.Button1.ClientID + "').disabled=false;") .Append("return false; }") .Append(" else { ") .Append(GetPostBackEventReference(this.Button1) + "; return false;}"); Page.RegisterOnSubmitStatement( "customSubmit", onSubmit.ToString()); } Sep 20, 2007 04:05 PM|JoshStodola|LINK I like to keep my client-side and server-side code completely separated if at all possible, but that is just a personal preference that I can live with going against. I don't have time to test with it today, but I have bookmarked it and will return when I get some free time. I'll let you know how it goes. Something tells me that the form data isn't going to make it to the server, though. Regards... Sep 20, 2007 04:11 PM|Frank Phillps|LINK haha great googaly moogaly but there's some activity here.;) I'll see about testing this stuff out in the next day or so (issue is backburnered for a day or so while i work on some other hot plate issues, fun fun). Thanks for all the input guys, appreciate it and will let you know what I find out. 27 replies Last post Sep 20, 2007 04:11 PM by Frank Phillps
http://forums.asp.net/p/1159888/1917157.aspx?Re+Javascript+calling+c+function
CC-MAIN-2015-18
refinedweb
2,257
58.28
IRC log of css on 2011-08-24 Timestamps are in UTC. 15:56:08 [RRSAgent] RRSAgent has joined #css 15:56:08 [RRSAgent] logging to 15:56:16 [Zakim] Zakim has joined #css 15:56:26 [plinss] zakim, this will be style 15:56:26 [Zakim] ok, plinss; I see Style_CSS FP()12:00PM scheduled to start in 4 minutes 15:56:34 [plinss] rrsagent, make logs public 15:56:49 [Zakim] Style_CSS FP()12:00PM has now started 15:56:56 [Zakim] +??P0 15:57:12 [florian] Zakim, I am ??P0 15:57:12 [Zakim] +florian; got it 15:57:50 [Zakim] +plinss 15:58:45 [Zakim] +nimbu 15:59:14 [Zakim] +stearns 15:59:28 [Zakim] -plinss 16:00:03 [Zakim] +plinss 16:00:05 [Zakim] -plinss 16:00:17 [Zakim] +[Microsoft] 16:00:50 [Zakim] +hober 16:02:02 [nimbupani] paging TabAtkins 16:02:03 [Zakim] + +1.858.354.aaaa 16:02:08 [plinss] zakim, aaaa is me 16:02:08 [Zakim] +plinss; got it 16:02:38 [dsinger] dsinger has joined #css 16:02:38 [alexmog] alexmog has joined #css 16:03:24 [Zakim] +dsinger 16:03:37 [TabAtkins_] TabAtkins_ has joined #css 16:03:57 [Zakim] + +2aabb 16:04:01 [Zakim] +fantasai 16:04:04 [vhardy] vhardy has joined #css 16:04:10 [nimbupani] i can do that. 16:04:16 [sylvaing] sylvaing has joined #css 16:04:17 [nimbupani] fantasai: sez she cant take minutes 16:04:39 [nimbupani] hahhahahahaaa 16:04:42 [Zakim] +??P15 16:05:16 [Zakim] +[Microsoft.a] 16:05:35 [JohnJansen] JohnJansen has joined #css 16:05:48 [JohnJansen] zakim, microsoft has JohnJansen 16:05:48 [Zakim] +JohnJansen; got it 16:05:58 [Zakim] +TabAtkins_ 16:06:12 [Zakim] +SteveZ 16:06:22 [Zakim] -fantasai 16:06:31 [Zakim] -TabAtkins_ 16:06:52 [Zakim] +fantasai 16:07:07 [nimbupani] yes 16:07:23 [nimbupani] plinss: anyone else has anything to add to the agenda? 16:07:39 [nimbupani] plinss: bunch of publishing requests 16:07:46 [nimbupani] plinss: css3-texts and writing modes. 16:08:04 [nimbupani] SteveZ: John sent a note about writing modes 16:08:18 [nimbupani] florian: the wording is not strong enough about being an unresolved problem here and he put out an alternative wording 16:08:28 [Cathy] Cathy has joined #css 16:08:30 [nimbupani] fantasai: is that something I can fix and publish? or should I hold off? 16:08:55 [nimbupani] SteveZ; the wording was only two sentences. Cant speak for John 16:09:01 [Zakim] +alexmog 16:09:51 [nimbupani] fantasai: that is not actually possible. we can get close to itb ut there is a problem with characters like quotes, where default orientation needs to be upright if its supported. 16:09:54 [Zakim] -florian 16:10:10 [nimbupani] stevez: that is not how vertical tables work 16:10:11 [Zakim] +??P0 16:10:13 [Zakim] +TabAtkins_ 16:10:22 [TabAtkins_] Excellent, now my phone works. 16:10:28 [florian] Zakim, I am ??P0 16:10:28 [Zakim] +florian; got it 16:10:46 [nimbupani] stevez: that is separate. you cant expect a vertical table to tell you what to do for the orientation 16:10:48 [Zakim] + +2aacc 16:10:58 [arno] Zakim, I am aacc 16:10:58 [Zakim] +arno; got it 16:11:23 [nimbupani] florian: we agree there is a difficult problem here, rather than saying we "may" try we should say we "will" try. 16:11:40 [nimbupani] florian: it is not guaranteed that we will successfully find a solution. 16:12:28 [vhardy] s/itb ut/it but 16:12:37 [nimbupani] stevez: JOhn publsihed a test case that shows that there is no uniform implementation across browsers, and none of the existing unicode properties would allow you to map to the upright characters. The point being there is no simple solution and cant say what the browsers do, and cant say do what unicode does. 16:12:56 [nimbupani] stevez: there is a separate effort to define a unicode property to define implementation, but thats separate. 16:13:03 [nimbupani] fantasai: we have a very long list of exceptions. 16:13:24 [nimbupani] fantasai: in some cases intentionally so, and we do not have a good answer yet. 16:14:29 [nimbupani] plinss: are we in agreement with John's sentiment here? 16:14:35 [nimbupani] plinss: anyone opposed to that. 16:14:40 [nimbupani] plinss: i take that as a consensus 16:14:57 [nimbupani] florian: i am not sure about how to resolve the issue, but i am with him on the concern on that. 16:15:08 [nimbupani] fantasai: i would like to take a quick look at florian's issue. 16:15:24 [nimbupani] fantasai: i have a patch for that I want to check with the rest of the people here before I check that in. 16:15:25 [oyvind] oyvind has joined #css 16:15:35 [nimbupani] florian: i have not been able to look at my mail last weekend 16:15:41 [bradk] bradk has joined #css 16:15:42 [nimbupani] fantasai: i think its a good idea. 16:15:53 [szilles] szilles has joined #css 16:16:03 [nimbupani] fantasai: i linked to it from my message requesting publication. 16:16:22 [florian] 16:16:57 [nimbupani] florian: there are 2 types of values in text-combine-horizontal property. 16:17:20 [nimbupani] florian: i am suggesting we can split these into two properties. the vis effect of squeeze text in is likely to be the same across document 16:17:31 [nimbupani] florian: if you split them it would reduce repetition 16:17:37 [nimbupani] florian: I do not have a good name for that. 16:17:55 [nimbupani] florian: what do people think about the idea. 16:18:18 [nimbupani] szilles: i have not thought about it, what you are saying makes sense. I prefer in general binary switch for turning things off and on, and a different property for the variance 16:18:23 [nimbupani] florian: thats my idea as well 16:18:35 [nimbupani] plinss: do we have any suggestions on this? 16:18:39 [Zakim] +[Microsoft.aa] 16:18:40 [nimbupani] florian: so we agree to split? 16:18:47 [arronei] zakim, microsoft.aa is me 16:18:47 [Zakim] +arronei; got it 16:18:48 [nimbupani] fantasai: i put text-combine-mode in my draft 16:18:53 [nimbupani] florian: its better than what I said 16:19:04 [nimbupani] plinss: are we happy to publish with that change 16:19:09 [nimbupani] szilles: yeah, it is still a draft 16:19:44 [nimbupani] szilles: i think the principle that florian is espousing is a good princile 16:19:49 [nimbupani] s/princile/principle 16:20:05 [nimbupani] RESOLVED publish writing mode working draft with updates mentioned 16:20:38 [nimbupani] florian: I am convinced the wording we now have is a good representation of the conclusion we reached at F2F. so that is solved as far as I am concerned. 16:20:41 [plinss] s/mode/mode and css3 text/ 16:21:23 [Zakim] -fantasai 16:21:34 [nimbupani] plinss: when are we going to publish the first draft of Selectors 4. W3C decided to wait until namespaces is out. Should we wait until selectors 3 is a rec or decide to publish it now. Anyone has strong opinions on that? 16:21:53 [Zakim] +fantasai 16:21:56 [nimbupani] ???: with selectors 3 is it just held up by namespaces right now? 16:22:09 [TabAtkins_] s/???/arronei 16:22:15 [TabAtkins_] zakim, mute fantasai 16:22:15 [Zakim] fantasai should now be muted 16:22:33 [nimbupani] szilles: you get less confusion if you wait and publish selectors 4 after the 3 rec goes out 16:22:47 [nimbupani] plinss: i agree, but I am not sure if its that big of a deal 16:23:20 [nimbupani] florian: i think we said the same thing at last f2f. as long as selectors 3 went to rec quickly then we have no issue, how long as we willing to wait. 16:23:22 [TabAtkins_] zakim, unmute fantasai 16:23:22 [Zakim] fantasai should no longer be muted 16:23:39 [nimbupani] plinss: did you see note about updating drafts for epub? 16:23:50 [nimbupani] fantasai: i dont know if fonts draft needs to be published or not. 16:24:03 [nimbupani] plinss: we will discuss those two over email and get some feedback from the editors (who are not here) 16:24:09 [nimbupani] TOPIC: regions 16:24:19 [nimbupani] plinss: display-inside and content property 16:24:31 [nimbupani] plinss: where are we on this 16:24:41 [nimbupani] alexmog: we had a conversation with vhardy we havenot agreed on a resolution. 16:25:00 [TabAtkins_] Darn, I've been muted this whole time. 16:25:05 [nimbupani] alexmog: my issue is using content it has a lot of meaning and behaviour in gneerated content as it interacts iwth model of before and after. 16:25:32 [nimbupani] alexmog: the use of that kind of content, might change the meaning of the element it is in and blows away before and after and we do not mean that content property 16:25:46 [nimbupani] alexmog: display property could be one way to do that or a separate from-flow property 16:26:09 [nimbupani] alexmog: if we had a display-inside property it would say display-inside: region and something else that would say where content comes from. It may be content property 16:26:49 [nimbupani] szilles: we have talked about having a region be a multicol, which is why i am not happy about display-inside: region. I like the principle of having a separate property that turns smthing into region and hten say what properties apply to region rather than putting of content in it turning on. 16:27:06 [nimbupani] alexmog: multicol will be display-inside if display-inside existed 16:27:32 [nimbupani] szilles: why not create a diff property with region yes/no with no as default 16:28:20 [nimbupani] vhardy: we could also go with the option of alexmog which is you have a flow-from property which would be what you are asking for and also say which region u are applying content form. the only tweak from your proposal alex is that before and after work on a region 16:28:34 [nimbupani] vhardy: we would be okay using flow-from proposal as it is close to what szilles is saying 16:28:57 [nimbupani] szilles: yes and no. it is using to say where text comes from to turn it into a region and I was trying to separate those two, but I am not strongly of any position. I can live with either 16:29:33 [nimbupani] alexmog: similar to float: positioned which we used to trigger exclusions and appears redundant as you also have to use wrap-type everytime you use that property. 16:29:46 [nimbupani] alexmog: so we ended up adopting adobe's solution, and here we use the same 16:29:53 [nimbupani] szilles: it is a valid point, and i can live either way 16:30:36 [nimbupani] fantasai: i think having two properties seems like too many levels of interaction. 16:30:52 [nimbupani] vhardy: i propose we try to resolve on flow-from and having before and after work with current pseudo selectors 16:31:05 [nimbupani] TabAtkins: what happens when you do flow-from form elements that is also a grid or flexbox 16:31:20 [nimbupani] vhardy: we have a resolution that sez you can only turn smthing into a region if it is a block container box 16:31:32 [nimbupani] TabAtkins: the point i wanted display-inside was to prevent unwanted interactions. 16:31:44 [nimbupani] TabAtkins: it is similar to what columns do. 16:32:08 [nimbupani] fantasai: still concerned about the interaction but have nothing concrete to say 16:32:23 [nimbupani] fantasai: interaction with display, and the content property as we are overriding with a different property 16:32:30 [nimbupani] alexmog: flow-from has a very diff meaning from content 16:32:38 [nimbupani] alexmog: content overrides WITHIN the element. 16:32:42 [bradk] What if we had content:flow-from() take the children of the named element, instead of the item itself? 16:32:46 [nimbupani] alexmog: flow-from overrides everything. 16:33:03 [nimbupani] alexmog: that is inside this element. it does not change the meaning of content. it just replaces everything within. 16:33:26 [nimbupani] fantasai: content property was intended to control what the contents are, and now we have another property that does essentially the same thing. 16:33:51 [nimbupani] fantasai: the most obvious thing that is changing is the contents of the element are not being displayed in favour of something else. 16:33:57 [nimbupani] fantasai: seems like a problem to me. 16:34:04 [nimbupani] vhardy: i think it is slightly different 16:34:12 [nimbupani] vhardy: u specify what content goes into the element 16:34:22 [nimbupani] vhardy: pull the content and this will be figured out atlyout. 16:34:37 [nimbupani] alexmog: what content property does is replaces the content of the element 16:34:49 [nimbupani] alexmog: flow-from does is what the box is showing 16:34:54 [TabAtkins_] zakim, mute fantasai 16:34:54 [Zakim] fantasai should now be muted 16:35:03 [TabAtkins_] zakim, unmute fantasai 16:35:03 [Zakim] fantasai should no longer be muted 16:35:09 [hober] Zakim, who is making noise? 16:35:10 [nimbupani] plinss: i had a proposal in kyoto we use flow-from property and then use content property 16:35:20 [Zakim] hober, listening for 10 seconds I heard sound from the following: nimbu (100%), plinss (9%), fantasai (24%), TabAtkins_ (14%) 16:35:24 [TabAtkins_] zakim, mute nimbu 16:35:24 [Zakim] nimbu should now be muted 16:36:11 [nimbupani] plinss: maybe we need another keyword to access actual content of the element rather than the flow content 16:36:29 [nimbupani] fantasai: the initial value of content property is normal, so normal computes to diff things depending on what the lement is 16:36:38 [bradk] content:flow-from() could replaces the content of the element with the contents of the flow. 16:36:44 [nimbupani] fantasai: it computes to list marker on a list marker, etc 16:37:02 [nimbupani] plinss: normal could compute to flow-from on elements that have a flow-from 16:37:17 [nimbupani] vhardy: i am not sure i understand what this means 16:37:36 [nimbupani] szilles: the normal behaviour of content is if you say flow-from it sez use it. 16:37:56 [nimbupani] plinss: if you say flow-from and content, content wins so you have a keyword within content. 16:38:01 [nimbupani] vhardy: i think flow-from should win 16:38:09 [nimbupani] s/vhardy/alexmog 16:38:44 [nimbupani] fantasai: i dont want to hold off progress on resolving other issues. i dont want to consider this resolved, but I amf ine with picking a solution and working with it. 16:38:51 [nimbupani] vhardy: what is the solution we are going for? 16:39:18 [nimbupani] alexmog: i completely disagree with that 16:39:36 [nimbupani] szilles: if you want to be able to use ::before and ::after you want to fit it into the model 16:39:43 [nimbupani] alexmog: before and after does not feed into region flow 16:39:54 [nimbupani] szilles: vhardy said he would like to feed into the regions model 16:40:11 [nimbupani] alexmog: i dont know what it would mean to have content before that is float right and ahve that merge with multicol flow 16:40:26 [nimbupani] vhardy: the feedback I got was that we should specify the behavior of before and after when element is a region 16:40:27 [Zakim] + +1.650.766.aadd 16:40:41 [nimbupani] alexmog: for before and after that would be special meaning do something different when they apply to a region 16:40:50 [nimbupani] szilles: it isnt completely different which is why people suggest we use it 16:41:25 [nimbupani] vhardy: can we go with doing a new iteration on ED using flow-from and trying to resolve what we can do with before/after 16:41:59 [nimbupani] vhardy: plinss you talked about using another keyword to define actual content. the proposal in kyoto, there is a separate proposal on adding a 'contents' keyword so you can combine the content that is already there. 16:42:07 [nimbupani] oops 16:42:15 [nimbupani] vhardy: plinss you talked about using another keyword to define actual content. 16:42:22 [nimbupani] plinss: the proposal in kyoto, there is a separate proposal on adding a 'contents' keyword so you can combine the content that is already there. 16:42:38 [nimbupani] plinss: i dont know if we need that, that was a separate proposal 16:42:43 [nimbupani] vhardy: for now we can live without that. 16:43:10 [nimbupani] szilles: i think it would be useful to put the issue under flow from that we need to clarify the interaction between the fow from and the contents property. 16:43:18 [nimbupani] vhardy: i was proposing to say smthing in the draft 16:43:36 [dsinger] dsinger has joined #css 16:43:49 [nimbupani] vhardy: we iterate on the draft and have a new ED proposed for the next F2F, and we can have an issue on the review of the new WD. 16:43:57 [Zakim] +[Apple] 16:44:05 [Zakim] -dsinger 16:44:07 [nimbupani] alexmog: lets keep it an issue. 16:44:19 [nimbupani] TabAtkins: how do I create an issue >_> 16:44:49 [nimbupani] vhardy: following the resolution about breaks to be container specific or region specific as decided on Seattle, I aligned it with multicol. 16:45:07 [nimbupani] vhardy: issues i raised on seattle meeting are not region specific they affect multicol pagination as one thing 16:45:27 [nimbupani] vhardy: how do breaks work in nested regions, multicol and when u start combining different kinds of break. it spans regions multicol and pagination 16:45:47 [nimbupani] vhardy: i dont think this is the right place to handle in the regions spec. what do we do about it? do we have a separate spec for breaks? 16:46:21 [nimbupani] alexmog: sorry I forgot how to add an issue >_> 16:46:31 [nimbupani] RESOLVED: use flow-from property to enable regions 16:47:41 [nimbupani] alexmog: my biggest concern with region break was that while behavior of page-break is undefined we would be creating a separate syntax for smthing that means something exactly same as page break or has same effect in same media 16:47:49 [nimbupani] plinss: we redefined breaking property in multicol 16:47:55 [nimbupani] vhardy: we already resolved to have a region break 16:48:12 [nimbupani] florian: when we want diff kind of break for diff kind of thing and we need to think about carefully. 16:48:28 [nimbupani] fantasai: we need a css3 pagination module? 16:48:33 [nimbupani] vhardy: maybe. 16:48:43 [nimbupani] alexmog: yeah that would be great to have one. we can ask for volunteers to write it. 16:48:51 [nimbupani] fantasai: there is some interaction with paged meda spec. 16:49:24 [nimbupani] fantasai: we might want to sync paged media spec to css 2.1 and push that out and ahve css3 pagination and then add whatever we need to add 16:49:39 [nimbupani] fantasai: the multicol spec defines aliases it was kinda expecting paged media to do that definition 16:49:46 [nimbupani] fantasai: maybe we can pull that into a separate module 16:49:55 [nimbupani] vhardy: sgtm 16:50:08 [nimbupani] plinss: who is going to work on the pagination module 16:50:16 [nimbupani] fantasai: i probably should do that 16:50:27 [nimbupani] fantasai: i hope its okay if you dont start until sept or oct 16:50:37 [nimbupani] fantasai: will be working more on pagination stuff this fall in either case. 16:50:54 [nimbupani] alexmog: MS and Adobe are most motivated people so maybe we and you should talk about it and figure out who should write the spec 16:50:56 [nimbupani] vhardy: yeah 16:51:19 [nimbupani] fantasai: i can rip out various pieces we need and create a framework 16:51:52 [nimbupani] whats the resolution? 16:53:12 [nimbupani] RESOLVED: CSS Regions has a region break like multicol and start on css3 pagination module and adobe and ms would sort out the editorship of that spec 16:53:26 [vhardy] 16:53:38 [nimbupani] TOPIC: Conformance markup within the spec 16:53:44 [nimbupani] TabAtkins: can we talk about print backgrounds 16:53:53 [nimbupani] fantasai: can we talk about css 2. test suites 16:53:56 [nimbupani] plinss: whats the issue? 16:54:15 [nimbupani] fantasai: apparently ?? filed a bunch of issues but has not received a response about getting them fixed 16:54:29 [plinss] s/??/Gerard Talbot/ 16:54:29 [nimbupani] fantasai: is ms planning to maintain those tests or find a new owner 16:54:44 [nimbupani] arronei: i can make changes whenever we feel its right 16:54:52 [nimbupani] plinss: no reason not to make updates. 16:54:57 [nimbupani] arronei: i can start working on it then 16:55:20 [nimbupani] plinss: TabAtkins is saying if we can get a resolution in printing bg last week 16:55:28 [nimbupani] TabAtkins: wiki page did not facilitate new discussion 16:55:47 [nimbupani] TabAtkins: 1. do nothing 2. add a hint that lets author provide extra info so UA can make a better choice 16:56:18 [nimbupani] florian: 1 and then come up with a UI that lets user switch based. 16:56:29 [nimbupani] TabAtkins: are u asking me to come up with a new browser UI for all browsers 16:56:58 [nimbupani] florian: seems like browsers have not made effort on print yet. Option1 is not silly and use ?? as heuristics it is not that silly 16:57:28 [nimbupani] plinss: there is no way we can get reasonable heuristics. there are print scenarios that do not have a direct user interaction 16:57:40 [nimbupani] ??? I like whats in 3 16:57:56 [Zakim] -arno 16:57:58 [nimbupani] alexmog: using !important 16:58:06 [bradk] bradk has joined #css 16:58:12 [nimbupani] TabAtkins: !important is already doing wrong things and it is not just bgs. 16:58:42 [nimbupani] alexmog: printing bgs is unique situation where browser refuses to display smthing that was specified. it is a special feature 16:58:47 [vhardy] vhardy: need to drop out. 16:58:55 [Zakim] - +2aabb 16:59:01 [Zakim] - +1.650.766.aadd 16:59:11 [nimbupani] alexmog: there is no other issue like that. we can create !print 16:59:15 [Zakim] + +1.650.766.aaee 16:59:33 [nimbupani] fantasai: we should ahve the principle that if someone has done the right thing, they should do one simple thing and it should just work 16:59:42 [nimbupani] fantasai: they should not reqrite stylesheet 17:00:16 [nimbupani] s/reqrite/rewrite 17:00:27 [nimbupani] fantasai: !important does not fit that bill 17:00:34 [nimbupani] alexmog: what is ur preferred answer TabAtkins 17:00:46 [nimbupani] florian: are we aligning with prop 7 17:00:49 [florian] 17:01:03 [nimbupani] plinss: print media stylesheet is not sufficient 17:01:06 [florian] I was just asking elika's position, not everybody's 17:01:26 [nimbupani] TabAtkins: 2 to 6 are unusable 17:01:30 [nimbupani] TabAtkins: i am for option 7 17:01:46 [nimbupani] alexmog: is this for document or elements 17:01:48 [nimbupani] TabAtkins: either way 17:01:56 [nimbupani] TabAtkins: putting on doc is 7.1 17:02:03 [nimbupani] TabAtkins: individual pages is 7.2 17:02:09 [nimbupani] TabAtkins: any of them works. 17:02:13 [nimbupani] alexmog: it could be a meta tag 17:02:14 [Zakim] -[Microsoft] 17:02:34 [nimbupani] ??? print or anything like that sez we know better than you. the user needs to decide. 17:02:40 [nimbupani] s/????/arronei 17:03:26 [nimbupani] arronei: as vendors we decided not to print bgs by default. if we decide to print bgs by default, we need to engage the community and teach authors that they need to author good stylesheets for print 17:03:37 [nimbupani] TabAtkins: we will not be changing browsers to print bgs by default 17:03:56 [nimbupani] arronei: now you need to provide a notification that you will be printing insane amount of stuff on these pages. 17:04:27 [nimbupani] ??? we need people to write good stylesheet 17:04:40 [nimbupani] alexmog: if we add an option to print bg we will never need user override with that. 17:04:45 [dsinger] printed backgrounds sometimes make the print unreadable 17:05:02 [nimbupani] alexmog: browser it is okay to print what the author has done that. the lack of the property means this is the old page and use it the old way. 17:05:17 [dsinger] making users miserable with the default is no way to educate site authors to make better stylesheets 17:05:28 [nimbupani] fantasai: an interesting heuristic to check would be if canvas has a bg that is not white then probably the page is not designed to print with ink 17:05:31 [Zakim] -[Microsoft.a] 17:06:00 [nimbupani] plinss: i dont think the simple heuristic is good enough. 17:06:07 [oyvind] I'm sure plenty of pages have white/transparent html/body and put everything in some div 17:06:22 [nimbupani] TabAtkins: i have designed pages with no canvas bgs and elements that span the canvas having bg 17:06:31 [nimbupani] dsinger: bg by default would make usesrs miserable 17:06:42 [szilles] I support Alex's point: that adding a flag, probably on the document, that says honor the style, would allow migration to using suitable 'print' stylesheets 17:06:49 [nimbupani] TabAtkins: are we going to make a decision or are we going to continue be undefined 17:07:01 [nimbupani] TabAtkins: we are unable to make any decision on this whatsoever 17:07:11 [nimbupani] alexmog: we are closer to a decision 17:07:30 [nimbupani] TabAtkins: dont do it at all or do it with a property, there is no useful conversation out of this. I am not sure how to proceed. 17:07:42 [nimbupani] TabAtkins: i am not seeing any progress towards a conclusion 17:07:59 [nimbupani] alexmog: u have proposal on the wiki 17:08:12 [nimbupani] alexmog: we can have things that are not in css but apply to whole doc 17:08:30 [nimbupani] TabAtkins: if we decide there is a mechanism for this, that would be sufficient for my needs. 17:08:47 [nimbupani] TabAtkins: can we assume 7 covers all variations on this idea? 17:09:05 [nimbupani] plinss: i propose we elect to do something 17:09:20 [nimbupani] plinss: i think we shold move forward anyway. 17:09:37 [nimbupani] plinss: tab should work on a concrete proposal get some implementation experience if folks hate it we can revisit 17:09:38 [szilles] +1 for Peter's proposal 17:09:43 [nimbupani] TabAtkins: cool for me 17:09:57 [nimbupani] RESOLVED: TabAtkins to create a proposal for print bgs 17:10:01 [Zakim] - +1.650.766.aaee 17:10:02 [Zakim] -fantasai 17:10:07 [Zakim] -[Apple] 17:10:08 [Zakim] -TabAtkins_ 17:10:09 [Zakim] -arronei 17:10:10 [Zakim] -SteveZ 17:10:11 [Zakim] -plinss 17:10:11 [Zakim] -nimbu 17:10:11 [Zakim] -hober 17:10:13 [Zakim] -stearns 17:10:13 [Zakim] -florian 17:10:16 [Zakim] -alexmog 17:10:18 [Zakim] -??P15 17:10:19 [Zakim] Style_CSS FP()12:00PM has ended 17:10:22 [Zakim] Attendees were florian, plinss, nimbu, stearns, hober, +1.858.354.aaaa, dsinger, +2aabb, fantasai, JohnJansen, TabAtkins_, SteveZ, alexmog, +2aacc, arno, [Microsoft], arronei, 17:10:24 [Zakim] ... +1.650.766.aadd, +1.650.766.aaee 17:51:03 [szilles] szilles has joined #css 18:21:29 [stearns] stearns has joined #css 18:46:46 [karl] karl has joined #CSS 18:57:12 [Zakim] Zakim has left #css 19:54:40 [szilles] szilles has joined #css 20:20:20 [tantek] tantek has joined #css 20:38:21 [Ms2ger] Ms2ger has joined #css 21:39:22 [szilles] szilles has joined #css 22:00:58 [szilles] szilles has joined #css 22:51:00 [nimbupani] nimbupani has joined #css 22:57:35 [homata] homata has joined #CSS 22:58:35 [homata_] homata_ has joined #CSS 23:04:12 [karl] karl has joined #CSS 23:21:50 [arronei_] arronei_ has joined #css
http://www.w3.org/2011/08/24-css-irc
CC-MAIN-2017-26
refinedweb
4,893
52.63
WCF is one of the best programming models supplied by Microsoft for building more secure, reliable, interoperable system for building, configuring and deploying network-distributed services. WCF being a unified programming model that has features of a Web Service, features of Remoting, and MSMQ and others. In this first article we will discuss Step by step on how we to create a simple WCF service. 1. Start visual studio and select a WCF service application template, Name the project as WcfService1, choose a location to save this project. 2. Remove all the predefined generated code from IService1 file and type as shown in the figure to create a Greeting method. 3. Now open the Service1.svc.cs file and implement the interface method. 4. Check the web.config file for the changes, comments are seft explanatory. 5.Build and run the service. 6. The WCF Service is ready and now we need to create a client application to test our service.7. Add a new console application project to the solution name it as SampleClient 8. Now right click on the references and click on ServiceReference, Specify the address to locate the service and Set the namespace Click Ok. 9. Create an object of the proxy client class and call the Greeting method as shown. 10. Check the app.config file for configuration changes 11. Build and execute the application You all saw how simple it is to create a simple WCF and test it using a console client application. In my next article I will explain you how to test the WCF service without creating any client application. Untill then Happy Coding... Latest Articles Latest Articles from Madhu.b.rokkam Login to post response
https://www.dotnetfunda.com/articles/show/1173/step-by-step-process-to-develop-a-simple-wcf-service
CC-MAIN-2021-04
refinedweb
285
66.64
: stack-overflow I have a JavaScript commandline program that needs more stack space. The option for this is node –stack-size but it’s not working for me. Test case: ‘use strict’ function f(…a) { console.log(a[0] + a[a.length – 1]) } var a = [] for (var i = 0; i < 1000000; i++) { a.push(i) } f(…a) Run .. I got a stack overflow exception in visual studio inside a coroutine in a loop and found that the loop had a bug that prevented it from termination but I wondered why the stack was overflowed ? the coroutine might not even was using the stack but the heap instead and even if the stack .. Take as input str, a string. Assume that value of a=1, b=2, c=3, d=4, …. z=26.Print all possible codes for the string. E.g. for “1123” possible codes are aabc, kbc, alc, aaw, kw. I tried to implement this ….. Here is my code…. #include<bits/stdc++.h> using namespace std; void helper(string str,int idx,string ans){ if(idx==str.length()){ cout<<ans<<","; return; .. Why is it that my first and second programs are running fine but the third one is giving segmentation fault? I don’t think the problem is with memory limit because even long long dp[40][100000] is running fine but if I try printing any value say std::cout << dp[0][0]; again it’s giving error. I am really .. As far as I know, something such as static int number = 5; will get initialised once, and then able to be modified later. To keep its value, the memory can’t then be free’d or it will have to initialise itself again, which would defeat the purpose of static anyway. Something such as this here .. I am coding an Inversed pyramid console application, when you enter a number, For example 3, It’ll output it with the number of staircase, ***** *** * It works and everything is fine but when it outputs the pyramid. It keeps spamming spaces till the program crashes. Here’s the source code: Note: This is a .. This is my code. When I run a programm it gives a stack overflow exception after "void tret(int* mas, int size, int left, int right){".I can’t get why and i’ve tried everything. What might be the reason? #include <iostream> #include <ctime> #define _CRT_SECURE_NO_WORNING using namespace std; void tret(int* mas, int size, int left, int right) .. I work in CentOs8 with g++ #include <stdio.h> int main() { int a[3]; for(int i=4;i<100000;i++){ printf("a[%d]=%dn", i, a[i]); a[i] = 0; } return 0; } then 1864 will be the first I value which will cause crash. I known stack-overflow will cause undefined behavior. I just want to know the memory structure of this process. .. Well, this is the problem: i was trying to compile my altoin in ARM and i get stack smashing error: . Aborted. then, i try to compile exactly the same code but with SSE2 flags in my other linux computer, and it success. if i disable stack protection on the makefile im able to compile. .. Recent Comments
https://windowsquestions.com/category/stack-overflow/
CC-MAIN-2021-21
refinedweb
533
83.46
Following on from my previous post where I introduced unit testing Angular Components, this post will give a quick overview on practices I employ to unit test my services. In this post we will cover: - Setting up a Service Test 💪 - Testing methods in the Service 🛠 - Mockng dependencies with Jasmine Spys 🔎 We will write some basic logic to handle a customer placing an order to illustrate the testing of the services involved. Let's Get Started 🔥 Before we get into the fun part, we need to scaffold up a new Angular Project so that we can write and run our tests. Open your favourite Terminal or Shell at a new directory. If you haven't already, I'd recommend installing the Angular CLI globally, it will be used frequently in this article: npm install -g @angular/cli Now that we are in an empty directory, the first thing we'll want to do is set up an Angular project: ng new test-demo When it asks if you'd like to setup Angular Routing, type N, and when it asks which stylesheet format you would like to use, select any, it won't matter for this post. Once the command has completed, you will need to navigate into the new project directory: cd test-demo We now have our basic app scaffold provided for us by Angular. Now we are going to want to set up some of the code that we'll be testing. At this point, it's time to open your favourite Text Editor or IDE (I highly recommend VS Code). Inside the src/app directory, create a new directory and name it models. We will create three files in here: user.ts export interface User { id: string; name: string; } product.ts export interface Product { id: string; name: string; cost: number; } order.ts import { User } from './user'; import { Product } from './product'; export interface Order { id: string; user: User; product: Product; } Once this is complete, we will use the Angular ClI to scaffold out two services: ng g service services/user and ng g service services/order These services will contain the logic that we will be testing. The Angular CLI will create these two files for us as well as some boilerplate testing code for each of the services. 💪 If we open order.service.spec.ts as an example we will see the following: import { TestBed } from '@angular/core/testing'; import { OrderService } from './order.service'; describe('OrderService', () => { let service: OrderService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(OrderService); }); it('should be created', () => { expect(service).toBeTruthy(); }); }); Let's break that down a litte 🔨: describe('OrderService', () => { ... }) sets up the Test Suite for the Order Service. let service: OrderService declares a Test Suite-scoped variable where we will store a reference to our Service. beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(OrderService); }); This tells the test runner (Karma) to run this code before every test in the Test Suite. It is using Angular's TestBed to create the testing environment and finally it is injecting the OrderService and placing a reference to it in the service variable defined earlier. Note: if using Angular < v9 you may notice TestBed.get(OrderService) rather than TestBed.inject(OrderService). They are essentially doing the same thing. it('should be created', () => { expect(service).toBeTruthy(); }); the it() function creates a new test with the title should be created. This test is expecting the service varibale to truthy, in otherwords, it should have been instantiated correctly by the Angular TestBed. I like to think of this as the sanity check to ensure we have set up our Service correctly. Service Logic Time 💡 Now that we have a basic understanding of what our Service Test file looks like, lets create some quick logic in our user.service.ts and order.service.ts file for us to test. In user.service.ts let's place the following code, which will store the active user in our app: import { Injectable } from '@angular/core'; import { User } from '../models/user'; @Injectable({ providedIn: 'root' }) export class UserService { // Store the active user state private activeUser: User; constructor() {} getActiveUser() { // We'll return the active user or undefined if no active user // The cast to Readonly<User> here is used to maintain immutability // in our stored state return this.activeUser as Readonly<User>; } setActiveUser(user: User) { this.activeUser = user; } } And in order.service.ts let's create simple method to create an order: import { Injectable } from '@angular/core'; import { Order } from './../models/order'; import { Product } from '../models/product'; import { UserService } from './user.service'; @Injectable({ providedIn: 'root' }) export class OrderService { constructor(private readonly userService: UserService) {} createOrder(product: Product): Order { return { id: Date.now().toString(), user: this.userService.getActiveUser(), product }; } } Awesome! We now have a nice little piece of logic that we can write some unit tests for. Testing Time 🚀 Now for the fun part 💪 Let's get writing these unit tests. We'll start with UserService as it is a more straightforward class with no dependencies. Open user.service.spec.ts and below the first test, we'll create a new test: it('should set the active user correctly', () => { // Arrange const user: User = { id: 'test', name: 'test' }; // Act service.setActiveUser(user); // Assert expect(service['activeUser'].id).toEqual('test'); expect(service['activeUser'].name).toEqual('test'); }); In this test, we are testing that the user is set active correctly. So we do three things: - Create a test user - Call the setActiveUsermethod with our test user - Assert that the private activeUserproperty has been set with our test user. Note: It is generally bad practice to access properties via string literals, however, in this testing scenario, we want to ensure correctness. We could have called the getActiveUser method instead of accessing the private property directly, however, we can't say for certain if getActiveUser works correctly at this point. Next we want to test that our getActiveUser() method is working as expected, so let's write a new test: it('should get the active user correctly', () => { // Arrange service['activeUser'] = { id: 'test', name: 'test' }; // Act const user = service.getActiveUser(); // Assert expect(user.id).toEqual('test'); expect(user.name).toEqual('test'); }); Again, we're doing three things here: - Setting the current active user on the service - Calling the getActiveUsermethod and storing the result in a uservariable - Asserting that the userreturned is the active user we originally arranged These tests are pretty straightforward, and if we run ng test now we should see Karma reporting TOTAL: 7 SUCCESS Awesome!! 🔥🔥 Testing with Mocks Let's move onto a more complex test which involves having to mock out a dependency. The first thing we are going to want to do is to mock out the call to the UserService. We are only testing that OrderService works correctly, and therefore, we don't want any ill-formed code in UserService to break our tests in OrderService. To do this, just below the let service: OrderService; line, add the following: const userServiceSpy = jasmine.createSpyObj<UserService>('UserService', ['getActiveUser']); And then inside the beforeEach we want to change our TestBed.configureTestingModule to match the following: TestBed.configureTestingModule({ providers: [ { provide: UserService, useValue: userServiceSpy } ] }); Let me explain what's going on here. Jasmine creates an object identical to the UserService object, and the we override the Service being injected into the Testing Module with the spy object Jasmine created. (This is a technique centered around the Dependency Inversion principle). Now we are able to change what is returned when our code calls userService.getActiveUser() to allow us to perform multiple test cases. We will see that in action now when we write our test for the OrderService: it('should create an order correctly', () => { // Arrange const product: Product = { id: 'product', name: 'product', cost: 100 }; userServiceSpy.getActiveUser.and.returnValue({ id: 'test', name: 'test' }); // Act const order = service.createOrder(product); // Assert expect(order.product.id).toEqual('product'); expect(order.user.id).toEqual('test'); expect(userServiceSpy.getActiveUser).toHaveBeenCalled(); }); We are doing 5 things in this test: - Creating the product that the user will order - Mocking out the response to the getActiveUsercall to allow us to set up a test user - Calling the createOrdermethod with our test product - Asserting that the order was indeed created correctly - Asserting that the getActiveUsermethod on UserServicewas called And now, if we run ng test again, we will see 8 tests passing! With just these few techniques, you can go on to write some pretty solid unit tests for your services! 🤓 Your team, and your future self, will thank you for well tested services! This is a short brief non-comprehensive introduction into Unit Testing Services with Angular with Jasmine and Karma. If you have any questions, feel free to ask below or reach out to me on Twitter: @FerryColum. Discussion (1) Hey, this article really helped me a lot for testing services. I would LOVE to see unit testing for ReactiveForms ! Thank you Colum Ferry
https://dev.to/coly010/unit-testing-angular-services-1anm
CC-MAIN-2022-05
refinedweb
1,471
54.73
Normalised logarithmic curve with variable steepness.Download UDO File This opcode implements a formula for generating a normalised logarithmic curve in range 0 - 1. It is based on the Max / MSP work of Eric Singer (c) 1994. kout LogCurve kfloat, ksteepness kfloat -- A normalised floating point value in range 0 - 1. ksteepness -- Steepness index of the resulting curve. This should be > 1. There exists a safeguard in the opcode to help minimize errors related to Not-a-Number (NaN) as a result of having a steepness index of <= 1. opcode LogCurve, k, kk kfloat, ksteep xin if (ksteep > 1) then ksteep = ksteep elseif (ksteep < 1) then ksteep = 1.00001 endif kout = (log(kfloat * (ksteep-1)+1)/log(ksteep)) xout kout endop sr = 44100 kr = 441 ksmps = 100 nchnls = 2 OSCinit 4201 #include "LogCurve.udo" instr 1 kf1 init 0 kf2 init 0 kk OSClisten "/logcurve/params", "ff", kf1, kf2 if kk =0 goto ex kout LogCurve kf1, kf2 printk2 kout ex: endin David Akbari - 2005
http://www.csounds.com/udo/displayOpcode.php?opcode_id=61
CC-MAIN-2016-40
refinedweb
165
72.76
further clarification needed - Java Beginners further clarification needed Dear Experts, I refer to the last answer you have written to me. The good news is that there's no error already but the code is still not working for me. As Tsuch, I hope to clarify about Quick Hibernate Annotation Tutorial information in Hibernate. The Java 5 (Tiger) version has introduced a powerful way.... Annotation is the java class which is read through reflection mechanism during... Table mapping. All the metadata is clubbed into the POJO java file along The quick overview of JSF Technology ; The quick Overview of JSF Technology This section gives you an overview of Java Server Faces technology, which simplifies the development of Java Based web applications. In this JSF How to Write a Calculator Program in Java? How to Write a Calculator Program in Java? In this Java Tutorial you will learn how to write a Calculator program in Java in easy steps. Calculator program in Java is often used by the developers for calculations like addition Quick introduction to web services Quick introduction to web services Introduction: Web services... talk to java web services and vice versa. So, Web services are Illegal State Exception Java Illegal State Exception The java. lang package include several classes and exceptional..., that is used further in exception handling. There are list of classes java Techniques: Insertion Sort Bubble Sort Quick Sort For more information, visit the following link: Java Books Of Java - Java Beginners Books Of Java Which Books Are Available for Short / Quick Learning Java Exercises for Beginners for the beginners of Java tutorials. The tutorial highlights the facts, which will enable you in terms of Java article and exercises. The exercises will provide you the basic opportunity and chance to understand the facts of Java syntax Struts Built-In Actions ; In this section we will give a quick look to the few of built-in utility...; provides mechanism to set a user's locale and further forwarding... class, in order to simplify the application design .Java map Free Java Training Free Java training is provided online by Roseindia for all the non-programmers and programmers so that they can learn the Java programming language... the fundamentals of the language and then proceeds further. The positive point for loop in java example .style1 { color: #0000FF; } for loop in java example We are going to discuss about for loop in java example. The for loop statement has type... the condition, if true than it will execute further. If it is false java Net Salary for the employee. Further on, you will need to build leave What is Java and its history? What is Java, it’s history? Java is a high-level object-oriented... it Oak. But later due to some patent conflicts, it was renamed as Java The Java Applet Viewer The Java Applet Viewer Applet viewer is a command line program to run Java applets.... Before going any further, lets see what an applet is? An applet is a special Java get Node Value Java get Node Value In this section, you will learn how to obtain the node value. Before any further processing, you need a XML file. For this we have create. Tomcat Quick Start Guide jMATLAB language for quick programming. It also provides ability to write toolboxes using java based plug-ins. Interface to GNUPLOT provides access to powerful plotting capabilities. Above all, the extendable java architecture allows a power java programming - Java Beginners java programming hi!!! we have been allocated a project "remote admin"? but we dont knw how to proceed further?? what should we do first? plz help me out? r there any user manuals to help us out, from this conditions Introduction to Java Technology are thing in which Java Programming Language will help you much: Quick...Introduction to Java Technologies and what it can do? In this first tutorial I will introduce you about the Java Technologies and teach you how it can java - Java Magazine other static methods and static variables defined in the class. For further more...:// I hope that this will work ( Interface in JAVA - Java Interview Questions the flaw available in the Java that it does not support Multiple Inheritance. To sort out this flaw java has provided Interface which supports the Multiple... in a class. Please visit the link for further more detailed information Free JSP Books you full access to servlet and Java technology for the dynamic part, rather... simple Java code into the servlet that results from the JSP page... requirements, you can wrap up Java code inside beans or define your own JSP tags want to get job on java - Java Beginners :// to get job on java want to get job on java what should be prepared. To know java quickly. Just click the following links:http Writing Quick Articles Using Information in Public Domain Writing Quick Articles Using Information in Public Domain Books, articles as well as other materials available in the public domain help in providing finished works which Java programming 1 - Java Beginners Java programming 1 Thx sir for reply me ^^ err how bout if using scanner class or further method to solve that code? instead of using array?  ...:// java - Java Beginners Nested class in Java What is a nested class in Java? Hi... class.Please let me know for further help.Hope it will help u.public class DataStructure... Popular Java FrameWork Popular Java FrameWork I am interested to learn any of the java framework in depth . Which could be the apt one so it can help me further in my carrier Java knowledge Java knowledge Hi, I am having 2yr IT experience in java. I know core java ana JSP, Serlets only. Further what shuld I need to know to get good growth in my career ? Please help Your base should be strong. You should Java Exception Class Hierarchy Diagram of java.lang.Throwable which further extends the java.lang.Object class java - JDBC as a Boolean class instance. All of the primitive wrapper classes in Java... further. Wrapper Classes are used broadly with Collection classes... to : Thanks java basics java basics What are wrapper classes? When we need... as a Boolean class instance. All of the primitive wrapper classes in Java... further. Wrapper Classes are used broadly with Collection classes java - Java Interview Questions java All the wrapper classes (Integer, Boolean, Float, Short, Long... be represented as a Boolean class instance. All of the primitive wrapper classes in Java... be changed further. Wrapper Classes are used broadly with Collection classes thread - Java Beginners java thread PROJECT WORK: Create a application using thread to implement the application. The application should consist of the following classes... of the customer. further create a setter method named setBalance() to set the balance Java - Java Interview Questions without any coding. In Swing, it requires page and pages of bubblegum. Further you.... ----------------------------------------------------- Read for more information. java java diff bt core java and java PHP Getting Started With PHP Tutorial PHP Getting Started Learn the basics of PHP with this quick and simple tutorial. Designed...: For further queries on basis of PHP, please visit our website: http java - Java Beginners in Java. PROGRAM TO IMPLEMENT LINKED LIST Implementation File... insert data herafter before further deletion."); } else { node... is empty so insert data herafter before further deletion."); } else java multidimensional array - Java Beginners java multidimensional array i have two arrays which will take numbers and no. of rows and columns fron method getArr() ifter that i want to ensure...) further code should be executed. code is: int a[][] = getArr(); int b java java what is java java - Java Beginners operation, requiring some thought since there might be other names further down... the list. Technicalities 1. Use Java 1.4 An Assertion status in java......... An Assertion status in java......... What is an Assertion status in java?...........can u plz explain in detail with e:g. MoreOver, to that i have encountered with different _AssertionStatus() method in ClassLoader in java iPhone 3G FAQ no further. We offer simple, straightforward answers to all the iPhone questions... and quick Safari web browser. In how many colours is the iPhone available how to create pdf file using java and itextjar how to create pdf file using java and itextjar How to create pdf file having paragraphs and alignments done using java and itextjar 5.10 version.? hope i get quick response hi roseindia - Java Beginners hi roseindia what is java? Java is a platform independent.... Object Oriented Programming structre(OOPS) concepts are followed in JAVA as similar to C++. But JAVA has additional feature of Database connectivity, Applets Java Exception - Handle Exceptions in Java Java Exception - Handle Exceptions in Java What is Exception in Java? How to handle the Exceptions in Java programming language. This section on
http://roseindia.net/tutorialhelp/comment/92874
CC-MAIN-2014-42
refinedweb
1,471
57.77
Create a 3D Domain consisting of eight rotated Blocks. More... #include <RotatedBricks.hpp> Create a 3D Domain consisting of eight rotated Blocks. The orientations of the blocks are described in two different ways: For reference, this is the notation used: For reference, D, L, and B ("down", "left", and "back") are the inverse rotation to the aforementioned ones, respectively. Note: Whereas Rubik's cube rotations rotate a layer of the 3x3 puzzle cube, we are adopting the notation to apply to rotations of the cube itself. This DomainCreator is useful for testing code that deals with unaligned blocks. Implements DomainCreator< 3 >. Obtain the initial grid extents of the Elements in each block. Implements DomainCreator< 3 >. Obtain the initial refinement levels of the blocks. Implements DomainCreator< 3 >.
https://spectre-code.org/classdomain_1_1creators_1_1RotatedBricks.html
CC-MAIN-2022-21
refinedweb
126
50.43
React is an open-source JavaScript library that helps you build user interfaces. It's a component-based, declarative, "learn once and write anywhere" tool. With 164K+ GitHub stars, 30K+ forks, and close to ~10 million weekly downloads, React is undoubtedly a great user interface library to learn and use. If you are a developer getting started with React or thinking of using it in your side-projects or enterprises, this article is for you. If you started learning React a while ago but you're finding it hard to grasp the basics, give this article a read. TL;DR This article is lengthy but should be a fun read if you want to learn React or if you're working with it already. It answers these questions: - How does modern JavaScript knowledge make you an efficient React developer? - What kind of changes do you need in your mindset when you design and develop a React application? - What are the ecosystems you need to be aware of and why? Just chill, grab your favorite beverage, and enjoy the article. Why I Wrote this Article At the beginning, when I was learning React, I made the mistake of not focusing on a few essential fundamentals. As my knowledge grew more substantial, I started learning those concepts and found myself more comfortable with React. Many of my mentees discussed the challenges they faced when dealing with React which also centered around these fundamentals. So this motivated me to write this article and share what I've learned. Modern JavaScript Concepts You'll Need to Know for React The standardized name of JavaScript is ECMAScript. ECMAScript 2015 (which is also the 6th edition, and why it's called ES6) brought lots of cool features and new syntax to the JavaScript language. React, and many other modern user interface frameworks and libraries, work well with ES6. It is essential to know its modern syntax and new features to make coding much easier. This doesn't mean you can not write a React application with ES5. You can if you have to, but you'll kind of be doing things the hard way. Here are a few concepts you need to learn well. 1. How to Use Let and Const in JavaScript Until ES5, the only way to declare a variable was to use the var keyword. ES6 introduced two more ways to declare variables, using the let and const keywords. Using these modern keywords gives us more predictability and fewer chances of introducing bugs in the code. The var Keyword A variable declared with var is function scoped. This means we will get a ReferenceError when we try to access the variable outside of the function. var x = 10; function someFunc(){ var y = 10; console.log('inside someFunc', x, y); } Now, if you call someFunc(), it will log the following in the browser console: inside someFunc 10 10 But try accessing the variable y outside of sumFunc() and you will get the following error: Uncaught ReferenceError: y is not defined The let keyword let is block scoped. This is the main difference between let and var. Take this function where we loop using a for loop and access the variable i inside and outside of the loop. function letsLoop() { for (var i=0; i<5; i++) { console.log('i inside the loop: ', i); } console.log('i outside of loop', i); } When you call the function letsLoop(), the output will be this: i inside the loop: 0 i inside the loop: 1 i inside the loop: 2 i inside the loop: 3 i inside the loop: 4 i outside of loop 5 Now, let's change the keyword var to let while declaring and assigning the variable i. function letsLoop() { for (let i=0; i<5; i++) { console.log('i inside the loop: ', i); } console.log('i outside of loop', i); } If you execute the letsLoop() function now, you will get a ReferenceError while accessing the variable i outside of the for loop. It is because the visibility and accessibility (or scope) of the variable i is limited to the for block. i inside the loop: 0 i inside the loop: 1 i inside the loop: 2 i inside the loop: 3 i inside the loop: 4 Uncaught ReferenceError: i is not defined at letsLoop (<anonymous>:6:35) at <anonymous>:1:1 The const Keyword const is almost the same as let. The only difference is that once you have assigned a value to a variable defined with the const keyword, you can not reassign a new value to it. const name = 'freeCodeCamp'; name = 'My freeCodeCamp'; // Uncaught TypeError: Assignment to constant variable. This applies to all types of variables we can create in JavaScript. You need to be careful when it comes to a complex data structure like object. When an object is declared and assigned value with const, you can still change the value of its properties. But you can not reassign the variable another object. Please have a look: const publication = { 'name': 'freeCodeCamp' } publication.name= 'My freeCodeCamp'; // Allowed publication = {}; // Uncaught TypeError: Assignment to constant variable. And now to compare the three keywords: Here are some rules for using var, let, and const: - Don't use varanymore. Use letor const. - Use constmore often. Use letwhen you need to reassign another value to a variable. In a React app, you will see code using let and const very often. A React component is usually declared using const. Have a look at the example below. The variable DifficultyLevels is declared using const and is assigned a function as a value. This function defines a React component. It makes sense to use const here, as it will not be reassigned with another value. Now, notice the usages of the variable level inside the useEffect. We need to reassign the values of it based on a condition. So it makes sense to use the let keyword there. But, you won't see any var anywhere! const DifficultyLevels = () => { const userDataLS = getFromLS(LS_KEY_USER_DATA); const [userData, setUserData] = useState(userDataLS || { 'fullName': '', 'age': '', 'email': '', 'gender': 'F', 'difficultyLevel': BEGINNER }); //... other code useEffect(() => { let level = 'beginner'; if (userData.age >=10 && userData.age <= 13) { level = 'intermediate'; } else if (userData.age > 13) { level = 'advanced'; } setUserData({ ...userData, 'difficultyLevel': level }); }, [userData.age]); //... other code return( <> {/*...other code */} <span> { userData.level } </span> {/*...other code */} </> ) } 2. How to Use Template Literals in JavaScript Gone are the days when we used to concatenate strings like this: var name = 'Tapas'; var publication = 'freeCodeCamp'; var greeting = 'Hello'; // Or Hola // It produces output like, "Hello Tapas, welcome to freeCodeCamp." var message = greeting + ' ' + name + ', welcome to ' + publication + '.'; The above way of handling string concatenation and dynamic values into it is too much work, it's hard to read, and it's error-prone. How about we get the same output by writing code naturally without worrying about +, spaces, and so on? With ES6, we have template literals, which are string literals that allow embedding expressions. We use backticks (` `) instead single or double-quotes in template literals. We can define the dynamic values (or expressions) as placeholders using the dollar sign ($) and curly braces (like ${expression}). Let's write the above example using template literals. // We are expecting the values to change dynamically, hence `let` let name = 'Tapas'; let publication = 'freeCodeCamp'; let greeting = 'Hello'; // Or Hola // A much better way of wrting like natural language sentence let message = `${greeting} ${name}, welcome to ${publication}.`; So do we use it in our React code? Yes, why not? You may want to use the above greeting message in your React component and render it in a UI element. Here is an article to help you learn about template literals in detail. Do you use styled-components in your React project? In that case, you are using template literals already! 3. How to Import and Export Modules in JavaScript To code efficiently in React, you need to think in React. One of the primary ways you need to think is to break the UI into a suitable Component Hierarchy. We will learn more about what this means below. But at a high level, every component in React can be a JavaScript module. You have to export that module to import it elsewhere in the code for better component composition. This is why it is essential to get a good grip on module concepts and import/export functionalities. Here is a simple example of how we can export a React component and import it into another component. // under-construction.js under the directory src/components/utility import React from "react"; const UnderConstruction = () => { return( <div className="column"> <p style={{marginTop:"10px"}}> If you are seeing this, I am probably working on it! Please give it a few days to get constructed. </p> </div> ) }; export default UnderConstruction; In another component: import UnderConstruction from './components/utility/under-construction' Please read this article to familiarize yourself with JavaScript modules and the import/export keywords. 4. How to Use Arrow Functions in JavaScript Just a heads up – you can write React code without JavaScript arrow functions. That's right. Then, why are we talking about them? An arrow function is useful in many ways: - It makes function writing much easier. You mostly type fewer characters when using arrow functions than with standard functions. const double = (num) => {return num * 2;}; - Unlike standard functions, an arrow function doesn't redefine the value of thiswithin its definition. This behavior makes it an easy choice for developers to use arrow functions as callbacks. Who wants more bugs because of this? Here is an excellent article to get you started with the arrow functions and their usages. 5. How Destructuring Works in JavaScript Destructuring is the JavaScript syntax for extracting values from an object property and assigning them to a variable. Destructuring is also possible for JavaScript Arrays. Once you learn destructuring well, it will help make things very simple. You can use destructuring in loops, like this: for(let { name, age } of users) { console.log(`${name} is ${age} years old!`); } With a function's return value: const getUser = () => { return{ 'name': 'Alex', 'address': '15th Park Avenue', 'age': 43 } } const { name, age } = getUser(); console.log(name, age); // Alex 43 In a function parameter: function logDetails({name, age}) { console.log(`${name} is ${age} year(s) old!`) } Here is an example of Array destructuring: let emojis = ['🔥', '⏲️', '🏆', '🍉']; let [fire, clock, , watermelon] = emojis; console.log(fire, clock, watermelon); // 🔥 ⏲️ 🍉 Of course, we could have done, emojis[0], emojis[1], so on. But, that's too much to write and assign to variables one by one. In a React app, you will see heavy usage of both object and array destructuring. An experienced React developer who may review your code would expect to see these implementations as well. Here is an in-depth article that covers object destructuring. You need to know about Array destructuring as well. 6. How the Spread Operator and Rest Parameter Work in JavaScript The Spread Syntax (also known as the Spread Operator) is another excellent feature of ES6. As the name indicates, it takes an iterable (like an array) and expands (spreads) it into individual elements. We can also expand objects using the spread syntax and copy its enumerable properties to a new object. Spread syntax helps us clone an object and array with the most straightforward syntax using the three dots ..., like this: const clone_some_object = {...some_object} This is extremely useful in React when you're setting back a state variable with a new instance of an object and array to help re-render the component. The Rest parameter is kind of opposite to the spread syntax. While spread syntax helps expand or spread elements and properties, the rest parameter helps collect them together. Check out the last half of this article to know more about the Spread Operator and Rest parameter. 7. How to Use Classes in JavaScript ES6's class is another great inclusion that helps you write Object Oriented Programming in JavaScript. class Employee { constructor(name) { this.name = name; } greeting() { return `Hello, ${this.name}`; } } let emp = new Employee("Tapas"); emp.greeting(); // "Hello, Tapas" We can also create a class by extending it from an existing class. In React, we can create components in two ways: - Using Class - Using Function. Here is an example of how we can create a React component using an ES6 class: class Greeting extends React.Component { render() { return <span>Hello World!</span>; } } You can watch this video on the freeCodeCamp YouTube channel to learn more about ES6 classes. Apart from these, knowing about the for-of loop, async-await, ternary operator, and so on would be very helpful. Component Architecture Welcome to the second section of the article. Let's talk about Components. If we are talking about React, we have to talk about components. A single source code file consists of all the functionalities of an app. But it creates some of the problems you want to avoid as a developer. Here are a few I have faced (and there could be many more): - More than one developer working on the app may increase collaboration problems like merge conflicts, independently working, and so on. - Code reusability decreases, and repetition increases. - The team ends up working in a single-threaded model, and the end delivery becomes slow. - Testing your app as a Unit is no longer possible. You always touch the entire application as you modify the single file. - Your designer will not like it. When you are working with React, you'll be breaking your app into as many small units as possible, called Components. Each of the components should ideally only do one thing. So how do we put this into practice? Let's learn how with an example. How to Visualize a React App as a Bunch of Components Let's assume we are building a web app using React that lists down each students' results by their grades. Our designer has come up with a mockup, as shown below. What we see is the following: - A top navigation with a logo and the app's name. - A clear break up of results by grades. - It shows the result of the top three students of each grade. - There is a view alloption to see all the results for a grade. - We can search for the result of any student by searching the student's name. Now we need to start thinking about Components. This means how to break this app into logical units that take care of a single responsibility. There's not necessarily just one answer. That's fine, but we need to make sure we do a better job of creating components. Here is how we can do it: - A root component called App. - A Navcomponent for the top navigation. - A Resultscomponent that is the whole page except the Nav. - A Searchcomponent. - A Scorescomponent that may include all the scores. - A Scorecomponent that contains a heading, score table, and the view all linked. - A ScoreHeadingcomponent that contains a heading like, Grade 1. - A ScoreListcomponent that contains the score table. The image below shows them by marking them with different colors. Great, we have all the components now. So, we need to start thinking about component composition. What does this mean? These components are indeed isolated units that are each supposed to do a single thing. However, most of the components in a React application will be tied to each other by data. We also need to add components to each other so that these units eventually build the entire app. From the image below, you can understand how these components can be composed. - The Appcomponent is a root level component that has two other components, Navand Results. - The Navcomponent has a logo and a heading. - The Resultscomponent has a Searchcomponent and a Scorescomponent. - A Scorescomponent can have many Scorecomponents. - Each of the Scorecomponents has a ScoreHeadingand ScoreListcomponent. Does the image below make sense to you? Here is another way to visualize it: Each of these components manage and use data using two important concepts, which are props, and state. Props vs State in React In React, props and state are the basic ways you can manage data inside and among components. Props: are the variables passed by a parent component to its children. Using the props component, we can pass the required data to its children down in the hierarchy. State: On the other side, stateis the variable that a component manages within itself. In many cases, a component's state variable can be initialized by the data passed to it using props. The NPM Ecosystem Here we are at the last section of the article. This section will explain why knowing about the NPM ecosystem makes you more comfortable with React. What is NPM? NPMis the package manager for the Node.js platform. It consists of modules that Node can find and it helps Node manage dependency conflicts intelligently. Most commonly, it is used to publish, discover, install, and develop programs. You can find more information on NPM here. Why do I need to know about NPM? React by itself is a tiny library that lets you create components and build complete web apps. However, you will often need to use something that React may not offer out-of-the-box. For example, for extensive state management, you may want to use Redux. You may want to opt for an external library that helps with it, and that library is available in the form of an NPM package you can download and install. Similarly, npm packages exist for various utilities, chart libraries, string externalization, routing – you name it, and there's likely a package for it. The Open-Source Mindset What if you are unable to find a specific functionality you are looking for as an existing npm module? Yes, it can happen. Also, it may be available as an exiting npm package, but it does not fit your needs as is. What do you do then? There are two straightforward ways to handle this situation: - You build that functionality as a component, test it, and publish it as an open-source npm package. - You contribute to an existing open-source npm package and make it better. It's quite natural to have an open-source mindset as a React developer. Proactively seek out opportunities to either create something new or contribute to something that already exists. It is a great feeling when your work is used and appreciated by someone the same way you use someone else's. I have created an open-source project to help to publish npm packages quickly using a script. Please feel free to have a look, fork, and contribute. You may find it useful. Before We End... I hope you've found this article insightful, and that it helps you start using these concepts more effectively. Let's connect. You will find me active on Twitter (@tapasadhikary). Please feel free to give a follow. You may also like these articles:
https://www.freecodecamp.org/news/learn-react-basics/
CC-MAIN-2021-43
refinedweb
3,166
65.83
Visit the free getting started tutorials on nativescript.org for JavaScript or Angular. Kindly note that we filter out plugins that: package.json $ tns plugin add nativescript-videoplayer-lr A NativeScript plugin to provide the ability to play local and remote videos. Sample 1 | Sample 2 -------------------------------------| ------------------------------------- | From your command prompt/terminal go to your app's root folder and execute: tns plugin add nativescript-videoplayer <Page xmlns="" xmlns: <StackLayout> <VideoPlayer:Video <!-- Remote file to test with --> </StackLayout> </Page> // somewhere at top of your component or bootstrap file import {registerElement} from "nativescript-angular/element-registry"; registerElement("VideoPlayer", () => require("nativescript-videoplayer").Video); // documentation: With AngularNative you have to explicitly close all components so the correct template code is below. <VideoPlayer src="" autoplay="true" height="300"></VideoPlayer> Set the video file to play, for best performance use local video files if possible. The file must adhere to the platforms accepted video formats. For reference check the platform specs on playing videos. Set if the video should start playing as soon as possible or to wait for user interaction. Attribute to specify an event callback to execute when the video reaches the end of its duration. Set to use the native video player's media playback controls. Mutes the native video player. Sets the native video player to loop once playback has finished. If set to true, the aspect ratio of the video will not be honored and it will fill the entire space available. Attribute to specify an event callback to execute when the video is ready to play. Attribute to specify an event callback to execute when the video has finished seekToTime. If set to true, currentTimeUpdated callback is possible. Attribute to specify an event callback to execute when the time is updated. Set headers to add when loading a video from URL. When running the iOS Simulator, after playing a video the iOS system may write log messages to the console every few seconds of the form [aqme] 254: AQDefaultDevice (173): skipping input stream 0 0 0x0 They will continue being logged even after the video has been properly destroyed. These messages can be safely ignored. To turn them off completely, run the following command in your shell before running tns run ios: tns run ios export SIMCTL_CHILD_OS_ACTIVITY_MODE="disable" Popularity metric based on: Quality metric based on: Maintenance metric based on:
https://www.nsplugins.com/plugin/nativescript-videoplayer-lr
CC-MAIN-2017-47
refinedweb
390
55.84
Opened 8 years ago Closed 8 years ago Last modified 16 months ago #8963 closed defect (fixed) Restore compatibility with Trac 0.11 Description It was my fault to blindly believe, that trunk has been tested by others with Trac 0.11 prior to the release. At several occurrences I've explicitly stated that, but the true solution is still DIY. Now I've done it and I'm aware of several issue, that will immediately pop-up when acct_mgr-0.3 is applied into a 0.11 environment: Plugin will not load due to unresolved imports, seen in Trac environment startup phase (from Trac[loader]): - ERROR: Skipping "acct_mgr.admin = acct_mgr.admin": (can't import "cannot import name to_utimestamp") - Skipping "acct_mgr.db = acct_mgr.db": (can't import "cannot import name ChoiceOption") Plugin depends on more unavailable methods and attributes: - AttributeError: 'LoginModule' object has no attribute '_referer' - UndefinedError: "dgettext" not defined The second list is most probably not final, since I'm still in the process of resolving the issue listed as the last one above. If you're aware of one, please add it below, preferably with a short description where to see and how to reproduce the error. I'm sorry, and many thanks in advance for your patience. I'll try to resolve this ASAP. Attachments (0) Change History (19) comment:1 Changed 8 years ago by comment:2 follow-up: 3 Changed 8 years ago by UndefinedError: "dgettext" not defined - fixed This method is simply not present before some revision of Trac 0.12dev, so I'll include code to mimic it's behavior, if required. Shameless copy-n-adapt from Trac sources here. TypeError: __call__() got an unexpected keyword argument 'user' - fixed Another case of missed instance while doing a rename user-> username. AttributeError: 'LoginModule' object has no attribute 'auth_cookie_path' - fixed This option is explicitely marked since 0.12 in the source, no wonder... Removing choices for setting the value works fine. TypeError: gettext_noop() takes exactly 1 non-keyword argument (3 given) - fixed Singular/plural translations do havoc here. Turned out, that the fallback assignment ngettext = _is not sufficient, if _alias gettextis replaced by gettext_noop, so another fallback for ngettextis requrired. ProgrammingError: Cannot operate on a closed cursor. - fixed Actually this points at returning a cursor object, that should be avoided in general, since the cursor get's too easy out of scope when being passed over to another instance. Wonder why later Trac releases handled this more gracefully, but let's correct this anyway: Immediately reading out the cursor and and returning the list object constructed that way is enough. Oh, and #3323 surfaces again. No wonder, since it relies on fixed Trac 0.12 redirection logic. Now it's getting worse. comment:3 Changed 8 years ago by TypeError: __call__() got an unexpected keyword argument 'user' - fixed Another case of missed instance while doing a rename user-> username. Wrong. It turned out to be an issue with tag_ being not capable of doing a string replacement for some reason, so has to be replaced with tag(_(. Oh, and #3323 surfaces again. No wonder, since it relies on fixed Trac 0.12 redirection logic. Now it's getting worse. Confusing indeed. Still figuring out how to apply fixes included in recent Trac revisions into AcctMgr for working around known redirection issues of older Trac releases without destroying the current sane state for Trac >= 0.12 again. comment:4 Changed 8 years ago by thx for your quick reaction. I just tried to install 0.3 (the Stable Version) under trac 0.11 - with the detected problems. Perhaps it would be a good idea to disable/remove the 0.11 version from the download area until the problem are solved? Hopefully this will not take to long... comment:5 Changed 8 years ago by I'm testing redirect fixes here. Anything else is ready and will be published within the next 48 hours. So I'm reluctant to work on extra commits right now. I'm looking forward to receiving your feedback for acct_mgr-0.3.1 then. comment:6 Changed 8 years ago by comment:7 Changed 8 years ago by AttributeError: 'Environment' object has no attribute 'secure_cookies' - fixed You'll be doomed, as soon as you check the "Remember me" box at AcctMgr's login page. As t:#8684 states, "AccountManagerPlugin expects Trac 0.11.2 or higher..." for a long time now. But I've not been aware of this restriction, so literally stumbled upon it while testing with 0.11, and I see, this can be fixed to work more graceful with that older Trac releases. The nasty redirect issue is fixed too, even if I'm sure that it could be done in a cleaner fashion. Now I prepare for the real thing: release of changes to trunk and release of patched 0.3 as acct_mgr-0.3.1. comment:8 Changed 8 years ago by (In [10415]) AccountManagerPlugin: Restore 0.11 compatibility, refs #8963. Use to_timestamp for older Trac versions without the mircosecond POSIX time stamps support (available since Trac 0.12). comment:9 Changed 8 years ago by (In [10416]) AccountManagerPlugin: Restore 0.11 compatibility, refs #8963. From pwhash.py remove import of ChoiceOption introduced in changeset [9274] without real demand. comment:10 Changed 8 years ago by (In [10419]) AccountManagerPlugin: Restore 0.11 compatibility, refs #8963. Getting redirection right with Trac 0.11 is quite tricky. First: extract referer from req.get_header('Referer'), if (the inherited) trac.LoginModule has no attribute '_referer'. comment:11 Changed 8 years ago by (In [10421]). comment:12 Changed 8 years ago by (In [10422]). comment:13 Changed 8 years ago by 8 years ago by (In [10426]) AccountManagerPlugin: Restore 0.11 compatibility, refs #8963. auth_cookie_path option is explicitely marked since 0.12 in the source, my own fault to access it unconditionally, sorry. comment:15 Changed 8 years ago by (In [10428]). comment:16 Changed 8 years ago by (In [10429]). comment:17 Changed 8 years ago by (In [10467]). comment:18 Changed 8 years ago by (In [10470]). Just some preliminary comments to the issues mentioned above: import of u_timestamp- fixed import of ChoiceOption- fixed no attribute '_referer' in trac.LoginModule - fixed Still working to bring in missing dgettext.
https://trac-hacks.org/ticket/8963
CC-MAIN-2019-43
refinedweb
1,049
59.3
28 February 2013 18:45 [Source: ICIS news] (updates with Canadian and Mexican data) HOUSTON (ICIS)--Chemical shipments on Canadian railroads rose by 13.1% year on year to 11,659 railcar loadings in the week ended 23 February, marking their eighth straight increase so far this year, according to data released by a rail industry association on Thursday. In the previous week ended 16 February, Canadian chemical railcar shipments rose by 6.9%, the Association of American Railroads (AAR) said. From 1 January to 23 February, Canadian chemical railcar loadings were up 10.4% to 88,276. in ?xml:namespace> US chemical railcar traffic fell by 0.3% year on year to 29,998 loadings in the week ended 23 February, marking its second straight decline and the seventh decline so far this year. In the previous week ended 16 February, US chemical car loadings fell by 1.5% year on year. From 1 January to 23 February, US chemical railcar traffic was down by 1.4% to 236,196 loadings. Meanwhile, overall US weekly railcar loadings for the week ended 23 February in the freight commodity groups tracked by the AAR fell by 1.2% year on year to 278,059 carloads. Overall Canadian loadings rose by 1.3% to 77,789, and Mexican loadings rose by 12.4% to 16
http://www.icis.com/Articles/2013/02/28/9645536/Canada-chemical-railcar-traffic-rises-for-8th-straight.html
CC-MAIN-2014-52
refinedweb
223
59.19
Message-ID: <1672934181.893.1427421648287.JavaMail.haus-conf@codehaus02.managed.contegix.com> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_892_133260222.1427421648287" ------=_Part_892_133260222.1427421648287 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location: Groovy supports most of the signatures you know from Java. Since= Groovy 1.5 Groovy supports full usage of generics in method declarations. = Please see a Java tutorial for details.=20 I will often show a more general method signature like def= foo(x, y, p1, p2, ..., pn) This is not valid Groovy = code, it is just there to show that a method named foo has n could= be 0. In that case, the real resulting method signature would look like: <= code>def foo(x,y) A form of def foo(x,y, p1, p2, ..., pn, q1, q2, ...., qm)<= /strong> would mean n+m+2 parameters. Likewise a method= call foo(x, p1, p2, ..., pn) is a method cal= l Like Java since Java5 Groovy supports variable arguments. To use them yo= u have to give a special method signature where the last parameter is an ar= ray. def foo(p1, ...., pn, T... args). Here f= oo supports n arguments by default, but also an unspecified nu= mber of further arguments exceeding n. Example:=20 def foo(Object... args){args.length} assert foo() =3D=3D 0 assert foo(1,2) =3D=3D 2=20 In this example we defined a method foo, that is able to ta= ke any number of arguments, including no arguments at all. args.lengt= h will then specify the number of arguments. T... is th= met= hods are seen as such by Java too, since the "variable arguments flag&= quot; is set. Methods defined in Java using T... behave like a= variable arguments method. Methods defined in Java using T[] = will not have the special flag set, but Groovy will still see them as varia= ble... wil= l not behave different. This is no special logic we thought of, that is how= variable arguments behave in Java too. One more important point to mention is maybe a method overloaded with a = method that takes variable arguments. Groovy (and java) will select the mos= t specific method, that means if there is a method taking one argument and = the parameter type is an array and there is also another method, that takes= also only one argument and the argument is not an array, then the other me= thod is preferred. Examples:=20 def foo(Object[] args) {1} def foo (x) {2} def foo (x,y} {3} assert foo() =3D=3D 1 assert foo(1) =3D=3D 2 assert foo(1,2) =3D=3D 3 def x =3D [1,2] as Object[] assert foo(x) =3D=3D 1 assert foo(1,1,1) =3D=3D 1=20 Note: T[] or T... do have to be the last parameter, t= his clashes with Closures See also Closures. Groovy= allows you to attach "blocks" to method calls like in: foo() { println it }=20 To be able to attach a "block" in this way, the method signatu= re must be def foo(p1, p2, ..., pn, T t), whe= re T is Object, Closure or no explicit type. Example:=20 def foo(x,closure) {x+closure.call()} assert 1 =3D=3D foo(1) {0} assert 2 =3D=3D foo(1) {1}=20 You are also allowed to use the "block" as normal argument=20 foo(1,{1})=20 If variable arguments and Closures are combined you will have the proble= m, that the closure needs to be the last argument, but the parameter enabli= ng variable arguments needs to be the last one too. You could use code like= this to check that at runtime:=20 def foo(Object[] args) { if (!args || !(args[-1] instanceof Closure)) { throw new IllegalArgumentException("Last argument must be a closu= re") } ... }=20 !args will be true if args is null or an array of length 0, args[-1] refers to the last elemen= t of the array. Note: the "block" is always the last argument=20 See Maps Named arguments requires the following method signature d= ef foo(T t, p1, p2, ..., pn), but the real work is done by = the compiler where the the method call is defined. A method call will alw= ays be transformed to foo([p1:e1, p2:e2, ..., pn:en], q1, q2,= ..., qm). If you mix the positions of the pi and qi elemen= ts, then the compiler will still force the same transformed signature. Example:=20 def foo(x,y,z) {[x,y,z]} assert foo(a:1,b:2,3,4) =3D=3D [[a:1, b:2], 3, 4] assert foo(a:1,3,b:2,4) =3D=3D [[a:1, b:2], 3, 4] assert foo(3,4,a:1,b:2) =3D=3D [[a:1, b:2], 3, 4] assert foo(4,3,b:2,a:1) =3D=3D [[b:2, a:1], 4, 3]=20 The type T can be Object, Map or no explicit type. (In fact other types are possible for T. Any type compatibl= e to [:].getClass() can be used. But the type may change for e= xample from HashMap (Groovy 1.0) to LinkedHashMap (since Groovy 1.5), so it= is only safe to use the less specialized types.) Combining named arguments with closures or variable arguments is no prob= lem. You can make the map the first element of the variable arguments part = or you can let it have its own parameter: That is for you to decide. If you= combine named arguments and closures, you will need two parameters. One fo= r the map and one for the closure.=20 In case of def foo(T t, p1, p2, ..., pn) a= ll named arguments will be in t, but that also means that you = can not make a method call where you access pi by name. Exampl= e def foo(x,y){} foo(x:1,y:2)=20 This code will fail at runtime, because the method foo expe= cts two arguments, but the map you gave is only one argument. Note: the map is always the first argument=20 Groovy supports also the usage of methods with default values for parame= ters. Any parameter T t can have a default value using T= t=3Dx, where x is the value. The usage of the default value is not = bound to a special type. In fact this is a short form to declare an overloa= ded method. def foo(p1, p2, ..., pn, T t=3Dx, q1, q2, ..., qm= ) becomes a method def foo(p1, p2, ..., pn, T= t, q1, q2, ..., qm), where t has no default v= alue and a method def foo(p1, p2, ..., pn, q1, q2, ..., qm)= strong> this implementation: def foo(p1, p2, ..., pn, q1, q2, ..., qm) { // note: this is not working groovy code, just pseudo code! foo(p1, p2, ..., pn, x, q1, q2, ..., qm) }=20 If multiple default values are used, then the parameter with the default= value most right will be eliminated like seen here and the resulting metho= d signature will be processed again. That means def foo(p1, p= 2, ..., pn, T t1=3Dx, T t2=3Dy, q1, q2, ..., qm) will first= produce def foo(p1, p2, ..., pn, T t1, T t2, q1, q2, ..., qm= ) as the most general method and then continue the processi= ng with def foo(p1, p2, ..., pn, T t1=3Dx, q1, q2, ..., qm)= strong> which calls the other method and sets by using y for t2. since the signature still contains a default value t= t= ogether in any way. Example:=20 def foo(x=3D1,y=3D2) {x+y} assert foo() =3D=3D 3 assert foo(2) =3D=3D 4 assert foo(5,10) =3D=3D 15=20 You can combine default values with maps def foo(Map m=3D[:],x,y)<= /code> to get optional named arguments, with closures def foo(x,y,Clo= sure c=3D{}) to get optional closures and theoretically with variabl= e arguments def foo(x,y, Object[] args=3D[1,2]), but there sho= uld be only rare cases where default arguments and variable arguments combi= ned like this is making sense.
http://docs.codehaus.org/exportword?pageId=97976422
CC-MAIN-2015-14
refinedweb
1,374
72.87
Introduction: Making a Mayan Tzolkin Calendar OK, I will admit that I am a little obsessed with things Mayan at the moment, which explains why I wanted to make a Mayan Tzolkin calendar. I modeled the general layout and fabrication on the very nice Sleek Word Clock by scottbez1 which you can see here:. You can read about the Tzolkin Mayan calendar on Wikipedia. It is one of several calendars, and consists of 13 numbers and 20 day signs which appear in 260 combinations that rotate. In other words, with every change of the day the numer increases from 1 to 13 and then back to 1 again. Similarly the 20 day signs rotate. What I needed was a frame and face with the numbers and day signs on it, which I modeled on the Sleek World Clock, and relied on scottbez1's great instructions on printing the face and making the actual calendar. The electronics are Arduino and I put the code together from bits and pieces to take the date from an RTC, calculate the Julian Date and then work out where in the two Tzolkin rotation that day falls. LED's are controlled via a shift register. This is my first ever Arduino project - a testament to the great ease of use of this amazing technology! Step 1: Assembling the Electronics on the Breadboard for Testing 1 Ikea RIBBA shadow box - $10 18 white, 5 red, 5 blue, 5 yellow LEDs ( SuperBright $0.50 each when bought in packs of 100) - $17 33 Resistors 330 Ohm 1/6th Watt - $2 1 Arduino Uno - R3 board - $30 1 Real Time Clock Module DS1307 BOB-00099 - $15 5 Shift Register 8-Bit - 74HC595 - $7 1 Wall Adapter Power Supply - 9VDC 650mA - $6 2 printed transparencies (see attached pdf on Step 2) - $1 Total cost: $88 Also: prototyping breadboards, prototyping leads, wire etc Cardboard and other household items Total cost: around $44 (using standalone ATMega168) or $67 (if you buy a full Arduino) Step 2: Wiring It Up After testing everything on the breadboard, I drew a wiring diagram on an enlarged photocopy of the board on which I would assemble the shift registers. You can see how I am collecting connections along the side for the different pins on the Arduino Uno. Also, the order of the shift registers is indicated. Then I put this part together, learning how to solder (not well, yet). The close up shows the different color coded wires. Brown and yellow wires going left are to the LED. Black is ground. Red is 5v. White and gray are latch and clock for the shift registers. Yellow exiting on the top and connecting shift registers on their right is data pin 2. Step 3: LED Mounting I made the LED board from black foam board, which was a mixed decision. The foam board is thick, holding the LED well, but not firmly, so that it was hard to control their angles. As a result, when everything is put together, some of the LED are at a slightly odd angle. Definitely an area for improvement. Not shown, on the other side I made a series of walls around the LED to contain their light, made from cardboard and painted black. This part closely followed the Sleek Word Clock by scottbez1 which you can see here:. Step 4: The Calendar Mask I relied entirely on the instructions from scottbez1 here:. I used my own mask made in Adobe Illustrator using purchased Tzolkin images from here:. You can see the pdf linked here. Attachments Step 5: Arduino Code Finally, the code which uses an RTC chip to set the time on the board, then calculates the Julian date and from that works out where in the two Tzolkin rotations the day falls. It then writes the appropriate bit sequence to the shift registers. This is my first Arduino program, and I relied heavily on the referenced sources and the Arduino cookbook to put it together. Code: /*With thanks to the following sources for parts of this code and resources: Playground Time Library: RTC chip: calculating days: Definition: The Julian date (JD) is a continuous count of days from 1 January 4713 BC. */ #include <Time.h> //include libraries needed for time calculation #include <Wire.h> #include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t int dataPin = 2; // define Pins for shift register int clockPin = 3; int latchPin = 4; int seqtzn1[] = {128,64,32,16,8,4,2,1,0,0,0,0,0};//arrays controlling the LEDs int seqtzn2[] = {0,0,0,0,0,0,0,0,128,64,32,16,8}; int seqtzds1[] = {128,64,32,16,8,4,2,1,0,0,0,0,0,0,0,0,0,0,0,0}; int seqtzds2[] = {0,0,0,0,0,0,0,0,128,64,32,16,8,4,2,1,0,0,0,0}; int seqtzds3[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,64,32,16}; void setup() { Serial.begin(9600); // set up serial communication to computer pinMode(dataPin, OUTPUT); // set pin modes pinMode(latchPin, OUTPUT); pinMode (clockPin, OUTPUT); setSyncProvider(RTC.get); // the function to get the time from the RTC if(timeStatus()!= timeSet) Serial.println("Unable to sync with the RTC"); else Serial.println("RTC has set the system time"); } void loop() { // calculate Julian Date and the two Tzolkin numbers using functions below long jd = JulianDate(); int tzn = TzolkinNumber(jd); int tzds = TzolkinDaysign(jd); Serial.println(jd); Serial.println(tzn); Serial.println(tzds); // send data to shift registers digitalWrite (latchPin, LOW); // pull latch LOW start sending data shiftOut(dataPin, clockPin, LSBFIRST, seqtzds3[tzds]); shiftOut(dataPin, clockPin, LSBFIRST, seqtzds2[tzds]); shiftOut(dataPin, clockPin, LSBFIRST, seqtzds1[tzds]); shiftOut(dataPin, clockPin, LSBFIRST, seqtzn2[tzn]); //send the data shiftOut(dataPin, clockPin, LSBFIRST, seqtzn1[tzn]); digitalWrite(latchPin, HIGH); // pull latch HIGH stop sending data delay(300000); // wait a while before repeating } // calculating Julian date jd long JulianDate(){ time_t t = now(); // store the current time in time variable t int todayDay = day(t); // the day for the given time t int todayMonth = month(t); // the month for the given time t int todayYear = year(t); // the year for the given time t long centuries = todayYear/100; long leaps = centuries/4; long leapDays = 2 - centuries + leaps; // note is negative!! long yearDays = 365.25 * (todayYear + 4716); // days until 1 jan this year long monthDays = 30.6001* (todayMonth + 1); // days until 1st month long result = leapDays + todayDay + monthDays + yearDays -1524.5; return result; } // calculating the two Tzolkin numbers that give position in Tzolkin rotation int TzolkinNumber(long jd){ int result = (jd - 2456214) % 13; // the Tzolkin day number is calculated as being 0 to 12 return result; } int TzolkinDaysign(long jd){ int result = (jd - 2456203) % 20; //calculate Tzolkin day sign 0 to 19 from 10.3.12 and number 0 wikipedia order return result; } Participated in the Make It Glow Be the First to Share Recommendations 6 Comments 8 years ago Just wanted to say that it is a very cool time clock you did and also love Mayan stuff 8 years ago on Introduction Great looking project, and a really nice writeup, too! You've got a terrific level of detail here, which means other people could easily replicate it or even use it as a launching point for their own calendars/clocks. In addition to the Tzolk'in (agricultural?) cycle, I guess that this could be expanded to include the Haab' (365-day solar year) cycle, and even a long-count (essentially, Julian number :-) index. The Haab' would probably be most easily done with a separate, second construction, with an appropriate display panel. The Long Count is much simpler computationally, using the Julian date with an offset for the Mayan epoch (something in 3114 BC, as I recall), and then just doing a series of modulo-20 and modulo-18 calculations. The display (with at least five digit positions) would probably have to be done differently, either with servos rotating the glyphs into position, or with maybe multi-pixel displays. Reply 8 years ago on Introduction Thanks for the kind comments. I agree - an expanded version would be fun to make. What I learned from this project is that the physical making of the object was the most challenging (for me). I had alot of wires and soldering and LED wrangling. There must be more elegant ways to work, and I will try it again with a better approach. That would be a good time to bring in the additional calendars. Reply 8 years ago on Introduction I'm not so sure about "more elegant." What you described is pretty much how projects like this work :-) You might have been able to do the LED's more stably by making a custom circuit board with holes to position them, rather than soldering the LED and resistor leads directly. In any event, this sounds like it was a lot of fun for you, and tied learning a new set of skills to something in which you were already interested. Congratulations! 8 years ago on Introduction I do have a question. Where did you get your Julian date function? It doesn't look quite right to me. The algorithm I'm familiar with is equivalent to the one in Wikipedia, which doesn't look the same as yours. Reply 8 years ago on Introduction Hi kelseymh - I got the function from this thread: You will see the exact code I used there, a little lower down. I looked at the Wikipedia page, but the math was too challenging for me ;-( For my purposes it may not be that critical to get the exact correct date, as the ultimate goal is to use Julian Date to calculate the Tzolkin state. Oliver
https://www.instructables.com/Making-a-Mayan-Tzolkin-Calendar/
CC-MAIN-2021-25
refinedweb
1,638
57.71
I have a FragmentActivity from which I call a Fragment within which I have a static field and ExpandableListView. After pressing exist or back button I re -open the app and the static field's value is still there (ExpandableListView is in the same shape as well). Which is what I expected. Unfortunately, after a while (but not always) when I go back to the app the static field has its default value rather than the latest one which I presume would mean that the Fragment class was instantiated again. But ExpandableListView is as it was before leaving the app originally. Why does such behavior happen? By the way, I am doing this because I want to remember which which group of items is expanded in ExpandableListView. Here is the pager adapter that calls a Fragment. public class CollectionPagerAdapter extends FragmentStatePagerAdapter { private Local local; private Online online; public CollectionPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { switch (i) { case 0: local = new Local(); return local; case 1: online = new Online(); return online; } return null; } @Override public int getCount() { return 2; } public void updateLocal(String update) { local.updateLocal(update); } My guess would be that FragmentStatePagerAdapter is keeping the saved information in memory for a period of time before removing them thus you will get the default value when returning after longer period as the data has been reinitialized. If you want to store the data you can use shared preference (for smaller data). Shared Preference - SQL database -
https://codedump.io/share/fxRgGIGvJTj3/1/static-field-in-a-fragment
CC-MAIN-2017-39
refinedweb
249
50.97
Interesting question from inside the firewall: I expected Char.IsLetter() to return true only if presented with ‘A’..’Z’ or ‘a’.. ‘A’..’Z’ or ‘a’..). I don’t think there is a method but you can easily write your own: bool IsAsciiLetter(char c) { return (c >= ‘A’ && c <= ‘Z’) || (c >= ‘a’ && c <= ‘z’); } Char.IsLetter docs says "Indicates whether a Unicode character is categorized as an alphabetic letter." – not just in the current locale. It would be nice if there was an override that let you pass CultureInfo to it, but I can see difficulties in that. By the way, for an English language scenario you would probably want to take it on a case by case basis as to whether you wanted to return "true" for accented letters (less clear cut that a different script like Chinese), depending on the point of the test, since these are certainly letters in the Roman alphabet (particularly in a validation scenario…telling people their names are invalid is a just a teensy bit culturally insensitive). Well, you can always P/Invoke GetStringTypeEx. > Is this because that we are using Unicode 3.0 in here? Where can I find Unicode 3.0 spec? I don’t think this method makes any sense at all in the scope of Unicode 3.0. Unicode allows 4-byte characters (which are represented as surrogates in CLR’s UFT-16 encoding), so you can’t reliably determine whether individual 2-byte CLR Char (which could be half of the character) is a letter. You have been Taken Out! Thanks for the good post. I agree with Kevin Daly that it would be nice if CultureInfo could be passed to it, but do not agree with his second paragraph. English writing does not have accented letters. If a person or program is testing whether an accented letter is a letter, in English it is not and in other languages it depends on precisely what their alphabets are. Sure it can be considered culturally insensitive for the Japanese government to require my wife to misspell her name in official documents. But Japanese Ro-maji do not include the Spanish letter which comes after n, so we wrote it as ny. Interestingly there is no trouble writing the pronunciation correctly in katakana. Surely it’s a bit more culturally insensitive for the Japanese government to prohibit visiting Chinese scholars from writing their names in Chinese characters on official documents, requiring Chinese to write their names in Ro-maji and/or katakana, saying that only Japanese citizens are allowed to write their names in Chinese characters. Sometimes this might have a purpose, if names are being entered in databases that have been encoded in SJIS or EUC for decades and are not being converted to Unicode, and Chinese characters that were not copied into Japanese cannot be represented. But sometimes it’s just offensive, as when it involves a name stamp (hanko). Back to English as discussed by Mr. Daly, sure it’s culturally insensitive to tell a Swede or Chinese that their name isn’t a valid name, but it’s not culturally insensitive to tell them that their scripting isn’t English. OK, I’m an admitted character set simpleton but wouldn’t a Char.IsAscii() method come in handy? If the encoding is ASCII then every value from 0 to 127 is ASCII. Some values represent printable characters and some values represent control codes. If the encoding is JIS Ro-maji or SJIS or EUC then every value from 0 to 127 is JIS Ro-maji. Some values represent printable characters and some values represent control codes. Up to this point, the return value of an IsAscii() method would have to depend solely on cultural information, not on the value of the Char. If the encoding is an extension of ASCII (I don’t know if there are standards for this, though Microsoft has code page 437) then values from 128 to 255 are in this extension of ASCII. I think IsAscii() should return False for these values, but would understand if it returned True, if code page 437 is near-standard. If the encoding is Latin-1, ISO-8859-1, then values from 128 to 255 are in this character set. But this encoding is not ASCII, so surely IsAscii() should return False. Up to this point, the return value of an IsAscii() method might depend on the value of the Char, but even if it does, so what? It still depends on cultural information as well. The Char is not enough. In SJIS, a few of the values in the range 128 to 255 are characters (half-width katakana, which no one likes but everyone has to contend with them because they exist). In EUC this does not happen, nothing in the range 128 to 255 is a character. In both SJIS and EUC, there are various ranges inside of the range 32768 (0x8000) to 65535 (0xFFFF) that are characters, and various ranges that are not characters. Of course the codings are completely independent, there happen to be a few values that overlap (but which represent different characters in SJIS and EUC) but mostly they’re different. Actually I’ve seen some 3-byte characters in EUC too. Anyway, these values obviously are not Ascii. But nearly all non-Ascii characters are letters. If you allow IsAscii to use cultural information together with the value of the Char then you can compute a return value for IsAscii, but what would you use it for? When answering issues like this, I begin by questioning the question itself: Why do you need a method which can return true only if presented with ‘A’..’Z’ or ‘a’..’z’? Is it because you’re going to use the result for something that may not allow other characters? It is usually much better to test that usage itself. For example, I remember an issue where accented characters were causing problems when used for file paths. This path was stored in the registry and later used to call functions using the ACP in some cases (most often, from user mode) and functions using the OEMCP in others (few instances but it was a kernel mode driver where I was told that codepage conversion was quite difficult to handle, and I didn’t find out until much later that in kernel mode there are flags that can be set for handling path codepages). We could have checked the paths for A..Z and a…z but the real problem wasn’t there. it was more effective to check if the path converted to ACP and the path converted to OEMCP were both identical. This allowed for many cases that are not A..Z or a..z but still work. For example, an e with a tilde would cause problems (0x82 on CP437, CP850 and a few others but it is 0xE9 on CP1252) but a Japanese character on a Japanese system would be ok (because the ACP and the primary OEMCP on Japanese systems are 932) In reply to Norman Diamond on allowing for accented characters in English: the reality is that people writing in English *do* have to take accented characters into account. And there are countries where the normal day to day language may be English, but names in a non-English language may be common and there may be very good social, cultural or political reasons for taking the care to spell them correctly. Ireland is a good example: names in Irish (surnames, Christian names, place names and names of government departments and institutions) are in common usage, they make extensive use of the acute accent, and it is simply incorrect to ignore those accents (it can also create confusion). So frankly it is not enough rest in the comfort of English linguistic chauvinism. And hell, it’s hardly a biggie to deal with…and the ability to do so was after all one of the reaons for everybody moving to Unicode. Replying to Kevin Daly’s posting of 3/15/2004 8:07 PM. Language issues: > the reality is that people writing in English *do* have to take accented characters > into account. Then people writing in English *do* have to take Chinese characters into account, for exactly the same reasons you stated, except possibly for one exception: > names in Irish (surnames, Christian names, place names and names of > government departments and institutions) are in common usage, they make > extensive use of the acute accent, You say those are names in Irish. If you meant English, then I have just learned from you that English uses the acute accent. If you meant English, then then people writing in English do have to take acute accented characters into account but don’t have to take Chinese characters into account. But if you meant Irish exactly as you wrote, then we’re back to the situation of accented characters and Chinese characters being equally not part of English while equally needing some non-English treatment on occasion. Encoding issue: > and the ability to do so was after all one of the reaons for everybody moving to > Unicode. Not exactly. A lot of people did not already use 16-bit character sets so they didn’t have to worry about backwards compatibility. Suppose Unicode required you to replace all your databases, filenames, e-mail archives, etc., with 8-bit encodings that differed from your legacy 8-bit encodings. You’d refuse, wouldn’t you? You’d keep using your legacy 8-bit encoding because you have so many legacy files using them. Now notice how many people have legacy files using legacy 16-bit encodings and you’re not helping them with the lack of backwards compatibility. Everyone’s not moving to Unicode. PingBack from PingBack from
https://blogs.msdn.microsoft.com/brada/2004/03/08/char-isletter-and-ascii/
CC-MAIN-2016-30
refinedweb
1,644
60.45
I know this has been asked before, but I've tried all the solutions and it's not quite working in my python code. I want to read ALL csv files in my directory: /root/Downloads and write some of the information to a new csv file called test.csv. So far, this code will only read and write from one csv file. Any ideas? for currFile in os.listdir('/root/Downloads'): if currFile.endswith('.csv'): f1 = open('/root/Downloads/' + currFile) c1 = open('/root/Downloads/test.csv', 'w') r2 = f1.readlines() w1 = csv.writer(c1) for row in r2: product = row.split(',')[1] quantity = row.split(',')[2] sales = row.split(',')[3] w1.writerow([product, quantity, sales]) c1.close() f1.close() You need to use glob, like this: import glob import csv with open('results.csv', 'w') as f: writer = csv.writer(f) for filename in glob.iglob('/root/Downloads/*.csv'): with open(filename) as i: reader = csv.reader(i) for row in reader: writer.writerow([row[1], row[2], row[3]])
https://codedump.io/share/0tDePexogmI7/1/python-read-all-csv-files-in-directory
CC-MAIN-2018-22
refinedweb
171
72.73
favicon.ico Creation and Screen Captures on Linux There are several tools and processes I’ve been wanting to make the subject of Weblog posts, but keep I forgetting about them until something comes up that makes me wish I wasn’t so lazy about such things. Two popped-up again yesterday. Last night, the sometimes mystical process of creating favicon.ico files for websites without the use of commercial tools came up as I was helping my wife put together a site for an organization with which she works. I often forget this process, as there is no built-in way to do this using my favorite image editor, The GIMP, directly. So, this post is primarily a breadcrumb for myself, but doubles as a useful tech tip for anyone else searching for ways to create these files easily. Earlier yesterday, I happened to notice someone entered the search engine keyword phrase, “linux ppc screen capture”, which is an almost monthly phenomenon, and results in a link to my (very) old Gentoo Linux PPC Screen Capture page. While this is pretty and all, it probably isn’t particularly useful for someone looking for ways to create screen captures (a.k.a. screenshots) on Linux. I always hate to be disappointed upon visiting a search engine result myself, so I endeavor to minimize that disappointment in others as they navigate to our site. favicon.ico 101 What is the favicon.ico file? A great question! The favicon.ico file is a graphic image that can be used to iconify your webpage in web browser bookmark entries, and in the path bar in some web browsers. You may have noticed cute little graphics just to the left of the URL path in Firefox, or to the left of the site name in your Bookmarks / Favorites in Firefox / Internet Explorer. Why should you care about having a favicon.ico file? Another splendid question! Aside from adding a little style to your site visitors can appreciate, the addition of this file can also decrease the size of your web server’s error log file. That’s right, not having a favicon.ico file results in “404 Not Found” errors everytime someone with a modern-era browser visits pages on your site. By default, most browsers now look for the favicon.ico file in the webroot (same level as the main index page) of your site, and the act of requesting something that does not exist creates the 404 error. How can one easily create the favicon.ico file without the use of commercial software? Now, that’s the best question of all! There are two methods, both of which require you to create your desired graphic as a 16×16 pixel image, a 32×32 pixel image, and optionally, as a 48×48 pixel image using image editing software. Once you have your images in GIF, JPG, PNG, or BMP format, you can use the first method of using the online Dynamic Drive FavIcon Generator. You simply check the appropriate boxes, browse to the sized image files, and click on “Create Icon”. Pretty simple. The second method is slightly more involved, requires you use the PNG format for your sized image files, and involves the Open Source tool png2ico, which is available for Windows and other platforms (like Linux in my case). With the tool in place, creation of the favicon.ico file was a simple matter of entering the following from the command-line working in the directory where the sized images reside: png2ico favicon.ico image_16x16.png \ image_32x32.png \ image_48x48.png Place the resulting favicon.ico file in your webroot, and you should be in good shape. You can also now add the following to the header portion of your web pages: <link rel="shortcut icon" href="favicon.ico" /> OK. Now, you know how to create the favicon.ico file…but I just recently read that the use of the ICO format for the favorites icon on the web is no longer a “best practice”. Instead, using a single PNG image is now recommended, and can be associated with your pages using the same link format as above: <link rel="shortcut icon" href="favicon.png" /> Although I have not tested this, I assume that if you use a 32×32 or 48×48 pixel PNG image, it will automatically be resized appropriately for use when the 16×16 size is required. Salt to taste. Quick, Easy Screen Capture from Linux There are probably many, many, many tools for grabbing screen captures out there, and probably a great many of them are Open Source. I have to admit, I haven’t done a lot of shopping. I found a tool that I like, and that’s what I’ve been using for years. The tool, part of the ImageMagick collection of tools, import, is my first and only choice. ImageMagick is included with most Linux distributions as an available package, and is also available for the Windows Cygwin(probably only for use with Cygwin X) and OS X environments. To bring up “cross-hairs” for capture selection, simply type this at the command-line: import selection.png The image format can be any of the ImageMagick supported formats (the usual suspects, plus some unusual ones), and is interpreted by the application intelligently based on the filename extension you provide with the file name. To capture just a window, use the “-window id” option, specifying the window manager’s name for the window as the capture id: import -window "Google - Mozilla Firefox" window.png To capture the entire X screen, use the “-window id” option, declaring the root window as the capture id: import -window root screenshot.png If you use GKrellM as a graphical system monitor for your Linux box, look for the GKrellShoot plugin. Along with proving an easy GKrellM-based means of launching a screen lock, it also provides a click interface to calling ImageMagick’s import tool for screen captures. Until next time… Chip View All
https://wittzend.com/2006/06/06/favicon_and_screen_cap/
CC-MAIN-2019-13
refinedweb
1,007
60.55
User:Walter Contents - 1 Sugar 2020 - 2 Sugar Stable/Sugar Future - 3 Walter Bender - 3.1 bio - 3.2 bio en es - 3.3 Regarding the Sugar Labs Oversight Board - 3.4 LibrePlanet 2016 - 3.5 OWF talk - 3.6 Pakistan talk - 3.7 CLEI talk - 3.8 Libre Planet talk - 3.9 To do - 3.10 Done - 3.11 Recent writing about Sugar and learning - 3.12 Sandbox - 3.12.1 Spinner palette gtk-2 - 3.12.2 Spinner palette gtk-3 - 3.12.3 Sound test - 3.12.4 Help palette - 3.12.5 Home View - 3.12.6 Keyboards - 3.12.7 Misc. - 3.12.8 Floss Manual - 3.12.9 Portfolio - 3.12.10 Turtle Art → Logo - 3.12.11 Turtle Art variables - 3.12.12 Turtle Art push and pop - 3.12.13 HBS-style analysis - 3.12.14 Sugar icons Sugar 2020 I've just reread my vision statement from 2 years ago and find it still relevant, although rather than a bifurcation, we have a trifrucation of effort: we still have multiple communities using the Sugar Desktop; we have some pilot programs emerging around Sugarizer, and we have a rapidly growing program in Music Blocks, which can run independently of either the desktop or Sugarizer. A professional curriculum for Music Blocks is being developed and the government of Japan is incorporating it into the primary-school curriculum. The latter effort has consumed the majority of my attention over the past two years as a developer and has been personally very rewarding. I am especially pleased that a team of educators has dedicated time and energy into ensuring that the tools are well matched to the needs of the schools – I anticipate that Music Blocks will be a big growth area for Sugar Labs and one we can point to as evidence of the value of our Constructionist approach to learning. My other efforts have been administer the Google Code-in and Google Summer of Code programs on behalf of Sugar Labs to leverage great work from new contributors, many of whom have become mentors for future contributors. (For example, Music Blocks has had more than 60 unique contributors.) It is largely this opportunity to work with bright young minds from around the world that keeps me excited about Sugar Labs and its mission. I also need to tip my hat to James Cameron, without whose efforts (and those of the developers he patiently supports), the Sugar Desktop would have atrophied by now. James works diligently to ensure that Sugar lives up to the standards of an open libre project with discipline sufficient to ensure a level of quality needed by our user community. That said, the past two years have been a personal struggle in regards to the Sugar Labs oversight board. It has been difficult to muster a quorum of board members even for our regularly scheduled one-hour monthly meetings. A disinterested, disengaged board has made it impossible to do any long term planning for Sugar Labs. I'm at an impasse: I have considered stepping down from the board since I feel it is so ineffective. As I outlined two years ago, we have lots of potential as an organization, but I have not been able to realize that potential unilaterally. I am disappointed that we have do so little to engage the Maker community, the existing Sugar communities, or take the time to discuss new opportunities. It all ultimately boils down to communication -- there has been none from the majority of my colleagues on the board. But having reflecting upon it, I have decided to run again for a seat on the oversight board, as I think I still have something to contribute to Sugar Labs. But I will not serve as chair of our meetings as I have not been effective in that role. I am hoping that the community will elect new members who will participate and the dead weight that prevents us from moving forward will be jettisoned. Together, we have much to accomplish. Sugar Stable/Sugar Future Sugar Labs has been pulled in two directions the past few years. On the one hand, it is getting much more stable, much more robust, and easier to maintain. The maintenance itself is being provided in large part by a dedicated group of youths and a small handful of professional developers. On the other hand, the world of educational technology continues to move in directions that make it more difficult for the typical individual or school to adopt Sugar as their core platform. While OLPC still stands behind Sugar -- indeed, FZT has launched a program for Sugar development at a university in Managua, the growth potential outside of OLPC for a GNU/Linux-based platform is smaller than it was a few years ago. I do think that the "tablet" meme has been discredited and increasing momentum behind the Maker movement has shifted things somewhat in our favor. We need to be aggressive in reaching out to potential new user communities. At the same time, it is also clear that mobile devices and the Web are going to be the predominant points of access to technology for much of the world, so we are also obliged to try to bring some of our ideas (if not our entire platform) to those worlds. We have some momentum there as well, with the Sugarizer platform and the various JavaScript initiatives underway, e.g., Music Blocks. I don't see any way to avoid splitting our efforts between these two worlds -- GNU/Linux desktop and Web/native Android. Not ideal, but we have things to contribute to both worlds and an opportunity to learn and grow as a community going forward. As a member of the Sugar community, I have been active as: (1) a developer -- more on the activity side than the platform side; (2) a liaison to the SFC; (3) the coordinator for both Google Summer of Code and Google Code In; (4) promoting Sugar within academic circles -- most recently a File:MusicBlocks-Constructionism-2016.pdf that Devin, Yash, and I wrote for the Constructionist 2016 conference on the work we did together during GSoC; (5) raising funds for internationalization and workshops; and (6) running the monthly SLOB meetings. I don't need to be a member of the oversight board in order to be a developer, but for the other activities, it is important to have a voice within the community. If I am returned to the board, I hope to hand off responsibility for running meeting to another board member. And the role of liaison to the SFC. I think continuity within the Google programs is important, and I plan to continue in that sphere. I will also continue to manage the Trip Advisor grant, which has been really helpful for outreach -- most recently I was able to get some new Arabic translations done and we are making great inroads in places like Jamaica through that grant. One final note: I am in the process of launching a new college for industrial design. I am instilling Free/Libre Software as a core principle of the college and I hope to be able to make Sugar be at the core of the educational technology section of the school. More on that effort soon. Walter Bender I was at OLPC for several years and now I am a volunteer on the project. My home page can be found here: [1] bio. bio en es Nota: Walter tiene una biografia en la Wikipedia en español, la misma es esta Walter Bender es el director de la Fundación Sugar Lab, una organización sin fines de lucro, desde donde ha diseñado el sistema operativo SUGAR que utilizan las computadoras XO de la organización OLPC (One Laptop per Child) Una Computadora por estudiante. Uno de los objetivos de Sugar Lab es ofrecer un espacio de reunión y apoyo para una creciente comunidad de educadores y desarrolladores de software que quieran extender la plataforma de Sugar y quienes han estado creando aplicaciones compatibles con esta. Antes de fundar el Sugar Lab, Walter fue parte de la organización OLPC todavía apoya los esfuerzos de esa organización en el desarrollo y diseminación de tecnologías que puedan revolucionar el mundo de los niños y niñas y los atraigan hacia el aprendizaje. Entre los años 2000 y 2006 Walter fue el Director Ejecutivo del Laboratorio de Medios Media Lab, del Instituto Tecnológico de Massachusetts MIT donde además, por muchos años dirigió el grupo de investigación llamado Las Noticias de Futuro que se fundó en 1996 y su proyecto Publicación Electrónica. En el marco de las investigaciones Publicación Electrónica Walter ayudó a desarrollar en el siglo pasado las herramientas tecnológicas para promover lo que hoy en el siglo XXI conocemos como periodismo ciudadano. Walter tiene dos experiencias realmente pioneras relacionados con el periodismo ciudadano. Una se llama los Silver Stringers o Periodistas de Plata, que reúne a un grupo de personas de la tercera edad de la comunidad de Melrose en Massachusetts que publican su periódico sistemáticamente para lo cual siguen el proceso que se lleva a cabo en los grandes medios de comunicación masivo. Para esta experiencia, Walter contó con el apoyo de Jack Driscoll, Editor Pensionado del diario The Boston Globe. Es interesante mencionar que una de las ediciones de Silver Stringers en el año 2001 estuvo dedicada a Costa Rica, cuando algunos de los vecinos de Melrose vinieron de vacaciones a nuestro país y reportaron en el periódico The Silver Stringers o los Periodistas de Plata sobre sus aventuras aquí. La otra experiencia es el Junior Journal o el Diario Joven, que iniciando 1998 reunió a 300 jóvenes, niños y niñas entre los 13 y los 18 años, viviendo en muchos países alrededor del mundo para, en aquella época (pre web y pre redes sociales) escribir artículos de interés nacional, regional y mundial, editarlos y publicarlos mensualmente en su periódico. Otras experiencias semejantes con niños, niñas y jóvenes incluyen La Fragola en Italia que a la fecha cuenta con 7400 periódicos escolares y colegiales en línea. Desde todas estas perspectivas Walter ha hecho una importante contribución al conocimiento en las áreas de publicación electrónica, medios digitales y tecnologías para aprender. Regarding the Sugar Labs Oversight Board I am in deep. I live and breath Sugar every moment of every day. Perhaps too much (Mentoring students in Google Code In doesn't help the situation any). But I really do think that Sugar is of great value to learners and, although we are swimming against the tide of the mainstream (learning as consumption), we have had and continue to have a positive influence. I've spent much of the past two years advocating on behalf of Sugar (I've literally traveled the world to speak about Sugar). The good thing is that being captive in an airplane is a great place to write code. When I speak about Sugar, I use Sugar: i.e., every talk I have given in the past 5 years has been written in Turtle Art. Of late, I have also been working on raising money towards specific goals. Most recently, with help from Chris and Claudia, I got a grant for Sugar Labs from Trip Advisor to support our localization efforts and our efforts to promote programming by children (See turtleartday.org). I plan to do more targeted fund-raising over the next two years as the needs of our community come more sharply into focus. At the same time, I have been working hard (with Gonzalo and Tincho) to help local deployments fill in some of the development gaps left by the dispersal of the OLPC engineering team. Finally, I am working on developing a new program at MIT to rally universities around Sugar as a research and development platform. All of these efforts are enhanced by my role as a member of the Sugar Labs oversight board. Having an "official" role in the organization gives me more clout with potential donors and collaborators. My colleagues on the oversight board and in the general community are the best. Thank you for your contributions to the project. 2011 Follow this link to my 2009 Position Statement. Two years ago, I said: While it has been my goal to help get Sugar Labs to a point of self-sustainability, I don't think we are yet at that point. My goals for 2010 are to focus on fund-raising and further refining the organizational and governance models. - I think we made lots of progress re structure and not much progress fund-raising. A bit about me and my role in Sugar Labs: I was part of the Sugar team at One Laptop per Child that left to found Sugar Labs in March of 2008. I have worn a few different hats within the organization: activity developer, occasional contributor to Sugar core, member of the deployment team, the marketing team, and the activity team. I was a lead author of the FLOSS Manual on Sugar. I am presently the executive director of Sugar Labs. I also represent Sugar on the GNOME technical advisory board and the Squeakland board. I have been a GSOC mentor and am participating in several pilot deployment projects of Sugar on a Stick. - This is much the same... although I am perhaps coding more now than ever. LibrePlanet 2016 File:Education-needs-free-software.pdf OWF talk Pakistan talk CLEI talk File:CLEI.odp(es) video(es y en) Libre Planet talk To do - Write up new feature requests for 0.96: - Activity-mounted volumes in the Journal - Audio notes in the Journal - Lower-right hover to invoke/dismiss frame - Write Journal thumbnail viewer activity - shows title, preview, and description in scrollable window get Frame test set up in Peru/Uruguay/Paraguay</srike> - <strike>New Activity templates - Much of the information that is consistent across activities can be held in activities.s.o. (dfarning 22:28, 16 June 2008 (UTC)) - Follow-up with Linux Foundation Draft membership agreement for Sugar Labs rebase Turtle Art on SVG ask SFC for pointers to lawyers in SA start writing NSF/USAID proposal local-labs proposals NSF Creativity grant Babson brief - Watertown follow-up - Curriculum guides from GPA programs Done - New Getting Started Guide (See The Sugar FLOSS Manual) - Add ParserFunctions to Sugar Labs mediawiki - Draft rules of governance for Sugar Labs - Start Community-News Sugar Weekly Digest list - CoSN proposal - rebase Gmail on new Browse - Finalize arrangements with SFC - Incorporate Sugar Labs Recent writing about Sugar and learning - Sugar (Linux Magazine ES) - Confessions of a fundamentalist (Part 1) - Confessions of a fundamentalist (Part 2) - A page from the Hilbert playbook - Media, Mathematics, and Mallard Fillmore (I also blog the weekly Sugar Digest.) The slides from a talk I gave about Sugar at the Women2Woman conference are here and here. Sandbox Spinner palette gtk-2 Spinner palette gtk-3 Sound testUser:Walter/Get Sugar Help palette Home View A new, tighter spiral for the Home View: class MyLayout(Ring): RingLayout.__init__(self) self.my_radius = _MINIMUM_RADIUS self.my_orientation = math.pi def _calculate_radius_and_icon_size(self, children_count): """Stub out this method; not used in `My Layout`.""" return _MINIMUM_RADIUS, style.STANDARD_ICON_SIZE def _calculate_position(self, radius, icon_size, index, children_count): """ Increment the radius as you go """ if index == 0: self.my_radius = _MINIMUM_RADIUS self.my_orientation = math.pi This version inherits from RandomLayout and lets you rearrange the icons. class MyLayout(Random): RandomLayout.__init__(self) self.my_radius = _MINIMUM_RADIUS self.my_orientation = math.pi def _calculate_radius_and_icon_size(self, children_count): """Stub out this method; not used in `My Layout`.""" return _MINIMUM_RADIUS, style.STANDARD_ICON_SIZE def _calculate_position(self, icon_size): """ Increment the radius as you go """ def append(self, icon, locked=False): """ Instead of assigning the position based on a hash, use spiral """ FavoritesLayout.append(self, icon, locked) min_width_, child_width = icon.get_width_request() min_height_, child_height = icon.get_height_request(child_width) min_width_, width = self.box.get_width_request() min_height_, height = self.box.get_height_request(width) if icon in self.fixed_positions: x, y = self.fixed_positions[icon] x = min(x, width - child_width) y = min(y, height - child_height) else: x, y = self._calculate_position(child_width) if x is None or y is None: self._grid.add(icon, child_width / _CELL_SIZE, child_height / _CELL_SIZE) else: self._grid.add(icon, child_width / _CELL_SIZE, child_height / _CELL_SIZE, x / _CELL_SIZE, y / _CELL_SIZE) KeyboardsI used to design the keyboards for OLPC. I am doing one for them for a 'high-school' version of the XO-1.5. Here is a first pass: Misc. - 2010 DML proposal - File:VisualMatch-18.xo - User:Walter/sandbox - User:Walter/favoriteslayout.py Obsolete - User:Walter/favoritesview.py Obsolete - User:Walter/View-mylayout.svg - Activities/Turtle Art/Patching Obsolete Floss Manual <img src=" "/> <style> @import url(""); </style> <script src="" type="text/javascript"></script> <script type="text/javascript"> FM.init({"paging":true,"preferred":["OLPC LAPTOP USERS GUIDE","SUGAR USERS GUIDE"]}); </script> Portfolio I am making a "TurtleArt: inspired portfolio tool. See TAPortfolio for more details. Turtle Art → Logo I added a "view source" for Turtle Art that exports Logo. Turtle Art variables Following the lead of Luis Michelena, I've added named blocks and stacks. I plan to add push and pop next, which should greatly expand the range of possible constructions. Turtle Art push and pop While it is not the intent that Turtle Art be a full implementation of Logo, but there has been some discussion on teh Sur list about adding some capability for passing arguments to stacks. (and to support recursion). I have added a FILO and push and pop blocks to enable this functionality. I am looking for feedback. regarding this choice. HBS-style analysis - our points of difference - our points of parity - their points of difference
https://wiki.sugarlabs.org/index.php?title=User:Walter&oldid=102388
CC-MAIN-2019-26
refinedweb
2,945
53.41
work-with-python Python Origin provides embedded python environment, so that you can either run python in Origin (support both command line and .py file), or use a PyOrigin module to access Origin from Python. The embedded Python in Origin could be either version 3.3.5 or version 2.7.8. By default, it is Python version 3.3 running in Origin. To switch to use Python version 2.7, open Script Window and select menu Edit: Script Execution: Python 2.7. It can be also switched by a system variable @PYV. When @PYV = 3 (Default), the embedded Python is 3.3.5, while if @PYV = 2, it is 2.7.8. To set value for a system variable, click Tools:System Variables to open the Set System Variables dialog. The following document page is written based on the assumption that Python 3.3.5 is used in Origin. Minimum Origin Version Required: 2015 SR0 In Origin, you can run Python command line, or Python files (.py extension). Additionally, you could evaluate a Python expression in Origin as well. To run python command line in Origin, there are a couple of ways: // Define the Python command line(s) as a LabTalk string variable str$ = "a = 2 ** 8;print(a)"; // Execute Python command lines run -py %(str$); // ** is the Exponent operator in Python //It should return 256, i.e. 2 to the power 8 run.python(myname='Origin';print(myname)); //Should output 'Origin' We can use LabTalk object Python to execute Python commands and pass variables between LabTalk and Python. if(Python.Init()<0) { type -b " Initialize failed. "; return; } // ** is the Exponent operator in Python //It should output256, i.e. 2 to the power 8 Python.Exec("a = 2 ** 8; print(a)"); //Active a workbook Python.Send("1!1", arr1); // Send Column 1 in Sheet 1 current workbook to Python object arr1 Python.Exec(“print(arr1)”); days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; You can receive the list as Origin DataSet: Python.Receive("1!1",days); //Receive the list days to Column1 in Sheet 1 of current workbook Python.GetReal(LTVar, 10%4); Python.GetStr(LTStr$, Origin); Or define a numeric or string variable in LabTalk, and then pass the value to Python object py in this way: Python.SetReal(LTVar, py) Python.SetStr(LTStr$, py) To execute multiple Python commands or a Python module in the Script Window, set the system variable @PYI to 0 to turn off interactive mode. Choose Tools:System Variables to open the Set System Variables dialog, enter Variable = pyi and Value = 0. In order to run a Python file (with .py extension) in Origin, use either of the following LabTalk command/object: // Define a string for the file path and name of the .py file string str$ = system.PATH.PROGRAM$ + "\Samples\Python\ListMember.py"; // Run the .py file run -pyf "%(str$)"; // This .py file list all provided functions in PyOrigin module You can also evaluate a Python expression using either of the following LabTalk command/object method run -pye 10 % 4; // It evaluates the Python expression 10 % 4, % is the Modulus operator in Python // It outputs the evaluated value 2, which is the remainder of 10 divided by 4 run.python("10 % 4", 1); // It also returns the evaluated value 2, which is the same as the example above In your Python code, you can import the PyOrigin module and make use of the functions it provided to access Origin object. To import the PyOrigin module, make sure to have the following command line in your .py file: import PyOrigin Note that PyOrigin module is supposed to be used for the interaction of the current Origin session and Python extension, so the .py files with PyOrigin module imported can only be called from Origin (See the above section of Run Python File in Origin), i.e. such .py files cannot be executed directly from an external Python editor. (e.g. IDLE) In order to inspect all the functions/global variable and classes/member functions accessible from embedded Python, you can run the following LabTalk script in the Script Window: //make sure the Script Execution Mode is LabTalk string str$ = system.PATH.PROGRAM$ + "\Samples\Python\ListMember.py"; run -pyf "%(str$)"; The functions/classes/global variables provided by the PyOrigin module are very similar to their counterpart in Origin, so you can refer to the Origin C Reference for detailed usage. (Help:Programming:Origin C and go to Origin C Reference Chapter) Several built-in Python examples are provided under Origin sample folder(<Origin EXE Folder>\Samples\Python) in order to show how to work with Python in Origin, including how to send data to worksheets, import data and plot, export graphs and publish graphs on a web page, etc. The example *.py files can be run directly by some labtalk commands, and Origin example project files with Python files attached can be run by clicking the customized buttons. The Python file SendDataToWorksheet.py under <Origin EXE Folder>\Samples\Python is an example to show how to send data from Python to Origin, it created a dialog using Python tkinter module to get user input such as column format, number of rows, etc. Then these inputted parameters will be passed to Origin. In order to run this .py file, execute the following LabTalk script in the Script Window: //Make sure the Script Execution Mode is LabTalk //Make sure a worksheet is active in Origin string str$ = system.PATH.PROGRAM$ + "\Samples\Python\SendDataToWorksheet.py"; run -pyf "%(str$)"; The example ImportMatrixPlotContour.opj under <Origin EXE Folder>\Samples\Python shows how to import a matrix into Origin and plot it as a contour graph. It also shows the concept of attaching Python files to Origin projects and execute. To use this example, select File:Open to open the project file in Origin, you will see a workbook Control Panel with two embedded buttons. Click the Import Matrix and Plot Contour button to run the attached Python file, this is equivalent to running the following LabTalk script in Script Window: run -pyp ImportMatrixPlotContour.py; You can also click the Show Python Code button to view the attached Python file in Origin's Code Builder. This is equivalent to the following LabTalk script: %z = system.path.projectAttachedFilesPath$; ed.open(%zImportMatrixPlotContour.py); Alternatively, you could open the Code Builder (View: Code Builder or Alt + 4), and browse to the Project folder in Workspace panel to access the attached Python file. To attach your Python files to an Origin project, right click on the Project folder and select Add Files... to include your Python file(s). Python ExtensionPython Binding The embedded Python in Origin includes all the basic modules and the modules which are installed to your Python application. If you want to use other Python extensions, e.g. PyQt4PyQt4, numpynumpy, scipyscipy, follow the procedure below: If the Python extension is installed in default path, such as C:\Program Files (x86)\Python\Lib\site-packages\, you can directly use the package as shown in example below: # For Python extension version 3.3 (default) import numpy x = numpy.array([[1, 2, 3], [4, 5, 6]], numpy.int32) print(x) Otherwise, you have to add its installation folder to the system path list before you import it. To add the installation folder to system path list, the recommended approach is to run the following Python statements in the embedded Python environment of Origin (either directly run statements, or run from files): import sys # Replace the value of string variable py_ext_path # with the actual Python extension installation path in your computer py_ext_path = "C:\Python33\Lib\site-packages" if py_ext_path not in sys.path: sys.path.append(py_ext_path) And after you have executed these Python statements, you will be able to access the Python extension in the current Origin session using for example: import PyQt4 But once you closed the current Origin session, you will need to add the Python extension path to sys.path list once again. For example purpose, you can click desired version folder and find the compatible packages to download in links Numpy and Scipy.
https://www.originlab.com/doc/LabTalk/guide/work-with-python
CC-MAIN-2020-05
refinedweb
1,351
53.81
TAR stands for Tape Archive Files and this format is used to bundle a set of files into a single file, this is specifically helpful when archiving older files or sending a bunch of files over the network. The Python programming language has tarfile standard module which can be used to work with tar files with support for gzip, bz2, and lzma compressions. In this article, we will see how tarfile is used to read and write tar files in Python. Reading a tar file The tarfile.open function is used to read a tar file. It returns a tarfile.TarFile object. The two most important arguments this function takes are the filename and operation mode, with the former being a path to the tar file and the latter indicating the mode in which the file should be opened. The operation mode can optionally be paired with a compression method. The new syntax, therefore, becomes mode[:compression]. Following are the abbreviations for supported compression techniques: gzfor gzip bz2for bz2 xzfor lzma Example: import tarfile with tarfile.open("sample.tar", "r") as tf: print("Opened tarfile") Extracting tar file contents After opening a file, extraction can be done using tarfile.TarFile.extractall method. Following are the important arguments accepted by the method: - path: path to a directory to which a tar file should be extracted, defaults to - members: specify files to be extracted, should be a subset of tarfile.TarFile.getmembers()output, by default all files are extracted Example: import tarfile with tarfile.open("sample.tar", "r") as tf: print("Opened tarfile") tf.extractall(path="./extraction_dir") print("All files extracted") Extracting single file In order to selectively extract files, we need to pass a reference of the file object or file path as string to tarfile.TarFile.extract method. To list all files inside a tar file use the tarfile.TarFile.getmembers method which returns a list tarfile.TarInfo class instances. Example: import tarfile with tarfile.open("./sample.tar", "r") as tf: print("Opened tarfile") print(tf.getmembers()) print("Members listed") Output: Opened tarfile [<TarInfo 'sample' at 0x7fe14b53a048>, <TarInfo 'sample/sample_txt1.txt' at 0x7fe14b53a110>, <TarInfo 'sample/sample_txt2.txt' at 0x7fe14b53a1d8>, <TarInfo 'sample/sample_txt3.txt' at 0x7fe14b53a2a0>, <TarInfo 'sample/sample_txt4.txt' at 0x7fe14b53a368>] Single file extraction import tarfile file_name = "sample/sample_txt1.txt" with tarfile.open("sample.tar", "r") as tf: print("Opened tarfile") tf.extract(member=file_name, path="./extraction_dir") print(f"{file_name} extracted") Writing a tar file To add files to a tar file, the user has to open the file in append mode and use tarfile.TarFile.add method, it takes the path of file to be added as a parameter. import tarfile file_name = "sample_txt5.txt" with tarfile.open(f"./sample.tar", "a") as tf: print("Opened tarfile") print(f"Members before addition of {file_name}") print(tf.getmembers()) tf.add(f"{file_name}", arcname="sample") print(f"Members after addition of {file_name}") print(tf.getmembers())
https://www.python-engineer.com/posts/tarfile-python/
CC-MAIN-2022-21
refinedweb
483
58.79
(For more resources related to this topic, see here.) When running a Spark shell and connecting to an existing cluster, you should see something specifying the app ID like Connected to Spark cluster with app ID app-20130330015119-0001. The app ID will match the application entry as shown in the web UI under running applications (by default, it would be viewable on port 8080). You can start by downloading a dataset to use for some experimentation. There are a number of datasets that are put together for The Elements of Statistical Learning, which are in a very convenient form for use. Grab the spam dataset using the following command: wget Now load it as a text file into Spark with the following command inside your Spark shell: scala> val inFile = sc.textFile("./spam.data") This loads the spam.data file into Spark with each line being a separate entry in the RDD (Resilient Distributed Datasets). Note that if you've connected to a Spark master, it's possible that it will attempt to load the file on one of the different machines in the cluster, so make sure it's available on all the cluster machines. In general, in future you will want to put your data in HDFS, S3, or similar file systems to avoid this problem. In a local mode, you can just load the file directly, for example, sc.textFile([filepah]). To make a file available across all the machines, you can also use the addFile function on the SparkContext by writing the following code: scala> import spark.SparkFiles; scala> val file = sc.addFile("spam.data") scala> val inFile = sc.textFile(SparkFiles.get("spam.data")) Just like most shells, the Spark shell has a command history.You can press the up arrow key to get to the previous commands. Getting tired of typing or not sure what method you want to call on an object? Press Tab, and the Spark shell will autocomplete the line of code as best as it can. For this example, the RDD with each line as an individual string isn't very useful, as our data input is actually represented as space-separated numerical information. Map over the RDD, and quickly convert it to a usable format (note that _.toDouble is the same as x => x.toDouble): scala> val nums = inFile.map(x => x.split(' ').map(_.toDouble)) Verify that this is what we want by inspecting some elements in the nums RDD and comparing them against the original string RDD. Take a look at the first element of each RDD by calling .first() on the RDDs: scala> inFile.first() [...] res2: String = 0 0.64 0.64 0 0.32 0 0 0 0 0 0 0.64 0 0 0 0.32 0 1.29 1.93 0 0.96 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.778 0 0 3.756 61 278 1 scala> nums.first() [...] res3: Array[Double] = Array(0.0, 0.64, 0.64, 0.0, 0.32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.64, 0.0, 0.0, 0.0, 0.32, 0.0, 1.29, 1.93, 0.0, 0.778, 0.0, 0.0, 3.756, 61.0, 278.0, 1.0) Using the Spark shell to run logistic regression When you run a command and have not specified a left-hand side (that is, leaving out the val x of val x = y), the Spark shell will print the value along with res[number]. The res[number] function can be used as if we had written val res[number] = y.Now that you have the data in a more usable format, try to do something cool with it! Use Spark to run logistic regression over the dataset as follows: scala> import spark.util.Vector import spark.util.Vector scala> case class DataPoint(x: Vector, y: Double) defined class DataPoint scala> def parsePoint(x: Array[Double]): DataPoint = { DataPoint(new Vector(x.slice(0,x.size-2)) , x(x.size-1)) } parsePoint: (x: Array[Double])this.DataPoint scala> val points = nums.map(parsePoint(_)) points: spark.RDD[this.DataPoint] = MappedRDD[3] at map at <console>:24 scala> import java.util.Random import java.util.Random scala> val rand = new Random(53) rand: java.util.Random = java.util.Random@3f4c24 scala> var w = Vector(nums.first.size-2, _ => rand.nextDouble) 13/03/31 00:57:30 INFO spark.SparkContext: Starting job: first at <console>:20 ... 13/03/31 00:57:30 INFO spark.SparkContext: Job finished: first at <console>:20, took 0.01272858 s w: spark.util.Vector = (0.7290865701603526, 0.8009687428076777, 0.6136632797111822, 0.9783178194773176, 0.3719683631485643, 0.46409291255379836, 0.5340172959927323, 0.04034252433669905, 0.3074428389716637, 0.8537414030626244, 0.8415816118493813, 0.719935849109521, 0.2431646830671812, 0.17139348575456848, 0.5005137792223062, 0.8915164469396641, 0.7679331873447098, 0.7887571495335223, 0.7263187438977023, 0.40877063468941244, 0.7794519914671199, 0.1651264689613885, 0.1807006937030201, 0.3227972103818231, 0.2777324549716147, 0.20466985600105037, 0.5823059390134582, 0.4489508737465665, 0.44030858771499415, 0.6419366305419459, 0.5191533842209496, 0.43170678028084863, 0.9237523536173182, 0.5175019655845213, 0.47999523211827544, 0.25862648071479444, 0.020548000101787922, 0.18555332739714137, 0.... scala> val iterations = 100 iterations: Int = 100 scala> import scala.math._ scala> for (i <- 1 to iterations) { val gradient = points.map(p => (1 / (1 + exp(-p.y*(w dot p.x))) - 1) * p.y * p.x ).reduce(_ + _) w -= gradient } [....] scala> w res27: spark.util.Vector = (0.2912515190246098, 1.05257972144256, 1.1620192443948825, 0.764385365541841, 1.3340446477767611, 0.6142105091995632, 0.8561985593740342, 0.7221556020229336, 0.40692442223198366, 0.8025693176035453, 0.7013618380649754, 0.943828424041885, 0.4009868306348856, 0.6287356973527756, 0.3675755379524898, 1.2488466496117185, 0.8557220216380228, 0.7633511642942988, 6.389181646047163, 1.43344096405385, 1.729216408954399, 0.4079709812689015, 0.3706358251228279, 0.8683036382227542, 0.36992902312625897, 0.3918455398419239, 0.2840295056632881, 0.7757126171768894, 0.4564171647415838, 0.6960856181900357, 0.6556402580635656, 0.060307680034745986, 0.31278587054264356, 0.9273189009376189, 0.0538302050535121, 0.545536066902774, 0.9298009485403773, 0.922750704590723, 0.072339496591 If things went well, you just used Spark to run logistic regression. Awsome! We have just done a number of things: we have defined a class, we have created an RDD, and we have also created a function. As you can see the Spark shell is quite powerful. Much of the power comes from it being based on the Scala REPL (the Scala interactive shell), so it inherits all the power of the Scala REPL (Read-Evaluate-Print Loop). That being said, most of the time you will probably want to work with a more traditionally compiled code rather than working in the REPL environment. Summary In this article, you have learned how to load our data and how to use Spark to run logistic regression. Resources for Article: Further resources on this subject: - Python Data Persistence using MySQL Part II: Moving Data Processing to the Data [Article] - Configuring Apache and Nginx [Article] - Advanced Hadoop MapReduce Administration [Article]
https://www.packtpub.com/books/content/using-spark-shell
CC-MAIN-2015-18
refinedweb
1,157
74.49
QDir Class The QDir class provides access to directory structures and their contents. More... Note: All functions in this class are reentrant. Public Types Public Functions Static Public Members Macros Detailed Description A: On Windows, the second example above will be translated to C:\Users when used to access files. Examples of relative paths: You can use the isRelative() or isAbsolute() functions to check if a QDir is using a relative or an absolute file path. Call makeAbsolute() to convert a relative QDir to an absolute one. Navigation and Directory Operations A directory's path can be obtained with the path() function, and a new path set with the setPath() function. The absolute path to a directory is found by calling absolutePath(). The name of a directory is found using the dirName() function. This typically returns the last element in the absolute path that specifies the location of the directory. However, it can also return "." if the QDir represents the current directory. The path for a directory can also be changed with the cd() and cdUp() functions, both of which operate like familiar shell commands. When cd() is called with the name of an existing directory, the QDir object changes directory so that it represents that directory instead. The cdUp() function changes the directory of the QDir object so that it refers to its parent directory; i.e. cd("..") is equivalent to cdUp(). Directories can be created with mkdir(), renamed with rename(), and removed with rmdir(). You can test for the presence of a directory with a given name by using exists(), and the properties of a directory can be tested with isReadable(), isAbsolute(), isRelative(), and isRoot(). The refresh() function re-reads the directory's data from disk. Files and Directory Contents Directories contain a number of entries, representing files, directories, and symbolic links. The number of entries in a directory is returned by count(). A string list of the names of all the entries in a directory can be obtained with entryList(). If you need information about each entry, use entryInfoList() to obtain a list of QFileInfo objects. Paths to files and directories within a directory can be constructed using filePath() and absoluteFilePath(). The filePath() function returns a path to the specified file or directory relative to the path of the QDir object; absoluteFilePath() returns an absolute path to the specified file or directory. Neither of these functions checks for the existence of files or directory; they only construct paths. QDir directory("Documents/Letters"); QString path = directory.filePath("contents.txt"); QString absolutePath = directory.absoluteFilePath("contents.txt"); Files can be removed by using the remove() function. Directories cannot be removed in the same way as files; use rmdir() to remove them instead. It is possible to reduce the number of entries returned by entryList() and entryInfoList() by applying filters to a setNameFilters(). Attribute filters consist of a bitwise OR combination of Filters, and these are specified when calling setFilter(). The sort order is specified using setSorting() with a bitwise OR combination of SortFlags. You can test to see if a filename matches a filter using the match() function. Filter and sort order flags may also be specified when calling entryList() and entryInfoList() in order to override previously defined behavior. The Current Directory and Other Special Paths Access to some common directories is provided with a number of static functions that return QDir objects. There are also corresponding functions for these that return strings: The setCurrent() static function can also be used to set the application's working directory. If you want to find the directory containing the application's executable, see QCoreApplication::applicationDirPath(). The. Path Manipulation and Strings Paths containing "." elements that reference the current directory at that point in the path, ".." elements that reference the parent directory, and symbolic links can be reduced to a canonical form using the canonicalPath() function. Paths can also be simplified by using cleanPath() to remove redundant "/" and ".." elements. It is sometimes necessary to be able to show a path in the native representation for the user's platform. The static toNativeSeparators() function returns a copy of the specified path in which each directory separator is replaced by the appropriate separator for the underlying operating system. Examples Check if a directory exists: (We could also use the static convenience function QFile::exists().) Traversing directories and reading a file: QDir dir = QDir::root(); // "/" if (!dir.cd("tmp")) { // "/tmp" qWarning("Cannot find the \"/tmp\" directory"); } else { QFile file(dir.filePath("ex1.txt")); // "/tmp/ex1.txt" if (!file.open(QIODevice::ReadWrite)) qWarning("Cannot create the file %s", file.name()); }; } See also QFileInfo, QFile, QFileDialog, QCoreApplication::applicationDirPath(), and Find Files Example. Member Type Documentation enum QDir::Filter flags QDir::Filters This enum describes the filtering options available to QDir; e.g. for entryList() and QDir will not filter out files based on their permissions, so entryList() and entryInfoList() function to get the associated QFileInfo objects and then use the QFileInfo::permissons() to obtain the permissions and ownership for each file. The Filters type is a typedef for QFlags<Filter>. It stores an OR combination of Filter values. enum QDir::SortFlag flags QDir::SortFlags This enum describes the sort options available to QDir, e.g. for entryList() and. The SortFlags type is a typedef for QFlags<SortFlag>. It stores an OR combination of SortFlag values. Member Function Documentation QDir::QDir(const QString &path, const QString &nameFilter, QDir::SortFlags sort = SortFlags(Name | IgnoreCase), QDir::Filters filters = AllEntries) Constructs a QDir with path path, that filters its entries by name using nameFilter and by attributes using filters. It also sorts the names using sort. The default nameFilter is an empty string, which excludes nothing; the default filters is AllEntries, which also means exclude nothing. The default sort is Name | IgnoreCase, i.e. sort by name case-insensitively. If path is an empty string, QDir uses "." (the current directory). If nameFilter is an empty string, QDir uses the name filter "*" (all files). Note that path need not exist. See also exists(), setPath(), setNameFilters(), setFilter(), and setSorting(). QDir::QDir(const QString &path = QString()) Constructs a QDir pointing to the given directory path. If path is empty the program's working directory, ("."), is used. See also currentPath(). QDir::QDir(const QDir &dir) Constructs a QDir object that is a copy of the QDir object for directory dir. QDir &QDir::operator=(QDir &&other) Move-assigns other to this QDir instance. This function was introduced in Qt 5.2. QDir &QDir::operator=(const QDir &dir) Makes a copy of the dir object and assigns it to this QDir object. QDir::~QDir() Destroys the QDir object frees up its resources. This has no effect on the underlying directory in the file system. QString QDir::absoluteFilePath(const QString &fileName) const Returns the absolute path name of a file in the directory. Does not check if the file actually exists in the directory; but see exists(). Redundant multiple separators or "." and ".." directories in fileName are not removed (see cleanPath()). See also relativeFilePath(), filePath(), and canonicalPath(). QString QDir::absolutePath() const Returns the absolute path (a path that starts with "/" or with a drive specification), which may contain symbolic links, but never contains redundant ".", ".." or multiple separators. See also setPath(), canonicalPath(), exists(), cleanPath(), dirName(), and absoluteFilePath(). [static] void QDir::addSearchPath(const QString &prefix, const QString &path) Adds path to the search path for prefix. This function was introduced in Qt 4.3. See also setSearchPaths(). QString QDir::canonicalPath() const Returns the canonical path, i.e. a path without symbolic links or redundant "." or ".." elements. On systems that do not have symbolic links this function will always return the same string that absolutePath() returns. If the canonical path does not exist (normally due to dangling symbolic links) canonicalPath() returns an empty string. Example: QString bin = "/local/bin"; // where /local/bin is a symlink to /usr/bin QDir binDir(bin); QString canonicalBin = binDir.canonicalPath(); // canonicalBin now equals "/usr/bin" QString ls = "/local/bin/ls"; // where ls is the executable "ls" QDir lsDir(ls); QString canonicalLs = lsDir.canonicalPath(); // canonicalLS now equals "/usr/bin/ls". See also path(), absolutePath(), exists(), cleanPath(), dirName(), and absoluteFilePath(). bool QDir::cd(const QString &dirName) Changes the QDir's directory to dirName. Returns true if the new directory exists; otherwise returns false. Note that the logical cd() operation is not performed if the new directory does not exist. Calling cd("..") is equivalent to calling cdUp(). See also cdUp(), isReadable(), exists(), and path(). bool QDir::cdUp() Changes directory by moving one directory up from the QDir's current directory. Returns true if the new directory exists; otherwise returns false. Note that the logical cdUp() operation is not performed if the new directory does not exist. See also cd(), isReadable(), exists(), and path(). [static] QString QDir::cleanPath(const QString &path) Returns path with directory separators normalized (that is, platform-native separators converted to "/") and redundant ones removed, and "."s and ".."s resolved (as far as possible). Symbolic links are kept. This function does not return the canonical path, but rather the simplest version of the input. For example, "./local" becomes "local", "local/../bin" becomes "bin" and "/local/usr/../bin" becomes "/local/bin". See also absolutePath() and canonicalPath(). uint QDir::count() const Returns the total number of directories and files in the directory. Equivalent to entryList().count(). See also operator[]() and entryList(). [static] QDir QDir::current() Returns the application's current directory. The directory is constructed using the absolute path of the current directory, ensuring that its path() will be the same as its absolutePath(). See also currentPath(), setCurrent(), home(), root(), and temp(). [static] QString QDir::currentPath() Returns the absolute path of the application's current directory. The current directory is the last directory set with QDir::setCurrent() or, if that was never called, the directory at which this application was started at by the parent process. See also current(), setCurrent(), homePath(), rootPath(), tempPath(), and QCoreApplication::applicationDirPath(). QString QDir::dirName() const exists(). See also path(), filePath(), absolutePath(), and absoluteFilePath(). [static] QFileInfoList QDir::drives() Returns a list of the root directories on this system. On Windows this returns a list of QFileInfo objects containing "C:/", "D:/", etc. On other operating systems, it returns a list containing just one root directory (i.e. "/"). See also root() and rootPath(). QFileInfoList QDir::entryInfoList(const QStringList &nameFilters, QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const Returns a list of QFileInfo objectsList(), setNameFilters(), setSorting(), setFilter(), isReadable(), and exists(). QFileInfoList QDir::entryInfoList(QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const This is an overloaded function. Returns a list of QFileInfo objectsList(), setNameFilters(), setSorting(), setFilter(), isReadable(), and exists(). QStringList QDir::entryList(const QStringList &nameFilters, QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const Returns a list of the namesInfoList(), setNameFilters(), setSorting(), and setFilter(). QStringList QDir::entryList(QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const This is an overloaded function. Returns a list of the namesInfoList(), setNameFilters(), setSorting(), and setFilter(). bool QDir::exists(const QString &name) const() and QFile::exists(). bool QDir::exists() const() and QFile::exists(). QString QDir::filePath(const QString &fileName) const Returns the path name of a file in the directory. Does not check if the file actually exists in the directory; but see exists(). If the QDir is relative the returned path name will also be relative. Redundant multiple separators or "." and ".." directories in fileName are not removed (see cleanPath()). See also dirName(), absoluteFilePath(), isRelative(), and canonicalPath(). QDir::Filters QDir::filter() const Returns the value set by setFilter() [static] QString QDir::fromNativeSeparators(const QString &pathName) Returns pathName using '/' as file separator. On Windows, for instance, fromNativeSeparators(" c:\\winnt\\system32") returns "c:/winnt/system32". The returned string may be the same as the argument on some operating systems, for example on Unix. This function was introduced in Qt 4.2. See also toNativeSeparators() and separator(). [static] QDir QDir::home() Returns the user's home directory. The directory is constructed using the absolute path of the home directory, ensuring that its path() will be the same as its absolutePath(). See homePath() for details. See also drives(), current(), root(), and temp(). [static] QString QDir::homePath() Returns the absolute path of the user's home directory. Under Windows this function will return the directory of the current user's profile. Typically, this is: C:/Users/Username Use the: - The path specified by the USERPROFILEenvironment variable. - The path formed by concatenating the HOMEDRIVEand HOMEPATHenvironment variables. - The path specified by the HOMEenvironment variable. - The path returned by the rootPath() function (which uses the SystemDriveenvironment variable) - The C:/directory. Under non-Windows operating systems the HOME environment variable is used if it exists, otherwise the path returned by the rootPath(). See also home(), currentPath(), rootPath(), and tempPath(). bool QDir::isAbsolute() const Returns true if the directory's path is absolute; otherwise returns false. See isAbsolutePath(). See also isRelative(), makeAbsolute(), and cleanPath(). [static] bool QDir::isAbsolutePath(const QString &path) Returns true if path is absolute; returns false if it is relative. See also isAbsolute(), isRelativePath(), makeAbsolute(), cleanPath(), and QResource. bool QDir::isEmpty(QDir::Filters filters = Filters(AllEntries | NoDotAndDotDot)) const Returns whether the directory is empty. Equivalent to count() == 0 with filters QDir::AllEntries | QDir::NoDotAndDotDot, but faster as it just checks whether the directory contains at least one entry. Note: Unless you set the filters flags to include QDir::NoDotAndDotDot (as the default value does), no directory is empty. This function was introduced in Qt 5.9. See also count(), entryList(), and setFilter(). bool QDir::isReadable() const Returns true if the directory is readable and we can open files by name; otherwise returns false. Warning: A false value from this function is not a guarantee that files in the directory are not accessible. See also QFileInfo::isReadable(). bool QDir::isRelative() const Returns true if the directory path is relative; otherwise returns false. (Under Unix a path is relative if it does not start with a "/"). See also makeAbsolute(), isAbsolute(), isAbsolutePath(), and cleanPath(). [static] bool QDir::isRelativePath(const QString &path) Returns true if path is relative; returns false if it is absolute. See also isRelative(), isAbsolutePath(), and makeAbsolute(). bool QDir::isRoot() const Returns true if the directory is the root directory; otherwise returns false. Note: If the directory is a symbolic link to the root directory this function returns false. If you want to test for this use canonicalPath(), e.g. QDir dir("/tmp/root_link"); dir = dir.canonicalPath(); if (dir.isRoot()) qWarning("It is a root link"); See also root() and rootPath(). [static] QChar QDir::listSeparator() Returns the native path list separator: ':' under Unix and ';' under Windows. This function was introduced in Qt 5.6. bool QDir::makeAbsolute() Converts the directory path to an absolute path. If it is already absolute nothing happens. Returns true if the conversion succeeded; otherwise returns false. See also isAbsolute(), isAbsolutePath(), isRelative(), and cleanPath(). [static] bool QDir::match(const QString &filter, const QString &fileName) Returns true if the fileName matches the wildcard (glob) pattern filter; otherwise returns false. The filter may contain multiple patterns separated by spaces or semicolons. The matching is case insensitive. See also QRegularExpression Wildcard Matching, entryList(), and entryInfoList(). [static] bool QDir::match(const QStringList &filters, const QString &fileName) This is an overloaded function. Returns true if the fileName matches any of the wildcard (glob) patterns in the list of filters; otherwise returns false. The matching is case insensitive. See also QRegularExpression Wildcard Matching, entryList(), and entryInfoList(). bool QDir::mkdir(const QString &dirName) const Creates a sub-directory called dirName. Returns true on success; otherwise returns false. If the directory already exists when this function is called, it will return false. bool QDir::mkpath(const QString &dirPath) const Creates the directory path dirPath. The function will create all parent directories necessary to create the directory. Returns true if successful; otherwise returns false. If the path already exists when this function is called, it will return true. QStringList QDir::nameFilters() const Returns the string list set by setNameFilters() See also setNameFilters(). QString QDir::path() const Returns the path. This may contain symbolic links, but never contains redundant ".", ".." or multiple separators. The returned path can be either absolute or relative (see setPath()). See also setPath(), absolutePath(), exists(), cleanPath(), dirName(), absoluteFilePath(), toNativeSeparators(), and makeAbsolute(). void QDir::refresh() const Refreshes the directory information. QString QDir::relativeFilePath(const QString &fileName) const Returns the path to fileName relative to the directory. QDir dir("/home/bob"); QString s; s = dir.relativeFilePath("images/file.jpg"); // s is "images/file.jpg" s = dir.relativeFilePath("/home/mary/file.txt"); // s is "../mary/file.txt" See also absoluteFilePath(), filePath(), and canonicalPath(). bool QDir::remove(const QString &fileName) Removes the file, fileName. Returns true if the file is removed successfully; otherwise returns false. bool QDir::removeRecursively() Removes the directory, including all its contents. Returns true if successful, otherwise false. If a file or directory cannot be removed, removeRecursively() keeps going and attempts to delete as many files and sub-directories as possible, then returns false. If the directory was already removed, the method returns true (expected result already reached). Note: this function is meant for removing a small application-internal directory (such as a temporary directory), but not user-visible directories. For user-visible operations, it is rather recommended to report errors more precisely to the user, to offer solutions in case of errors, to show progress during the deletion since it could take several minutes, etc. This function was introduced in Qt 5.0. bool QDir::rename(const QString &oldName, const QString &newName) Renames a file or directory from oldName to newName, and returns true if successful; otherwise returns false. On most file systems, rename() fails only if oldName does not exist, or if a file with the new name already exists. However, there are also other reasons why rename() can fail. For example, on at least one file system rename() fails if newName points to an open file. If oldName is a file (not a directory) that can't be renamed right away, Qt will try to copy oldName to newName and remove oldName. See also QFile::rename(). bool QDir::rmdir(const QString &dirName) const Removes the directory specified by dirName. The directory must be empty for rmdir() to succeed. Returns true if successful; otherwise returns false. bool QDir::rmpath(const QString &dirPath) const Removes the directory path dirPath. The function will remove all parent directories in dirPath, provided that they are empty. This is the opposite of mkpath(dirPath). Returns true if successful; otherwise returns false. [static] QDir QDir::root() Returns the root directory. The directory is constructed using the absolute path of the root directory, ensuring that its path() will be the same as its absolutePath(). See rootPath() for details. See also drives(), current(), home(), and temp(). [static] QString QDir::rootPath() Returns the absolute path of the root directory. For Unix operating systems this returns "/". For Windows file systems this normally returns "c:/". See also root(), drives(), currentPath(), homePath(), and tempPath(). [static] QStringList QDir::searchPaths(const QString &prefix) Returns the search paths for prefix. This function was introduced in Qt 4.3. See also setSearchPaths() and addSearchPath(). [static] QChar QDir::separator() Returns the native directory separator: "/" under Unix and "\" under Windows. You do not need to use this function to build file paths. If you always use "/", Qt will translate your paths to conform to the underlying operating system. If you want to display paths to the user using their operating system's separator use toNativeSeparators(). See also listSeparator(). [static] bool QDir::setCurrent(const QString &path) Sets the application's current working directory to path. Returns true if the directory was successfully changed; otherwise returns false. QString absolute = "/local/bin"; QString relative = "local/bin"; QFileInfo absFile(absolute); QFileInfo relFile(relative); QDir::setCurrent(QDir::rootPath()); // absFile and relFile now point to the same file QDir::setCurrent("/tmp"); // absFile now points to "/local/bin", // while relFile points to "/tmp/local/bin" See also current(), currentPath(), home(), root(), and temp(). void QDir::setFilter(QDir::Filters filters) Sets the filter used by entryList() and entryInfoList() to filters. The filter is used to specify the kind of files that should be returned by entryList() and entryInfoList(). See QDir::Filter. See also filter() and setNameFilters(). void QDir::setNameFilters(const QStringList &nameFilters) Sets the name filters used by entryList() and entryInfoList() to the list of filters specified by nameFilters. Each name filter is a wildcard (globbing) filter that understands *and ?wildcards. See QRegularExpression Wildcard Matching. For example, the following code sets three name filters on a QDir to ensure that only files with extensions typically used for C++ source files are listed: QStringList filters; filters << "*.cpp" << "*.cxx" << "*.cc"; dir.setNameFilters(filters); See also nameFilters() and setFilter(). void QDir::setPath(const QString &path) Sets the path of the directory to path. The path is cleaned of redundant ".", ".." and of multiple separators. No check is made to see whether a directory with this path actually exists; but you can check for yourself using". See also path(), absolutePath(), exists(), cleanPath(), dirName(), absoluteFilePath(), isRelative(), and makeAbsolute(). [static] void QDir::setSearchPaths(const QString &prefix, const QStringList &searchPaths)StringList(QDir::homePath() + "/images")); QDir::setSearchPaths("docs", QStringList(":/embeddedDocuments")); ... QPixmap pixmap("icons:undo.png"); // will look for undo.png in QDir::homePath() + "/images" QFile file("docs:design.odf"); // will look in the :/embeddedDocuments resource path File name prefix must be at least 2 characters long to avoid conflicts with Windows drive letters. Search paths may contain paths to The Qt Resource System. This function was introduced in Qt 4.3. See also searchPaths(). void QDir::setSorting(QDir::SortFlags sort) Sets the sort order used by entryList() and entryInfoList(). The sort is specified by OR-ing values from the enum QDir::SortFlag. See also sorting() and SortFlag. QDir::SortFlags QDir::sorting() const Returns the value set by setSorting() See also setSorting() and SortFlag. void QDir::swap(QDir &other) Swaps this QDir instance with other. This function is very fast and never fails. This function was introduced in Qt 5.0. [static] QDir QDir::temp() Returns the system's temporary directory. The directory is constructed using the absolute canonical path of the temporary directory, ensuring that its path() will be the same as its absolutePath(). See tempPath() for details. See also drives(), current(), home(), and root(). [static] QString QDir::tempPath() Returns the absolute canonical path of the system's temporary directory.). See also temp(), currentPath(), homePath(), and rootPath(). [static] QString QDir::toNativeSeparators(const QString &pathName) Returns pathName with the '/' separators converted to separators that are appropriate for the underlying operating system. On Windows, toNativeSeparators("c:/winnt/system32") returns "c:\winnt\system32". The returned string may be the same as the argument on some operating systems, for example on Unix. This function was introduced in Qt 4.2. See also fromNativeSeparators() and separator(). bool QDir::operator!=(const QDir &dir) const Returns true if directory dir and this directory have different paths or different sort or filter settings; otherwise returns false. Example: // The current directory is "/usr/local" QDir d1("/usr/local/bin"); d1.setFilter(QDir::Executable); QDir d2("bin"); if (d1 != d2) qDebug("They differ"); bool QDir::operator==(const QDir &dir) const Returns true if directory dir and this directory have the same path and their sort and filter settings are the same; otherwise returns false. Example: // The current directory is "/usr/local" QDir d1("/usr/local/bin"); QDir d2("bin"); if (d1 == d2) qDebug("They're the same"); QString QDir::operator[](int pos) const Returns the file name at position pos in the list of file names. Equivalent to entryList().at(index). pos must be a valid index position in the list (i.e., 0 <= pos < count()). See also count() and entryList(). Macro Documentation void Q_CLEANUP_RESOURCE(name) Unloads the resources specified by the .qrc file with the base name name. Normally, Qt resources are unloaded automatically when the application terminates, but if the resources are located in a plugin that is being unloaded, call Q_CLEANUP_RESOURCE() to force removal of your resources. Note: This macro cannot be used in a namespace. Please see the Q_INIT_RESOURCE documentation for a workaround. Example: Q_CLEANUP_RESOURCE(myapp); This function was introduced in Qt 4.1. See also Q_INIT_RESOURCE() and The Qt Resource System. void Q_INIT_RESOURCE(name) Initializes the resources specified by the .qrc file with the specified base name. Normally, when resources are built as part of the application, the resources are loaded automatically at startup. The Q_INIT_RESOURCE() macro is necessary on some platforms for resources stored in a static library. For example, if your application's resources are listed in a file called myapp.qrc, you can ensure that the resources are initialized at startup by adding this line to your main() function: Q_INIT_RESOURCE(myapp); If the file name contains characters that cannot be part of a valid C++ function name (such as '-'), they have to be replaced by the underscore character ('_'). Note: This macro cannot be used in a namespace. It should be called from main(). If that is not possible, the following workaround can be used to init the resource myapp from the function MyNamespace::myFunction: inline void initMyResource() { Q_INIT_RESOURCE(myapp); } namespace MyNamespace { ... void myFunction() { initMyResource(); } } See also Q_CLEANUP_RESOURCE() and The Qt Resource.
https://doc.qt.io/QT-5/qdir.html
CC-MAIN-2022-21
refinedweb
4,170
50.73
Built-in Package Support in Python 1.5 Built-in Package Support in Python 1.5 Starting with Python version 1.5a4, package support is built into the Python interpreter. This implements a slightly simplified and modified version of the package import semantics pioneered by the "ni" module. "Package import" is a method to structure PIL from having to worry about each other's module names. Starting with Python version 1.3, package import was supported by a standard Python library module, "ni". (The name is supposed to be an acronym for New Import, but really referrs to the Knights Who Say Ni in the movie Monty Python and the Holy Grail, who, after King Arthur's knights return with a shrubbery, have changed their names to the Knights Who Say Neeeow ... Wum ... Ping - but that's another story.) The ni module was all user code except for a few modifications to the Python parser (also introduced in 1.3) to accept import statements of the for "import A.B.C" and "from A.B.C import X". When ni was not enabled, using this syntax resulted in a run-time error "No such module". Once ni was enabled (by executing "import ni" before importing other modules), ni's import hook would look for the submodule of the correct package. The new package support is designed to resemble ni, but has been streamlined, and a few features have been changed or removed. An Example Suppose you want to design a package for the uniform handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, e.g. .wav, .aiff, .au), so you may need to create and maintain a growing collection of modules for the conversion between the various file formats. There are also many different operations you might want to perform on sound data (e Utils/ Subpackage for internal use __init__.py iobuffer.py errors.py ... dolby.py ... Users of the package can import individual modules from the package, for example: import Sound.Effects.echo - This loads the submodule Sound.Effects.echo. It must be referenced with its full name, e.g. Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4) from Sound.Effects import echo - This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows: echo.echofilter(input, output, delay=0.7, atten=4) a the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, ImportError. Importing * From a Package; the __all__ Attribute Now what happens when the user writes from Sound.Effects import *? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. Unfortunately, this operation does not work very well on Mac and Windows platforms, where the filesystem does not always have accurate information about the case of a filename! On these platforms, there is no guaranteed way to know whether a file ECHO.PY should be imported as a module echo, Echo or ECHO. (For example, Windows 95 has the annoying practice of showing all file names with a capitalized first letter.) The DOS 8+3 filename restriction adds another interesting problem for long module names. Sounds its initialization code, __init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py. It also includes any submodules of the package that were explicitly loaded by previous import statements, e.g. In this example, the echo and surround modules are imported in the current namespace because they are defined in the Sound.Effects package when the from...import statement is executed. (This also works when __all__ is defined.)In this example, the echo and surround modules are imported in the current namespace because they are defined in the Sound.Effects package when the from...import statement is executed. (This also works when __all__ is defined.)import Sound.Effects.echo import Sound.Effects.surround from Sound.Effects import * Note that in general the practicing of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions, and certain modules are designed to export only names that follow certain patterns. Remember, there is nothing wrong with using from Package import specific_submodule! In fact this becomes the recommended notation unless the importing module needs to use submodules with the same name from different packages. Intra-packagepackage (as with the Sound package in the example),. (One could design a notation to refer to parent packages, similar to the use of ".." to refer to the parent directory in Unix and Windows filesystems. In fact, ni supported this using __ for the package containing the current module, __.__ for the parent package, and so on. This feature was dropped because of its awkwardness; since most packages will have a relative shallow substructure, this is no big loss.) Details Packages Are Modules, Too! Warning: the following may be confusing for those who are familiar with Java's package notation, which is similar to Python's, but different. Whenever a submodule of a package is loaded, Python makes sure that the package itself is loaded first, loading its __init__.py file if necessary. The same for packages. Thus, when the statement import Sound.Effects.echo is executed, it first ensures that Sound is loaded; then it ensures that Sound.Effects is loaded; and only then does it ensure that Sound.Effects.echo is loaded Once loaded, the difference between a package and a module is minimal. In fact, both are represented by module objects, and both are stored in the table of loaded modules, sys.modules. The key in sys.modules is the full dotted name of a module (which is not always the same name as used in the import statement). This is also the contents of the __name__ variable (which gives the full name of the module or package). The __path__ Variable The one distinction between packages and modules lies in the presence or absence of the variable __path__. This is only present for packages. It is initialized to a list of one item, containing the directory name of the package (a subdirectory of a directory on sys.path). Changing __path__ changes the list of directories that are searched for submodules of the package. For example, the Sound.Effects package might contain platform specific submodules. It could use the following directory structure: Sound/ __init__.py Effects/ # Generic versions of effects modules __init__.py echo.py surround.py reverse.py ... plat-ix86/ # Intel x86 specific effects modules echo.py surround.py plat-PPC/ # PPC specific effects modules echo.py The Effects/__init__.py file could manipulate its __path__ variable so that the appropriate platform specific subdirectory comes before the main Effects directory, so that the platform specific implementations of certain effects (if available) override the generic (probably slower) implementations. For example: platform = ... # Figure out which platform applies dirname = __path__[0] # Package's main folder __path__.insert(0, os.path.join(dirname, "plat-" + platform)) If it is not desirable that platform specific submodules hide generic modules with the same name, __path__.append(...) should be used instead of __path__.insert(0, ...). Note that the plat-* subdirectories are not subpackages of Effects - the file Sound/Effects/plat-PPC/echo.py correspondes to the module Sound.Effects.echo. Dummy Entries in sys.modules When using packages, you may occasionally find spurious entries in sys.modules, e.g. sys.modules['Sound.Effects.string'] could be found with the value None. This is an "indirection" entry created because some submodule in the Sound.Effects package imported the top-level string module. Its purpose is an important optimization: because the import statement cannot tell whether a local or global module is wanted, and because the rules state that a local module (in the same package) hides a global module with the same name, the import statement must search the package's search path before looking for a (possibly already imported) global module. Since searching the package's path is a relatively expensive operation, and importing an already imported module is supposed to be cheap (in the order of one or two dictionary lookups) an optimization is in order. The dummy entry avoids searching the package's path when the same global module is imported from the second time by a submodule of the same package. Dummy entries are only created for modules that are found at the top level; if the module is not found at all, the import fails and the optimization is generally not needed. Moreover, in interactive use, the user could create the module as a package-local submodule and retry the import; if a dummy entry had been created this would not be found. If the user changes the package structure by creating a local submodule with the same name as a global module that has already been used in the package, the result is generally known as a "mess", and the proper solution is to quit the interpreter and start over. What If I Have a Module and a Package With The Same Name? You may have a directory (on sys.path) which has both a module spam.py and a subdirectory spam that contains an __init__.py (without the __init__.py, a directory is not recognized as a package). In this case, the subdirectory has precedence, and importing spam will ignore the spam.py file, loading the package spam instead. If you want the module spam.py to have precedence, it must be placed in a directory that comes earlier in sys.path. (Tip: the search order is determined by the list of suffixes returned by the function imp.get_suffixes(). Usually the suffixes are searched in the following order: ".so", "module.so", ".py", ".pyc". Directories don't explicitly occur in this list, but precede all entries in it.) A Proposal For Installing Packages In order for a Python program to use a package, the package must be findable by the import statement. In other words, the package must be a subdirectory of a directory that is on sys.path. Traditionally, the easiest way to ensure that a package was on sys.path was to either install it in the standard library or to have users extend sys.path by setting their $PYTHONPATH shell environment variable. In practice, both solutions quickly cause chaos. Dedicated Directories In Python 1.5, a convention has been established that should prevent chaos, by giving the system administrator more control. First of all, two extra directories are added to the end of the default search path (four if the install prefix and exec_prefix differ). These are relative to the install prefix (which defaults to /usr/local): - $prefix/lib/python1.5/site-packages - $prefix/lib/site-python The site-packages directory can be used for packages that are likely to depend on the Python version (e.g. package containing shared libraries or using new features). The site-python directory is used for backward compatibility with Python 1.4 and for pure Python packages or modules that are not sensitive to the Python version used. Recommended use of these directories is to place each package in a subdirectory of its own in either the site-packages or the site-python directory. The subdirectory should be the package name, which should be acceptable as a Python identifier. Then, any Python program can import modules in the package by giving their full name. For example, the Sound package used in the example could be installed in the directory $prefix/lib/python1.5/site-packages/Sound to enable imports statements like import Sound.Effects.echo). Adding a Level of Indirection Some sites wish to install their packages in other places, but still wish them to to be importable by all Python programs run by all their users. This can be accomplished by two different means: - Symbolic Links - If the package is structured for dotted-name import, place a symbolic link to its top-level directory in the site-packages or site-python directory. The name of the symbolic link should be the package name; for example, the Sound package could have a symbolic link $prefix/lib/python1.5/site-packages/Sound pointing to /usr/home/soundguru/lib/Sound-1.1/src. - Path Configuration Files - If the package really requires adding one or more directories on sys.path (e.g. because it has not yet been structured to support dotted-name import), a "path configuration file" named package.pth can be placed in either the site-python or site-packages directory. Each line in this file (except for comments and blank lines) is considered to contain a directory name which is appended to sys.path. Relative pathnames are allowed and interpreted relative to the directory containing the .pth file. The .pth files are read in alphabetic order, with case sensitivity the same as the local file system. This means that if you find the irresistable urge to play games with the order in which directories are searched, at least you can do it in a predictable way. (This is not the same as an endorsement. A typical installation should have no or very few .pth files or something is wrong, and if you need to play with the search order, something is very wrong. Nevertheless, sometimes the need arises, and this is how you can do it of you must.) Notes for Mac and Windows Platforms On Mac and Windows, the conventions are slightly different. The conventional directory for package installation on these platforms is the root (or a subdirectory) of the Python installation directory, which is specific to the installed Python version. This is also the (only) directory searched for path configuration files (*.pth). Subdirectories of the Standard Library Directory Since any subdirectory of a directory on sys.path is now implicitly usable as a package, one could easily be confused about whether these are intended as such. For example, assume there's a subdirectory called tkinter containing a module Tkinter.py. Should one write import Tkinter or import tkinter.Tkinter? If the tkinter subdirectory os on the path, both will work, but that's creating unnecessary confusion. I have established a simple naming convention that should remove this confusion: non-package directories must have a hyphen in their name. In particular, all platform-specific subdirectories (sunos5, win, mac, etc.) have been renamed to a name with the prefix "plat-". The subdirectories specific to optional Python components that haven't been converted to packages yet have been renamed to a name with the prefix "lib-". The dos_8x3 sundirectory has been renamed to dos-8x3. The following tables gives all renamed directories: Note that the test subdirectory is not renamed. It is now a package. To invoke it, use a statement like import test.autotest. Other StuffXXX I haven't had the time to write up discussions of the following items yet: Changes From ni The following features of ni have not been duplicated exactly. Ignore this section unless you are currently using the ni module and wish to migrate to the built-in package support. Dropped __domain__ By default, when a submodule of package A.B.C imports a module X, ni would search for A.B.C.X, A.B.X, A.X and X, in that order. This was defined by the __domain__ variable in the package which could be set to a list of package names to be searched. This feature is dropped in the built-in package support. Instead, the search always looks for A.B.C.X first and then for X. (This a reversal to the "two scope" approach that is used successfully for namespace resolution elsewhere in Python.) Dropped __ Using ni, packages could use explicit "relative" module names using the special name "__" (two underscores). For example, modules in package A.B.C can refer to modules defined in package A.B.K via names of the form __.__.K.module. This feature has been dropped because of its limited use and poor readability. Incompatible Semantics For __init__ Using ni, the __init__.py file inside a package (if present) would be imported as a standard submodule of the package. The built-in package support instead loads the __init__.py file in the package's namespace. This means that if __init__.py in package A defines a name x, if can be referred to as A.x without further effort. Using ni, the __init__.py would have to contain an assignment of the form __.x = x to get the same effect. Also, the new package support requires that an __init__ module is present; under ni, it was optional. This is a change introduced in Python 1.5b1; it is designed to avoid directories with common names, like "string", to unintentionally hide valid modules that occur later on the module search path. Packages that wish to be backwards compatible with ni can test whether the special variable __ exists, e.g.: # Define a function to be visible at the package level def f(...): ... try: __ except NameError: # new built-in package support pass else: # backwards compatibility for ni __.f = f
https://www.python.org/doc/essays/packages/
CC-MAIN-2016-18
refinedweb
2,920
57.57
Row Level Security using VPD and ADF By Sandra Muller on Nov 05, 2007 Suppose you have an ADF web application, and you want multiple users to look at the same database table, but to make certain rows invisible for some users. Also, you might want the possibility to have some of the visible rows (but not all) be read-only, depending on the user. In this blog post, I will explain how we used VPD with JHeadstart and ADF Business Components in my latest project to get such row level security in our web application. What is VPD?VPD or Virtual Private Database is a feature of the Enterprise Edition of the Oracle Database. It is also known as Fine-Grained Access Control (FGAC), and some call it Row Level Security (RLS). The database package used for VPD is called DBMS_RLS. The main functionality of VPD is to automatically add extra where clauses to SQL statements. Depending on how you defined your VPD policies, it can be applied to select, update, insert, and/or delete statements of specific tables. Quote from Lonneke Dikman's article Implementing Row-Level Security in (TopLink) Java Applications: The database dynamically alters the query [or DML statements] based on the security policy and session context. [...] Security policies can be created using stored procedures. Such policies restrict access by using the content of application data stored in Oracle Database or context variables, such as user name or IP address. Oracle Label Security (OLS), an Enterprise Edition option, is an implementation of VPD. Using OLS, administrators can create policies without writing PL/SQL. Access to data is mediated based on four factors: Label of the row, Label of the user session, Policy privileges of the session,Policy enforcement options for the table. To make the VPD policies user / role specific, VPD must know which end user is currently accessing the database. This might seem trivial, but it isn't if you want to use connection pools in the application server. If you want to use Oracle Label Security (OLS) and you can use Oracle Internet Directory to identify the users, you might be interested in the article How to integrate Oracle Label Security with Oracle Internet Directory, which describes how to take the users and the OLS policies from OID. In other cases, you have more flexibility if you use generic VPD in the database with the Global Application Context feature. The Global Application Context FeatureTo apply this technique you define a global context object in the database, which is like a namespace that has key/value pairs. The only way to set a context is through the PL/SQL package that is bound to that context, for example MY_VPD_CONTEXT_PCK. This method is also explained in the abovementioned article by Arup Nanda and in Pete Finnigan's article Oracle Row Level Security: Part 1. Only Authorized IP AddressesTo ensure that the end user name is only set in the database context when that user has successfully logged in to the web application, you can add security checks to procedure that sets the context. A simple but effective check is to verify that the call comes from an authorized IP-address like the application server. It relies on the fact that by other means you will have made sure that no unauthorized persons can execute database calls from the application server. This security check is also described in the abovementioned article by Pete Finnigan. Here is the example code to perform such an IP address check: the function IS_AUTHORIZED_IP_ADDRESS in package MY_VPD_CONTEXT_PCK returns true if the current IP address occurs in a table of authorized IP addresses. You can use this function just before setting the context. In addition you could create an AFTER DATABASE LOGON trigger in which you use the same function to ensure that only authorized IP addresses can log on as the APPUSER. In the interests of security the MY_VPD_CONTEXT_PCK package, and the MY_AUTHORIZED_IP_ADDRESSES table should not be owned by the APPUSER schema. Instead you can create an APPOWNER schema to which you cannot connect, which owns all application database objects, and only grants privileges that are needed by the web application to the APPUSER schema, for example grant execute on MY_VPD_CONTEXT_PCK. The APPUSER should certainly not be able to modify the MY_AUTHORIZED_IP_ADDRESSES table. The Set Context ProcedureNow, we can add a procedure SET_CONTEXT to the package MY_VPD_CONTEXT_PCK, that first checks the IP address and then puts the user name in the context, so that they are available for use in VPD policies. Note 1 This procedure also sets the Client Identifier. This is a kind of session attribute that is used in Fine Grained Auditing, to audit who has done what. Of course we want to know the end user name in the auditing trails, and not the APPUSER schema name. Note 2 The SET_CONTEXT procedure uses a global package variable g_database_user that is initialised with the value of the current database user: in our example that would be 'APPUSER'. This value is used to identify the key/value pairs in the context object. Note 3 In this example one key/value pair are placed in the context: username. Of course you could also pass other parameters to the procedure and store them also as key/value pairs. You could also maintain a cache for frequently used information in the VPD policies, depending on the passed parameters. Setting the Context from ADF BCTo ensure that the ADF web application sets the context correctly, the context must be set each time a different end user uses a database connection. When you use a pool of database connections, you can never be sure that the next request in a session will use the same database connection as the previous request. In ADF Business Components, the prepareSession() method gets invoked by the application module when it is used for the first time by a new user session (see the ADF Developer's Guide for Forms/4GL Developers: 8.6.3 How to Override prepareSession() to Set Up an Application Module for a New User Session). So that's the ideal method to override in your custom application module class to set the VPD context. If you let the application server manage your users in the J2EE container, you can implement prepareSession() like this (see also Implement JAAS based Authentication and Authorization for ADF Faces applications on OC4J 10.1.3 by Lucas Jellema): Note that in this example we assume that SET_CONTEXT has only one parameter: the username. If you manage the application users in the ADF application itself, then you of course derive the username in some other way. In my latest project we found out that setting the VPD context just in prepareSession() was not enough. We had implemented a custom authentication in a servlet filter (using the AuthenticationFilter class supplied in the JHeadstart Runtime library). If the AuthenticationFilter determines that the user has logged in and is not in the process of logging out, it loops over all active data controls and if they are of type JhsApplicationModule it calls setUser() on each application module. If you use JHeadstart you have this JHeadstart superclass in all your Application Modules. To make sure that each active Application Module sets the correct VPD context, even in case of web time outs or deep links, we have overridden the JHeadstart setUser() method and added a call to setVPDcontext() (see the above code example). Making Rows InvisibleAfter doing all these preparations, to get Row Level Read Security all you need to do is add select policies on your tables. For instructions how to apply such policies, see the Oracle By Example tutorial Restricting Data Access Using Virtual Private Database. Only instead of calling sys_context('userenv','session_user'), you need to call a function in MY_VPD_CONTEXT_PCK that returns sys_context(g_database_user, 'USERNAME'). Depending on the policy, this will ensure that user A might see different rows than user B when the web application performs a certain database query. If certain role information is needed often during the execution of the VPD policies, it is advisable to cache as much as you can, because VPD can have a serious impact on performance. Of course you must test carefully that the cache always contains the correct information. Making Rows Read OnlyThe next step is to add Row Level Update Security to the application. This is more tricky, because we not only want to prevent certain users from updating certain rows (by showing an error message if they try), we also want to make the rows read-only in the screens (so that they won't even be able to try it). So we want to be able to use some boolean JSF expression to apply to the readOnly property of the JSF / ADF Faces components in our user interface. Furthermore, this expression must be row specific; for each row there could be a different return value. We implemented this row-level boolean JSF expression using a special IsUpdateable attribute in the ADF BC View Objects. You could make this a transient attribute and code the logic in the getIsUpdateable() method of the ViewRowImpl class, but that get method would be executed each time the attribute is used in an expression, each time the page is displayed or refreshed. We implemented it as a calculated attribute instead, which means the calculation is only executed when the View Object's select-statement is executed in the database. This normally happens only once per user session, unless an explicit "Execute Query" is programmed for the View Object. For more information how calculated attribute values are cached, see the ADF Developer's Guide for Forms/4GL Developers, section 7.7 Understanding How View Objects and Entity Objects Cooperate at Runtime. The calculated attribute is implemented by calling a database function specific for the table. For example: if we have an Orders table, and we want some Orders to be read-only to certain users, we would add a calculated attribute IsUpdateable to the Orders View Object. In the select-clause we would call a database function MY_UPDATEABLE_PCK.IS_ORDER_UPDATEABLE(p_ord_id number). We pass in the primary key of the row (the order id), and return a string 'TRUE' or 'FALSE'. Then in the JSF pages, you can add the following expression to the readOnly property of each relevant UI component: readOnly="#{!bindings.IsUpdateable!='FALSE'}" or, in case of a table layout, readOnly="#{!row.IsUpdateable!='FALSE'}". Now you might argue, why this triple denial? Why not simply use something like #{bindings.IsReadOnly=='TRUE'}? Well, there are two reasons: - When generating these pages using JHeadstart, the appropriate place to put this expression is the Update Allowed EL Expression property. To allow for easy-to-read expressions in this property, we prefer to write bindings.IsUpdateable instead of bindings.IsReadOnly. A side effect of using JHeadstart's Insert/Update/Delete allowed expressions is that the New and Save buttons will also be made invisible when they do not apply. - When we used bindings.IsUpdateable=='TRUE', we found out that just after inserting a new row, that row would become read-only, even though it was supposed to be updateable. That's because calculated attributes are only refreshed when re-querying the database. So to make sure that in case the value is unknown (like it is just after insert), the row will be updateable, we use !='FALSE' instead of =='TRUE'. Thank you for this great article. What do you think of the following small improvement. I have a calculated attribute names 'IsRowUpdatable' which is defined on the EO or VO. Let's say it's defined on the EO with 'Selected in Query' option checked which contains a call to a function in a package : AXI_SECURITY.ISROWUPDATABLE(DEPARTMENT_ID). Then on the EO class I override the isAttributeUpdateable methode with the following code : With that in place, you have nothing to do left in the view layer. Posted by S�bastien POUILLET on November 05, 2007 at 01:50 PM PST # That is a great idea, thank you for this suggestion! You are then enforcing the rule in the Business Components instead of the View layer, which has the added advantage that it applies to any page/VO that uses the same EO. I think it could even be used if you have combined the IsUpdateable expression with other conditions in the JHeadstart insert/update allowed properties. Have you tried that? I do wonder if this still allows you to calculate the updateability for each row separately. Is the built-in method isAttributeUpdateable re-calculated for every row? Have you tried if you can use this technique in a table layout and have some rows read-only while others are updateable? kind regards, Sandra Posted by Sandra Muller on November 12, 2007 at 03:53 AM PST # The updateability is recalculated for each row. To prove that I wrote a simple app that does not use VPD but instead allows to mark a row as read only depending on the value of the primary key. This sample was written on the HR DEPARTMENT TABLE. Here is my function in the DB : And my IsRowUpdatable attribute is defined with the following expression : AXI_SECURITY.ISROWUPDATABLE(DEPARTMENT_ID) I then build a ADF Faces table on top of this and the rows with id 103,104,405 were in read only, others were updatable. Next step for me is to integrate VPD but it should behaves the same. Seb. Posted by S�bastien POUILLET on November 12, 2007 at 08:08 AM PST # That sounds good! It would definitely be an improvement from an architectural point of view. Thanks again, Sandra Posted by Sandra Muller on November 12, 2007 at 06:23 PM PST # Posted by Ibrahim Ajubi on January 22, 2008 at 10:50 PM PST # Thank you for your feedback. Of your 3 questions, the appropriate place for the first and the last is the JHeadstart discussion forum at . Can you please post them there? Regarding your second question: You can continue to use the setUser() method, it shouldn't have been deprecated. kind regards, Posted by Sandra Muller on January 29, 2008 at 01:47 AM PST # Thank you for post. Very helpful as starting with ADF and VPD. Posted by Ivan Budzel on September 13, 2012 at 06:10 AM PDT # Worked for me. Absolutely Excellent Explanation!!! Posted by Bilal on January 19, 2013 at 11:35 PM PST #
https://blogs.oracle.com/jheadstart/entry/row_level_security_using_vpd_a
CC-MAIN-2015-35
refinedweb
2,419
51.07
During a fine breakfast at Global Summit 2016 I was asked about the %DEFAULTDB database that now appears when creating the %ALL namespace. Until the documentation on "Mapping a Package Across Multiple Namespaces" is updated to include the use of subscript level mapping for all namespaces here is a brief explanation for this change in 2016.1: When creating a global subscript level mapping in the %ALL namespace the database that was used for the non-subscripted global could not be set to be the default database for each namespace. This behavior prevents using %ALL namespace to help manage subscript level mappings that are configured on all namespaces. Now in 2016.1.0 one enters %DEFAULTDB as the destination. For example ^james("doc") mapped to COMMON database and ^james mapped to %DEFAULTDB means data in ^james("doc") will come from the COMMON database when in any namespace but all other ^james data will be stored in the default global database for a namespace. Thanks to John Murray for the question. Thanks to James for a prompt and detailed reply to my breakfast table question. Here I'm going to add this link to a previous posting of mine about %ALL, in part to highlight that %ALL mappings don't apply to 100% of the namespaces you have. The DOCBOOK and SAMPLES namespaces are apparently exempt. I can rationalize the DOCBOOK extension to myself, but the SAMPLES one puzzles me, especially given that the ENSDEMO namespace of an Ensemble or HealthShare instance is not exempt even though it's effectively another "samples" namespace. On the other hand: if we would deal with SAMPLES and ENSDEMO similarly, and %ALL mapping would work in SAMPLES the same way as for others, then leaving DOCBOOK alone would not make much sense :) I'd prefer %ALL to work everywhere, without exceptions, that would significantly simiplify global mapping creation in some package manager you may be aware of. I'd prefer not to use %ALL at all for a couple of reasons: - if the mapping is created programmatically, it is not a problem to create it for each namespace, - if it's created manually, one day you may forget about it and loose some important data or some other usefull things stored in non-default DB for years... of course, all this stuff should be documented and re-checked, but for me it is easier to do it once (for my nsp mappings) than twice (for my and for %ALL).
https://community.intersystems.com/post/explanation-defaultdb-database-201610
CC-MAIN-2019-39
refinedweb
414
52.83
Hi, I'm getting this error with Pycharm with try to run a Odoo project. Traceback (most recent call last): File "/opt/odoo/odoo/setup/odoo", line 8, in <module> odoo.cli.main() AttributeError: module 'odoo' has no attribute 'cli' I'd like what is the problem or it's a problem with a package or something like that. I'm working with Oddo v 11 and Python 3,6 This is the file "odoo" #!/usr/bin/env python3 # set server timezone in UTC before time module imported __import__('os').environ['TZ'] = 'UTC' import odoo if __name__ == "__main__": odoo.cli.main() Hello, I am wondering if the code can be executed in a system terminal (out of PyCharm) with the same intepreter?
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360007616740-Problem-with-Pycharm-AttributeError-module-odoo-has-no-attribute-cli-
CC-MAIN-2022-27
refinedweb
122
73.27
#include <sys/pccard.h> int32_t csx_SetEventMask(client_handle_t ch, sockevent_t *se); int32_t csx_GetEventMask(client_handle_t ch, sockevent_t *se); Solaris DDI Specific (Solaris DDI) Client handle returned from csx_RegisterClient(9F). Pointer to a sockevent_t structure The function csx_SetEventMask() sets the client or global event mask for the client. The function csx_GetEventMask() returns the client or global event mask for the client. csx_RequestSocketMask(9F) must be called before calling csx_SetEventMask() for the client event mask for this socket. The structure members of sockevent_t are: uint32_t uint32_t /* attribute flags for call */ uint32_t EventMask; /* event mask to set or return */ uint32_t Socket; /* socket number if necessary */ The fields are defined as follows: This is a bit-mapped field that identifies the type of event mask to be returned. The field is defined as follows: Client's global event mask. If set, the client's global event mask is returned. Client's local event mask. If set, the client's local event mask is returned. This field is bit-mapped. Card Services performs event notification based on this field. See csx_event_handler(9E) for valid event definitions and for additional information about handling events. Not used in Solaris, but for portability with other Card Services implementations, it should be set to the logical socket number. Successful operation. Client handle is invalid. csx_RequestSocketMask(9F) not called for CONF_EVENT_MASK_CLIENT. No PCMCIA hardware installed. These functions may be called from user or kernel context. csx_event_handler(9E), csx_RegisterClient(9F), csx_ReleaseSocketMask(9F), csx_RequestSocketMask(9F) PC Card 95 Standard, PCMCIA/JEIDA
https://docs.oracle.com/cd/E36784_01/html/E36886/csx-geteventmask-9f.html
CC-MAIN-2018-09
refinedweb
247
58.58
Configuring remote_write with a Prometheus ConfigMap In this guide you’ll learn how to configure Prometheus to ship scraped samples to Grafana Cloud using Prometheus’s remote_write feature. This guide assumes you have Prometheus installed and running in your cluster, configured using a Kubernetes ConfigMap. To configure a Prometheus Operator, kube-prometheus, or Helm installation of Prometheus, please see the relevant guide from Configuring Prometheus remote_write for Kubernetes deployments. Prerequisites Before you begin, you should have the following available to you: - A Kubernetes >=1.16.0cluster. - A Grafana Cloud Standard account. To learn how to create an account, please see Grafana Cloud Quickstarts. - A Grafana Cloud API key with the MetricsPublisherrole. To learn how to create a Grafana Cloud API key, please see Create a Grafana Cloud API key. - The kubectlcommand-line tool installed on your local machine and configured to connect to your cluster. You can read more about installing kubectlin the official documentation. - The Prometheus monitoring system installed and running in your cluster as a Deployment, configured using a ConfigMap. Installing Prometheus goes beyond the scope of this guide, but to learn how to install Prometheus Operator in your cluster, please see the Installing Prometheus Operator with Grafana Cloud for Kubernetes quickstart guide. Prometheus Operator abstracts away much of Prometheus’s configuration and management overhead. Step 1. Modify Prometheus ConfigMap Begin by locating your Grafana Cloud Metrics username and password.. Once you’ve noted your username and password, inject it into your Prometheus configuration file by modifying the Kubernetes ConfigMap resource containing Prometheus’s configuration. Unfortunately Prometheus does not support pulling environment variables from the execution environment so we can’t readily use a Kubernetes Secret object in this case. A safer, more elegant solution using Secrets or envsubst goes beyond the scope of this guide. Locate the ConfigMap manifest and open it in your favorite editor. It should look something like the following: apiVersion: v1 kind: ConfigMap metadata: name: prometheus namespace: monitoring data: prometheus.yml: |- global: scrape_interval: 5s evaluation_interval: 5s rule_files: - /etc/prometheus/prometheus.rules alerting: alertmanagers: - scheme: http static_configs: - targets: - "alertmanager.monitoring.svc:9093" . . . This ConfigMap is installed in the monitoring Namespace, where the Prometheus Deployment should also be running. Modify this ConfigMap by adding the following remote_write configuration block: apiVersion: v1 kind: ConfigMap metadata: name: prometheus_v2 namespace: monitoring data: prometheus.yml: |- global: scrape_interval: 5s evaluation_interval: 5s . . . remote_write: - url: <Your Metrics instance remote_write endpoint> basic_auth: username: <your_grafana_cloud_metrics_username> password: <your_grafana_cloud_metrics_password> You can find the /api/prom/push URL, username, and password for your metrics endpoint by clicking on Details in the Prometheus card of the Cloud Portal. This block creates a default remote_write configuration that ships samples to the Cloud Metrics Prometheus endpoint. It also sets the authorization header on remote_write requests with your Grafana Cloud credentials. To tune the default remote_write parameters, please see Remote Write Tuning from the Prometheus documentation. Be sure to give the ConfigMap a new versioned name as well, by appending a suffix like _v2. When you’re done, save and close the file. In the next step you’ll roll out this updated configuration into your cluster. Step 2. Update running Prometheus Deployment To roll out your configuration changes, update the Prometheus Deployment with the new versioned ConfigMap. You can roll out configuration changes in Kubernetes clusters in many different ways. The steps in this guide focus on configuring remote_write and are not meant to cover blue-green or production Prometheus rollout scenarios. Given that in the previous step you assigned the ConfigMap a new name, when you update the ConfigMap reference in the Deployment, Kubernetes will redeploy any Pods using the old ConfigMap. Open the Prometheus Deployment in a text editor. You should see something like the following: apiVersion: apps/v1 kind: Deployment metadata: name: prometheus-deployment labels: app: prometheus spec: replicas: 2 selector: . . . template: metadata: labels: app: prometheus . . . spec: containers: - name: prometheus image: prometheus ports: - containerPort: 9090 volumeMounts: - name: config-volume mountPath: /etc/prometheus/ volumes: - name: config-volume configMap: name: prometheus This file may vary depending on how you configured and deployed Prometheus. The above manifest defines a 2-Pod Prometheus Deployment that references a ConfigMap called prometheus. The prometheus.yml key containing Prometheus’s configuration is mounted to /etc/prometheus/prometheus.yml. To update this Deployment, change the ConfigMap: . . . volumes: - name: config-volume configMap: name: prometheus_v2 We update the configMap’s name field from prometheus to prometheus_v2 to reference the new ConfigMap defined in the previous step. When you’re done, save and close the file. Roll out the changes using kubectl apply -f: kubectl apply -f <your_prometheus_deployment_manifest>.yaml Step 3. Check your work At this point, you’ve configured Prometheus to remote_write scraped metrics to Grafana Cloud. You can verify that your running Prometheus instance is remote_writing correctly using port-forward. First, get the Prometheus server Service name: kubectl get svc Next, use port-forward to forward a local port to the Prometheus Service: kubectl --namespace monitoring port-forward svc/<prometheus-service-name> 9090:80 Replace monitoring with the appropriate namespace, and <prometheus-service-name> with the name of the Prometheus service. Navigate to in your browser, and then Status and Configuration. Verify that the remote_write block you created above has propagated to your running Prometheus instance configuration..
https://grafana.com/docs/grafana-cloud/metrics-kubernetes/remote_write_prometheus/
CC-MAIN-2021-43
refinedweb
871
55.13
Automatic time using DS3231 RTC Module with Arduino UNO. Also, a servo motor is used to rotate the containers to provide the food and 4*4 matrix keypad to manually set up the time for feeding the Pet. You can set the rotation angle and container opening duration according to the quantity of food you want to serve to your pet. The quantity of food may also depend upon your pet whether it’s a dog, cat or bird. Material Required - Arduino UNO - 4*4 Matrix Keypad - 16*2 LCD - Push Button - Servo Motor - Resistor - Connecting Wires - Breadboard Circuit Diagram In this Arduino based Cat Feeder, for Getting Time and Date, we have used RTC (Real Time Clock) Module. We have used the 4*4 Matrix Keypad to set the Pet’s eating time manually with the help of 16×2 LCD. The Servo motor rotates the container and drop the food on the time set by the user. The LCD is used for displaying the Date and Time. Complete working can be found in the Video given at the end. 3D-Printed Pet Feeder Model We have designed this Arduino Pet Feeder container using the 3D-printer. You can also print the same design by downloading the files from here. The material used for printing this model is PLA. It has four Parts as shown in the image below: Assemble the four parts and connect the Servo Motor as shown in the picture below: If you are new to 3D printing here is the starting guide. You can download the STL files for this pet feeder here. DS3231 RTC Module DS3231 is a RTC (Real Time Clock) module. It is used to maintain the date and time for most of the Electronics projects. This module has its own coin cell power supply using which it maintains the date and time even when the main power is removed or the MCU has gone through a hard reset. So once we set the date and time in this module it will keep track of it always. In our circuit, we are using DS3231 to feed the pet according to the time, set up by the Pet’s owner, like an alarm. As, clock reaches to the set time, it operates the servo motor to open the container gate and the food drops in the Pet’s food bowl. Note: When using this module for the first time you have to set the date and time. You can also use RTC IC DS1307 for reading the time with Arduino. Code and Explanation Automatics Pet Feeder’s Complete Arduino Code is given at the end. Arduino have default libraries for using the Servo motor and LCD 16*2 with it. But for using DS3231 RTC Module and 4*4 Matrix Keypad with the Arduino, you have to download and install the libraries. The download link for both the libraries is given below: In the below code, we are defining libraries, “#include <DS3231.h>” for RTC module, “#include <Servo.h>” for Servo Motor, “#include <LiquidCrystal.h>” for 16*2 LCD, and “#include <Keypad.h>” for 4*4 Matrix Keypad. #include <DS3231.h> #include <Servo.h> #include <LiquidCrystal.h> #include <Keypad.h> In the below code, we are defining the keymap for the 4*4 matrix keypad and assigning the Arduino pins for the Row and Columns of keypad. char keys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = { 2, 3, 4, 5 }; byte colPins[COLS] = { 6, 7, 8, 9 }; Here, we are creating the keypad by using the command below in the code. Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); Assigning A4 and A5 Arduino pins to connect with SCL and SDA pins of DS3231. Also, assigning pins to the LCD and initializing the Servo motor. Read more: Automatic Pet Feeder using Arduino This Post / Project can also be found using search terms: - how to open a container using servo motor - makerpro automatic pet feeder using arduino - pet feeder aurduino lcd rtc keyoard 4*4 - arduino automatic pet feeder
https://duino4projects.com/automatic-pet-feeder-using-arduino/
CC-MAIN-2020-16
refinedweb
688
71.14
Each Answer to this Q is separated by one/two green lines. I am using Python email and smtplib to send an email from Python. I am doing this via the Gmail SMTP server using my Gmail credentials. This works fine, however I would like to specify a Reply-to email address different from the from address, so that replies go to a separate address (non-Gmail.) I have tried creating a reply to parameter like this: msg = MIMEMultipart() msg['From'] = "[email protected]" msg['To'] = to msg['Subject'] = subject msg['Reply-to'] = "[email protected]" But this doesn’t work. Can’t find any info on this in the Python docs. Thanks. Here’s my take on it. I believe that the “Reply-To” header should be set explicitly. The likely reason is that it’s less commonly used than headers such as “Subject”, “To”, and “From”. python Python 2.6.6 (r266:84292, May 10 2011, 11:07:28) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>>>>>>>>> import smtplib >>> import email.mime.multipart >>> msg = email.mime.multipart.MIMEMultipart() >>> msg['to'] = TO_ADDRESS >>> msg['from'] = FROM_ADDRESS >>> msg['subject'] = 'testing reply-to header' >>> msg.add_header('reply-to', REPLY_TO_ADDRESS) >>> server = smtplib.SMTP(MAIL_SERVER) >>> server.sendmail(msg['from'], [msg['to']], msg.as_string()) {} I had the same question and all I had to do to make it work was to set the header in lowercase like so: msg['reply-to'] = "[email protected]" For Python3 in 2021 I would recommend the following to construct the message: from email.message import EmailMessage from email.utils import formataddr msg = EmailMessage() msg['Subject'] = "Message Subject" msg['From'] = formataddr(("Sender's Name", "[email protected]")) msg['Reply-To'] = formataddr(("Name of Reply2", "[email protected]")) msg['To'] = formataddr(("John Smith", "[email protected]")) msg.set_content("""\ <html> <head></head> <body> <p>A simple test email</p> </body> </html> """, subtype="html") Then to send the message I use the following for my mail server which uses StartTLS on port 587: from smtplib import SMTP from ssl import create_default_context as context with SMTP('smtp.domain.com', 587) as server: server.starttls(context=context()) server.login('[email protected]', password) server.send_message(msg) As Jonathon Reinhart pointed out, the “To” needs to be upper case: msg['Reply-To'] = "[email protected]" Only this worked for me: msg['In-Reply-To'] = "[email protected]" Look here: [Reply to email using python 3.4] by urban 1
https://techstalking.com/programming/python/setting-different-reply-to-message-in-python-email-smtplib/
CC-MAIN-2022-40
refinedweb
407
50.02
Thanks! What I have done in the mean time is simply clone code from two classes, AbstractSAXEventGenerator and the class that extends it and, from that, written my own exporter that works fine! I don't have the results in front of me, and perhaps I should try another export just to prove it again (in case some code changed recently), but, the general form of an export I did looks like this: <node ...> <property...> </property> <property...> </property> <node...> ... I did not see any </node> But, I will say this: I only hand cleaned up the first half dozen nodes in a fairly large export. Exports come without any line breaks for prettyprinting, so it's quite a chore to turn the file into a "prettyprint" appearance to see the missing </node> I should point out that I remain most pleased with jackrabbit! Thanks Jack Stefan Guggisberg wrote: > On 8/6/06, Jack Park <jack.park@sri.com> wrote: >> What might be the objections raised to turning this abstract class into >> a public one (in future distributions) for purposes of allowing others >> to write exporters in jackrabbit applications that have different >> behaviors? That would be done by externally extending this class. (I >> realize that, as a default, one can simply duplicate the code in this >> class externally). > > AbstractSAXEventGenerator is a core class. i try to avoid making internal > jackrabbit classes public in order to discourage their use from > outside of the > core package. core classes should not be externally referenced as they > might > change at any time and without notice. > > if AbstractSAXEventGenerator is reasonably generic and without > dependencies on the core we could consider moving it to a 'util' > package. feel free to file an 'enhancement' issue. > >> >> As a for instance, I would prefer to be able to just export an arbitrary >> node (perhaps there is a way, but I haven't found it), and I'd prefer to >> have the namespace declarations not go with the first node exported, but >> instead, go with a set of declarations outside nodes. >> And, I wouldn't mind a closing </node> tag (not available in an svn >> build from a month ago, possibly changed lately?) > > i seriously doubt that the exported xml is not wellformed. please > create a > jira issue if you can proof me wrong. > > cheers > stefan > >> >> Thanks. >> Jack >>
http://mail-archives.apache.org/mod_mbox/jackrabbit-dev/200608.mbox/%3C44D74B91.9020604@sri.com%3E
CC-MAIN-2016-30
refinedweb
387
58.72
This Week in SCIENCE, Volume 327, Issue 5967, Food Security dated February 12 2010, is now available at: Standing High (requires free registration to view). … Sea-level rises and falls as Earth’s giant ice sheets shrink and grow. It has been thought that sea level around 81,000 years ago—well into the last glacial period—was 15 to 20 meters below that of today and, thus, that the ice sheets were more extensive. Dorale et al. (p. 860; see the Perspective by Edwards) now challenge. … ,). ============ h/t to WUWT reader David Hagen 141 thoughts on “New Paper in Science: Sea level 81,000 years ago was 1 meter higher while CO2 was lower” Hopefully the less ideological pro-AGW’s will; be looking at this sort of excellent research based on the real world, and will be thinking a lot about their position. I know it is nothing new, but Science, as a journal, has been right up there with Nature in blocking this type of thing. Have they finally found some integrity? And some say you don’t have real science here! Think again. This just shows that the environment responds the way it does regardless if we are on it or not. This means the glacial/inter-glacial temperature and CO2 reconstructions from ice cores are completely wrong. The reconstructions say it was 2C to 4C colder than present. Cue the, “Well just think of how bad things would have been IF CO2 had been elevated” spin. Either sea level was a meter higher OR the land level at the location of measurement was 1 meter lower. Sea level at that distance into the past is all relative to the land surface, and means absolutely nothing. REPLY: True, but they have a section in the complete paper where they ruled out isotasy issues. – Anthony Philip_B said; “This means the glacial/inter-glacial temperature and CO2 reconstructions from ice cores are completely wrong.” As a proponent of Becks research I have always believed the ice cores to be wrong as I think the historic co2 readings from the 1830’s onwards are broadly correct. The two measurements are said to be incompatible and therefore ice cores ‘must’ be right. Tonyb Philip_B (15:46:23) : I guess we all know that the CO2 concentration extracted from ice cores are questionable but I am not too sure if the concentration of CO2 in that cave was in equilibrium with that in the atmosphere. My guess is it was in equilibrium with that in the water. Not sure if the water in the cave was at equilibrium with sea water though. Observe how various editors, authors and researchers are beginning to tippy-toe away from their previous AGW position. Who will make it to the door before the big rush? Who’ll be left in the room? And who was behind all the misinformation? Why not Bush and the Jews? Requires some tweaking…but the AGW gang will need some really solid, proven scapegoats to get out of this one. For anyone interested I started playing with Cheifio’s dT/dt data and think I found some interesting tidbits. Cheers, AJStrata Or was Mallorca 1 meter lower? Is Mallorca that tectonically stable? It is at the intersection of two major plates – With the African plate creating enough pressure to build the Alps. The entire Balearic chain is on a fault line. I am simply asking. Given the tectonic activity of the Mediterranean region – I would have to see convincing evidence that this was not due to uplift. I know what the warmers will say: That was proven wrong long ago That was caused by global warming That is not peer reviewed The author is obviously funded by oil companies They use it with just about everything Wierd, a brief melting period maybe?? Well, duh. Being a resident of Florida it always struck me as odd when warmists use the threat of rising sea levels as a consequence if we don’t change our ways, but it was common knowledge growing up that in the recent past (geologically speaking) almost all of the Florida peninsula was under water. I wondered why that was never brought up to refute the rising sea level claim by the warmists. If I am reading the graph correctly, sea level maxima and minima seem to lag insolation maxima and minima by 2,000 to 10,000 years. If so, we might be at or just past the sea level peak of the Holocene interglacial. More evidence that Milankovitch Cycles govern global climate change. Probably a red herring but the Med is land-locked apart from the Straits of Gibraltar, with shallow sills. There is also a salinity density difference between Atlantic and Mediterranean, with complex tides and bores through the straights. It might have variably affected sea level equilibrium with the open oceans in the past. This is no coming around, just an editorial strategy that backfired: I bet these papers were supposed to be drowned by the noise of the Copenhagen accord… hence their publication AFTER copenhagen. However this was without counting with climategate and the failure of COP15 and the renewed scrutiny… It is obvious that since sea level is the datum by which land elevation is determined, an increase in CO2 concentration has caused the earth to rise(?) Anywayz… just a random thought. Interesting read thanks! A meter plus minus is just margin of error. The seas have risen and fallen 100 meters through the ice ages. But what did I miss the last glaciation period started about about 120,000 bp and lasted until 11,000 bp. So how does this fit in the the established time lines? As John Egan states, this is all about tectonics, not climate. Sea levels were definitely ~250 feet lower 80,000 years ago. This has got to give the warmists pause. (Not that they’ll openly admit it.) I wonder how many other findings like this have been suppressed, spun, or soft-pedaled in the past.. Dylan Ratigan Responds To Glenn Beck’s Global Warming Attack With His Own Chalkboard (VIDEO) “This data implies that temperatures were as high as or higher than now”: really? I can see that the data are consistent with its having been as warm or warmer, but I don’t see why they imply that it was. Anyway, the big deal is that it certainly implies that the science isn’t settled. Off topic but worth mentioning. Dallas is about to shatter almost all their snow records. I wonder how the pro-agw crowd will spin this newest record snowfall being that it’s so far south. The articles are grtting more and more desparate… “Most climate scientists respond that the ferocious storms are consistent with forecasts that a heating planet will produce more frequent and more intense weather events.” Here’s another one;. Colbert Rips Fox News For Using Snowstorm To Deny Global Warming (VIDEO) Quote: Alan S (15:34:23) : “I know it is nothing new, but Science, as a journal, has been right up there with Nature in blocking this type of thing. Have they finally found some integrity?” No. Science is running scared. What will happen if decades of filth beneath the climategate iceberg come floating to the surface? The public will see the unholy, international alliance of politicians, publishers, federal research agencies and news media that have been manipulating science as a tool of propaganda to control the people. It is no mere coincidence –- were all distributing the same misinformation. With kind regards, Oliver K. Manuel Emeritus Professor of Nuclear & Space Science Former NASA PI for Apollo o/t carl sagan quotes: “Modern science has been a voyage into the unknown, with a lesson in humility waiting at every stop. Many passengers would rather have stayed home.” “Extraordinary claims require extraordinary evidence” Where is the humility, or the evidence. Slightly OT but over at AMSU-A sea surface temps are showing a sharp rise over the last week or so of about 1/4 of a degree. That would equate to about 1.5 watts/m2 additional energy being radiated from 3/4 of the earth’s surface. Near surface channel? down. 14,000 ft channel? down. 25,000 ft channel? down. 36,000 ft channel? down. What? did the CO2 take the week off? Extra energy is coming out of the ocean surface and (gasp!) not even taking a pee break on its way to outer space? Seriously is there a way to graph the channels versus each other instead of a given channel against the previous year? One week does not a dataset make. I’ve contacted the SMH Online dept and The Sydney Morning Herald will be streaming the Monckton/Lambert debate live at 12.30 Sydney time. You can see it on their main page it will appear in the main picture top left currently joyce/abbott. for overseas viewers you can sync your time here. Sorry. Not possible. They didn’t have SCUBA gear 81,000 years ago. So the cabinet of the government of Tuvalu could not have conducted any meetings, now could they have? / sarcasm OT The Monckton – Lambert AGW debate in Sydney is starting right now. You can watch it LIVE at You don’t have to go back 81,000 years to see sea level changes occur sans benefit of SUVs and heavy industry. Well it seems obvious that a non light speed capable interstellar craft topped off it’s tanks about 18,000 years ago for the next leg of it’s voyage – there wasn’t anyone that would complain about it here at the time. So they sucked up 3 feet of water off the earth’s oceans for fuel – the missing three feet of ocean is explained without freezing anything and the lack of CO2 doesn’t matter. The question really is “how far could one travel with that much water/mass at sub light speed?” (While they were here they built Nazca lines, pyramids, lost temples and the Sphinx to keep the crew’s morale up). Also you will notice, I did not have to resort to chart’s, graphs, math or any other old fashioned methods to prove my statement. I bet I could sell a few thousand books to Bill Nye’s young people who are open to “new ideas”! I know this strays way off topic but I hope someone will laugh. Here is the Glenn Beck video that set off the MSNBC FOX media opinion war on man-made climate change. The One Thing: 2/10 Well if California coast hasn’t budged an inch, the pics of 50 years on the Lost Coast are the truth of the matter. Nuthin’ going on as far as sea levels rising. Colder ocean cycles mean contraction, so that is what we should expect to be happening. Sorry, Oliver Manuel, but George Bush was the token global warming denier out of the sorry group you list. He took a lot of flak for it. When after several years of thrashings he made some token obeisance to the gods of environmental fascism, he was still treated as a warming denier. Remember: information is the difference that makes a difference. If you try to make everyone equally stupid in the name of political correctness, it removes all the information. Sounds more like the land rose and subsided than the sea level rose that high in the middle of the ice age. The biggest benevolent bank with the little people’s best interest at heart receives major awards. “Winners announced in voluntary carbon markets survey London, 11 February: US investment bank JP Morgan has won three out of eight categories in Environmental Finance’s survey of the voluntary carbon markets. The bank and its recent acquisitions, EcoSecurities and ClimateCare, were voted respectively Best Trading Company, Best Project Developer and Best Offset Retailer by the readers of Environmental Finance magazine.” The international banksters own everything. Now they want to completely own you. Hats off to Miskolczi and Sorokhtin and al. I’ve been studying this stuff for several years, trying to get a handle on all the standard CO2/GW theories, including the handwaving about back radiation and the various pretty pictures of heat flow in the atmosphere. None of it really made any sense when water is the most important greenhouse gas by far and readily available in such huge quantities. Coming up with the idea that CO2 absorbed enough radiation to cause any kind mlultiplier effect seemed totally superfluous. Not having the programming skills or mathematics available it seemed that a simple, overall model, like the one Arrhenius used to start all this, treating water as the major IR absorber would be the simplest and most effective model. Glad somebody has been able to do that. ALL the various AGW models and all the hand-waving at the IPCC looked just like people trying to come up with an explanation in search of a problem. The earth has stayed at a relatively constant temperature for aeons, so all the radiation absorbed has to be re-radiated out. The only real question is how does the atmosphere and oceans work to insulate the heat loss and maintain the higher surface temperature. The upper bound to the atmosphere and the weird assumptions used by Arrhenius and continued to this day just seemed so wrong.? Is this paper any good? It’s wrong to just assume that because it supports your position that it has merit. I’m just a hack but….. How did the study control for the movement of cave wall “up and down”? Admitedly I have not read the study but assuming the cave wall stayed still for 81,000 years is a point that should require considerable evidence. Where I live the seascape has change dramatically in the last 1,000 let alone 81,000. I have to agree with John Egan (16:12:53). Alone this is not strong evidence. From, : . ” Again,: “the present geological architecture of the island is the result of a complex evolution involving extensional processes -occurred from the Neogene to the Quaternary- which are superimposed on the alpine compressive structure. The Upper Miocene carbonate platform of Migjorn [where the critical caves occur] was affected by such extensional tectonic activity and, in this way, the resulting coastal morphology was mostly controlled by recent normal faults which delimit the seaward border of the platform. Furthermore, this extensional post-orogenic activity is responsible for a marked tilting that affects the Migjorn plateau, being depressed towards the south and uplifted when reaching the W and NE ends of the karst area (Fornós et al., 2002b). The differential uplifting left the reefal Tortonian facies outcropping near the sea level at the southernmost part of the island whereas it appears higher than 40 m in the western and northeastern borders of Migjorn. There is no direct evidence that this tectonism died out in the Holocene. But the comparisons with Bahamas, the U.S. Atlantic Coastal Plain, Bermuda, Cayman Islands, and California [the latter not such a good example] give credence to the authors’ conclusions. The more we learn the more we don’t know! geoff pohanka (16:14:21) : “I know what the warmers will say: … The author is obviously funded by oil companies” British Petroleum and Royal Dutch Shell have been funding the CRU since 1974. This can only mean that it’s worse than we thought. While I have no reason to disbelieve the article, I think that it is important to keep a level head and open mind when researching the climate change topic () It is vital that those who seek the truth and not just a political position to maintain integrity. Those with a political or personal stake in the controversy have done great damage to truth detecting with their lies, misstatements and conspiratorial altering of data to fit their worldview intstead of fitting their worldview to the data. Michael: “The international banksters own everything. Now they want to completely own you.” I like the term ‘bankster’. Has a nice ring to it. Adam from Kansas (18:17:52) :?> I’m only looking at AMSU-A so I can’t answer your question, and I wouldn’t be qualified to in any event. That said I’m sorta surprised that some climalarmist hasn’t started screaming that we just hit the tipping point based on just that small part of the graph as it really stands out. I notice that there is a gap in the data entirely for a few days just before that and have just started wondering if the sensor was off line for a while due to some problem that is affecting current results. On the other hand wouldn’t it be hilarious if it went up to say… I don’t know… number at random…. 3.7 Watts/m2 with all the other channels still trending down? CO2 MIA? way o/t u.s. budget 3.8 trillion. if the $1 bills were lined up end to end, a photon of light (yes, in a vacuum) would take 32 minutes to cover the distance. correct? Quote: Oliver Jack (17:58:14) : “Sorry, Oliver Manuel, but George Bush was the token global warming denier out of the sorry group you list.” I agree, Jack, that George Bush was the “token global warming denier”. George Bush also took the advice of NAS President, Dr. Ralph Cicerone, in 2001 in formulating the US policy toward global climate change. With kind regards, Oliver K. Manuel I must say I just finish watching the Lamberton Mockton Debate on Climate in Autrailia. Their was no contest Mocton overwhelmed Lamberton. I am sure the alarmists were not happy. Sincerely John. janama (17:19:57) : I’ve contacted the SMH Online dept and The Sydney Morning Herald will be streaming the Monckton/Lambert debate live at 12.30 Sydney time. ——- Thanks so much for the link in your post – I followed it up and caught most of the debate. It was brilliant. Kudos to Tim Lambert for agreeing to battle Lord Monckton, but Monckton swept Lambert away. Amazing how often Lambert was appealing to authority and the huge ranks of climate scientists in concensus. A question, though. Monckton at one point referred to a theory that the El Nino is precipitated by undersea volcanic activity in the western Pacific. This one is new to me. WUWT? I For last 1.5+ hrs I was watching debate Moncton vs Lambert in Sydney Two points. 1. I’m speachless 2. I feel sorry,…. no, I feel very sorry, no, I feel extremly very sorry for Lambert Boys & Girls: I’m not a warmist. Just know that where I live several winter storms can wipe out a foredune and entie cliffs are casued to collapse, not to mention what goes on below the surface. Now in a far off cave the water level has been measured to move upward at a rate of 0.00123456 meters per century. I’ll wait a bit longer to accept this a face value. This info might not be “rock solid” black sea, tectonic activity,validity of the sampling. many things can be put in questions. Maybe a trap to let the less cautious “deniers” get in and then publish a “rock solid” refutation? Don’t worry, in three years time, pro-AGW scientists will go down there to produce their own tests and refute this finding or cast doubt on it. And so it goes .. The report on the research is good, the conclusions look like B.S. (bad science) to me. After 3 readings I see to many loose ends or poor assumptions. The idea that the area in question has been elevation stable over the time period is very hard to accept. That said, There is evidence from all over the world that the oceans water level rises and lowers up to 3 feet on a requalar bases Sorry to go completely off topic folks… But I just need a peaceful haven for two minutes where I can scream at the top of my lungs and get it out of my system… !!! Okay. I think I’m okay now. I needed that. Sorry… thank god for this sanctuary (I’m not bloody kidding). The rest of the internet is nuts, they are all blooming nuts ! I’m so very very grateful for these skeptic blogs, you have no idea ! I think I have to just simply stay away from all of the forums, these people are completely hopeless. Okay, I’m going to go back to WUWT’s home page, read some refreshing posts and claw my way back to sanity. Thank you for allowing me to vent. /rant Or was Mallorca a meter lower? Caution! If I understand correctly, the following have been considered “facts”: A. ~17,000 years ago the oceans reached a minimum level of ~120 meters below present, marking the depth of the Ice Age. B. Sometime since that low, as it rose to its present level, it broke through the Strait(s) of Gibraltar and brought the Mediterranean up to “Sea Level” in a relatively short period of time (swallowing ancient cities). C. Sometime later the same occurred through the Bosporus, flooding cities (towns?) with a sudden rise of the Black Sea (giving rise to the Noah Flood/Ark Legend). (B. & C. were unique to the Mediterranean and the Black Sea.) D. ~85,000 years ago, during the long descent into the depth of the last major ice age the “average” world sea level rose for a few thousand years to only ~30 meters below present. (There were many somewhat smaller deviations in the 100,000+ year descent.) E. ~82,000 years ago, the “sea level” rose to ~ 18 meters below present as measured at the Huon Peninsula of New Guinea. Perhaps during that rise during the long descent into the depths of the ice age, the Mediterranean was still connected to the “Atlantic”? Or perhaps it was on its own already and was fed by rivers, glaciers, or… Or was the land level changing? In any case, throughout the last 100,000 years, the sea level has been up and down significantly, over the short and long term. We may or may not live to see anything dramatic. But the “publish or perish” mandate combined with please your superior in the academic hierarchy combined with a proliferation of Enviro- Cult religious pressures, unethical ethicists, lawyers, (some of whom are politicians), and “academic” scientists who never check or understand the instrumentation and its limitations, which is giving them the data they massage to make the “truth”. And the journalists never did get science right, even back in the 40’s and 50’s. I hope this doesn’t upset people I’d rather not upset. I agree with Nick. The most sensible explanation is geology. Mallorca could have been lower. This doesn’t really prove much about the global sea levels, especially when we’re talking just about one meter. Sea levels were changing by 100 meters during tens of millennia, anyway, so why would suddenly we talk about this amazing 1-meter accuracy? Just that the result goes in the “convenient way” for us doesn’t mean that it’s correct to correlate it with the climate. That would be the same distortion as the climate doomsday prophets are doing all the time, just with the opposite sign. janama (17:19:57) : A question, though. Monckton at one point referred to a theory that the El Nino is precipitated by undersea volcanic activity in the western Pacific. This one is new to me. I think it has been discussed by Joe D’Aleo. The Indian Ocean warm pool can feed warm water through the relatively shallow and tectonically active Indonesian islands into the west Pacific. What is really interesting is that there is apparently very little difference between the MIS 5a and 5e sea-levels, only a meter or two. This is in good agreement with results from tectonically stable far-field areas like Australia and makes claims for sea-levels of 6 or even 9 meters during MIS 5e even more dubious than they were before. This is important since claims for “runaway” sea-levels as a result of even moderate warming are largely based on the presumed high seal levels during the last interglacial. John Egan (16:12:53) : “I am simply asking. Given the tectonic activity of the Mediterranean region – I would have to see convincing evidence that this was not due to uplift. As a structural geologist I can only agree with you. I can’t find the paragraph that describes how Neanderthal SUVs brought about Neanderthal extinction. Shome mishtake shurley? This doesn’t show that seeohtwo does or doesn’t play a role in warming, it merely shows that natural forcing factors are sufficiently strong to modulate temperatures in a manner consistent with amplitudes of temperature fluctuation seenin the past 250 years…… NickB. (16:30:54) :(?) — I know that theory and I often wonder about the water from the Danube, Dnieper, Dnister etc and what happened to it before the land dam broke, the Black has salinity roughly half that of the Atlantic etc. Suggesting an outflow of water. So the question is where did it (the water) go before the Black Sea was connected to the Med? One of these days I’ll get round to calculating how long it took (would take) to fill a blocked off Black Sea with all that fresh water. The mediteranean is a very special case and warrants a study subject of its own. It is tektonically very active and therefore not an ideal location from which to make definitive measurements. Never the less it is a reasonble piece of science with no notable biases.. I’m not saying this validates AGW but of course it strengthens the case. Pretending otherwise truly is denial. If you notice, we are now in the process of trying to discredit the authority (IPCC, CRU, NOAA, ETC). And there’s been a couple of wins. But really, this subject will not go forward with any credibility until these authorities line up with us. Forget about thinking otherwise, science always finds its way to the truth. I suggest that you challenge them to make a bet. (Conclude your challenge with “puck/puck/puck” to encourage them to get cracking.) There are three bets they can make on how warm 2010 will be (based on GISStemp’s online figures), at the well-known, Dublin-based event prediction site (Click on Markets → Climate & Weather → Global Temperature). They are: Will 2010 be THE warmest year on record? (32% chance) Will 2010 be warmer than 2009? (31% chance) Will 2010 be one of the five warmest years on record? (66% chance). There are also six other bets on future global temperature as well, having to do with the temperatures in the years 2011 through 2019. These haven’t yet attracted any betting and only a few bids and offers, so the odds are a guess. But a bettor can make a bid or offer he thinks is reasonable and wait for someone to take him up on it. It’s a bit of a hassle to get registered, learn the bidding process, figure out how to navigate the site, etc. but it’s much more practical than trying to arrange a one-on-one bet with a distant, antagonistic stranger. (Other problems: who will hold the bet? Who will adjudicate disputes? What if one bettor wants to bet on one of the nine propositions mentioned above and the other wants to bet on another?) And Intrade has the advantage of allowing a bettor to exit his bet if he changes his mind or there’s an emergency, or if he thinks the odds have become unreasonably biased in his favor so that the bet is no longer attractive (rational). Wow, Science Magazine printing an article on climate which is 180 degrees off message – looks like ‘cover your arse’ syndrome to me! Oliver K. Manuel (17:13:04) : “Have they finally found some integrity?” No. Science is running scared. What will happen if decades of filth beneath the climategate iceberg come floating to the surface?“ I think it more a case of when rather than if. The way ‘science always finds its way to the truth’ is buy inviting and sincerely confronting the criticism of those who disagree with the established view. Science, as a social institution, is conjecture plus organised attempts at refutation by sceptics. Isn’t this just weather? >>Just thinking out loud here, but isn’t there a theory >>floating around that up until the last 10,000 years or >>so the Black Sea was land locked and then flooded? I >>wonder how much that might have affected sea levels… Yes, it was proven by cores, that struck salt flats, that the Black Sea almost dried up during the last ice age. Then, some 7000 BC, the Bosphorus was finally breached and “the largest waterfall in human memory” was unleashed as the Black Sea refilled. However, if you compare the width of the Bosphorus and the Gibraltar Strait, I don’t think this would affect the levels of the Med. But I have to agree, that the stability of Mallorca, geologically, would have to be better established before this report can be taken seriously. . I just love this website. Now we have a really interesting paper being reviewed and debated. I seem to have read somewhere once, maybe it was my granddaughter’s science classroom, that the heart of science is open discussion and debate of observations. UK Sceptic (00:19:19) : And didn’t they have problems with sticky gas pedals and brakes that didn’t work? And the recalls didn’t fix the problems? The proper view of this research is to regard it with skepticism. What the paper does is invite further research in other parts of the world to add evidence in support or falsify the result. Nothing is proved or disproved by this paper. This is the way science should be done. Oliver K. Manuel (19:50:17) : “George Bush also took the advice of NAS President, Dr. Ralph Cicerone, in 2001 in formulating the US policy toward global climate change. ” Oliver, you have to remember that allmost all political parties in the west was forced to do this. Because all voters are brainwashed by media. Which again are brainwashed by post-modern science institutes. So, as a politician, you have 2 choices; 1) Say no to post-modern science, and loose all voters, or , say yes, swollow hard, and go on…… Its terrible, but there you have it. They’ve been very clever to follow Michael Hulmes advise. To redefine what Science is…. Its a travesty.. As for tectonics, it does seem that the Tyrrhenian block (including the Balearics) may be just about the only part of the Mediterranean that is relatively stable. See for example: Ferranti, L. et al. 2006. Markers of the last interglacial sea-level high stand along the coast of Italy: Tectonic implications. Quaternary International 145–146 (2006) 30–54. Ralph (04:24:19) :. Well, just because it’s getting colder and wetter doensn’t mean that its not getting warmer and drier! Pretty hard to argue with logic like that! John Hooper (00:56:19) : .” ______ When I mentioned that Tim Lambert in the Monckton-Lambert debate made constant appeals to authority, what I was implying – but realize I did not state clearly – was that rather than explain the mechanisms of what is going on, Lambert referred to individual studies as being done by recognized experts and therefore they must be right, or stated that since there is a huge consensus on a certain “scientific fact” then the fact must be right.. The Dorale et. al. article which forms the basis of this thread does look convincing; as someone noted above, however, the Mediterranean is a special case in terms of its oceanographic history. The authors seem to have done their best to answer this by indicating sea-level correlations in Bermuda and elsewhere. One wonders how they could definitively rule out isostatic effects, however. Either the sea level was higher or the crust raised. BTW regardless my motto is “Humans are not responsible for global warming … politicians are” I don’t think anyone mentioned this paper: Lambeck K, Bard, E. 2000. Sea-level change along the French Mediterranian coust for the past 30 000 years. Earth and planetary sciences letters 175, 203-222. This indicates rising sea levels in Medit before the SUV. Interesting because of the potential role of sea level differences in the time span between absolute myth, prehistory, and history. The Mahabharata includes Krishna foretelling the sinking of Dwarka (India); archaeology has discovered a submerged Dwarka along with present-day, dry-land Dwarka. They have an estiamted data range of this phenomenon – subsidence or flooding – of 2000 to 300 BCE. There are submerged archaeological locations in the Nile delta in the same era: who would build a town under water? Also, in Jericho, arguably well-established before 2000-3000 years ago, there is a story of the walls falling. Archaeology supports that there was a former town, with a fallen wall, circa the Biblical timline (Kathleen Kenyon, etc.); this town sits between the hills and the valley of the Jordan, obviously with water from the hills providing the springs well-known in the area. It is possible that rising water in the Persian Gulf, which drains the Jordan, raised the water table in the Jordan Valley, weakening the ability of the underlying soil to support this substantial (had small residences or storage areas built into it, concordant with the story) wall. The wall collapse is on the “downhill” side of the old city, supporting this possibility. Whether a parade of a millin people could de-stabilize the soil is another topic for another day; but the submerged archaeology across this vicinity of the globe – Nile delta, trans-Jordan, and nortwestern subcontinent, demonstrate non-SUV rise in sea levels in the past few thousand years. As for tectonics, it does seem that the Tyrrhenian block (including the Balearics) may be just about the only part of the Mediterranean that is relatively stable.> I’ve always wondered how one would establish this. The only way to say that any one given thing has moved a certain amount over time is to be able to measure it against something that hasn’t moved. We don’t have anything that we KNOW hasn’t moved, so we can only compare multiple things to each other to compare relative distance, height, etc. I thought of parking a laser on the moon but that darn thing moves about 3.8 cm farther away each year. come to think of it, that would mean it was about 3 km closer to earth 81,000 years ago. F=Gm1m2/r^2 current r=384,000 km, so gforce between moon and earth would have been about 1.5% higher meaning higher tides, etc. Med and Black Sea being low tidal oscillation no much difference, but high/low tide marks in high oscillation areas….? The other interesting thing is that the paper suggests a way to correlate atmospheric insulation with sea levels. Eyeballing the graphs suggests that sea level isn’t very responsive to changes in insulation at the upper end. Even when the insulation was ~550w/m^2 125k years ago, the sea level looks to be identical to today’s. vigilantfish (06:38:40) :. Yes, that’s the problem with Monckton. As witnessed with Glaciergate, you only need to be caught out on one exaggeration, let alone unsupported/debunked claim, and your entire house of credibility starts tumbling down around you. Watching him debate is like yes, yes, yes, oh no Chris not the mud pie story again, mate, just leave it out. You’re just setting yourself up for ridicule. I had a girlfriend who lied compulsively. She always had proof for all her outlandish stories, which was all you had to do was call one of her friends you didn’t know and ask them. Monckton’s a bit the same. He cites fact after fact after fact – and it sounds great – but honestly, his audience rarely has any idea, certainly not as he speaks, whether his data is sound. The press then picks up one of his claims, rips it apart, leaving the rest of his argument likewise suspect. Sometimes less is more. The editorial boards of Science and Nature need to do some very serious review of their policies with respect to the critics of man made CC and man made GW. These two publications have been at the forefront for years of intentionally blocking and censoring those legitimate and scientific fact based evidenced papers that have challenged the lies and the fraud and the hoax that are man made CC and man made GW. The greens still cannot clearly, accurately, and precisely show and demonstrate the causal relationship between man’s behavior and the alleged man cause CC and GW. We are just supposed to accept their unproven hypotheses because their positions are “superior to the positions of the critics” and their work and causes are “so much more important” than that of the critics. If the data of the East Anglia CRU, NASA, and NOAA are so scary accurate, precise, and predictive, then why did Phil Jones and Michael Mann put up such obstacles to having such data reviewed by the Canadians M&M? Where was the skeptical media? Where were the critical thinking skills of the media when Al Gore told his lies. (By the way, Al Gore told the public that the earth’s subsurface is millions of degrees hot. It isn’t. It is 4,000 to 7,000 degrees C.) Science should not be for sale or be manipulated by the corrupt media and by corrupt scientists. Until the leaders in science decide that science is not to be manipulated and compromised to promote and support the lies, bias, distortions, and prejudiced policies of politicians, then the four corners of deceit shall remain academia, government, media, and science. tty (05:56:21) :. —- So how did it (the Bosporus river) do that if there was a dam which was breached by water coming in from the Mediterranean which then formed the Black Sea? There must have been a depression which became the Black Sea? So why wasn’t it a lake before it became the Black Sea with the Bosporus river flowing out ? I am very puzzled by it. “It’s not logical Captain” >. The Black Sea dried out to an extent that it was less than 50% its current area – a vast volume change. And yes, this left a series of salt pans around the perimeter. The rivers that fill the Black Sea are not sufficient to prevent evaporation of the sea to much lower levels – which is why the Bosphorus only flows in one direction. See Ryan and Pitman “Noah’s Flood”. Despite the non-scientific title, this research was peer reviewed in ‘Nature Mag’. . >>The water went into the Mediterranean the same >>as now, only the Bosporus was a river rather than >>a strait. No it was not. The world sea levels and the Med dropped below the level of the current Bosporus during the ice Age – thus the Black Sea started drying out (yes, not completely dry, but substantially dry). After the Ice Age, sea levels rose again, and finally they reached the level of the Bosporus. The Bosporus would have been a ‘river’ for all of one or two WEEKS. After that, with such a head of water behind it, the Mediterranean would have eroded a bigger and bigger path through the Bosporus – resulting in a vast torrent. Ryan and Pitman estimate the water in the Bosphorus moving at some 120 miles and hour and the resultant Bosporus waterfall being the largest in human memory – while the Black Sea filled at some 2km per hour (lateral displacement, so you could easily walk ahead of it, if you did not get cut off.) A distant memory of this may be present in the Flood myths, and also in Homer’s Odyssey. The ‘clashing rocks’ are a reference to the Bosporus, and the myth indicates these rocks open and close, much like the Bosporus actually did. Incidentally, the epic of Gilgamesh describes a boat being pulled along by rocks, which is still a current method of navigating the Bosporus – rocks in a basket under a boat will be pulled along by the current and pull the boat along, as the current is still towards the evaporating Black Sea. . I haven’t seen that issue of SCIENCE yet; well unless it’s already buried under papers. My initial reaction to the story, is that this is just another “anecdotal” piece of evidence, that reaffirms my belief that there really isn’t any correlation between CO2 and global climate; well certainly not in the manner of the first being causative of the second. The 600 million year purported proxy record here:- should convince anybody (assuming the data is correct) that global mean temperature IS NOT;and never has been, proportional to the logarithm of the atmospheric CO2 abundance; so Dr Steven Schneider’s invention, (apparently) of “Climate Senitivity.” as being the slope of that logarithmic relationship, simply doesn’t hold water. Sorry I just couldn’t resist. I know that Lord Monckton, has used that ancient climate data graph in his presentations; perhaps someone who knows how to access the raw numbers used to plot it, could actually plot Temp vs log(CO2), so we can see just how wrong that concept is. I don’t care what base for the logs; but 2.0 would be a good choice to match with Schneider’s thesis. But back to the current paper under discussion; it will be interesting reading to see where this leads,in the direction of just what the heck WAS actually going on 81,000 years ago,that led to this (apparent) result. “”” u.k.(us) (17:13:24) : o/t carl sagan quotes: “Modern science has been a voyage into the unknown, with a lesson in humility waiting at every stop. Many passengers would rather have stayed home.” “Extraordinary claims require extraordinary evidence” Where is the humility, or the evidence. “”” Well this often repeated (purported) quote of Carl Sagan, has a nice touchy feely aura about it; one might almost describe it as “Churchillian.” But of course, other than being immortalized along with “Billions and Billions” by Sagan, it is quite wrong. The standards of scientific “proof” are fairly well understood, and the level of adequacy, is not influenced by the overall importance of the outcome. If Sagan’s edict is to be assumed true; then one must also accept that non-extra-ordinary claims do not require extra-ordinary proof; in other words sloppy workmanship is ok if the outcome is not of great significance. That will not do; one must always explore under every rock, for supporting evidence (or the contrary) for ANY claims; if one wants to have any scientific integrity at all. In fact the outcome, of one’s work, should be the least of one’s concerns. Getting the facts correct, is ALL that matters; not the eventual outcome of those revelations. That’s so true. Overkill will kill you. Tone it down. If you don’t have a winning hand, play for a draw. Don’t open yourself to a counterpunch. Etc. I live in Mallorca!!! lol! On the stability of Mallorca – We had a small earthquake last weak in the bay of Palma. As predicted, Monckton let us down by spending too much time bignoting himself and bluffing and not enough time checking his data. This is exactly what we’re accusing the AGWers of doing. Get it together will you, Monckton! John Hooper (04:21:44), I watched the entire Lord Monckton/Tim Lambert debate. From your comment, I doubt that you did..] Being a braggart and AGW purveyor, Lambert would naturally claim in his blog that he won the debate. In fact, he lost. I saw it all. Throughout the debate Lord Monckton was confident, interesting, and had the facts at his fingertips much better than Tim Lambert, who often lapsed into technical minutiae, losing the audience in the process. The audience was clearly won over by Monckton, who received repeated rounds of applause – quite a contrast to Lambert, who made his points and sat down to a quiet but polite audience. By the Q&A session, Lambert’s body language and defeated attitude told the story, with his slumped shoulders, bowed head, and by allowing Monckton to answer questions directed at Lambert, or to either of them – with no rebuttal to Monckton’s energetic replies. By conceding the field of battle to his opponent, Lambert made it clear that he knew at that point who the victor was. If Lambert has actually convinced himself now that he won the debate, he should watch it like the viewers did, and pay attention to the audience’s response. So should you. John Hooper, I have a problem with understanding your posts, and it seems to stem from confusion between the various meanings of the word ‘truth’ Pease could you post your definitions?.] If Lambert has actually convinced himself now that he won the debate, he should watch it like the viewers did, and pay attention to the audience’s response. So should you. So you’re saying Monckton won because a partisan crowd who paid to see him beat up a warmist cheered clapped him on? And that’s not Argumentum ad Populum? Me, I think it’s a little embarrassing to have the author of a paper you cite state you’ve misinterpreted their findings. It’s not an isolated incident either, as you might recall from the fallout after ” The Great Global Warming Swindle” Too many on this side of the debate are guilty of prematurely piling on.. You are complaining about the outcome of the debate, by posting an anonymous link copied from the skeptic-censoring deltoid blog, but I doubt even with your cheerleading that Lambert would consent to another public spanking by Lord Monckton. Being humiliated once in front of a worldwide audience is quite enough for Lambert, I would think. [And: ‘prematurely piling on’?? I, for one, would love to see a rematch, because the first debate was so much fun.] We all know you would never make your complaint of the audience’s decision about who won the debate if Timmy had won. Just like we all know who the honest scientific skeptics are here, and who are the chameleons. supercritical (06:28:58) : John Hooper, I have a problem with understanding your posts, and it seems to stem from confusion between the various meanings of the word ‘truth’ Please could you post your definitions? I suspect you’re being facetious, but nevertheless I see skepticism as a healthy part of the body of science, and I see forums like this as part of the extended “peer review” process. Our goal as I see it is to help steer science not simply nay-say everything emanating from the establishment on principle. Doing so not only puerile and counterproductive, but really is being a [snip]. It is reasonable to assume in good faith that the established body of science will gravitate towards a more watertight premise. One that punishes both the preposterous extrapolations of warmist doom, as well as the knee-jerk conspiracy theories too common on this board. Don’t loose sight that we’re all on the side of science. Lose not loose. Dammit. Smokey (07:01:53) :. Smokey, Please note one link emanated from Andrew Bolt, the loudest skeptic in world media (often featured on this blog), who also echoes my sentiment. Go abuse him if it gets you off. The other was an email from one of the sources quoted by our ally, Lord Monckton. Had you read the email you would see that Monckton’s talked-up source politely says our Lord has misunderstood (not even misrepresented) the paper. Belligerently cheerleading regardless makes you look a fool. You would be better off direct your bile at Lord Monckton for letting you down. For letting science down. I have no stake in this other than I can plainly see misrepresentation on the AGW front, but am frustrated by the often even sloppier cases against it. Science isn’t about picking a team. It’s about punishing a theory. John Hooper I was serious in enquiring as to the ‘truth’ in your posts. For example the method of public competition (such as the Monckton/Lambert duel) will produce certain truths, but not scientific truths. Neither can a consensus of an established body, which again will produce certain truths, but not scientific ones. In other words science is a method by which scientific truths can be discovered. For other kinds of truths, the other appropriate methods are required. So when you posted on the duel I assumed you were communicating what struck you as ‘true’. But it was not clear to me because it did not make sense in the context of science, or politics, or sport. [snip] We do not approve of calling people “denialists” here. ~dbs, mod. Roger Knights (01:24:50) : Not Amused (22:28:13) : !!! “I suggest that you challenge them to make a bet. . . ..” That’s a questionable interpretation of the odds. There are a hundred and thirty years of instrument records, so absent a warming trend, the odds that 2010 will be one of the 5 warmest is 5/130 = 4%. The asking bid for “warmest” is 0.74 on the dollar (3 to 1). In other words, if you bet 2010 will not hitting the top five, and there is no warming trend, you would have a 96% chance of tripling your money. Given the number of skeptics who claim “the world has been cooling since 1998” or crow about record snowfalls, I would think more of them would be willing to take a bet with an average 288% return. Not Amused, don’t be a sucker. Roger clearly knows the ins and outs of Intrade; that means he’s probably smart enough to know that the world is rapidly warming. He’s likely trolling here for suckers who he can bait into betting against global warming, improving his own 33% return on his pro-warming bet. John Hooper, Again, I simply responded to your post [as you responded to those above you] by pointing out who won the debate. Other posters here saw the same debate and came to the same conclusion. You don’t appear to see things like others do, as pointed out above. For example, you completely misrepresented what vigilantfish (06:38:40) stated. You should remember that fact checking is easy on a thread. Psychological projection seems to be another of your traits. I was not ‘belligerently cheerleading,’ I was pointing out who won the debate. And since you think I’m a fool, that’s fine with me. I prefer to be underestimated. There should be many more such formal debates. Unfortunately, Mr Lambert will undoubtedly be reluctant to again debate the always-willing Lord Monckton after being bested. [He certainly shouldn’t have used Mann’s debunked hokey stick chart as his claimed authority.] It’s amusing to see the consternation this has caused in Lambert world. To understand how disreputable he is, see the post by “S. Lindsey” @8:09 a.m. on the Congenital Climate Abnormalities thread. Here at WUWT we regularly see comments like that. It is no compliment to alarmist blogs that they denigrate and censor opposing views. I suppose that since they cannot provide empirical evidence to support their CO2=CAGW hypothesis, it’s a face saving tactic. Your impotent hatred of Lord Monckton will not change reality. Monckton has a long list of defeated debate opponents under his belt besides Lambert, including Gavin Schmidt, Pierrehumbert and others – who are now afraid to debate him. Public humiliation is acutely distressing, especially when it is done by the always polite Lord Monckton, who wins his debates without name calling or raised voice, simply by showing the audience that the AGW emperor has no clothes. @ George E. Smith (10:23:36) : I liked the “Many passengers would rather have stayed home.” part of his quote. Made me think of the “hockey team” et al, they SHOULD have stayed home. Is the Lambert – Monckton debate on video anywhere? . At the end of the day, whether you deny evolution, or AGW, or argue that the Earth is flat, is 10,000 years old, you will always be able to “sell” that belief to somebody. Clearly there are many people here who are gloating at the prospect of “winning” the argument, for example: “I was not ‘belligerently cheerleading,’ I was pointing out who won the debate. And since you think I’m a fool, that’s fine with me. I prefer to be underestimated.” Clearly somebody whose loyalties are not to the truth: his focus is merely on “winning.” It might be better if the people who believe the science, like me, just come right out and admit that we may very well lose the public relations battle with the anti-AGW true believers. Anti-AGW believers may not be very cogent, but they are very loud, and they have the very great advantage that all they are trying to do is delay and confuse, when inaction is easier and more comfortable than action. We need to get past the question of who will win the public debate. Anti-AGW believers probably will, at least to the extent they need to, at least until it’s too late. If we concede that, maybe they can get past the thrill of victory to think seriously about what evidence they would need to see to question their own convictions. If you are wrong, Smokey, how will you realize it, and what will you do about AGW? Ralph (12:22:11), I’ll see if I can find it. Someone posted the link just as the debate started, and I clicked on it. But I don’t remember where or under what article, so it may take a while to find it. Robert (12:34:50), First off, enough with the “deny” language. It is deliberately insulting. The proper term is skeptic. I am a skeptic, which every honest scientist is, first and foremost. Belief has nothing to do with it. Those preaching AGW want everyone to take their word for the coming global warming apocalypse, without providing any empirical evidence whatever that a rise in CO2 will cause any more than a little insignificant warming. If that. You may not like it, but debate results are based on who won or lost; on who has the better argument. Since the purveyors of the CO2=Catastrophic AGW hypothesis have no solid, testable evidence showing it to be factual, debates like this are necessarily about who has convinced the audience that they have the better argument. Your boy lost, just as Gavin Schmidt lost to Lord Monckton in their debate. That one was done better, however: prior to the debate the audience was polled about their belief in AGW. The majority were convinced that AGW was a fact. Following that debate, the same audience was again polled. The result: they had changed their minds, and the majority rejected the AGW argument. That is now happening world wide on sites like this. The debate is being decided, and the AGW side is losing it. The AGW crowd have been desperately seeking something, anything, they can ‘gloat’ about, because they have been so consistently wrong, outmaneuvered and discredited by skeptical scientists. I was not gloating – only pointing out the audience’s applause, in response to being labeled a ‘fool’ and a ‘belligerent cheerleader’ by a chameleon who posts here as an AGW skeptic. I appreciate the concession speech in your last couple of paragraphs. Even Phil Jones is beginning to sound like that now, on his own personal road to Damascus. More will follow. Because as it has been repeatedly pointed out here for quite some time, the truth will eventually emerge. That’s what is happening: click on “Climategate” at the top of the page. See the truth exposed. As far as being “wrong” about CAGW, you are assuming there is any more evidence for it than for Prince Charles’ “grey goo” that he’s afraid will destroy the world. Are we to spend $trillions on that monster under the bed, too? Because there is about as much evidence for grey goo as there is for CAGW. Read up on the null hypothesis, then get back to us. Debate link: click “First off, enough with the “deny” language. It is deliberately insulting. The proper term is skeptic. I am a skeptic, which every honest scientist is, first and foremost.” I don’t agree with your self-description. Skepticism is a habit of mind, an approach to problems, one which, with a few noble exceptions, I have found sadly lacking in anti-AGW believers. What is evident from your comments as well as those of many of your peers here is an attitude of uncritical acceptance and celebration of anything which seems to confirm your beliefs, and endless attacks on anything which threatens them. This is the hallmark of an ideologically driven belief system, and it is not “skeptical” merely because the position you are embracing is one rejected by most climate scientists. Being against instead of for something may make you a critic, but it doesn’t make you a skeptic. “You may not like it, but debate results are based on who won or lost;” “your boy lost” “I appreciate the concession speech” Again, I suggest you get past your desire to “win” the public relations fight (and you probably will, if not as overwhelmingly as you’ve lost the scientific debate) and take an interest in the truth. Get your focus off your dog in the fight, and address the real questions: what is the truth about global warming? How will you know if you have been mistaken about it? What evidence would make you question your belief that the vast majority of climate scientists are wrong about global warming? A skeptic would have answers to those questions. I won’t be surprised if you don’t. But there IS a warming trend and we’re at its peak, as a chart of the temperature trend of the past 130 years shows: v On that page, GISS points out that “The ten warmest years all occur within the 12-year period 1997-2008.” Further, 2009 is the 2nd warmest year on the GISS record (which is the record used by Intrade to settle bets), the trend up from 2008 is sharp, and Jan. 2010 has set an all-time record (per UAH). Even if there were no recent warming trend but only random variation — yet, given that 2009 happened to be in the upper 10% (say) of the historical range, the odds of 2010 being either THE warmest or among the five warmest would be considerably better than 1/130 or 5/130. As I explained above, 2009 was the second warmest year on record and 2010’s January is setting a record, so there’s no reason to expect that 2010 is as likely to be as cool as, say, 1948 (which is much further away) as to be as warm as 2009 (i.e., among the top five). If yearly variations are random, as per your hypothesis, then the most likely prediction for next year is that it will most closely resemble this year. Ha-ha! (For the record, I haven’t yet placed any temperature-related bets there. I plan to in a few weeks. When I have, I’ll “declare my interest” in any posts on the topic I submit here.) I see that you, like me, enjoy turning the tables — i.e., amusingly suggesting that I’m playing a double game. That’s perceptive. There’s a saying in gambling circles that “there’s no right side to a bet, there’s only the right odds,” so I do have a “cushion shot” in mind — i.e., I might take the “Yes” (warmist) side of one of the bets I mentioned under certain circumstances. For instance, I think that 2010 will continue to rack up record high temperatures for the next two months and that eventually this trend (plus the predictions of Gavin, Hansen, and Ms. Pope) will tempt enough warmists to bet Yes on “THE warmest?” that the odds will rise over 50%. I think that the actual rational odds ought to be 25%. Therefore what I plan to do is place a standing order to “buy” the bet at 25% (hoping it will dip down there again soon) and “sell” it at 50%. I might even buy it at its current 33% and aim to sell it at 55%. If it got higher, then I’d take the other (coolist) side of the bet. Robert: “I don’t agree with your self-description.” That’s tough, Robert; I am a scientific skeptic. Most of the people on this “Best Science” site are skeptics. And if it weren’t for skeptics, you’d still be going to your local witch doctor to treat diseases. So be grateful. You try to equate scientific skeptics with Holocaust deniers. Reprehensible. No wonder you’re confused about the role of skeptics. Their purpose is to ask questions regarding a new hypothesis, not answer them. I can easily answer your questions. Do you think you’re the first to ask them here? The problem is that the promoters of the CAGW hypothesis are the ones who repeatedly dodge skeptics’ questions, such as: show us the raw data and methods that you used to formulate your conclusions. Answer: *crickets*. As climatologist Roy Spencer says, “No one has falsified the theory that the observed temperature changes are a consequence of natural variability.” If the climate ever exceeds its natural long term parameters, then you can start looking for a cause. Until then, it’s just natural variability. Adding an extraneous entity like CO2 violates Occam’s Razor: Never increase, beyond what is necessary, the number of entities required to explain anything. ~William of Ockham (1285-1349). You need to understand that skeptics have nothing to prove. The burden is entirely on the promoters of a new hypothesis:. Therefore, regarding the hypothesis that CO2 produced by human activity is causing “unprecedented” global warming which will lead to climate catastrophe: the onus lies upon those making that claim. Regarding the claim that there has been an alarming rise in global temperatures: the onus lies on those who say so. And they have the obligation to disclose all of their raw and adjusted data and methodologies to skeptical scientists – which they refuse to do. The believers in the CO2=CAGW hypothesis have no empirical [real world], testable, reproducible, verifiable evidence showing that a given increase in CO2 will result in a measurable rise in temperature. So they try to put the burden back on skeptics, demanding that skeptics must prove a negative. The insistence that CO2 is the central culprit in their hypothesis is an argumentum ad ignorantiam: the fallacy of assuming that something is true, simply because it hasn’t been proven false, or that it must be true because they haven’t thought of any alternative explanations. What they are lacking is empirical evidence showing a verifiable connection between a rise in CO2 and a rise in global temperature. But there is no real world evidence that CO2 is anything other than a harmless and beneficial trace gas, comprising only 0.00038 of the atmosphere. To propose spending trillions of dollars to ‘mitigate’ a non-problem is extremely irresponsible. That money would be sidetracked from truly deserving areas of science, which have already been starved of funding due to the AGW scare. Robert, you sound like someone in the humanities, with little technical expertise. Sociology? English Lit? Certainly you are no engineer or scientist; your misunderstanding of the scientific method is apparent. [C’mon, did I guess correctly? Was I close?] “That’s tough, Robert; I am a scientific skeptic.” Wrong on both counts. Again, you can’t answer the questions. Again, you spout unscientific nonsense, mangling such basic concepts as parsimony and the scientific hypothesis. “You try to equate scientific skeptics with Holocaust deniers. Reprehensible.” I guess your propensity of making stuff up is not limited to climate discussions. Godwin’s Law FAIL. “No wonder you’re confused about the role of skeptics.Their purpose is to ask questions regarding a new hypothesis, not answer them.” Sorry, no. Nor is AGW a new hypothesis. You are proposing a new hypothesis: that climate scientists are wrong about AGW, the unprecedented warming of the latter twentieth century is somehow being caused by “natural variation.” I question your unsupported hypothesis. Call me skeptical. “I can easily answer your questions. Do you think you’re the first to ask them here?” Then answer them. .” Sorry, “CAGW” is your term, which you have attributed to me without evidence. State it as a hypothesis, and the points for it and against it, and then we can discuss it. The hypothesis, now the theory, of AGW, has succeeded by every rational and empirical test. That’s why faith-based critics like you are reduced to analyzing the posture of of scientists, rather than their data. “What they are lacking is empirical evidence showing a verifiable connection between a rise in CO2 and a rise in global temperature.” No, Smokey, you’re wrong. Look here: Note the absorption bands of the radiation. ” propose spending trillions of dollars to ‘mitigate’ a non-problem is extremely irresponsible. That money would be sidetracked from truly deserving areas of science, which have already been starved of funding due to the AGW scare.” Straw man argument. We might call it “catastrophic global warming migation theory”: despite economic analysis to the contrary, you assert (without evidence) that reducing carbon emissions would cost “trillions” of dollars. “Robert, you sound like someone in the humanities, with little technical expertise.” Again, rather than address the science, or answer the questions, you want to fight and argue. Maybe, you hope, a little ad hominem will get us into the kind of back-and-forth you like, and away from the uncomfortable science stuff you don’t want to deal with. The questions still stand: 1) How will you know if you’re wrong about AGW? What evidence would lead you to question your beliefs? 2) How would you suggest we proceed if in fact you are wrong in your claim that CO2 is “a harmless trace gas” (speaking of comments that display a lack of literacy in basic science)? Roger: I like your analysis of the odds. I’m curious if 2010 will be the warmest year on record, but I wouldn’t like to lay odds on it. Top five, though, seems like a pretty safe bet. I’m surprised you can get a 33% return on it. I’m thinking of opening an account myself. Robert, Since you’re a noob here, I highly recommend that you go through the WUWT archives. There is plenty to learn, and unlike the echo chamber alarmist blogs with a handful of true believers shouting the same globaloney at each other, WUWT allows all points of view – as you can see. In the archives you will see the evolution of the “denier” label, and plenty of debate surrounding it. Yeah, yeah, godwin’s law, it’s all there. But that violation was by the alarmist contingent, not by skeptics. And anyone who claims that “denier” isn’t a deliberate insult taken straight from “Holocaust denier” is incredible. Don’t be incredible. You’re already on shaky ground here with what you believe to be the scientific method. “The hypothesis, now the theory, of AGW, has succeeded by every rational and empirical test.” So give us some of that empirical, falsifiable evidence showing that a specific, measurable rise in CO2 results in a measurable increase in global temperature …oh, that’s right. I already asked that. No answer – because there is no such evidence. The fact is that CO2 rises as a function of temperature. In other words, CO2 rise is an effect of rising temperature, not a cause. Cause can not precede effect. At least not in my universe. And the theory of natural climate variability, as taught in schools for many decades and elucidated by Dr Spencer above [an actual climatologist, not a sociologist], is the theory that must be falsified by any upstart hypothesis such as CAGW. Here’s a pretty good description of natural climate variability: click Since you didn’t answer my question about your background, did I guess right? Non-science? That being very likely, I’ll give you a break – and some worthwhile knowledge along the way. You asked… 1) How will you know if you’re wrong about AGW? What evidence would lead you to question your beliefs? Backwards again. It is the CAGW hypothesis that must be defended, according to the scientific method, not skeptical scientists who question it. The conjecture/hypothesis, which you won’t state so I will, is that a rise in CO2 will lead to runaway global warming and climate catastrophe. Shorthand: CO2=CAGW; even shorter: CAGW, or AGW. The scientific method requires that a hypothesis [which in this case is more of a conjecture] must withstand falsification. Further, it must be structured in a way that allows falsification. Just like any religion, AGW does neither. The AGW conjecture can not be falsified. Why? Because the raw, unadjusted data it is based on has been *ahem* “lost.” Thus, past instrumental temperature measurements can never be falsified. We are now expected to take the word of the same people who have stated, in writing, that they fabricated entire temperature data sets to support their AGW hypothesis. In other words, we are expected to take it on faith. Even worse for climate alarmists, the planet itself has falsified the CO2=CAGW conjecture by cooling for most of the past decade, even as harmless CO2 ramps up: click Note that Hadley, GISS, and both satellite records all show cooling since 2002. In addition, the 3,300 ARGO buoys show deep ocean cooling. Planet Earth is laughing at the hubris of the AGW contingent. So who should we believe? An English Lit major? Or Planet Earth? 2) How would you suggest we proceed if in fact you are wrong in your claim that CO2 is “a harmless trace gas” (speaking of comments that display a lack of literacy in basic science)? Yes, a harmless trace gas, English Lit major. There is no empirical evidence showing that the atmospheric trace gas is harmful in any way. None. Furthermore, CO2 is a beneficial plant food that directly helps the world’s poorest to eat: click Your questions lack rigor. Asking how we are to proceed if I am wrong is a completely “what if” question, which could be asked about nearly anything. What if there are alligators under your mother in law’s bed? What if global warming is caused by postal rate increases? Questions like that are specifically what the scientific method was designed to weed out. One could just as easily claim that methane is the problem. But the alarmist crowd hung their collective hats on carbon dioxide, based on a recanted 1896 Arrenhius paper, and now they are looking extremely foolish. Their choice is to move the goal posts once again this late in the game, by admitting they were wrong about CO2, or to be a part of the slow motion train wreck that started with Climategate. Lose-lose. If you really believe that my statement that CO2 is harmless is wrong, then show us, using real world evidence, how it is harmful in the trace amounts we’re discussing: 0.00038 of the atmosphere; one part in 2,600. Of course, you can’t. You’re just a humanities major. Or something similar. [Am I right? C’mon, ‘fess up! I stepped up and answered your questions. Thoroughly, and with plenty of citations. Fair is fair.] “But that violation was by the alarmist contingent, not by skeptics.” You brought it into this discussion, and while I would certainly class you as an “alarmist” and you’re certainly not a “skeptic,” I don’t think that was what you meant “Since you didn’t answer my question about your background, did I guess right? Non-science? ” What’s the point in making claims about our backgrounds that can’t be verified? Just because you don’t understand basic scientific concepts like a null hypothesis or parsimony, what does it gain us to speculate on your level of education of lack thereof? Nothing at all. It’s a distraction from the discussion of the facts, where you know you lose. Case in point: “Note that Hadley, GISS, and both satellite records all show cooling since 2002.” 2005 was the hottest year on record according to the GISS data. So your claim is false. The oughts were the hottest decade on record, same source. January 2010 was the hottest ever recorded, by the satellite data. Even in this too-short term frame, your claim fails. Let’s get to the meat: again, you refuse to answer the skeptic’s basic questions, and you justify your failure to do so with a misstatement of how scientific debates work, and lame excuses: “Your questions lack rigor.” Add rigor to the list of scientific concepts you don’t understand. You state the hypothesis of “CAGW”: “a rise in CO2 will lead to runaway global warming and climate catastrophe.” That’s vague to the point of uselessness. How big a rise? How much is “runaway”? What is your definition of “catastrophe”? You’d be much better served with specific claims (all true/false): 1. CO2, methane, CFCs and other GHG warm the climate. Without them, it would be colder. With more of them, more solar energy is captured by the climate system instead of radiating into space. 2. The past several decades have shown progressive warming compared to the rest of the instrumental record. The warming trend falls well outside what could be explained by a standard distribution (p = very small). 3. The warming of the past several decades does not correspond with changes in the sun’s radiance, Milankovitch cycles, changes in the Earth’s albedo, or other natural forcings. 4. The increase in CO2 and other GHGs is primarily due to human activities, with some feedbacks. Hence: The observed rise in CO2 and other GHGs is the most likely explanation for the rise in global temperature. That would be one way to state the theory of AGW. But, of course, the problem with saying it that way, as opposed to the hyperbolic straw man you’ve constructed, is that 1-4 are all supported by rock-solid science, and once you concede 1-4, the conclusion is pretty obvious, even without the mountain of empirical data that supports it. BTW, I like what you do here: “Yes, a harmless trace gas, English Lit major.” So we see you’ve proceeded from making stuff up with no evidence “you sound like someone in the humanities, with little technical expertise. Sociology? English Lit? Certainly you are no engineer or scientist;” and you rapidly progress from wishing something was so to assuming that it is: “English Lit major.” Such is your idea of “rigor.” Again, the questions are: 1) How will you know if your hypothesis that AGW is not happening is false? 2) How do you think we should handle the problem of AGW if you are wrong? Let’s add one more easy question for any real skeptic: 3) What are the three best arguments in favor of the theory of AGW? Robert (16:42:03) : Sorry, no. Nor is AGW a new hypothesis. You are proposing a new hypothesis: that climate scientists are wrong about AGW, the unprecedented warming of the latter twentieth century is somehow being caused by “natural variation.” I question your unsupported hypothesis. Call me skeptical. A fair point. Too many self-anointed climate change “skeptics” aren’t really skeptics, but disciples of a few notable mouthpieces, who either stand apart from the peer-review process or have failed to gain traction with the mainstream consensus. Extraordinary claims demand extraordinary proof. And the claim of a worldwide conspiracy that’s fooled, or corrupted, every prominent scientific organization and journal in the world, with really only fringe dissent, is quite unprecedented. So yes, there is a massive burden of proof on those asserting this claim. And that’s why I contend to find the truth, we must debate within the scientific establishment, not against it. That’s very well put, John. Confirmation bias is something that affects us all. I know it affects me. When I see an article, like Solomon et al recently, that suggests that climate change may not be advancing as fast as has been thought, I often find myself checking disappointment. Which is absurd. Better, if we have a choice, for me to be proven wrong and look silly, than for the most threatening possibilities of global warming to come to pass. I try and discipline my mind by greeting such findings, when they happen, positively, but it isn’t easy by any means! Robert (07:12:50) : That’s very well put, John. Confirmation bias is something that affects us all. I know it affects me. Indeed. Yet, no doubt we disagree on other issues. My bias is more against those who: 1. exploit any weather-related event as evidence of AGW. 2. assert we need to urgently tax/ration the planet into stability. 3. pile on blindly in support of whatever camp they’ve joined. 4. argue expensive energy or rationing as a morality. 5. deny our current energy model is sustainable. I also fall into the skeptic’s camp who suspect 1. For whatever reason the Earth has been warming. 2. Am not yet convinced, but open to convincing, that it’s continuing trend. 3. The C02 may play some role, albeit only slight, in forcing the warming. 4. Oceans might be affected, though I’m not sure how. 5. If AGW really is an issue, we’re pretty much buggered. 6. Wind, solar, tidal. Expensive and impotent. However, I see all research that undermines AGW as good news – so should anyone with a heart – and C02 to be less troubling as a pollutant than the very visible photochemical smog and particulates. Robert (21:39:42): “…while I would certainly class you as an “alarmist” and you’re certainly not a ‘skeptic,’…” Robert me boi, the Devil quotes Scripture and you call me an alarmist. You can classify me any way you like, and you can insist that black is white, down is up, evil is good and unusual cold is caused by global warming. None of it is true, of course. So. I was right. You’re background is not from the hard sciences. Around here, we can tell a poseur, you know. OK, I’ll play the Q&A game even if you won’t: 1. Since the question is not quantified, I’ll be lenient and give you a Yes. But the effect is minuscule, and will never lead to a “tipping point.” 2. Wrong. 3. Wrong. Let me reiterate: Wrong. 4. As usual, no rigor. Are the feedbacks positive, or negative? Since you don’t know, I’ll guess you mean positive. In that case, the answer is No. See here. Per the IPCC itself, for every 34 molecules of CO2 emitted, 33 are from natural processes. One molecule of CO2 out of 34 is the result of human activity. You have been spoon fed false information by climate alarmist blogs. Stick around here, and learn the actual facts. Moving on to the last two questions [see? I answer yours; you hide from mine]: 1. I don’t have a hypothesis. None. I am a scientific skeptic. The alarmist contingent has a hypothesis/conjecture: CO2=CAGW. Unfortunately for them, it has been falsified… by mother Earth herself. 2. The same way we handle the question of alligators under your mother in law’s bed: by following the scientific method. 3. As I previously showed you with a citation: catastrophic AGW is not a “theory.” It is a repeatedly falsified hypothesis/conjecture. But if you still want to believe that “theory” nonsense, it’s OK. Anyone can post here, there’s no censorship like there is on RealClimate. So, to answer your final 3 questions [noting for the record that you refuse to answer any questions yourself]: 1) “Because we can’t think of any alternate explanation, it just has to be due to CO2.” [An Argumentum ad ignorantium, like most AGW explanations.] 2) “We have a consensus of 52 IPCC scientists, all political appointees with their CAGW marching orders, and they can’t be wrong… can they?” 3) The global temperature has increased over the past century, correlating with an increase in a tiny trace gas and postal rates. The correlation with postal rates is a better fit. I enjoy your questions, Robert, they’re fun and easy to answer. But stick to the humanities, and leave the science explanations to the engineers and physicists. Around here, when you’re digging yourself a hole, my advice is to quit digging. If you don’t, you’re handing folks an opportunity to have some fun because you’re not up to speed on the subject. Smokey, I have a question for you: So you’re convinced all these organizations (and more) are corrupt to the core and unlike your learned self, are incapable of recognizing the politicizing of bad climate science: And you have all the proof you need. So while you’re on a roll. What else are they wrong about? [John, I was in the process of responding to your posts when I saw that you had posted a question to me @10:05. I’ll post what I’ve already written, then answer your question below it]: John Hooper (08:21:11), I’m in agreement with just about everything you said in that post. Particularly the spending of [at last count] upwards of $50 billion in the U.S. alone on grants to study AGW. When you want pigeons, throw out bird seed. When you want AGW, throw out grants. However, in your post @02:46:40, you appear to think that scientific skeptics are somehow special, or that people who are skeptics must pass some sort of litmus test to call themselves skeptics. That is incorrect. Every honest scientist is a skeptic, first and foremost. It is a method, not a title. I’d like to say a little bit about your list, John: 1. exploit any weather-related event as evidence of AGW. The trouble with an issue like this is that straw men are all around; there’s always someone saying something grossly stupid just across the fence, who can become an easy proxy for “them.” We would never evaluate the strength of our own arguments by the loons on our own side, of course. 2. assert we need to urgently tax/ration the planet into stability. Stability, of course, is not an option. It is reasonable to be very concerned, I would argue, when (or, as you might say, if) humans are rapidly changing the climate to one very different from the one humanity has enjoyed through the last 13,000 years of settled existence. The planet is our life support system, and rapidly warming the climate is like someone randomly fiddling with the knobs on your SCUBA when you’re a hundred feet under water. It could be fine. Probably not. 3. pile on blindly in support of whatever camp they’ve joined. Yes. 4. argue expensive energy or rationing as a morality. I would agree, if they are using moral suasion to short-circuit discussion of the need or efficacy of such a program, a la won’t-somebody-please-think-of-the-children. On the other hand, we do need to think of the children, as well as all the other people affected by climate change, which does make mitigating it a moral issue, I believe. 5. deny our current energy model is sustainable. You mean in the sense of limited reserves? I’ve had that argument with my fellow greens until I was — well, green in the face. Peak oil and the like are nonsensical comments. On the other hand, if we burn a significant portion of the fossil fuels left in the ground, the warming is likely to be very dangerous. I also fall into the skeptic’s camp who suspect 1. For whatever reason the Earth has been warming. 2. Am not yet convinced, but open to convincing, that it’s continuing trend. What evidence are you looking for? Serious question. 3. The C02 may play some role, albeit only slight, in forcing the warming. Why only slight? Venus, for example, has an atmosphere that is less than 1% CO2, yet the surface temperature is hot enough to melt lead. The greenhouse gas effect of CO2 was known far in advance of the debate over AGW.* 4. Oceans might be affected, though I’m not sure how. Well, they’re getting more acidic, for one thing. Sources on request. 5. If AGW really is an issue, we’re pretty much buggered. Yeah, that could be. To cheer myself up I try to remember that story about Richard Fenyman: How after working on the bomb, he sat in New York and watched people building bridges and skyscrapers and thought they were all wasting their time: it was all going to be nuked in short order. Who would have thought we’d get through sixty years with no more nukes used in anger? Sometimes humanity doesn’t disappoint. 6. Wind, solar, tidal. Expensive and impotent. Too slow, certainly. Hansen’s new book, Storms of My Grandchildren, which I recommend, comes down strongly in favor of 4th-generation nuclear. * Which points to how deep the conspiracy among the scientists must go. Climatologists and physicists were faking results on things like the greenhouse gas effect of CO2 for decades prior to the rollout of AGW! Think of the discipline, the planning it required. It all points to the Illuminati, doesn’t it? Smokey (10:23:09) : That is incorrect. Every honest scientist is a skeptic, first and foremost. It is a method, not a title. Exactly. Which is why I have so much trouble accepting the assertion that all these scientific bodies are somehow blind. Correction: Venus’ atmosphere is over 95% CO2. John Hooper (10:05:44) : I’m not sure what you’re responding to, since you don’t reference a particular comment or post. Where did I say all those organizations are corrupt to the core? You misrepresent me. I never said that. In fact, I’ve never seen that link before, not that its appeal to authority surprises me. Of course there is plenty of corruption in the climate sciences, as we have seen in the Climategate emails. But most scientists are honest. They are simply being prudent by not speaking their minds – as we can see by the relatively large number of retired scientists who are openly critical of the AGW hypothesis, but who kept quiet while employed. That does not make them corrupt; I doubt you would risk your job by raising a contrary opinion. I wouldn’t either [but being retired now, I can say what I want]. You’ve taken my position a bridge too far. But I do agree that many organizations have been hijacked by pro-AGW activists, as Prof Richard Lindzen of MIT also points out. I was the elected CFO [treasurer] of a large statewide organization, and I’ve seen first hand how easily an organization can be hijacked by even one activist. In fact, it is incredibly easy once one becomes knowledgeable about the bylaws, committees and subcommittees, key players, how motions can be structured to reach a predetermined agenda over time, and Roberts Rules of Order. Once one or more influential activists are in place, it is easy to get other activists appointed to key positions. In fact many organizations, particularly those with unpaid volunteers serving on committees, often have a hard time finding enough willing members to fill all the positions. So an activist can often simply step into a vacant position. And if the head of the organization is in agreement with an activist’s agenda, nothing can stop the propaganda push. Every organization keeps its membership contact list confidential for a number of reasons. But its committees and the governing board have access. This problem has been discussed repeatedly here at WUWT. Dr Lindzen also points out the problem here. The system has been gamed. As has been repeatedly pointed out here, the honest way to determine the views regarding AGW of the rank-and-file members in an organization [as opposed to the handful on the governing board] is to have each side [pro-AGW and skeptical scientists] appoint an equal number to an ad-hoc committee, with a remit to formulate the questions that will be sent out, in a secret ballot format, to the dues paying membership. Only those questions that contain mutually agreed language would be allowed. That way, the true views of the membership will be made clear. But this is never done. Why not? Because those activists intend to use their position to speak in the name of the entire membership. Saul Alinsky explained the method in his Rules for Radicals. It is surprisingly easy to redirect a professional organization, such as the APS, toward a particular agenda. The membership is interested in furthering the professional society, not in political advocacy. But the members do not have access to contact information, making it very difficult to organize in opposition to the board taking a pro-AGW position. And to most, it is simply a minor irritant that their journal uncritically endorses AGW; for the average member it is not worth the trouble of fighting a war with the society. It is easier to simply cancel their membership if they are in disagreement. Also, almost every charitable foundation that has been in existence for more than twenty five years also funds AGW grants – but not grants to AGW skeptics – even though AGW was generally unknown 25 years or more ago when the foundation was set up. Foundations are, if anything, easier to hijack than professional organizations, because votes are traded: each trustee has their own funding interest, and all it takes is one from, e.g., the Grantham Foundation, to fund large AGW grants. And the religious orders that are listed in your link are even easier to hijack. They are concerned with faith, not science. I challenge anyone to find a mainstream religion that promotes the skeptical scientific method over AGW. The human nature of groups [as opposed to individuals] is easy to game. The methods have been known for quite a long time. The old Soviet Union made a continuous study of the nature of democratic organizations, as the Venona papers showed. Adam Smith, in his 1775 Wealth of Nations, pointed out that as soon as two shopkeepers get together, they begin to form a conspiracy to raise prices. Anyone who believes that AGW isn’t primarily about massive tax increases and the growth of government is, to put it mildly, ignorant. There are, of course, well meaning people who sincerely believe in catastrophic AGW. But make no mistake: the main driver of AGW is money and increased government bureaucracy and control. And the truly corrupt UN is salivating like ravenous hyenas at the prospect of its proposed annual .7% of GDP “World Tax” to ‘fight the effects of climate change.’ Naturally the tax would be paid by only the G-8 countries, into the opaque and unaccountable UN [staffed 99.9% by Pachauri-like creatures], and the fraction that emerged would be paid out to the other 184 countries – including “developing countries” like Russia, China, Brazil and India. Does it need to be pointed out that there are always effects from climate change and there always have been, and that CO2 induced catastrophic AGW is completely unproven? I notice that you’ve posted another follow-up comment, so I will post this, and answer any questions you may have. But I won’t argue [not that you’ve been argumentative], because this thread is stale, and I’m going to move on to the current articles. Smokey still can’t answer the questions. Sad: “I enjoy your questions, Robert, they’re fun and easy to answer.” Yet you didn’t. You again failed to answer any of the “skeptic’s question,” trying to weasel out of them with various non sequiturs and quickly returning to ad hominem and arguments from authority: “But stick to the humanities, and leave the science explanations to the engineers and physicists.” Again, assuming that I don’t have a scientific background, because you wish it were true. Now implicitly claiming you have a scientific background, despite your failure to understand simple scientific and statistical concepts like the null hypothesis or parsimony (and here’s a pro tip for you when you’re impersonating someone with a science background: no one in the business calls parsimony “Occam’s razor.” You’re no skeptic, Smokey. You’re a true believer, and fervent follower of a political movement attempting to discredit working scientists. You fail every test of the skeptic. You aren’t able to articulate the opposing position; you aren’t able to consider evidence that challenges your view; you aren’t able to imagine what the world would be like or what you would do if you were wrong. And you justify this ludicrously anti-science and flat-out irrational faith-based system with a complete misunderstanding of how science works. You and your activist heroes (how ironic that you deride supposed activism by climate scientists when the anti-AGW believers’ spokepeople consist of virtually nothing else!) need to calm down and learn some basic intellectual honesty before there’s any hope of reaching you with rational thought. I hope you do register there. There are hundreds of bets on many topics available (mostly politics-related). At 66%, the bet on “Will 2010 be one of the five warmest years on record?” would return 50% a year if it pays off. (I.e., put down $2, get back $3.) All the previous top-5 years are in the past decade, IIRC; 2009 was the 2nd warmest; January 2010 is setting a record and so is Feb. so far; and the hiatus since 2002 in the rising trend suggests that there is pent-up heat in the pipeline; so from a warmist’s perspective it’s very likely — say 87.5%, or 7/8, that this bet will be a winner. Here’s how a warmist should figure his expected return, allowing for a loss 1 time in 8: 7 bets of $2 = $14 + payoff of $7 = $21 1 bet of $2 a loss; net payoff after 8 bets = $7 – $2 = $5 average payoff per $2 bet = $5 payoff / 8 bets = .62 cents Expected return per $1 = .31 cents, or 31% The odds on this bet have risen to 69%; people are realizing that it is a bargain. So the expected return (from a warmist’s perspective) is less, a bit under 30% now. But that’s a great expectation, so it’s still a good buy for him at odds of under 80% or so. (BTW, a bettor doesn’t have to buy at the current odds %age. He can place a “bid” below the market price that will be executed only if the odds move in his direction.) The real issue is how do we address the consequences of GW? Clearly GW exists and has in the past. Whether or not it is AGW or just plain old GW doesn’t matter. We are not going to stop and reverse it. The effort must be to destermine when and how much seas will rise and the consequences and then prepare. Those folks so caught up in AGW just want more government control over our lives to try to reduce this great country to a basket case of global equality. Dear Anthony (above), At this time-depth, the control over isostatic effects really need to be very, very strict (less than 0.005 mm error in uplift or subsidence [est.]/y would seem to be req.). Are the controls really that strict (is this why morphological evidence from the Eemian always seems a bit elevated?)? Sea-level studies are notoriously hard, esp. with respect to acheiving close controls isostatic effects (e.g., see Ian Shennan papers in QSR). Certainly though, the paper achieves a better standard than the more recent (ASU) Overpeck work (that puts Eamian-style sea-level responses in the context of Holocene-style climate changes), the latter should have avoided the clique, listened to his father, and stuck with aeolian stuff! Anyway, the greater the time-depth, the greater the potential error. Bruce Sorry, Eemian, not Eamian the second time (cf. MIS 5e esp.). Also “…controls OVER isostatic…”). Luboš Motl and several others here appear to think that this interesting paper supports their position. I would at least consider the contrary argument, that this paper suggest that the climate system is very sensitive to greenhouse gases. Compare 80000 with 10000 years ago. The insolation levels at 60N is similar in both period. This new paper demonstrates that the sea-levels are similar, hence global ice volume must be similar, but the temperature over Greenland and Antarctica was much colder 80000 years ago. Why? One obvious difference in forcing factors between the two periods is that Holocene CO2 concentrations were much higher.
https://wattsupwiththat.com/2010/02/11/new-paper-in-science-sea-level-81000-years-ago-1-meter-higher-while-co2-was-lower/
CC-MAIN-2020-50
refinedweb
16,523
71.95
scrypt-d 0.1.1 A D library for using the scrypt encryption function To use this package, run the following command in your project's root directory: Scrypt.d A library for using Scrypt encryption in the D programming language Implemented as a DUB package (optionally buildable as a regular D library) Features Scrypt.d comes with bindings for crypto_scrypt.h and scryptenc.h which means you can use this to either encode or decode data/files or use it to hash data (one way). It also comes with it's own wrapper around crypto_scrypt to make it easier to hash passwords in D, there are instructions on how to do that right below! Using the scrypt.password module Because you don't wanna deal with typecasting and other bullshit, I decided to make it easy to hash your goddamned passwords. password.d comes with 3 functions: string genRandomSalt(); string genScryptPasswordHash(string password, string salt, size_t scrypt_outputlen, ulong N, uint r, uint p); bool checkScryptPasswordHash(string hash, string password); Okay so password is obviously the parameter for the password you either wanna check or hash, salt is the random salt that you want to use in the hashing process (passing genRandomSalt() should be fine), and hash is the already hashed version of your password that you want to check against in checkScryptPasswordHash. Now where it gets tricky is when you see the scrypt_outputlen, N, r and p parameters. What the fuck are those things? Let me explain: scrypt_outputlen is basically the size of the buffer that scrypt outputs to, it isn't the length of the final hash or anything, since that's a sha1 digest of the hash prepended by the salt. N is the General work factor. This should be a power of two. The suggested one for passwords is currently 2^14 (but if you want to use SCRYPTNDEFAULT, although I wouldn't trust an external library not to change that value so I'd just put my own constant in the code, do as you like, I will probably not change it ever though) 2^20 is what you should use for sensitive stuff atm e.g credit card numbers. r is the blocksize used for the hash. Currently 8 seems to be fine (or SCRYPTRDEFAULT) and p is the parallelization factor, 1 is currently a nice default. (or SCRYPTPDEFAULT) Now here is an example of using the password module for great win: import scrypt.password; // Some function for saving a password in to your database for example string password = genScryptPasswordHash(input_password_string, genRandomSalt(), SCRYPT_OUTPUTLEN_DEFAULT, SCRYPT_N_DEFAULT, SCRYPT_R_DEFAULT, SCRYPT_P_DEFAULT); db.save("foo", password); // end // Some function pulling out the data from the db to check if the password matches the one you saved earlier string password_hash = db.get("foo"); bool authenticate = checkScryptPasswordHash(password_hash, input_password); // end Simple right? Yes it's a bit wordy, but I'm giving YOU full control here remember? Now go store passwords securely! No insecure md5 or sha1 hashes, I'll smack you down! Dependencies Tarsnap (you'll need to build scrypt as a library, see "Build Instructions" below) Build Instructions POSIX instructions (this means linux, freebsd etc) The way I got this to run properly on my machine was to download and compile tarsnap (found at) I then grabbed the libtarsnap.a and put it where my compiler would find it e.g (/usr/local/lib) and after that it's done as tarsnap is listed in the package.json file as a dependency! Windows instructions Someone else will have to write this as windows ain't worth my time. Should be similar to POSIX - Registered by Isak Andersson - 0.1.1 released 6 years ago - BitPuffin/scrypt.d - github.com/BitPuffin/scrypt.d.git - Zlib - Authors: - - Dependencies: - none - Versions: - Show all 4 versions - Download Stats: 0 downloads today 0 downloads this week 0 downloads this month 878 downloads total - Score: - 0.9 - Short URL: - scrypt-d.dub.pm
https://code.dlang.org/packages/scrypt-d
CC-MAIN-2019-35
refinedweb
657
61.87
Description. As an example, by inserting 2 characters, the string “Ab3bd” can be transformed into a palindrome (“dAb3bAd” or “Adb3bdA”). However, inserting fewer than 2 characters does not produce a palindrome. Input Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from ‘A’ to ‘Z’, lowercase letters from ‘a’ to ‘z’ and digits from ‘0’ to ‘9’. Uppercase and lowercase letters are to be considered distinct. Output Your program is to write to standard output. The first line contains one integer, which is the desired minimal number. Sample Input 5 Ab3bd Sample Output 2 Solution below . . . Steps for Solving Dynamic Programming Problems This is a dynamic programming problem but it’s an interval DP problem, which means that the solution is not found in a linear, bottom-up way. Since I’ve already solved it, I know that we’re going to have to tweak the generic DP algorithm in a way that the interval DP algorithm is not easy to tweak, so we’ll convert this to a Longest Common Subsequence (LCS) problem, a 2-dimensional DP problem that is easy to tweak. What we’re going to do is reverse the input string to get . The solution then is (length of ) – (length of the LCS of and ). To obtain a palindrome, we will have to add one character for each character not in the LCS. 1. Define subproblems Let be the length of the LCS of and . NB: subsequence is not the same as substring. A subsequence need not be consecutive, e.g., 2. Write down the recurrence that relates subproblems If , they both contribute to the LCS: Otherwise, either or does not contribute to the LCS, so one can be dropped: 3. Recognize and solve the base cases The base cases are: . So far, so good, but if we implement and submit the algorithm described above, we get a Memory Limit Exceeded error. The input string can be up to 5,000 characters so the DP matrix alone can be up to 25MB. Fortunately, we calculate the matrix values one row at a time, based only on the values of the previous row. So we really only need to maintain 2 rows at a time, not 5,000. import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); String s = sc.next(); sc.close(); StringBuilder sb = new StringBuilder(s); String rev = sb.reverse().toString(); int a = s.length(); int b = rev.length(); int[] dpPrev = new int[b + 1]; int[] dpCurr = new int[b + 1]; for (int i = 0; i <= b; i++) dpPrev[i] = 0; for (int i = 1; i <= a; i++) { for (int j = 1; j <= b; j++) { if (s.charAt(i - 1) == rev.charAt(j - 1)) dpCurr[j] = dpPrev[j - 1] + 1; else dpCurr[j] = Math.max(dpPrev[j], dpCurr[j - 1]); } dpPrev = Arrays.copyOf(dpCurr, dpCurr.length); dpCurr = new int[b + 1]; dpCurr[0] = 0; } System.out.println(N - dpPrev[b]); } }
http://eppsnet.com/2018/05/competitive-programming-poj-1159-palindrome/
CC-MAIN-2020-40
refinedweb
534
74.69
How to Set Up Outbound Calls From Browser With Africa's Talking-Part 1 Building a call centre is crucial for most businesses today. In this post, I take you through simple steps to setting up outbound calls from the browser. I will be using a React based frontend and a Django backend. The tutorial also assumes you have knowledge of the two frameworks and have set up your Africa's Talking account. If you don't have one, you can create one here: Africa's Talking Django Rest Framework Backend Setting Up First, create your Django project and install Django Rest Framework. The backend will use Django Rest framework library to expose our callback URLs. pip install djangorestframework After installing DRF, we need to set up a Django app. If you haven't set up your Django project yet, head on here to know how to create a Django project. Then install an app from the root folder of your Django project using the command (Ensure you add it to your apps in the settings file) python3 manage.py startapp outbound_calls Making calls from the browser via Africa's Talking (AT) requires you to have a virtual number. Before we continue, please make sure you set up you have a working phone number provided by Africa's Talking. The voice feature is not yet enabled for AT sandbox and you'll need a live number. Now that all that is set up, let's dive into creating our REST endpoints. Creating Views On your outbound_calls app, navigate to the views file. Import viewsets from rest_framework and action from rest framework decorators from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.response import Response Next, we need to setup the callback route to handle our calls action logic. class OutboundViewset(viewsets.ViewSet): @action(methods=["POST"], detail=False) def callaction(self, request): return Response( { "Dial": { "phoneNumbers": request.data["clientDialedNumber"], "callerId": request.data["destinationNumber"], } }, status=status.HTTP_200_OK, ) So what's happening, - First, we set up our viewset class by subclassing the restframework viewsets class. In my code, I use the simple viewsets.ViewSet but you are free to use any other viewset type, e.g. model viewsets - Then finally we return a response to Africa's Talking on how to handle the call. Please note that in our case, I am only catering for the "Dial" action, but there are many other actions as documented here. The "clientDialedNumber" and "destinationNumber" are sent within the payload from Africa's Talking. destinationNumber is Your Africa’s Talking phone number. This will also be presented in an international format, starting with a +. clientDialedNumber refers to the number dialled from the browser. It is the number you intend to call from the browser. You can read more about the other information contained in the payload later on here. When a call is made from the browser, AT will send the request to this callback endpoint. From this endpoint, we ask AT to perform a dial action which will then call the number we are trying to connect to. There's one problem though; AT expects an XML response meaning we need to use an XML renderer rather than the default JSON renderer. The minimum Dial action XML (read here) needs to look like: <Response> <Dial phoneNumbers="+254711XXXYYY,+25631XYYZZZZ,test@ke.sip.africastalking.com" /> </Response> The phoneNumbers refer to the phoneNumber(s) you intend to call. In our case, however, we also include the callerId since we are calling from the browser. From AT docs, This (callerId) contains the Africa’s Talking number you want to dial out with. It is mainly important when you call using a sip number. If not specified, the number called by the user will be used. Since we are calling from the browser, the calls from the browser client come in the form of an SIP number. The clientId, therefore, helps the user receiving our call to view it as incoming from a user-friendly (regular) number defined by us which in this case is our destinationNumber. Therefore, at minimum our XML will have both a callerId attribute and a phoneNumbers attribute <Response> <Dial phoneNumbers="+254711XXXYYY,+25631XYYZZZZ,test@ke.sip.africastalking.com" callerId="AT number to use" /> </Response> XML Renderer After creating the view, we need an XML renderer that will return an XML response instead of a JSON response. Create a file called custom_xml_renderer.py in your app directory. from io import StringIO import six from django.utils.encoding import smart_text from django.utils.xmlutils import SimplerXMLGenerator from rest_framework import renderers class CustomRenderer(renderers.BaseRenderer): """ Renderer which serializes to CustomXML. """ media_type = "application/xml" format = "xml" charset = "utf-8" item_tag_name = "list-item" root_tag_name = "Response" def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders *obj* into serialized XML. """ if data is None: return "" stream = StringIO() xml = SimplerXMLGenerator(stream, self.charset) xml.startDocument() xml.startElement(self.root_tag_name, {}) self._to_xml(xml, data) xml.endElement(self.root_tag_name) xml.endDocument() return stream.getvalue() def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: xml.startElement(self.item_tag_name, {}) self._to_xml(xml, item) xml.endElement(self.item_tag_name) elif isinstance(data, dict): for key, value in six.iteritems(data): if isinstance(value, dict) and key == "Dial": xml.addQuickElement(key, attrs=value) continue else: xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) elif data is None: pass else: xml.characters(smart_text(data)) Now, I will not explain in detail how the function works as that is beyond the scope of this tutorial. Notice that we subclass the Base renderer class. media_type = "application/xml" format = "xml" charset = "utf-8" item_tag_name = "list-item" root_tag_name = "Response" The media_type and format set our outcome to xml. The item_tag_name is used to set the xml key as list-item whenever a list is passed(in our case though we are not passing any lists). The root_tag_name is of importance. The default root tag name in xml is root in the AT's case as shown previously; the XML response needs to have the root tagged as Response; hence we override the default. elif isinstance(data, dict): for key, value in six.iteritems(data): if isinstance(value, dict) and key == "Dial": xml.addQuickElement(key, attrs=value) continue else: xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) The section above is also another key section. As you notice in our views file, we were returning a response that performs a Dial action. Hence the dictionary with the key Dial in the response payload. In this XML renderer, we check for any dict item embedded within the Response that has a key of Dial and a value that's a dictionary. We then set the xml attributes for the Dial tag to be the keys of that dictionary. Let's say our viewset returned a dictionary that looks like { "Dial": { "phoneNumbers": "+254711123456", "callerId": "+254701112233", } } Then the outcome of our XML would be <Response> <Dial phoneNumbers="+254711123456" callerId="+254701112233" /> </Response> Since in the scope of this tutorial we are only using the Dial action, then its the only one that we check for, If you try to understand the custom XML renderer deeply, then keep in mind that the conversion happens recursively. Add Custom Renderer to Views Even though we now have a working custom renderer, we need to tell our views to use it. So customize your views file to look like from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.response import Response from .custom_xml_renderer import CustomRenderer #This line added class OutboundViewset(viewsets.ViewSet): renderer_classes = (CustomRenderer,) #This line added @action(methods=["POST"], detail=False) def callaction(self, request): return Response( { "Dial": { "phoneNumbers": request.data["clientDialedNumber"], "callerId": request.data["destinationNumber"], } }, status=status.HTTP_200_OK, ) And that's it, guys. All you need to do now is to register your URL in your urls file and test it out. If you have been following along using viewsets and not Class Based Views or Function Based Views, I like to create a router.py file in the project folder then have it look something like from rest_framework import routers from outbound_calls import views router = routers.DefaultRouter() router.register("outbound", views.OutboundViewset, basename="outbound") Then I would register that in the projects urls.py file # import all needed packages from myproject.router import router urlpatterns = [ path("admin/", admin.site.urls), path("", include((router.urls, "outbound"))) ] Register the URL endpoint as a callback on AT. Follow instructions here to do so. To configure events callback, set up a simple URL endpoint of POST method to receive events. Incase your callback endpoint refuses to work, ensure to also setup events endpoint as opposed to leaving it blank. If you'd love to register a localhost endpoint for callback, consider using ngrok for tunnelling, See you on the next tutorial as we look on setting up the frontend with React. Happy Coding :-)
https://developers.decoded.africa/setting-up-outbound-calls-with-africas-talking/
CC-MAIN-2020-50
refinedweb
1,481
57.47
This program connects a microcontroller to a mySQL database via a Lantronix Xport and a PHP script. The PHP script it uses is the SQL_datalog.php script in the Network Data Logging Suite. Technorati Tags: networked objects, networks The relevant Xport settings for this application are as follows: *** Channel 1 Baudrate 9600, I/F Mode 4C, Flow 00 Port 10001 Remote IP Adr: --- none ---, Port 00000 Connect Mode : D4 Disconn Mode : 00 Flush Mode : 00 *** Expert TCP Keepalive : 45s ARP cache timeout: 600s High CPU performance: disabled Monitor Mode @ bootup : enabled HTTP Port Number : 80 SMTP Port Number : 25 The code: ' Xport_to_SQL ' Microcontroller is connected to a Lantronix Xport ' serial-to-ethernet device. This program connects ' to a HTTP server through the Xport, makes a HTTP GET ' request for a PHP script, and sends the value ' of an analog sensor through as a part of the ' GET request. ' Xport communicates at 9600-8-n-1 non-inverted (true) serial. ' By Tom Igoe, 31 oct 2005 ' updated 25 Oct. 2005 ' Define ADCIN parameters DEFINE ADC_BITS 10 ' Set number of bits in result DEFINE ADC_CLOCK 3 ' Set clock source (3=rc) DEFINE ADC_SAMPLEUS 50 ' Set sampling time in uS ' pins to define serial RZX and TX tx var portc.6 rx var portc.7 ' pins with LEDs to indicate whether we're connecting ' or sending an HTTP request: var portb.7 TCPPin var portb.6 output TCPPin output ' constant to set the baud rate: inv9600 con 16468 ' for non-inverted connections (PIC to Xport direct): true9600 con 84 ' define variables: adcVar var word inByte var byte connected var bit TRISA = %11111111 ' Set PORTA to all input ADCON1 = %10000010 ' Set PORTA analog and right justify result connected = 0 ' pause to let Xport boot up: pause 2000 main: ' if you're connected to the server, then ' make a HTTP call. If not, then connect ' to the server: if connected = 1 then ' read sensors, convert to bytes: adcin 0, adcVar ' send HTTP GET request for php script: gosub else ' attempt to connect to the server: gosub xport_connect endif tcpPin = connected ' pause so we're not overwhelming the server: pause 3000 goto main xport_connect: ' turn off LED to indicate HTTP GET is in progress: 'low tcpPin ' wait for a "C" byte to come back: while inByte <> 67 serout2 tx, true9600, ["C128.122.253.189/80", 10] serin2 rx, true9600, [inByte] wend ' turn on TCP pin to indicate that we connected: 'high TCPPin connected = 1 return ' light LED to indicate HTTP GET request in progress: high SEROUT2 TX, true9600, ["GET /~tqi6023/sql_datalog.php?action=insert&"] serout2 tx, true9600, ["sensorValue=", DEC adcVar] serout2 tx, true9600, [" HTTP/1.1", 10] serout2 tx, true9600, ["HOST: itp.nyu.edu", 10, 10] ' wait for bytes from server: ' php script sends a 0 to end transmission: while inByte <> 0 serin2 rx, true9600, [inByte] wend ' now we're disconnected: connected = 0 ' turn off LED, since GET request is complete: low return
https://www.tigoe.com/pcomp/code/picbasic-pro/35/
CC-MAIN-2022-21
refinedweb
487
61.09
I was talking to a friend last summer about what resources might be helpful for folks learning to program. My friend said they thought some people might benefit from a list of small and fun programming projects – the kind of thing you can do in an evening or weekend. So let’s talk about that! I like to write small programs that have some marginal utility in my life. Kind of like this: - ah! A minor problem in my life! - I know, I bet I can solve this problem with CODE. YAY. - 4 hours of happy programming ensues This isn’t always the most practical (many of the problems I’ve solved with programming could have been solved in less time in other ways), but as long as your goal is actually to have fun programming and your programs don’t hurt anyone else, I think this is a great approach :) So here are a few examples of small personal programming projects I’ve done. I’m not going to talk about “learning projects” where my goal was to learn something specific because I’ve already written a billion blog posts about that. These are more about just doing something fun with no specific learning goal. a theatre festival didn’t have a calendar The local Fringe Festival had a bunch of shows, but there was no place I could see a calendar all one one page. So I wrote a Python script to scrape their website and generate a calendar. Here’s the code and the output. printing out covers for tiny books I saw a TikTok video recently where someone made miniature physical versions of the ebooks they read. I decided to try it out, so I needed to print tiny versions of a bunch of book covers. I could have resized all of them manually, but I decided to do it with programming instead. So I wrote a little bit of HTML and CSS (tinybooks.html), converted it to a PDF, and printed it out. getting my scanner to work better This is barely “programming”, but I needed to scan a bunch of documents for a family member, and I didn’t like the available software. So I wrote a tiny shell script wrapper for scanimage to make the process simpler. This one actually helped me a lot and I still use it when scanning. getting a vaccine appointment. This didn’t turn out to be necessary (more appointments opened up pretty soon anyway and there were enough for everyone), but it was fun. In general I try to be careful when using APIs like this in a way the developers didn’t intend to avoid overloading the site. looking at housing market data We were thinking of buying a condo a few years ago and I was mad that I couldn’t get any information about historical prices, so I wrote an iPython notebook that queried the API of a local real estate website to scrape some information and calculate some statistics like price per square foot over time. I don’t think this actually helped us at all with buying a condo but it was fun. (“using the API of local services” seems to be an ongoing theme, one of my favourite things is to use secret undocumented APIs where you need to copy your cookies out of the browser to get access to them) crossword business cards in 2013, I thought it might be fun to have a business card that was a crossword with some of my interests. So I wrote general software to generate crosswords from a text file. I’m pretty sure never printed the business cards but it was fun to write. generating envelopes I was mailing some zines a while ago, and I decided I wanted to print custom labels on every envelope – sort of a “mail merge” situation. So I wrote a Python program to go through all of the mailing address and generate some HTML and CSS. Then I turned the HTML/CSS into a PDF and printed the envelopes. This worked great. investigating dice rolling patterns A friend showed me a dice rolling game where you roll a bunch of dice and add up the values. I mentioned that if you roll enough dice and add up all the values, at some point it gets a lot less “random”. But then I wanted to see exactly how much less random it gets. So I wrote a tiny program to roll 2500 dice and add up the resulting sums a bunch of times to see how it works. (presumably you could calculate the same thing with math, but it’s easier with code) This was so little code I’ll just inline it here. (it’s Python). Here’s [the output]( import random def roll(): return sum(random.randint(1, 6) for i in range(2500)) while True: print(roll()) getting drawings into the Notability app I was using an app called Squid to do drawing, and I was switching to Notability and wanted to get my old drawings into Notability. So I reverse engineered the Notability file format. I don’t think this was ultimately that useful (I ultimately ended up switching to a different drawing app which had a real SVG import), but I had fun. turning off retweets This is a slightly less tiny project (it took more than one day), but I decided I didn’t want to see retweets on Twitter anymore so I wrote a small website so I could turn off retweets. I really love tiny projects All of these examples are more recent, but I think that when I was starting to learn to program tiny low-stakes projects like this really helped me. I love that - they’re just for me (if it goes wrong, it doesn’t matter!) - I can finish them in an evening or weekend (it’s not a Huge Giant Thing hanging over my head) - if it works, there’s some tangible output in my life (like some envelopes or miniature books or a schedule a business card or a better Twitter experience)
https://jvns.ca/blog/2022/03/08/tiny-programs/
CC-MAIN-2022-21
refinedweb
1,029
66.37
Docs | Forums | Lists | Bugs | Planet | Store | GMN | Get Gentoo! Not eligible to see or edit group visibility for this bug. View Bug Activity | Format For Printing | XML | Clone This Bug Ebuilds needs to be updated. Reproducible: Always Steps to Reproduce: 1. 2. 3. Stepmania 3.9 has been released, and it seems that the maintainer of the stepmania gentoo ebuilds didn't update the last version so now I will try it myself. I have tried the new ebuild on ~x86 and ~amd64 and everything seems to be in order. The only bad thing I noticed was that stepmania + ffmpeg can create some problems. (Apparently this isn't unknown) Stepmania stopped compiling after recieving some ffmpeg errors, but this problem can be fixed temporarily by using older ffmpeg versions. media-video/ffmpeg-0.4.9_p20050906 didnt work, but 0.4.9_p20050226-r5 did. Hopefully the stepmania developers will fix this. Have fun! Created an attachment (id=72985) [edit] Updated patch for file locations Created an attachment (id=72986) [edit] stepmania-3.9.ebuild I think the IUSE flag "mad" should be changed to "mp3". Without libmad no mp3-files can be read. I don't know wich of the two are correct, so it would be nice if someone with more knowledge regarding correct useflags could set it straight. It would be mp3. The reason for mad is if there is more than one way to get mp3 sounds, for example, a built-in method, or mad. In that case, the ebuild would have both mp3 and mad, unless mp3 support *wasn't* optional. In which case, there would be just mad, and it would switch between mad and the built-in mp3 decoder. Make sense? Anything else that is wrong? Would like to know what needs to be done if this ebuild is going to find it's way to portage. I'll edit the current ebuild and change to "mp3. Created an attachment (id=73107) [edit] stepmania-3.9.ebuild-r1 *** Bug 90036 has been marked as a duplicate of this bug. *** Created an attachment (id=75729) [edit] stepmania-3.9.ebuild This ebuild solves the ffmpeg errors (this bug and Bug 107818), and adds the "force-oss" (Bug 94554) and "mp3" (this bug) USE flags. The previous ebuild "stepmania-3.9.ebuild-r1" doesn't use the "mp3" USE flag : use mad || myconf="${myconf} --without-mp3" I also added a new patch to allow me to run the game with alsa ("SetHWParams failed" but I can play if I disable it). Created an attachment (id=75731) [edit] stepmania-3.9-alsa.patch Alsa patch Created an attachment (id=75732) [edit] stepmania-3.9-ffmpeg.patch FFmpeg patch Created an attachment (id=75733) [edit] stepmania-3.9-gentoo.patch Gentoo patch Created an attachment (id=75736) [edit] stepmania-3.9-ffmpeg.patch oops... forgot one #if/#else/#endif test How's this ebuild coming along? I can test it if need be (I'm just emerging _rc3 right now). It'd be great to have v3.9 non-RC in portage. :) Just thought I'd add that my emerge of _rc3 failed (the version that is currently marked stable in portage), and that the emerge of this proposed ebuild update to v3.9 final compiled and merged cleanly. Since it's almost midnight, I cannot check to see if the build in fact functions, but it at least compiled cleanly. I'll report back with more info later. The stepmania-specific deps I compiled both against are dev-lang/lua-5.0.2, media-libs/imlib2-1.2.0-r2, and media-video/ffmpeg-0.4.9_p20051216, all of which are keyworded x86. Works for me, too. ~amd64 with dev-lang/lua-5.0.2 media-libs/imlib2-1.2.1.009 media-video/ffmpeg-0.4.9_p20051216 (In reply to comment #18) > > Are you sure you're using the right ebuild? The -r1 ebuild is outdated, use the one right below it in the list. The -r1 only applies a -gentoo patch, but the better one (dated 2005-12-29) applies all three. I'm not sure why the outdated one wasn't marked obsolete, but it's not the current ebuild. ok, forgive what I said. I've modified the ebuild to add the ffmpeg patch and now it compiled cleanly :-) I have installed the ebuild with all three patches but my version won't list any of the songs I have with mp3's. I've got the mp3 use flag set and libmad is emerged. I also added mad to my USE line my make.conf to see if that might fix it. My list of songs has all of the ones with ogg files but none of the mp3. Is there maybe some other trick to this? It seems like it should have worked fine. There are no error messages at startup and it seems to scan through the entire song list. Created an attachment (id=79386) [edit] stepmania-3.9.ebuild Hi, this is Damien's ebuild, with two extra lines that create a stepmania menu icon. ? Works for me, with the same USE flags. (In reply to comment #23) > ? > The ebuild compiles fo me but fails tests: i686-pc-linux-gnu-g++ -finline-limit=300 -O2 -march=athlon-xp -mfpmath=sse -fomit-frame-pointer -pipe -rdynamic -o test_file_errors AssertionHandler.o GetSysInfo.o SignalHandler.o LinuxThreadHelpers.o RunningUnderValgrind.o EmergencyShutdown.o Backtrace.o BacktraceNames.o CrashHandler.o CrashHandlerChild.o chartables.o get.o maketables.o pcre.o study.o RageFile.o RageFileDriver.o RageFileManager.o RageFileDriverDirect.o RageFileDriverDirectHelpers.o RageFileDriverMemory.o RageFileDriverZip.o ArchHooks.o ArchHooks_Unix.o Threads_Pthreads.o Dialog.o test_misc.o IniFile.o PrefsManager.o RageException.o RageLog.o RageThreads.o RageTimer.o RageUtil.o RageUtil_FileDB.o global.o test_file_errors.o MsdFile.o XmlFile.o CryptManager.o algebra.o algparam.o asn.o cryptlib.o files.o filters.o integer.o iterhash.o misc.o modes.o mqueue.o nbtheory.o oaep.o osrng.o pkcspad.o pubkey.o queue.o randpool.o rsa.o sha.o strciphr.o CryptHelpers.o CryptBn.o CryptMD5.o CryptNoise.o CryptPrime.o CryptRSA.o CryptRand.o CryptSH512.o CryptSHA.o -lavformat -lavcodec -lpng -lz -lm -ljpeg -lz -lpthread XmlFile.o: In function `XNode::SetValue(DateTime const&)': XmlFile.cpp:(.text+0x9e1): undefined reference to `DateTime::GetString() const' XmlFile.o: In function `XAttr::GetValue(DateTime&) const': XmlFile.cpp:(.text+0x1069): undefined reference to `DateTime::FromString(CStdStr<char>)' XmlFile.o: In function `XNode::GetValue(DateTime&) const': XmlFile.cpp:(.text+0x1179): undefined reference to `DateTime::FromString(CStdStr<char>)' collect2: ld returned 1 exit status make[2]: *** [test_file_errors] Error 1 make[2]: Leaving directory `/var/tmp/portage/stepmania-3.9/work/StepMania-3.9-src/src' make[1]: *** [check-am] Error 2 make[1]: Leaving directory `/var/tmp/portage/stepmania-3.9/work/StepMania-3.9-src/src' make: *** [check-recursive] Error 1 !!! ERROR: games-arcade/stepmania-3.9 failed. Portage 2.0.54 (default-linux/x86/2005.1, gcc-3.4.4, glibc-2.3.6-r2, 2.6.15-gentoo-src i686) ================================================================= System uname: 2.6.15-gentoo-src i686 AMD Athlon(tm) XP 1800+ -mfpmath=sse -fomit-frame-pointer -mfpmath=sse -fomit-frame-pointer -pipe" DISTDIR="/usr/portage/distfiles" FEATURES="autoconfig ccache distlocks maketest nostrip sandbox sfperms strict test"52 aac acpi aim alsa apache2 audiofile avi bcmath berkdb bitmap-fonts bzip2 caps cdb cdparanoia cdr cpdflib crypt cscope ctype cups curl dbus dbx debug dedicated dga dio dlloader doc dri dts dv dvb dvd dvdr dvdread emboss encode erandom esd ethereal examples exif expat fam fbcon ffmpeg flac flash flatfile fontconfig foomaticdb fortran ftp gb gcj gd gdbm ggi gif ginac glibc-omitfp glut gmp gnutls gphoto2 gpm gstreamer gtk gtk2 gtkhtml hal hardened howl iconv icq idn ieee1394 imagemagick imap imlib inifile ipv6 jabber javascript jpeg kdexdeltas kerberos lcms ldap libg++ libwww linuxthreads-tls live lm_sensors lua lzo mad maildir matroska matrox mbox mikmod mime ming mmap mmx mmxext mng motif mozilla mp3 mpeg msn multislot nas ncurses nls nptl nptlonly nsplugin offensive ogg oggvorbis openal opengl osc oscar oss pam pcntl pcre pdflib perl png ppds python quicktime readline real recode rtc ruby samba sasl sdl session sharedmem shorten skey slp sndfile snmp sockets sox speex spell sqlite sse ssl svg sysvipc tcltk tcpd test tetex theora threads tidy tiff truetype truetype-fonts type1-fonts udev unicode usb userlocales v4l vcd videos vorbis wifi win32codecs wmf xanim xface xml xml2 xmms xosd xpm xprint xv xvid xvmc yahoo zlib userland_GNU kernel_linux elibc_glibc" Unset: ASFLAGS, CTARGET, LC_ALL, LDFLAGS, LINGUAS *** Bug 123660 has been marked as a duplicate of this bug. *** Now in portage, thanks for report and patches
http://bugs.gentoo.org/109535
crawl-002
refinedweb
1,455
55.54