text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
I have an internal DNS as part of my AD setup. I have an hosted DNS for public resources (which are typically at some data centre somewhere) Occasionally while on our internal network I need to get to a public resource --- for example since there isn't a www record in our internal DNS I cant get the name resolved. How do I configure my DNS to forward names it doesn't recognise to the public DNS. Update: As per the comment yes I have a "split-horizon" dns (which seemed like a good idea at the time) This AD setup is less than 24 hours old, and can be redone if need be -- (although I would rather not) It sounds like you have split-horizons DNS, where your AD namespace and public-facing namespace are the same. If this is the case, you'll need to make an A record for www in your internal AD zone and set the correct external IP. Without this, internal clients won't be able to resolve it. This is because you have two sets of servers with disjoint information that are both authoritative for your DNS zone. www This is the exact reason that Microsoft recommends using an unused third-level domain name for your AD namespace. For example, if you own mycompany.com and you host public websites on it, you should use something like corp.mycompany.com or internal.mycompany.com for your Active Directory namespace. If you can do a domain rename (i.e. you have a simple client/server infrastructure with no Exchange in the domain), you should look into it. If you can't do a domain rename to fix this, you're in for some headaches. mycompany.com corp.mycompany.com internal.mycompany.com Edit: Per your update, you should absolutely redo this since the install is only 24 hours old. Absolutely no doubt about it. Having a split-horizon DNS situation is never a good idea when it can be avoided. You can still have mycompany.com be the NetBIOS name of the domain, so users see MyComapny\User instead of something like Corp\User, but the FQDN of your AD namespace and the FQDN of your public facing DNS namespace should not be the same. MyComapny\User Corp\User Go into your DNS Management Snapin. Right click on the DNS server you are managing. Select the "Forwarders" Tab and enter the DNS servers you want to forward requests to. Your internal zone matches your external zone, right? So company.com is your internal AD zone and your external public zone? If that's the case then it can't be done with Windows Server DNS, that I'm aware of. The Windows DNS server is authoritative for the zone as far as it's concerned so it's not going to forward requests for the zone to another DNS server, even if the request is for a DNS record that doesn't exist. It should in principle be fairly simple to create a PowerShell, VBScript or other tool that periodically queries an external DNS server, reads the external DNS IP addresses for given hosts, and updates them accordingly on the internal Windows server. I have looked several times but have yet to find one, and am disinclined to write it myself. By posting your answer, you agree to the privacy policy and terms of service. asked 2 years ago viewed 18617 times active
http://serverfault.com/questions/430274/how-to-configure-my-internal-dns-to-resolve-external-resources/430277
CC-MAIN-2015-32
refinedweb
579
62.17
I am using Jupyter notebook to manage 3D slicer. I am trying to control 3D slicer using python commands to automate the use of one Module. I want to edit the buttons of the module so that I can insert the data from Jupyter. For example, when it says insert Input volume, instead of using the 3D slicer GUI, use python commands. Can anyone help me with this, thank you!! I am using Jupyter notebook to manage 3D slicer. I would recommend to start with the Scripting and module development tutorial and then check out the Python FAQ for information on how to use CLI and Loadable modules from Python scripting. You can also find many examples in the script repository and in the modules section of the developer manual and in Python-scripted module tests. Since all these documentations are indexed by search engines, you can also google any question that you have. If you don’t find answers to any specific question (e.g., how to access a certain feature of certain module from a Python script) then you can ask it here. Thank you for your answer Andras, I am going to check all the provided information Hi. I couldnt find the solution to my problem. I am going to explain it better. I am using the a module and I want to automate the process. For example, in this box I need to choose “Create new volume”. Do you know if there is any python code I can write instead of having to click it with the mouse. If the YourExtension you want to automate has a YourExtensionLogic(ScriptedLoadableModuleLogic) class then you would need to find the settable parameters in that class. Example: This code sets some necessary things in the LungCTAnalyzer extension logic from a Python script. import LungCTAnalyzer from LungCTAnalyzer import LungCTAnalyzerTest from LungCTAnalyzer import LungCTAnalyzerLogic logic = LungCTAnalyzerLogic() # loadedVolumeNode and loadedMaskNode were created before logic.inputVolume = loadedVolumeNode logic.inputSegmentation = loadedMaskNode logic.rightLungMaskSegmentID = loadedMaskNode.GetSegmentation().GetSegmentIdBySegmentName("right lung") logic.leftLungMaskSegmentID = loadedMaskNode.GetSegmentation().GetSegmentIdBySegmentName("left lung") logic.setDefaultThresholds(-1050,-990,-650,-400,0,3000) logic.detailedSubsegments = True logic.shrinkMasks = False logic.countBullae = False When ready, you would logic.process() to do the actual work. Thank you for your answer. I am trying to use SlicerIGT (SegmentationUnet module) but there is no SlicerIGTLogic class, do you know any other way to achieve this? Gee this module is complicated. Could maybe @Sunderlandkyl or @lassoan provide a starting point for Isabella?
https://discourse.slicer.org/t/jupyter-notebook/24150
CC-MAIN-2022-40
refinedweb
412
50.73
mlockall() Lock all of a process's address space Synopsis: #include <sys/mman.h> int mlockall(int flags); Since: BlackBerry 10.0.0 Arguments: - flags - Flags that indicate which pages to lock; one or more of the following bits: - MCL_CURRENT - Lock the pages currently mapped into the address space of the process. - MCL_FUTURE - Lock the pages that become mapped into the address space of the process in the future, when the mappings are established. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The mlockall() function causes all of the pages mapped by the address space of a process to be locked and made memory-resident until unlocked, or the process exits or executes another process. The pages that are locked depend on the flags argument. Memory-resident is a term used to indicate that the addresses always reside in physical memory. For more information, see " Locking memory " in the Process Manager chapter of the System Architecture guide. In order to lock pages, your process must have the PROCMGR_AID_MEM_LOCK ability enabled. For more information, see procmgr_ability(). Follow either of the following approaches when attempting to lock pages: - Tightly controlled approach - Lock the pages one by one, by calling mmap() and then mlock(). - Global approach - Lock all pages at the same time, by doing one of the following: - Call mlockall(MCL_FUTURE), followed by one or more calls to mmap(). - Optionally call mmap(), and then call mlockall(MCL_CURRENT). Errors: - EAGAIN - Some or all of the memory identified by the operation couldn't be locked when the call was made. - EINVAL - The flags argument is zero. - ENOMEM - Locking all of the pages currently mapped into the address space of the process would exceed an implementation-defined limit on the amount of memory that the process may lock. lock. This implementation-defined limit is set by RLIMIT_MEMLOCK rlimit. - EPERM - The calling process doesn't have the required permission; see procmgr_ability(). Classification: Last modified: 2014-11-17 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/m/mlockall.html
CC-MAIN-2017-04
refinedweb
350
56.76
Our ListeningThread class will need to inherit from threading.Thread and contain a run method, which can happen in the background. Since we want to be always checking for new messages until the user closes their ChatWindow, we shall put our request inside a loop which the ChatWindow will be able to end when closed. Let's begin our ListeningThread class, as follows: import arrowimport threadingimport timefrom requester import Requester Our class will be making use of the following modules: - arrow: This is used to create the timestamps - threading: This is used to run in the background - time: This is used to sleep for two seconds between requests - requester: This is used to contact our web service With the imports taken ...
https://www.oreilly.com/library/view/tkinter-gui-programming/9781788627481/c147838c-7b74-4301-ab50-d186303de2ef.xhtml
CC-MAIN-2019-22
refinedweb
121
58.15
Advertisement how to logout the one link to another link hi, Iam Manikandan I want how to logout the page one link to another link. i given the link to my design pages logout only didn't came please mail me. HTTP Status 500 - ------------------------------------------------------------------------- Html Link I am vijay, I need,how to connect to one html link to another html link? and How to give 3 power points in one html link. Thanks. link link how can we give hyperlinks on data retrieved from the database and when a particular option is clicked it should be saved in another database and details related to that link should be diaplay and stored in the database swings:how to link from one form to another form swings:how to link from one form to another form how to link from one form to another form jdbc (); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost... information, visit the following link: JDBC Tutorials...jdbc how to display database contents? import java.sql. Hypertext link Hypertext link hii, What is a Hypertext link? hello, A Hypertext link is a special tag that links one page to another page or resource. If you click the link, the browser jumps to the link's destination mysql datasource - JDBC mysql datasource hello there......... i'm a real beginner for mySql can any one tell me how i do configurations in my windows machine after...,configuration and important mysql executable files etc.This link also contains some mysql how to give link from jsp to jsp page how to give link from jsp to jsp page hi this is my following code...;/tr> <% Connection con = null; String url = "jdbc:mysql://localhost:3306...(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost jdbc - JDBC = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "root...jdbc How can i store images in a database column without a front end... Friend, For inserting image into database,please go through the following link
http://roseindia.net/tutorialhelp/allcomments/4619
CC-MAIN-2015-48
refinedweb
327
55.54
4: The cost In July 2014, JS Bin finally landed Pro accounts. The aim of this would be for JS Bin to eventually be self-sustaining. It's been running out of my pocket for the previous 6 years (for server and related costs), and development and design (2014 excluded) had been lovingly "donated" by myself and Danny (who is responsible for the design). In 2014, I decided to give JS Bin a full shot, and employed two (amazing) developers, Giulia Alfonsi and Fabien O'Carroll to work with me full time on JS Bin. At the end of May 2015 (10 months after launching pro) the income JS Bin has provided has only just covered operating costs for the previous year. That's awesome and terrible at the same time. Before "pro" it was making a 100% loss - so that's something, but it doesn't even touch the edges of what I had hoped it would return (and I wasn't even being optimistic, as any British person would expect). But there is a cost to taking money... VATMOSS VATMOSS was a change to the way that VAT is processed in the EU. Unfortunately, the geniuses behind the change at the EU (or whatever rock they hide under) hadn't quite thought the whole thing through. The information was thin, convoluted, confusing and not really accessible to small companies like myself and many others. This is the landing page for the EU European Commission's Digital Market: The European Commission is the EU's executive body. It represents the interests of the European Union as a whole (not the interests of individual countries). The slogan: bringing down barriers to unlock online opportunities. What a crock of shit. VATMOSS has single handedly killed off new business and for others made it more difficult for others do to their commerce. It's worth reading around the back story of VATMOSS, and even in mid-2015, it's there's a fight for change going on. The VATMOSS reporting is now (as of 1-Jan 2015) a requirement for anyone in the EU selling digital services or goods (i.e. ebooks, apps, subscriptions...JS Bin Pro subscriptions), and there was (and is) the threat of fines if you don't report and pay on the sales correctly. VATMOSS requires that you charge the VAT of the country of your customer. i.e. if the customer is English, 20%, if they are Danish 25%. Also, you have to capture three proofs that you're charging the right country (it's actually 2 proofs, but you need a 3rd backup proof). If these are all in conflict... ¯\(ツ)/¯ The last month of 2014 were riddled with stress from the VATMOSS changes that I had to complete on JS Bin. It took weeks to try to fully understand VATMOSS, and what exactly would be required to satisfy requirements. In the end, the development time was about 2 week for both myself & Fabien (employed to work on JS Bin) and about two weeks of research, filing and accounting time on Julie's part (my business partner - and wife). Estimated business cost: £3,500. £11.70p. VATMOSS, the stress of it all, to collect pennies from seven people. It would have been cheaper to book flights to each of their addresses to collect the cash by hand. It was not fun. Fraud credit cards Since pro accounts initially cost £6 for month, it turns out that this is low enough that it won't send red flags to stolen cards. This means that JS Bin was being used as a testing ground for stolen card numbers. If the card went through then they would use the card. Unbeknownst to me, the user wouldn't do anything on JS Bin, and I'd be on my merry way thinking I had a new pro sign up. Eventually, the rightful owner would think, "What's this 'JS BIN PRO MONTHLY' doing on my statement", follow up with their bank, and raise a fraud complaint. I can't win the complaint. The card was stolen, the £6 belongs to the original card owner, no question. But! If there's a dispute on Stripe, there's transaction fees for reversing charges. £15.34 in fact. Since I know I'll lose the dispute, it's cost me, £21.54 to allow some shithead to use JS Bin as a stolen card testing facility. My process now is that I've taken to checking each and every individual sign up and their bins to see if they look spammy. I caught my first fraud card and reported on 13-April 2014. Not a huge success but very satisfying to know I've avoided the charge. Woot! Pro Pro accounts was never the intention when I launched JS Bin back in 2008. I'd made stupid efforts to avoid having user accounts for quite a few years, but insisted that it should be 100% free. I don't know why. During 2013, I attended a lot of events where individuals kept coming up to me asking how do they pay for JS Bin, or why don't I add Pro, or explained that the only reason they used CodePen over JS Bin was that they were paying (i.e. the perceived security of data from the business exchange). The more I considered it, the more I realised I wanted to do JS Bin full time, and work on something I loved. I ran some numbers based on registered users in the database, and factored for about 20% spam/idle users, and then put my aims at 1% conversion. It didn't seem like much. The problem was: that's all I did. There was no business plan. There was no business development team. There was no marketing plan. There was no deadlines. There were no aims. So there my amazing product sat. To others it was ready to launch, but I was still heads down focused on the last 1% stretch, so it was parked. I'd had the odd conversation that suggested I might be able to get funding from the government (as JS Bin is a tool primarily for learning), but I'd shy away from the idea of having to do "business" stuff. It scared me a little too. Launching became the well know problem of chasing the end of the rainbow. Striving for the perfect, polished product before everyone else had access to it. Sure we had some alpha users in there, but they weren't invested in JS Bin any more than you are, so feedback came when they had some time. This went on for months and months. All the while JS Bin isn't making money, my entire company is focusing it's time on JS Bin and not producing any cash flow from any other sources. Pro (eventually) went live on 23 July 2014. And the first wave of registrations was an amazing feeling. In fact, one user (David Gauld, who actually worked for me doing the Left Logic redesign and built a fair amount of confwall) was the first to go pro catching the commit landing in Github, even before I had announced it - a cool side effect of the open source. Users did come, but looking back, it really wasn't very much if you consider the costs of running JS Bin, let alone paying for development, and then look at what the monthly (or yearly subscriptions) got us. A total of 42 upgrades in the first week (26 were on the first day). I had always tucked money aside for a rain day (actually rainy year), and yeah, I can look back and say "sure, I took a shot" - but it came at a pretty penny. The next 6 months I lost my love for the project. Very simply: any new development had to justify its existence and its demand on my time. I did continue development until the end of 2014, but by that point, all love had been sucked dry and I needed a break. JS Bin is solid enough that it can run without day to day attention and I could return to client work and try to recover my now sad looking business bank balance. Plan, and know what your users need There were two major problems that hurt the success of JS Bin Pro. The first was the nearly zero planning, and strange fear of business, marketing and actually making money. I often associate with the underdog, and those users looking for free access. But I run a service that's abused from all directions and every new user is more of a burden than growth. Very simply put: should I want to run a service for 100 paying users or for 100,000 non-paying users? Me? Now, I realise it's the 100 paying users, because, honestly, I've got bills that I want to pay. I'd rather pay those bills building something I love rather than building something I begrudge. I lost a lot of love in this area of working with JS Bin. I can take the spam, and the junk, but this part of JS Bin required that the project actually raises money to support itself - and constantly feeling that I had to deliver some part of code for JS Bin to continue...it just didn't work for me. The second, major issue was that I had hoped, naively, that the web community will swoop in and pony up some cash. But the bottom line was JS Bin Pro had nothing that users needed. Sure, now it has asset uploads and other features, but at the time, there wasn't anything users really needed. I pay for my Github account because I need private repos. I pay for Gmail, because I need real business email accounts. I pay for Dropbox because I need the extra space. With JS Bin, everything users need is given away and open source. That's honourable, but doesn't pay the mortgage. The next time around, with products like Confwall, I launched as soon as it was usable. I offer a free area, but I make sure that you can't get to the stuff you need unless you pay. The way it should be! In fact, at time of writing this post, Confwall still doesn't take payment online - I cut that part to launch as early as possible, and we handle payments via email & invoices. Part 5 sees our conclusion and tells of the police encounters I've had, along with the worst email I've ever received.
https://remysharp.com/2015/09/17/jsbin-toxic-part-4
CC-MAIN-2018-51
refinedweb
1,786
79.6
GNULife wrote .. > Now, it return the error: > > Mod_python error: "PythonHandler mod_python.publisher" > > ImportError: No module named head Sorry, my psychic powers aren't working very well today. :-) You are going to have to provide your code, what the name of that code file is and what URL you were using is. > How to access like " under > mod_python.publisher ? You can always set up mod_python.publisher as: AddHandler python-program .html PythonHandler mod_python.publisher Do this though and you can't have static .html files in the same directory as mod_python.publisher expects to be handling all .html requests. It also doesn't work well if you expect to have multiple published methods in the same file, whether in a flat namespace or hierarchical by using objects. This is because the URL for the published methods ends up actually being something like: Ie., the ".html" extension isn't at the end of the URL. The only other option you have is to get messy and use mod_rewrite to remap actual ".html" URLs to mod_python.publisher style URLs on the fly. Other than that, you would have to look at using an alternate extension package for mod_python that focuses more on resource based URLs where the URL reflects the type of content being returned. When using mod_python.publisher you almost have to use REST style URLs, ie., no extension to stop the ".py" appearing. Maybe you would like to explain what you are trying to achieve and whether you are using some templating system or using handcrafted HTML. People may then be able to suggest better alternatives. Graham
https://modpython.org/pipermail/mod_python/2005-July/018567.html
CC-MAIN-2022-21
refinedweb
266
68.26
8 6 910 CALIFORNIA POLICY OPTIONS School of Public Affairs The Ralph and Goldy Lewis Center for Regional Policy Studies 1 California Policy Options 2010 Copyright 2009 for Regional Policy Studies, UCLA School of Public Affairs, Box 951656 Los Angeles, California 90095-1656. Editor: Daniel J.B. Mitchell Editorial Assistant: Mohib Qidwai Publication Design: Tiffany Huang 4 2010 CALIFORNIA POLICY OPTIONS EDITED BY DANIEL J.B. MITCHELL School of Public Affairs The Ralph and Goldy Lewis Center for Regional Policy Studies 3 About the Ralph and Goldy Lewis Center About the UCLA School of Public Affairs The Ralph and Goldy Lewis Center for Regional Policy Studies in the Founded in 1994, the UCLA School of Public Affairs incorporates UCLA School of Public Affairs was established to promote the study, best practices in scholarship, research and teaching in the fields of understanding and solution of regional policy issues, with special ref- Social Welfare, Urban Planning, and Public Policy. The unique erence to Southern California, including problems of the environment, intersection of these disciplines within one School allows for academic urban design, housing, community and neighborhood dynamics, trans- cross-collaboration and a graduate education that values perspectives portation and economic development. It is a focus of interdisciplinary at the macro- and micro- organizational levels. Graduates of the activities, involving numerous faculty members and graduate students master’s degree and doctoral programs are well prepared to take from many schools and departments at UCLA. It also fosters links with leadership roles and effect change as practitioners, researchers, researchers at other California universities and research institutes on and policymakers in the public, private, and non-governmental issues of relevance to regional policy. sectors. Faculty of the School of Public Affairs are actively engaged in research that address pressing national and regional issues including immigration, drug policy, prison reform, health care financing, transportation and the environment, national security, economic development, and an aging U.S. and world population. 201 TA B LE O F CON T EN TS 6 7 p.10 1 p . 6 Preface p . 7 Introduction Planning at the Intersection of State and Main: Update on California’s SB 375 Cara A. Horowitz p.28 2 Carbon Costs and Household Electricity Expenditures in California Michael J. Sandler p.44 3 Getting on Board: How Public Transit Can Put California Back on Track Dustin Maghamfar p.68 4 Harnessing the Market to Discourage Sprawl in California Philip J. Romero p.88 5 Passing a Gun Control Law in California: A Case Study of the Crime Gun Identification Act William Parent p.104 6 Stagnant Wages: California’s Interior Metropolitan Areas Michael Manville and Matthew P. Drennan p.122 7 Shades of Gray Daniel J.B. Mitchell p.162 8 California’s Volatile Taxes: Healing a Self-Inflicted Wound Jerry Nickelsburg p.182 9 Recovery is Certain for California —When is Not Christopher Thornberg 5 P R E FA C E The Ralph and Goldy Lewis Center’s’s. Many thanks go to Professor Daniel J.B. Mitchell for editing a volume that is both timely and provocative, giving a broad perspective on the historical policy decisions that led to our current situation, and innovative perspectives on building a sustainable future for all Californians. Franklin D. Gilliam, Jr. Dean UCLA School of Public Affairs 6 I NTRODUCTION California faces particularly difficult issues in 2010. Philip Romero, in his chapter, suggests a market- Some of the challenges are immediate and revolve based mechanism for reducing urban sprawl. He around the state budget, dysfunction in state suggests that such a mechanism would be preferable government, and the severe slump in the California to zoning mandates. His “smart district” concept economy. Other challenges are longer-term and involve would encourage higher density by giving some of the trends in income distribution and the environment. revenue generated in district back to the district itself. Romero provides estimates of the impact of adoption In the opening chapter, Cara Horowitz reviews the of the smart district concept on state economic activity features and implication of SB 375, a major piece and job creation. of environmental legislation enacted in 2008. The new law potentially touches on land-use planning The California legislature has been especially subject to and regulation and transportation (especially criticisms of dysfunction and is perceived unfavorably driving). While the law creates a variety of planning by the public according to opinion polls. However, requirements to mitigate greenhouse gas emissions, William Parent provides an example of a 2007 law— Horowitz notes that it is unclear whether the result AB 1471—that did pass successfully through the will be a proliferation of planning documents or legislative process involving gun control. His chapter actual implementation. provides a detailed description of the background of the proposed law and how it developed within Michael Sandler, in his chapter, focuses on a related the legislative system. The law involved use of topic: state electricity regulation as it relates to carbon microstamping technology, a process enabling guns to dioxide emissions. Sandler notes that efforts to reduce be traced more easily. Parent describes the techniques such power-related emissions will add costs to the used by proponents and opponents as the bill moved typical California household electricity bill. A switch to through the legislature and provides insights into the renewable energy sources involves a higher direct cost workings of the state’s legislative branch. of electricity than, say, coal-generated power. Sandler provides alternative calculations of what that cost Michael Manville and Matthew Drennan describe might be. the gap between wage income in central California relative to the more prosperous coastal regions. In the The third chapter by Dustin Maghamfar looks at how 1960s and 1970s, the trends in real wage growth in California might encourage the use of public transit. the central and coastal regions were broadly similar, Because of the state budget crisis, funds that might go although the central areas had lower real wages than for transit are being diverted to the general operating the coast. Thereafter, however, the central-coastal budget of the state. Such diversion goes against state gap began to widen. Manville and Drennan examine policy aimed at reducing greenhouse gas emissions, the the usual suspects cited in explaining the growing goal of SB 375. Maghamfar argues that price signals gap—changing demographics (including immigration), need to aim at making use of public transportation industry mix, and educational attainment. They find more attractive to Californians. that the locational trend in the development and shift 7 of the knowledge sector toward the coast provides an In effect, the added Prop 13 revenue to the state important explanation. would be used to reduce the income tax in an equivalent amount. Daniel Mitchell notes that Governor Gray Davis was recalled in the midst of a major state budget crisis California is part of the larger U.S. economy and in 2003 and replaced by Arnold Schwarzenegger its recession—and the budget crisis the recession who campaigned on his ability to fix the budget. But triggered— reflects national trends. However, as Governor Schwarzenegger, after borrowing to deal with Christopher Thornberg points out in his chapter, the the Davis crisis, began to face a renewed budget crisis state has its own unique characteristics including in late 2007. In his chapter, Mitchell analyzes the fiscal having played a disproportionate role in the housing rise and fall of Governor Davis. He suggests there is an bubble. There were some signs of an economic underlying economic reality that caused California to turnaround in late 2009, but problems remained to be be prone to budget crises, despite the substitution one resolved including mortgage foreclosures to come. governor for the other. Mitchell notes that California Thornberg notes that California retains important had experienced particularly rapid economic growth locational and other advantages. Permanent decline from World War II to the end of the Cold War, growth is not likely although a continued soft economy is that provided revenue for infrastructure and social probable in the near term. programs. In a sense, California has never recovered from the recession of the early 1990s when the Cold War came to an end. The state has not adjusted to the Daniel J.B. Mitchell slower growth thereafter. Professor Emeritus UCLA Anderson Graduate School of Management One problem that has been highlighted in discussions of California’s budgetary problems is the volatility of its tax sources, particularly the income tax. Jerry Nickelsburg suggests a possible solution to tax volatility. Although Proposition 13 of 1978 is often seen as a cause of California’s proneness to fiscal distress, Nickelsburg suggests it could be the key to reducing tax volatility. Because Prop 13’s assessment mechanism means that most property is valued below market, it has become a comparatively stable revenue source for local government. A modest increase in Prop 13’s tax rate, combined with its current under-market assessment mechanism, could lead to greater state revenue stability, if the incremental revenue could be diverted to the state in a revenue-neutral fashion. 8 and UCLA School of Public Affairs 9 1 10 P L A N N I N G AT THE INTERSECTION O F S TAT E A N D M A I N : U P D AT E O N CALIFORNIA’S SB 375 CARA A. HOROWITZ 1 Cara Horowitz is the Andrew Sabin Family Foundation Executive Director of the Emmett Center on Climate Change and the Environment. The Emmett Center, housed at UCLA School of Law, was founded in 2008 as the nation’s first law school center focused exclusively on climate change. Horowitz teaches classes on climate law and policy and directs the Emmett Center ’s research and advocacy. 11 1 A little more than a year ago, with a fair amount of hoopla, California became the first state in the nation to pass a bill aimed at decreasing driving as a means to reduce greenhouse gas (GHG) emissions. Such emissions are those responsible for global warming and other forms of climate change. The state did so by taking on the complex nexus of land use, transportation, and housing. Simply put, the legislature set a course aimed at changing neighborhoods, highways, transit options, and other land-use patterns to reduce our miles on the road. The goal was ambitious, especially for the purported home of the drive-through restaurant. 2 And it is too early to determine whether the law, known as SB 375, 3 will significantly and cost-effectively reduce greenhouse gas emissions from the transportation sector. But it has certainly garnered media attention. The law won praise from the New York Times editorial board (which called it “[t]he latest example of California’s originality” and urged other states to follow suit).4 At the other end of the spectrum, the Orange County Register called it “one of the most authoritarian, far-reaching and elitist bills that has ever made it to the Governor ’s desk”.5 Other media reaction ranged between these two points of view. For land use planners, SB 375 has served as a Rorschach test. At the time of its enactment, some observers considered it the most important change in planning law since the California Environmental Quality Act (CEQA). Others saw it as providing “incremental change, not land use revolution.” Opinions about its worth often reflected both varied beliefs in the utility of centralized land use planning and one’s stake in the bill’s creation and passage. 6 The first few steps of SB 375 implementation have now been taken. Much has been written about the law, but this chapter provides relatively brief answers to three questions: What gave rise to the law? What does it say? And what has the first year of implementation revealed about its significance and its likelihood of success? 12 GRAPHING THE VMT GORILLA “In order to reach California’s greenhouse gas reductions goals set out in the Global Warming Solutions Act of 2006 (AB 32), we must rethink how we design our communities.” 7 Figure 1. Percent of GHG Growth 1990-2004 60% 50% 50.2% 40% 30% 23.4% 20% —California Office of the Governor 11.6% What gave rise to SB 375? In short, the state was inspired to act by a tale of two graphs and a city. The 8.9% 10% 4.9% 0% tale begins with California’s passage, in 2006, of its C a r s a n d L i g h t Tr u ck s landmark Global Warming Solutions Act, also known A g r i cu l t u re , F o re s t r y, e t c . as AB 32. That act calls for a return to 1990 levels of In du s t r i a l P ro ce s s e s a nd P rod uc t s state greenhouse gas emissions by the year 2020. Two E l e ct r i ci t y initial questions were asked by the agency assigned Ne t Ot h e r Horowitaz 1 the task of figuring out how to reach this goal, the California Air Resources Board (ARB). First, what are It made plain that returning to 1990 levels of GHG the main sources of our current emissions? Second, emissions would be very difficult without including which emissions sources have accounted for the most significant measures to tackle transportation emissions growth in emissions since 1990, the target year? and, in particular, passenger vehicle emissions. T R A N S P O R TAT I O N EMISSIONS This result was no surprise. Indeed, California had already begun, even before the passage of AB 32, to design measures to reduce greenhouse gases from passenger cars. In 2002, the legislature required new, first-in-the-nation standards to lower greenhouse gas The answers to both questions pointed toward a high- emissions from passenger vehicles to the maximum profile emissions culprit: transportation. ARB learned extent feasible and cost-effective. Known as the that about 40% of the state’s greenhouse gas emissions Pavley regulations (for assembly representative Fran come from transportation sources, 30% from passenger Pavley, sponsor of the bill), the standards required vehicles such as cars and light trucks. Even more improvements in vehicle efficiencies and design. striking, passenger vehicles accounted for more than These requirements included—but were not limited to 50% of the growth in the state’s GHGs since 1990 – the —improved fuel efficiency. 9 The state also had begun growth that AB 32 sought to erase. This damning fact work on a low-carbon fuel standard, aimed at reducing —illustrated in the graph at Figure 1—appeared early the carbon intensity of fuels used to power passenger in the AB 32 implementation process: 8 vehicles by at least ten percent by 2020. 1 0 13 INSUFFICIENT MEASURES fuel standard and the Pavley regulations. But what about the third leg of the stool, the number of miles driven? The state quickly concluded, however, that measures Enter the second influential graph—Figure 2—which addressing fuel content and vehicle technology alone can be thought of as the VMT Gorilla Graph. It are insufficient to tame greenhouse gas emissions from served to convince legislators that California had to passenger vehicles. GHG emissions from cars are address the third leg, too. The graph, of which there a product of three variables, sometimes referred to as were actually several versions, was crafted by the three legs of a stool. These variables are 1) the carbon environmental advocacy group, Center for Clean content of fuels (GHG per gallon), 2) the design of Air Policy. It was widely distributed through several the vehicle (determining miles per gallon and other channels in 2007 and 2008, including via the California efficiencies), and 3) the number of vehicle miles League of Conservation Voters (CLCV), Natural traveled (VMT). California had plans underway to Resources Defense Council (NRDC), and Smart address the first two of these, through the low-carbon Growth America. The graph was also included in an Figure 2. Percent of GHG Growth 1990-2004 170% 160% 150% 140% 130% 120% 110% 100% 9 0% 8 0% 7 0% 6 0% 5 0% 2005 Vehicle Miles Traveled 2010 C O 2 E missio n s 2015 2020 Fu el: Lo w C a r b o n S t d Ve h i cl e S t ds ( A B 1 4 9 3 ) 2025 2030 1 9 9 0 : Tr a n s p C O 2 E missions H o r o w i t a z 2 : C e n t e r f o r C l e a n A i r P o l i c y, B a s e d o n C E c , C A R B a n d C A LT R A N S d a t a 14 influential new book on transportation and greenhouse gases, Growing Cooler. 11 Most developments would no longer be single-use subdivisions or office parks, but would mix shops, schools, and offices together with homes. They In a visually stark way, it showed that California’s might feature ground-floor stores and offices with projected growth in VMT—because of both population living space above, or townhomes within walking growth and growth in miles driven per person—would distance of a retail center.” cause GHG emissions from passenger vehicles to rise at a rate that would outstrip our planned low- This statement reflected a vision of compact carbon-fuel-standard and Pavley-regulation advances. development that had been around for a while, but the It would prevent California from reaching its 2020 fight to reduce GHG was giving it new life. 1 5 emissions goals. VMT was simply the unstoppable gorilla in the equation, keeping CO2 emissions rising even after accounting for other measures: 12 So, too, was the experience of the most influential city in the SB 375 tale, Sacramento. In 2004, the greater Sacramento region undertook a project to coordinate As the authors of Growing Cooler wrote, “The local governmental planning decisions. With phrase ‘you can’t get there from here’ has a new coordination, they all might be guided, for the first application.” 13 California’s passenger vehicle GHG time, by a larger, voter-approved vision for growth in emissions would remain well above 1990 levels in the region. Called the Blueprint project and led by the 2020 unless something was done to reduce the number Sacramento Area Council of Governments (SACOG), of miles Californians were projected to drive. And a regional planning organization, the project aimed that meant tackling land use—literally changing the to curtail the sprawl pattern developing around the structure of our communities—which for so long had state’s capitol.1 6 been built on assumptions of cheap gas, expanding freeways and suburban growth. SACOG crafted, through extensive public involvement, several options for “growth alternatives” and asked REDUCING VMT: THE SACRAMENTO APPROACH county residents to vote on those options. Ultimately, SACOG adopted a regional blueprint that “provided the same number of housing units and jobs, and served the same population” as did the business-as-usual scenario, yet with a much smaller urban footprint. 1 7 Development would be constrained to areas close to the urban core, transportation options would be What would VMT-reducing land-use patterns look like? Ewing et al. described their vision: improved, and congestion would be reduced. 14 More importantly for this story, VMT would be “Many more developments would look like the reduced, too—as much as 25% per household by transit-oriented developments and new urbanist 2050, according to ARB, largely due to more compact neighborhoods already going up in almost every development and improved transit.1 8 Sacramento had city in the country, and these developments provided a blueprint for the state just at the right time, would start filling in vacant lots or failing strip illustrating how planning that reduces miles travelled shopping centers, or would revitalize older town could be politically palatable and provide significant centers, rather than replacing forests or farmland. ancillary benefits. State senator Darrell Steinberg, 15 SB 375’s author, emphasized early and often that the for large developments. But they were willing to do so bill simply called for: to get strong greenhouse gas targets tied to regional transportation planning requirements. The building “a process similar to a process pioneered in [his] industry, according to Ray Becker, chairman of the region of Sacramento, known as “the blueprint,” California Building Industry Association, had spent which essentially says that we need to plan as a three decades fighting “regional planning and regional region, not just as individual cities and counties. government.” But it endorsed the bill after concluding Air quality, traffic congestion, and carbon know that “we cannot continue to do business as usual.” no artificial boundaries. These issues must be The industry was wooed, in part, by the potential for tackled regionally. . . . SB 375, again, does not streamlined CEQA approvals. 2 1 20 impose any particular vision on any region. It says, ‘We want you to do what SACOG has done so successfully.’” 19 The California League of Cities and other local and regional governmental representatives initially opposed the bill. But they lobbied hard for It certainly didn’t hurt that the successful Sacramento amendments to ensure it would not restrict local model was playing out in legislators’ front yards. authority or, importantly, access to transportation Having seen both the need for a land-use GHG bill and funding. 2 2 Having won those and other amendments, a path to success, the legislature was primed to act. the League came around in the last weeks of debate to endorse it unanimously.2 3 In Senator Steinberg’s words, this was “the first time in the country that the THE “IMPOSSIBLE COALITION” issues of land use, transportation, housing and climate change ha[d] been brought together in a comprehensive piece of legislation.”2 4 SB 375 passed and was signed into law in September 2008. Though the global warming crowd and key legislators were convinced of its necessity, winning passage of SB 375 was not easy. Its success ultimately depended W H AT S B 3 7 5 S AY S on bringing together, and holding together, interest groups that had been at loggerheads for decades. “SB 375 does both less and more than you think.” 2 5 In the past, there had been collisions over housing, —Bill Higgins, legislative representative, transportation, and CEQA issues, involving the League of California Cities building industry, environmental groups, local governments, and affordable housing advocates. The The central goal of SB 375 is to reduce greenhouse gas disparate grouping of supporters attracted by the bill emissions from passenger vehicles by reducing VMT was, in late summer 2008, seemingly held together below business-as-usual projections. It aims to achieve with package twine and was dubbed by many the this goal by requiring regional planners to envision “impossible coalition.” and set forth a strategy for how such GHG reductions could be achieved in their region. Then it provides Environmentalists, including the California League incentives for on-the-ground land use decisions to of Conservation Voters and NRDC at the fore, had match the regional plan. As many observers have historically been loathe to lessen CEQA requirements noted, the bill contains no mandates that might control the outcome of any particular land use, housing, or 16 transportation decision.2 6 At its heart, SB 375 is In addition, there is the availability and convenience a planning tool. of alternative transportation (such as public transit, carpool/vanpool choices, and bike lanes) and pricing As the first step, the law requires the California Air signals (gas prices, congestion pricing, parking costs). Resources Board, the same state agency charged with implementing AB 32, to give each of California’s 18 SB 375 gives each region the flexibility to design a plan pre-defined planning regions a numerical target for to meets its GHG target through any combination of reducing their passenger vehicle GHG emissions. measures affecting these or other factors. One region How that target is set, and what it is likely to look like, might adopt an urban growth boundary, hike parking is discussed below. ARB is charged with announcing fees and improve bike paths. Another might build these regional targets by September 2010. new light rail to serve outlying regions and impose congestion pricing to discourage car commuters. The From there, regional planning bodies—called sole requirement is that the state, through ARB, review metropolitan planning organizations or MPOs—take the plan and agree that it would, if implemented, their GHG reduction target and craft a land-use achieve the regional GHG target. and development plan of their choosing. The plan, if implemented, must meet the target, taking into Once the plan is approved and in place, nothing account projected growth, housing needs, and natural requires the MPO, local governments, developers, or resources and farmland. The resulting plan is called anyone else to follow its contours. Such laxity was a Sustainable Communities Strategy (SCS). It is at the necessary for passage of the bill. But incentives kick in heart of SB 375. For reasons made clear below, the bill which are designed to make projects that are consistent requires that the Sustainable Communities Strategy with the plan look more attractive than those that be incorporated into the region’s periodic Regional are not. Transportation Plan. Regional Transportation Plans are preexisting planning requirements undertaken by each MPO every four years or so. These plans derive from federal law. 27 INCENTIVES T O C O M P LY CONTENTS OF A S U S TA I N A B L E COMMUNITIES S T R AT E G Y First, federal transportation funding is available only for projects consistent with a Regional Transportation Plan—including the new Sustainable Communities Strategy element . 2 8 As explained by the bill’s sponsors, NRDC and CLCV, “[b]y placing the SCS inside the regional transportation plan, transportation funding becomes a powerful incentive for its implementation.” 2 9 Second, certain residential What sorts of measures might be included in and mixed-use developments that are consistent a Sustainable Communities Strategy? There are with the regional plan are offered exemptions from many determinants of VMT, including housing select environmental review requirements under the and commercial development choices such as the California Environmental Quality Act. density, diversity, and location of new construction. 17 For example, some developments need not include an “good” projects and, just as importantly, limits federal analysis of growth-inducing impacts or impacts on funding for projects inconsistent with its vision. global warming from project-related car trips. A smaller, more carefully selected group of high- How many MPOs adopt Sustainable Communities density projects near transit stops need only complete Strategies that meet their GHG reduction targets an environmental assessment (EA), not a full environ- in this first round of SB 375 compliance is an open, mental impact statement (EIS). And a very narrow and important, question. Both forms of the required class of projects escape CEQA review entirely. 30 These regional plan, of course, serve to chart a concrete CEQA incentives may be attractive to developers and path toward communities in which people drive local governments now that the California Attorney less—potentially helping build political will to follow General’s office has stepped up enforcement of CEQA that path. Each region, for the first time ever, will have requirements related to global warming. Over time, harmonized its transportation growth plans, housing the theory goes, such incentives will slowly change the growth plans, and greenhouse gas reduction plans into structure of a community so as to reduce VMT. one comprehensive strategy. THE FEASIBILITY I M P L E M E N TAT I O N ISSUE S O FA R But what if a region concludes that meeting the GHG A year after passage, the state has met its statutory reduction target set by ARB is simply infeasible, given deadlines for implementation. But much still remains realistic travel forecasts or constraints on the region’s to be done. As required by SB 375, an advisory funding, land-use authority, or ability to impose fees? board consisting of wide-ranging stakeholders was What if the region believes it can’t realistically get convened in early 2009 to assist the ARB. It included the job done? In that case, the region must prepare representatives of local governments, environmental a standalone document called an Alternative Planning groups, developers, transportation agencies, housing Strategy (APS). In an APS, regions must identify advocates, and others. The board, called the Regional the main impediments. They must then show what Targets Advisory Committee (RTAC), was given the alternative development patterns, increased transit task of recommending “factors to be considered and programs, or other policies would—if impediments methodologies to be used” by ARB in setting regional were overcome—accomplish the GHG goal. GHG reduction targets. It held discussions for about 8 months and issued its final report on The decision about whether it is “feasible” to meet September 30, 2009. 3 1 ARB’s targets is left largely to the discretion of each MPO. And that decision appears to matter greatly. Key recommendations of the report include: Although both Sustainable Community Strategies and Alternative Planning Strategies provide CEQA 1. That ARB’s regional targets be expressed as incentives to projects consistent with them, only an a percent per-capita GHG emission reduction SCS is formally part of the transportation plan. Only from a 2005 base year. This metric, the committee an SCS, therefore, is tied to transportation funding concluded, would appropriately account for mechanisms in a way that funnels federal funding to differences in growth rates among regions. It 18 would require the greatest changes in regions with The disagreement reflected a fundamental division the highest per capita emissions. between committee members and, in some, perhaps 2. That ARB choose targets based on a statewide ambivalence about the entire project of judging uniform target. But that it allow for adjustments land-use decisions based solely on their ability to up or down for each region, depending on regional reduce GHGs. To some, the purpose of SB 375 is to differences (such as transit infrastructure). create better transit, more compact neighborhoods, 3. That chosen targets be “the most ambitious and other on-the-ground changes to development achievable” for each region and “not be set low patterns. So why not permit regions to declare success simply to allow MPOs to meet their targets with once they can show a plan that adopts these best the SCS.” 32 land use practices and on-the-ground changes—even 4. That the state quickly develop a spreadsheet tool for “Best Management Practices” (BMP). This tool without a model capable of predicting resulting GHG reductions? would list available land-use and transportation policies and practices and associated VMT What more should the state be asking for beyond reductions, to assist ARB and the regions in the embrace of best practices, in the view of some their planning. committee members, especially from smaller MPOs? 5. That the state take steps to secure increases in Others, especially those who had witnessed the funding for transit and transportation planning. success of the model-driven Sacramento Blueprint Project, believed that a list of best practices would be DISAGREEMENTS no substitute for calculations of the amount of GHG reductions actually achieved over time. Unable to agree on a recommendation on this point, the RTAC sent the question on to ARB. 3 5 Potentially even more illuminating than its final recommendations, however, are the debates RTAC had as a committee and the points on which it could not agree. Much of the committee’s time was spent assessing available travel demand models, the modeling capabilities of the state’s 18 MPOs, and the UPCOMING DEADLINES extent to which use of those models should be required for all MPOs in implementing the bill. The committee The next implementation steps will be critical. Under agreed that its assessment revealed significant the plan recommended by RTAC, each region will variations among the models being used and the gather data and work cooperatively with ARB to capacities of MPOs to employ them. It also agreed on suggest its own regional target by March 1, 2010. 3 6 the need to “augment” travel demand models with ARB then must propose draft regional targets by June other methods to inform choices under SB 375, such as the Best Management Practices tool described above. 33 30, 2010 and decide on final targets by September 30 of that year. San Diego will be the first region to attempt It could not agree, however, on whether MPOs should to prepare a Sustainable Communities Strategy, for have the choice of relying solely on BMP tools, rather inclusion in its Regional Transportation Plan slated than travel demand models, to assess compliance with to be adopted in July 2011. Other regions, including the ARB target. 34 Southern California, will follow closely behind. 19 OPEN QUESTIONS AND POTENTIAL BARRIERS regional coffers and transit funding in an attempt to do it. It has taken nearly $2 billion from the State Transit Assistance program since 2007, essentially defunding that program over a three year period . 3 9 And municipalities, counties, and regional organizations have all been squeezed. At this writing, litigation over “If we want to do this stuff, we’ve got to figure out such raids is ongoing.4 0 how to pay for it.” 3 7 —Gary Gallegos, RTAC member and executive director of the San Diego Association of Governments The effects of the state budget crunch on local planning departments, in particular, have been dramatic. These departments are where regional plan theory meets Given these developments, what did the first year of project approval practice. They are where much of implementation indicate about SB 375’s significance the work of implementing Sustainable Communities and its likelihood of success? There are at least two Strategies will take place. potential speed-bumps (or even roadblocks) to success. The first and most important obstacle concerns the In the last year, Sacramento County proposed effect of the state’s budget woes. The second is the a $900,000 cut from its planning department, the nature of Southern California. equivalent of more than six full-time positions. 4 1 The City of Petaluma is reported to be disbanding its T H E S TAT E BUDGET CRISIS planning department entirely, laying off all remaining planners and its development director after reducing from 23 to 11 employees. 4 2 And the visionary Los Angeles City Planning Director Gail Goldberg has reduced her staff by a third and imposed furloughs It is clear from RTAC’s deliberations that current on nearly all who remain. The consequence, in her planning models do not yet provide realistic words, is that “[l]ong-range policy work has stopped projections of VMT reductions from land-use and or slowed.”4 3 transportation changes. Many of the state’s MPOs do not have the data, expertise, or manpower to employ these models. 38 Money will be needed to improve Unless the SB 375 mandate is followed with money, it won’t yield the results desired. There are a few models and to design “best management practice” mechanisms underway, or being considered, to tools such as those recommended by RTAC. improve funding for planning. A bill was passed by the legislature in fall 2009, sponsored by the California Money will also be needed to employ the planners Association of Councils of Governments. SB 406 necessary to create accurate regional forecasts and would have permitted regions, county transportation translate them into project approvals. Finally, funding commissions, and specified air regions to impose up to is needed to ramp up transit projects to support a $2 surcharge on vehicle registrations. The surcharge envisioned smart growth developments. would pay for models, planning staff, and other planning expenses related to reducing VMT. If each But since SB 375 was passed, California has struggled agency adopted at $2 fee, it was expected to generate mightily to balance its budget and has raided local and about $63 million per year. 4 4 But on October 12, to 20 the dismay of many environmentalists and planning SOUTHERN advocates, Governor Schwarzenegger vetoed the bill, CALIFORNIA objecting to any new motor vehicle fee. Some funding is still available through Proposition “I have a board of 84 elected officials actually, and 84 and the state’s Strategic Growth Council. The I would say 99 percent of them didn’t like the bill. Council has set aside $12 million to assist in SB 375 They didn’t want anything to do with it. It’s not implementation and model development, with $10 just because they didn’t want to do the right thing. million going directly to MPOs. But the money won’t It’s because they didn’t understand it. I just want to go nearly far enough. Twelve MPOs have already make a couple of points. I don’t think 375 should be submitted applications for Prop. 84 funding that, if considered a global-warming bill. I don’t think it’s granted, would deplete the fund entirely. the most cost-effective way to reduce greenhouse gas emissions.” Transit funding is similarly precarious. As the RTAC put it, 46 —Hasan Ikhrata, executive director of the Southern California Association of Governments “California’s continued trend of eliminating state After funding, the second obstacle to successful sources of transit capital and operating funds implementation of SB 375 is, in a phrase, Southern presents an implementation dilemma. Without California. The Southern California region is both restoration of state sources of transit funding that the most important for SB 375’s success and the most are reliable and long term, it will be unrealistic troubling, and the last year has done little to suggest for transit to meet any increased demand in a way around its troubles. services. This will diminish the state’s ability to achieve its greenhouse gas emission reduction It is the most important because of its size and its goals. The Committee urges the state to address relative contribution to statewide GHG emissions this discontinuity between the elimination of state from passenger vehicles. The region, whose MPO is transit funding in its budget and the mandates the Southern California Association of Governments of SB 375.” 45 (SCAG), is home to nearly half the state’s population and covers six counties. All of these counties are There are a few bright spots. At the height of fears expected to grow significantly by 2030: Los Angeles, about the recession, in November 2008, more than two- Orange, Imperial, San Bernardino, Riverside, and thirds of the voters in Los Angeles, Marin-Sonoma, Ventura. 4 7 It is far larger in area than any other and Santa Clara counties approved tax increases to California MPO—larger, in fact, than Indiana and fund transit projects. Voters statewide approved a twelve other states. bond-financed high speed rail project. But given the state’s ongoing fiscal crisis, it remains unclear whether, Southern California is also a huge contributor to and when, it may be able to provide more money for VMT and, therefore, to passenger vehicle GHG SB 375 efforts—without which the success of the bill is emissions. Alone, the SCAG region generates nearly highly uncertain. 50% of the total statewide passenger vehicle miles driven. Although ARB’s regional targets will not be set until fall 2010, SCAG expects that its region will be “required to take about half the reduction in the 21 state.” 4 8 Thus, if SCAG doesn’t make the changes that balloon, they also openly questioned SB 375’s premise. are necessary to reduce miles driven, it will be hard for From their viewpoint, GHG reductions should be California to reach its GHG reduction goals from the achieved through cleaner fuels and energy passenger vehicle sector. efficiency instead. 5 2 But SB 375 implementation is more difficult in SCAG’s Strong SCAG leadership, committed to the SB 375 region than perhaps anywhere else. In addition to vision and process, might still save the day. But as the being large, SCAG is also politically divergent and quote above attests, SCAG Executive Director Hasan complex. It represents 189 separate cities and five Ikhrata himself occasionally doubts the wisdom of county transportation commissions. SCAG operates changing land-use and transportation patterns for the under the often-unwieldy direction of a Regional purpose of reducing GHG emissions. Like some of his Council made up of more than 80 elected officials board members, he may prefer that GHG reductions be from 67 districts within the region. 49 To say that it found elsewhere. 5 3 Perhaps his doubts will make him faces conflicting mandates and political pressures is an the perfect ambassador to his unwilling sub-regions. understatement. It is difficult to see how SCAG might Only time will tell. reconcile these conflicts to create a single, palatable regional plan for reducing GHGs. ACHIEVEMENT Recognizing SCAG’s unique complexities, the law O R J U S T PA P E R - makes some adjustments in its requirements for SCAG regional planning. Alone among MPOs, it is permitted SHUFFLING? to devolve some of its planning work to sub-regions, allowing local councils of government (at their option) to work with the county transportation commission to propose a plan for their sub-regional area. 50 In “[A] lot of people will do a lot of paper-shuffling in an attempt to meet the bureaucratic requirements of addition, the RTAC report recommends that SCAG be SB 375. But on the ground, using land use strategies given an extra sixty days, until April 30, 2010, to put to reduce greenhouse gas emissions from the burning together its proposed regional target for consideration of transportation fuels means one thing: Figuring out by ARB. how to lay out California in such a way that people drive less.” 5 4 However, early signs indicate that SCAG will, indeed, struggle to win widespread support for any —Bill Fulton, land-use author and Deputy Mayor of the city of Ventura meaningful regional plan, whether that plan originates with the MPO, the sub-regions, or some combination Even if planning efforts are properly funded of the two. It floated a conceptual land-use plan last throughout the state; even if money is made available May, a sort of Sustainable Communities Strategy trial for transit; even if Southern California manages to balloon. The SCAG plan concentrated development on garner support from its sub-regions for a Sustainable a half-million acres of land near rail, bus rapid transit, Community Strategy; and even if all other questions and local bus lines. The plan wasn’t nearly aggressive about bill implementation are answered favorably - enough, and would have achieved only 60% of the what then? To what extent will the “paper-shuffling” region’s likely SB 375 target—but local officials still required by the SB 375 actually result in changes on balked. 22 51 They not only reacted negatively to the trial the ground and, ultimately, reductions in driving? Whether SB 375 will lead to real achievement will depend on at least three things. First, there is the issue of whether the law’s incentive structure will work to spur compact housing development. It might turn out that CEQA exemptions are not nearly enough to entice builders into compact infill projects. A host of other structural and political barriers may make those projects very difficult despite the exemptions. 5 5 Second, it is unclear if the bill’s varied incentives will work well together. Sustainable Community Strategies are holistic plans, with parts dependent on each other for success (increased housing built near improved transit lines, for example). Incentives, however, operate project by project. What if the bill succeeds in spurring high-density development along transit corridors proposed for expansion, but the dollars to make that transit expansion a reality never come? Third, and last, it remains to be seen how influenced people are by being shown what is possible. Part of the impetus for the bill might best be described as hope: if we envision it, they will come. Whether that hope is justified will not be apparent for many years. 23 A P P E N D I X : G L O S S A R Y O F A B B R E V I AT I O N S AB = assembly bill EIS = environmental impact statement APS = Alternative Planning Strategy GHG = greenhouse gas ARB = (California) Air Resources Board MPO = metropolitan planning organization BMP = best management practice NRDC = Natural Resources Defense Council CALTRANS = California Department RTAC = Regional Targets Advisory Committee of Transportation CARB = see ARB SACOG = Sacramental Area Council of Governments CEC = California Energy Commission SB = senate bill CEQA = California Environmental Quality Act SCAG = Southern California Association CLCV = California League of Conservation Voters SCS = Sustainable Communities Strategy CO2 = carbon dioxide VMT = vehicle miles traveled EA = environmental assessment 24 of Governments ENDNOTES 1 The author is the Andrew Sabin Family Foundation resolved only when the incoming Obama administration changed Executive Director of the Emmett Center on Climate Change and the federal policy. It both granted California its waiver and is largely Environment at UCLA School of Law. She thanks Todd Garber and incorporating the Pavley regulations into a nationwide mandate for Jesse Swanhuyser for helpful research assistance. cleaner cars. 2 10 An In-n-Out Burger restaurant in Baldwin Park that opened in 1948 is often cited as the first drive-through restaurant in the country (see, e.g., Wikipedia’s entry on drive-throughs at. See California governor ’s Executive Order S-01-07 (Jan. 18, 2007). org/wiki/Drive-through), though In-n-Out itself claims only that it 11 was the first in California. See In-n-Out History webpage Development and Climate Change (2007). A version of this graph (). appears on page 3. 3 12 Cal. Gov’t Code § 65080 et seq. (text available at http:// Reid Ewing, et al., Growing Cooler: The Evidence on Urban This version of the graph is from a PowerPoint presentation emailed to the author in early 2009 by Tom Adams of the California bill_20080930_chaptered.pdf) League of Conservation Voters, and put together jointly by CLCV 4 and NRDC. See also Tom Adams et al., “Communities Tackle Global “Cut the Sprawl, Cut the Warming,” New York Times (Oct. 6 2008). 5 NRDC and California League of Conservation Voters). A more recent version of the graph has been crafted to take account of the newly “Hot Air Gets Priority Over Housing,” Orange County Register (Oct. 8 2008). 6 Warming: A Guide to California’s SB 375” at 9 (2009) (published by proposed federal greenhouse gas emissions standards for cars. It likewise shows CO2 emissions well above 1990 levels in 2020, due to VMT growth. See Steve Winkelman et al., “Cost-Effective GHG Bill Higgins, Legislative Representative of the League of Reductions through Smart Growth & Improved Transportation California Cities, used the “Rorschach test” formulation in a speech Choices,” 2009 (published by the Center for Clean Air Policy). on SB 375 given at the 23rd annual UCLA Land Use Law and Planning Conference in Los Angeles (held on January 23, 2009). For divergent views on the bill’s likely significance, see William Fulton, “SB 375: Legislation Provides Incremental Change, Not Land Use Revolution,” California Planning & Development Report (Nov. 2008). 7 “Senate Bill 375: Redesigning Communities to Reduce 13 Reid Ewing et al., supra note 11, at 1. 14 Id. at 8. 15 For a discussion of some of California’s prior attempts to achieve more compact land use, see John Darakjian, “SB 375: Promise, Greenhouse Gases,” Office of the Governor (October 1, 2008) Compromise and the New Urban Landscape,” 27 UCLA J. Envtl. L. & (available at). Pol’y 371, 380-383 (2009). 8 16 California Air Resources Board, 1990-2004 GHG Inventory (Nov. 2007). 9 See generally “Sacramento Region Blueprint Transportation/ Land Use Study, Special Report: Preferred Blueprint Alternative” (June 2007) (available at: Long and hard-fought delays in securing the federal Clean Air sacregionblueprint/the_project/BP_Insert_JUN_2007.pdf). Act “waiver” necessary to implement the Pavley regulations were 25 17 Tom Adams et al., “Communities Tackle Global Warming: A Guide to California’s SB 375” at 10 (2009). 18 27 See 23 U.S.C. § 134(i). SB 375 also realigns regions’ periodic housing forecasts to be more consistent with its transportation planning cycle. The realignment allows regions to consider these Presentation of Kurt Karperos, chief of the Air Quality and Transportation Planning branch of the Air Resources Board, at a Senate interrelated questions, using the same data, in a coordinated fashion. staff briefing in Washington, D.C. (Sept. 25, 2009). 28 23 U.S.C. § 134(j)(3)(C). 19 29 Tom Adams et al., “Communities Tackle Global Warming: A Interview with Sen. Darrell Steinberg in “SB 375 Connects Land Use and AB 32 Implementation,” The Planning Report (July 2007) (available at: tpr/?module=displaystory&story_id=1257&format=html). Guide to California’s SB 375” at 19 (June 2009). 30 See Higgins, supra note 26, for a detailed discussion of these CEQA exemptions. 20 A. Rojas, “Foes Back Anti-Sprawl Measure”, Sacramento Bee 31 “Recommendations of the Regional Targets Advisory (Aug. 7, 2008). Committee (RTAC) Pursuant to Senate Bill 375” (Sept. 30, 2009). 21 Id. 32 Id. at 27. 22 See Bill Higgins, “Technical Overview of SB 375” at 94 33 Id. at 17. Legislative Report. 34 Id. at 6. 23 35 Id. 36 The exception is SCAG, which has until April 30, 2010 to (Oct. 2008), appended to the League of California Cities’ 2008 A. Rojas, “Foes Back Anti-Sprawl Measure”, Sacramento Bee (Aug. 7, 2008). 24 Id. suggest a regional target to ARB. 25 Bill Higgins, Legislative Representative of the League of 37 Quoted in Paul Shigley, “State Funding Doesn’t Match GHG California Cities, speaking at the 23rd annual UCLA Land Use Law Goals, Committee Says,” California Planning & Development Report and Planning Conference in Los Angeles (January 23, 2009). (July 29 2009). 26 38 See RTAC Final Report, supra note 31, at Appendix A. (July 1 2009). For more detailed descriptions and analyses of SB 39 “State Transit Assistance (STA) Program Funding Allocations 375’s provisions, see Tom Adams et al., “Communities Tackle Global and Diversions: FY 2007-08 through FY 2009-10” (California Transit Warming: A Guide to California’s SB 375” (June 2009); John Darakjian, Association). However, on October 1, 2009, the California Supreme “SB 375: Promise, Compromise and the New Urban Landscape,” 27 Court denied the appeal of a decision holding these diversions from UCLA J. Envtl. L. & Pol’y 371, 380-383 (2009); Alexandra Lampert, transit budgets to be illegal. See Shaw v. Chiang, 175 Cal.App.4th 577 “California’s Fight Against Global Warming: Finally Getting Smart (2009). The immediate effect of that decision on available transit funds About Sprawl?” 20 Stan. L. & Pol’y Rev. 193 (2009); and Bill Higgins, is still unclear, but it will undoubtedly be helpful to those advocating “Technical Overview of SB 375” (Oct. 2008), appended to the League of for better transit. See, e.g., Bill Fulton, “Bureaucratic Compliance with SB 375 May Not Reduce Driving,” California Planning & Development Report California Cities’ 2008 Legislative Report. 26 40 Id. 41 “Sacramento County Cuts,” Sacramento Bee (Aug. 26, 2009). 42 Paul Shigley, “Petaluma Disbands its Planning Department,” California Planning & Development Report (May 5, 2009). 43 Paresh Dave, “Thousands of City Employees Still at Risk in Budget Negotiations,” Neon Tommy (available at. uscannenberg.org/neontommy/2009/09/post-25.html#). 44 Legislative analysis of SB 406 (available at http:// cfa_2090916_155934_sen_floor.html). 45 RTAC Final Report, supra note 31, at 34. 46 Quoted in “SB 375: Changing California’s Transportation and to reduce greenhouse gas emissions. . . . I believe we lost a lot by muddying the water and saying we’re going to reduce two tons of greenhouse gas emissions with a land-use bill.”). 54 Bill Fulton, “Bureaucratic Compliance with SB 375 May Not Reduce Driving,” California Planning & Development Report (July 1 2009). 55 For an analysis of structural barriers to infill development and policy recommendations on how to overcome them, see Ethan Elkind, “Removing the Roadblocks: How to Make Sustainable Development Happen Now” (August 2009) (available at https:// cdn.law.ucla.edu/SiteCollectionDocuments/missing%20files/ removing%20the%20roadblocks%20--%20august%202009_final.pdf). Planning Future,” The Business Press (June 1, 2009). 47 “SCAG General Fact Sheet” (available at. ca.gov/factsheets/pdf/2009/SCAG_Factsheet_0509.pdf). 48 Bill Fulton, “Proposed SCAG Plan Falls Short of Likely SB 375 Target,” California Planning & Development Report (May 11 2009). 49 See “SCAG General Fact Sheet” (available at http://. pdf); “Governing Structure” (available at structure.htm). 50 Cal. Gov’t Code § 65080(b)(2)(C). 51 Bill Fulton, “Proposed SCAG Plan Falls Short of Likely SB 375 Target,” California Planning & Development Report (May 11 2009). 52 Id. 53 See also Louis Amestoy, “New Law Puts Compact Development Into Focus,” The Business Press (June 1, 2009) (quoting Mr. Ikhrata as saying “I don’t think [SB] 375 should be thought of as a global-warming bill. I don’t think it’s the most cost-effective way 27 2 28 CARBON COSTS AND HOUSEHOLD ELECTRICITY EXPENDITURES IN CALIFORNIA MICHAEL J. SANDLER Michael Sandler is co-founder of the Climate Protection Campaign based in Sonoma County, California. He has helped develop climate change programs for cities, water agencies, air quality districts, and the faith community. He received his MA in Urban Planning from UCLA, where he conducted research on carbon markets at the Lewis Center for Regional Policy Studies. 29 2 Once people are satisfied that climate change is real and something should be done about it, they want to know, “What do we have to do, and how much is it going to cost?” This chapter begins to answer the second part of that question. It examines a $15/ton cost on carbon dioxide (CO2) to household electricity bills in California, based on research conducted with support from the Lewis Center for Regional Policy Studies at UCLA. Although carbon pricing is an important economic lever in the economywide transition away from fossil fuels, the chapter concludes with a brief discussion of policies for returning revenues to consumers as a dividend, tax rebate, or share in order to assist households with the short-term costs of capping carbon. M O V I N G A W AY F R O M FOSSIL FUELS Climate change policies that shift economic production and consumption away from fossil fuels over the next few decades may produce a net economic gain over time. They could do so by increasing energy efficiency, by creating new jobs in industries such as renewable energy, and by avoiding the enormous costs of catastrophic climate instability. However, climate change legislation is also expected to add shortterm costs to the utilization of fossil fuels including coal and natural gas used to generate electricity and transportation fuels. This chapter estimates the increase to the average California household’s annual electricity bill if a $15 per ton CO 2 cost had been applied retroactively to coal and natural gas prices in 2005. The results are based on projections of a carbon cost’s effect on coal and natural gas prices from a model developed at MIT. Also projected is the contribution to California’s carbon costs resulting from the carbon-intensive, coalfired electricity that is generated in the neighboring states of Oregon, Nevada, Utah, Arizona, and New 30 Mexico and imported into California. Although climate change is global in scope, there populations within their jurisdictions. As a leader are numerous reasons why a state-level analysis of in state-level climate policy, California will likely carbon costs is important. Federal climate laws must see a carbon cost as a result of its landmark climate pass through the U.S. Senate, where senators will be legislation, AB32. primarily concerned with how such legislation will affect their state in particular. National estimates CALIFORNIA overlook differences between states in the amount of fossil fuel in their electricity mix, their historic AND AB32 investment in end-use efficiency, and in climatic factors that drive heaters and air conditioners. Even after a federal law is passed, states will continue to AB32, California’s Global Warming Solutions Act play an important role in climate policy. of 2006, sets a statewide greenhouse gas emission reduction goal of returning emission levels to 1990 Several states have adopted carbon emission reduction levels by 2020. 1 AB32 authorized the California goals and climate action plans, including California, Air Resources Board (CARB) as the lead agency to the northeastern states, and others. Electricity policy, implement the Act. The Climate Action Team’s 2006 Renewable Portfolio Standards, public goods charges report estimates that the Act must reduce statewide for energy efficiency, state gas taxes, and some fuel emissions by 174 million metric tons of carbon dioxide composition and air quality requirements are set at the equivalent emissions (MMTCO2E) from a projected business-as-usual scenario by 2020.2 state level. States have the ability, and are the most likely entities, to create policies to assist vulnerable Figure 1. California’s CO 2 Emission Reduction Strategies G r a p h i c f r o m h t t p : / / w w w. c l i m a t e c h a n g e . c a . g o v / a b 3 2 / i n d e x . h t m l 650 No “New Actions” Emi ssi on s Lev els (MMT CO 2 e ) 600 550 500 450 2020 Goal—426 MMT CO 2 e 400 350 300 199 0 1992 1994 1996 1998 2000 2002 2004 2006 2008 2010 2012 2014 2016 2018 2020 Tr a n sp o r ta tio n R ed u c tio n s— Pa vle y, D i e s e l A n t i - Idl i n g El ec tr ic ity & N a tu r a l Ga s R ed u c ti o n s — E f f i ci e n t y S t a n dr a ds , M u n i pro g r a m s . . . O th er K n o w n R ed u c tio n s— Fo rest C o n s e r v a t i o n , U r b a n F o re s t r y. . . Ne e d e d A d d i t i o n a l R e d u c t i o n s t o M e e t 2 0 2 0 G o a l 31 SCOPING PLAN carbon price could be achieved through a carbon tax. In addition, some environmental justice The California Air Resources Board (CARB) adopted advocates are wary of the complex rules that could a Scoping Plan for AB32 implementation in December disproportionately impact certain communities. 2008, which describes policies to achieve GHG Previous cap and trade systems have come 3 emission reductions between 2010 and 2020. The under scrutiny from analysts who have detailed Scoping Plan describes dozens of regulatory and shortcomings of the design of the European Emissions market mechanisms to reduce the emissions from Trading Scheme (ETS). the transportation, electricity, industrial, and other sectors. Some of the policies include expansion In 2007, to help sort out the intricacies of the design of of energy efficiency programs and building and a cap and trade system, the California Environmental appliance standards, expansion of the Renewables Protection Agency appointed a panel of economists Portfolio Standard to 33 percent, California’s clean car and experts to a Market Advisory Committee (MAC), standards, goods movement measures, and the Low which produced a report that was later referenced in Carbon Fuel Standard, and targeted fees to fund the the Scoping Plan. The Scoping Plan reiterated many State’s long-term commitment to AB32 administration. of the MAC’s recommendations, but left unanswered the formula for allocation and specifics about the use Although the Plan mentions these and other policies, it of revenue collected from auctioning permits. It also is written as an overview. As such, it does not provide noted that the Western Climate Initiative (WCI) is also specific timelines or detailed policy analysis. Perhaps developing market design principles and guidelines most pertinent to a discussion of carbon costs is the for several Western states. proposed development of a California cap-and-trade program that links with other jurisdictions in the To continue this work, in April 2009, Governor Western Climate Initiative (WCI) to create a regional Schwarzenegger announced the formation of another market system in greenhouse gas emissions. expert panel, the Economic and Allocations Advisory Committee (EAAC). EEAC was to be comprised of CAP AND TRADE some former MAC members and others. Its report will review CARB’s previous estimates of the economic impact of meeting AB32’s goals, and also inform the The phrase “cap and trade” refers to a tradable permit market design, especially methods and formulas system that allows regulated firms to decide how for allocating emission allowances under the cap. to comply with an emissions limit, choosing either Assuming that Californians will face a carbon cost to reduce emissions to a specified level or to buy from these activities (this assumption is laid out in permits from other firms that have reduced beyond more detail below), how would such a cost affect compliance. Supporters cite the precedent of the 1990 household electricity bills? Clean Air Act Amendments’ market for sulfur dioxide (SO 2) in helping to reduce acid rain. Theoretically, distributing tradable permits allows for more cost- ASSUMPTIONS effective emission reductions. The analysis below relies on numerous assumptions. Cap and trade also has detractors, including First, carbon costs could reach households in several economists who believe that a more transparent ways: through a carbon tax, through a cap and trade 32 system, or through costs incurred as businesses comply a momentary, not dynamic, incidence on consumers. with command and control regulations. For this paper, In effect, the results presented are a policy snapshot we will assume that businesses can pass allowance and do not account for changes made as a result of the costs on to their customers, whether allowances are price increase, or in anticipation of a carbon price. allocated freely to some regulated businesses, or allowances are auctioned. This contention is supported by the experience of the European Emissions Trading A $15/ton CO 2 cost is analyzed for several reasons. Although higher and lower amounts appear in policy Scheme (ETS). When businesses in the ETS were given discussions, many other studies cite a number near free allowances, they added the opportunity costs $15/ton CO 2 as a low-end early carbon cost (Hassett, represented by the allowance value into their prices. 4 Mathur, and Metcalf 2007; Metcalf 2007; Green et al 2007; Burtraw 2008). The MIT-EPPA model predicts Second, while acknowledging that choosing any single $18/ton as a starting price in 2015 to freeze GHG year in the past to represent or imply future markets, emissions at 2008 levels (Paltsev 2007). prices, or costs is problematic, instead of forecasting future costs, this chapter compares two scenarios for In 2007, Senator Jeff Bingaman, chairman of the Senate 2005. These scenarios are 1) a baseline as experienced Energy & Natural Resources Committee, along with without any carbon cost, and 2) a hypothetical 2005 Senator Arlen Specter proposed a “safety valve” that had a $15/ton carbon cost. There are several of $12/ton CO 2 for a future national cap and trade reasons for this approach. system. Early estimates based on President Obama’s budget forecast for 2012 released in March 2009 predict The MIT Emission Prediction and Policy Analysis (MIT-EPPA) model (Paltsev 2007) uses a “base year” centered on 2005. Other data such as the EIA State Energy Profiles for 2005 were readily available as this chapter was being written. Even though Hurricanes CO 2 prices of just under $14/ton. As noted by Metcalf (2007), a $15/ton CO 2 tax may be converted to a $55/ ton tax on carbon by multiplying by 44/12, the ratio in molecular weight between C (carbon) and CO 2. Katrina and Rita occurred in late summer 2005, and natural gas and coal prices rose, prices were still lower then than they were in late 2008. 5 Results presented in this chapter are based on the assumption of average cost pricing of electricity. California’s electricity prices, as a partially deregulated market, are theoretically determined by the marginal costs (defined as the operations and maintenance (O&M) costs of the most expensive generating plant needed to supply the immediate demand for electricity). However, the estimate here assumes average cost pricing is used as under traditional regulated state electricity systems. (Average costs are determined by the cost-of-service of the regulated entity, i.e. total costs divided by total sales.) The resulting carbon costs are meant to represent 33 METHODOLOGY gas per million cubic feet using a “benchmark price” described in MIT Emission Prediction and Policy The electricity sector is a major source of greenhouse Analysis (MIT-EPPA) model (Paltsev 2007). EPPA’s gas emissions, and the primary target for emission benchmark for converting CO 2 cost into tons of reductions in many proposed greenhouse gas laws. coal, million cubic feet of natural gas, and gallons of According to Green, Hayward, and Hassett (2007), gasoline is derived from the energy content and the the carbon content of coal per energy unit is 1.9 MT emissions intensity measured in megatons of carbon CO 2/unit compared to .432 for crude oil, .054 for dioxide per British thermal units (BTU) of fuel, as natural gas, and .009 for gasoline. Due to its carbon shown in Figure 2. For example, coal has an emissions intensity, the imposition of a carbon price will have the intensity of approximately 95 million MT CO 2/Quad first and greatest impact on coal. Coal comprises about 50% of the U.S. electricity supply. However, each state, and each utility within states, has a unique BTU, while gasoline contains about 71 million MT CO 2/Quad BTU. However, the energy content of coal is 19 million BTU/energy unit, while gasoline’s is only portfolio of contracts and generators from which it 124 thousand BTU/ energy unit. When energy content purchases electricity. and emissions intensity are combined, a carbon price affects coal 200 times more than it would affect The number of statewide residential accounts, and gasoline. the state’s average annual household electricity bill are obtained from the California Energy Commission. The MIT-EPPA model’s benchmark price of $27/ton The U.S. Department of Energy’s Energy Information CO 2 equivalent produces an increase in price per short Administration’s State Energy Profiles for 2005 lists ton of coal of $55.30/short ton. The $27 benchmark coal and natural gas consumption by state. Also listed price can be converted to other carbon prices following are the percent of residential customers and household the instructions in Paltsev et al 2007 (Paltsev 2007, electricity consumption as a percent of each state’s to- Table 5, Figure 5, page 21-22). For example, the $15/ tal electricity consumption and the amount of coal in ton is 55% of $27/short ton of coal benchmark price. short tons and natural gas consumed in million cubic feet Therefore, 0.55 is multiplied by MIT-EPPA’s result of used to generate electricity for residential customers. $55.30 to get an added fuel cost of $30.42/short ton of coal. If the base price of coal is $26.70/short ton, then The $15/ton CO 2 cost is converted to an increase in the price of coal per short ton and the price of natural 34 the new price of coal given a carbon price of $15/ton CO 2 is $57.12/short ton. For natural gas, the Paltsev EPPA model’s benchmark of $27/ton CO 2 produces an added price of $1.50/ TCF to a base price of $11.05/TCF. The same 55% calculation (rounded) results in $830/MCF as the added price of natural gas given a carbon price of $15/ ton CO 2. R E S U LT S Applying a $15/ton CO 2 cost (through the MIT-EPPA model’s added fuel cost for coal of $30.42/short ton of coal, and $830/MCF for natural gas) to California’s 2005 coal and natural gas consumption for household electricity, would have raised the average household annual electricity bills by $20.92. Figure 3 shows how this result compares to the average U.S. state. Figure 2. Carbon Cost Impact per Energy Unit for Various Fuels E nerg y Unit M T C/ Q uad B t u C o a l ( Sh o r t t o n ) C rude Oi l ( B a rre l ) Na tura l G a s ( m cf ) G a sol i ne ( G a l l on) 2 5 ,9 8 0 ,0 0 0 20,300,000 14,470,000 19,340,000 M T CO 2/ Quad Bt u 9 5 ,2 6 0 ,0 0 0 74,433,333 53,056,667 70,913,333 BTU/ E nerg y Un it 1 9 ,9 8 0 ,0 0 0 5,800,000 1,027,000 124,167 M T CO 2/ E ne rgy Un it 1 .9 0 3 0.432 0.054 0.009 $ 2 8 .5 5 $6.48 $0.81 $0.14 Tax / E nerg y Un it C h a r t f r o m G r e e n , H a y w a r d , a n d H a s s e t t ( 2 0 0 7 , Ta b l e 1 ) . S o u r c e f o r c a r b o n c o n t e n t o f f u e l s f r o m w w w. e i a . d o e . g o v / e n v i r o n m e n t . h t m l ; e n e rg y c o n t e n t o f f u e l s f r o m U . S . D e p a r t m e n t o f E n e rg y ( D O E ) , E n e rg y I n f o r m a t i o n A d m i n i s t r a t i o n ( E I A ) , A n n u a l E n e rg y R e v i e w 2 0 0 5 , D O E / E I A - 0 3 8 4 ( 2 0 0 5 ) , W a s h i n g t o n , DC: EIA, 2006. Figure 3: Carbon Cost Impact per Energy Unit for Various Fuels A v e r a g e U.S . S t a t e Ca l i f or ni a An n u al elect r ici ty bi l l i n 2 0 0 5 ($ ) 1,016 858 An n u al elect r ici ty consumpti on per househol d (K WH) 11,193 6,859 Aver ag e co s t per K WH (cents) 9.49 Ho u s eh o lds 2,411,107 12,480,545 M illio n s h o r t tons of coal (resi denti al ) 7.52 2.25 Pro ject ed added costs to coal and natural gas 160.77 20.92 12.51 t o t h e aver age househol d el ectri ci ty bi l l ($ ) 35 ELECTRICITY Figure 4. California’s Out-of-state Coal-fired Powerplants IMPORTS AND EXPORTS TO Boardman CALIFORNIA The EIA data for coal consumption used above did not account for interstate commerce of electricity. As a result, the value for coal in California’s electricity Inter-mountain Power Project mix was only 1%. However, according to the California Energy Commission, coal represented 15% of the Bonanza Hunter Reid Gardner state’s electricity mix. Almost all the coal used by Navajo California electricity consumers is combusted at outof-state powerplants, and the electricity is imported San Juan Four Corners Mohave Power Plant from neighboring states. This occurs at several large powerplants located in Utah, Nevada, and Arizona (Figure 4). The U.S. Environmental Protection Agency’s eGrid data listed the specific coal-fired power plants, the percentage ownership by California utilities, and M a p c r e a t e d b y M i k e S a n d l e r b a s e d o n d a t a f r o m 2 0 0 5 S t a t e E n e rg y P r o f i l e s , E n e rg y I n f o r m a t i o n A g e n c y ; 2 0 0 5 e G r i d , U S E PA megawatt hours (MWh) of electricity generated from coal in 2005. Imported coal-produced electricity costs were estimated using the MIT-EPPA model, added to California, and subtracted from the neighboring states. MWH are converted into tonnage of coal using the Figure 5. Out-of-state Coal consumed by CA Utilities average heat transfer of 6,150 MWH/ton and the typical coal powerplant efficiency coefficient of 40 60,000,000 percent. The resulting 2,460 tons per MWH is similar Inter-mountain Power Project 50,000,000 electricity found in Metcalf (2007) and 2,395 used by Green, Hayward and Hassett (2007). The resulting tonnage of coal is converted to dollars following Paltsev (2007) as described above in the methodology section. It is subtracted from the exporting states’ total, and added to California’s total (Figure 6). 36 S h or t Tons Co al to the 2,376 pounds of CO2 per megawatt hour of 40,000,000 Mohave Power Plant 30,000,000 Four Corners 20,000,000 San Juan 10,000,000 0 Navajo Reid Gardner Boardman Bonanza Hunter Figure 6. Changes in Household (HH) Electricity Bills The coal used in exported electricity represented due to Redistributing California’s Out-of-state Coal 33% of the change in Nevada’s household electricity bills, lowering Nevada’s increase in average annual household electricity bills by $45.42 from $134 to $89. Imported coal-fired electricity accounted for almost half of California’s increase, raising the increase in average annual household electricity bills by $16.83, from $20.92 to $37.66. ( $2.84) Export Alongside AB32, California passed another bill in 2006—SB1368—which sets an emissions performance standard for major utilities and limits the future ( $45.42) Export procurement of coal-powered electricity. The ( $26.72) Export performance standard is set at a limit that may not be ( $16.83) Import met by existing coal powerplants, but future plants that incorporate carbon sequestration may meet it. ( $7.98) Export This law will have the effect of reducing the coal in ( $36. 34) Export Map created by Mike Sandler using data sources: 2 0 0 5 S t a t e E n e rg y P r o f i l e s , E n e rg y I n f o r m a t i o n A g e n c y ; M I T E P PA M o d e l ( P a l t s e v 2 0 0 7 ( ; E 3 R e p o r t t o C P U C California’s electricity mix as current interstate coal contracts expire. T R A N S P O R TAT I O N A similar analysis can be performed on household C h a n ge in Avg. HH C h a n ge i n A v g . HH e le c b ill, ign o rin g e le c b ill , i ncl ude s e xp o r t s t o CA e xp o r t s Ar izo n a 1 ,0 1 6 858 Calif o r n ia 1 1 ,1 9 3 6 ,8 5 9 Nevada 9 .4 9 New M exico 2 ,4 1 1 ,1 0 7 1 2 ,4 8 0 ,5 45 Oreg o n 7 .5 2 2 .2 5 U t ah 1 6 0 .7 7 2 0 .9 2 1 2 .5 1 expenditures for fuel in the transportation sector. Transportation fuel consumption is based on U.S. Department of Transportation data on gasoline consumption for private vehicles by state for 2005. Because gasoline has a lower carbon content than coal (see Figure 2), the MIT EPPA model adds only 14.3 cents per gallon to 2005 motor fuel prices compared to over $30 per short ton of coal. When the same $15/ton CO 2 cost is added to 2005 household transportation fuel consumption in the 50 states, the average household’s transportation fuel expenditure increases $76, from $1,811 to $1,887. For California, when the gasoline price goes from $3.78 to $3.93, the average household pays an additional 37 $84.75. Adding the carbon costs from electricity to those of transportation, the average California household would pay $122.41. This still leaves out indirect costs paid by households for other goods and services due to increased electricity prices. OTHER STUDIES OF CARBON COSTS M O D E R AT I N G CONSUMER COSTS W I T H R E B AT E S Carbon costs play a positive role in reducing demand by creating a price signal that encourages reduced fossil fuel consumption, fuel switching toward lower carbon content, and conservation and end-use efficiency. However, a case may be made How do these results compare with other, more for moderating the carbon costs to households. complex estimates of carbon costs? James Boyce and Such a case is typically based on 1) the potential Matthew Riddle of the University of Massachusetts, for regressivity from a carbon cost (costs falling Amherst estimates that a $25/ton CO 2 price would disproportionately on low-income households), lead to a mean per capita price impact of $288 to the and 2) the need for long-term widespread political average Californian (Boyce 2009). Boyce and Riddle’s support for economy-wide emission reductions. estimate includes transportation and the increased costs of goods and services as energy costs are passed In this view, it may be both desirable and politically through the economy. They estimate that the poorest expedient to rebate part of the cost of transition back decile would see only a $108 price impact, while to consumers. Several studies have concluded that the carbon costs for the wealthiest decile were $593. effect of a carbon price on regressivity depends on how The Congressional Budget Office (CBO) and the the revenues from the carbon tax or allowance price Energy Information Administration (EIA) conducted are used. This section presents two possible methods national studies of carbon costs, but did not break for returning a rebate or dividend to households from them down by state. CBO estimated that the net carbon tax or allowance price revenues. annual economywide cost of the cap-and-trade program in 2020 would be $22 billion—or about $175 per household.6 EIA projected scenarios for the cost CAP AND DIVIDEND impact of H.R. 2454, the American Clean Energy and Security Act of 2009. ACESA would add 30 cents per “Cap & Dividend” provides a very direct method gallon of gasoline by 2020, with allowance prices at of compensating consumers. Lump-sum rebates, $32 per metric ton in 2020, and, “in 2020, the reduction also called “dividends,” from carbon tax or permit in household consumption is $134 (2007 dollars) in the auction revenues are returned to households (Barnes ACESA Basic Case.” 7 2001; Boyce and Riddle 2007). Cathy Kunkle and Dan Kammen from UC Berkeley projected that a policy that returns 50% of allowance value to households through dividends would benefit households in the poorest deciles more than the wealthiest deciles. They also find that California’s northeast counties generally have higher carbon costs than the coastal counties.8 38 Figure 7. Fraction of Households Receiving Positive Net Benefits From Cap and Dividend by County, at $30/tC with 50% to Govt Source: Cathy Kunkle and Daniel M. Kammen, Draft Memo to EAAC, August 11, 2009 77% Weal t hi est Dec i l e P o o rest Dec i l e 78%– 91% 92%– 95% 96%– 97% 98%– 99% CAP AND SHARE Similar to Cap & Dividend, “Cap & Share” returns revenues to consumers, but does so by allocating tradable certificates or shares representing emission 0%–3% 4%–11% 12%–24% 25%–48% 49%–86% CONSUMER C O M P E N S AT I O N DISTRIBUTION permits under an emissions cap directly to consumers. Consumers would receive income by selling their Consumer compensation could be distributed in many shares to regulated fuel and energy companies, ways. If it were tied to the cost impact by state, for possibly through banks or brokers. As people sell their example rebating 75% of fees paid, then households in shares to the upstream companies, the companies high-coal states such as North Dakota would receive raise fuel prices, but the purchase of the share ensures a larger dividend than low-coal consumers in Vermont. that the “scarcity rent” of the permits is returned back If it were a national flat rate, then consumers in all to households. The Cap & Share concept has been states would receive the same rebate even if they promoted since 2006 by a non-profit organization paid more in added costs. For the national flat rate, based in Ireland and the UK called FEASTA—The for example, if the dividend were set according to the Foundation for the Economics of Sustainability. 9 In both Cap & Dividend and Cap & Share, the point global per capita average of CO 2 emissions (4 tons), and if the carbon cost were $15/ton, then each person’s of regulation is upstream. Fossil fuel producers and dividend would be $60. Since California has lower importers are required to purchase either the permits carbon costs than higher-coal states such as Wyoming from the government or the shares from people. and North Dakota, the flat rebate would return more money to California consumers than they spent, turning carbon costs to Californians net negative. The carbon costs paid by consumers in high-carbon states would remain higher in the flat rebate scenario than in the percent-of-fees-rebated scenario. 39 Figure 8: Carbon Costs and Dividends for Selected States CONCLUSION H ous eho ld An n u a l Ne t ca rbo n co st Ne t c a rbon cost This paper estimates an increase of $20.92 to the Car bon C o st f o r if re b a t e o f $60/ if 75% of average California household’s annual electricity bill elec tr icit y a t pe rso n we re give n ca rbon costs if a $15 per ton carbon cost were applied retroactively $15/ ton CO 2 t o h o u se h o ld s w e re re ba te d in 2005. When the carbon content of electricity exports to California from Oregon, Nevada, Utah, Arizona, O rego n $32. 13 - $ 1 1 3 .1 0 $ 8 .7 4 and New Mexico are included, California’s carbon C a l i for nia $37.75 -$137.98 $5.23 costs increase by an additional $16.83 per household, A r iz on a $135. 61 - $ 1 8 .9 5 $ 3 5 .90 for a final cost of $37.66. The results include numerous W y o min g $557. 46 $ 4 2 6 .6 8 $ 1 3 9 .36 assumptions and are based on the state’s electricity N o r t h Dak o t a $881. 95 $ 7 5 6 .8 1 $ 2 2 0 .49 mix, household consumption, electricity prices, and the MIT-EPPA model’s projection of a carbon cost’s effect on coal and natural gas prices. Although a carbon cost will shift demand away from fossil fuels and toward renewable energy, moderating household carbon costs can address disproportionate costs to low-income households and encourage longterm political support for economy-wide emission reductions. The most direct method to moderate consumer impacts is to return a portion of carbon costs back to consumers through a cash dividend, tax rebate, or transferable emissions share. The return of allowance value could represent a transfer of billions of dollars. Depending on the distribution method, the net cost to Californians could be entirely eliminated, albeit at the expense of other states. Policies to assist households with shortterm carbon costs are an important, part of state and national climate policy, and deserve further discussion. 40 41 REFERENCES Barnes, Peter (2001). Who Owns the Sky?: Our Metcalf, Gilbert. E. (2007). “A Proposal for a U.S. Common Assets and the Future of Capitalism. Carbon Tax Swap: An Equitable Tax Reform to Address Island Press: Washington, DC. Global Climate Change.” The Hamilton Project, Brookings Institution. Boyce, James K. and Matthew Riddle (2007). “Cap and Rebate: How to Curb Global Warming while Protecting Metcalf, Gilbert E. (2007b). “An Empirical Analysis the Incomes of American Families.” University of of Energy Intensity and Its Determinants at the State Massachusetts, Amherst, Political Economy Research Level,” Medford, MA: Tufts University Department Institute, Working Paper Series 150. of Economics. Boyce, James K. and Matthew E. Riddle (2009). Paltsev, Sergey, Reilly, John M. Jacoby, Henry D., “Cap and Dividend: A State-By-State Analysis,” Gurgel, Angelo C., Metcalf, Gilbert E., Sokolov, Andrei Political Economy Research Institute University of P., and Holak, Jennifer F. (2007). “Assessment of U.S. Massachusetts, Amherst, August.. Cap-and-Trade Proposals,” MIT Joint Program on the umass.edu/236/hash/928ccab881/publication/352/ Science and Policy of Global Change. Report No. 146. Burtraw, Dallas, Rich Sweeney, and Margaret Walls (2008). “The Incidence of U.S. Climate Policy: Where You Stand Depends on Where You Sit,” Resources for the Future Discussion Paper. Burtraw, Dallas (2008a). Congressional Testimony, House Appropriations Committee. Burtraw, Dallas (2008b). “Cap, Auction, and Trade: Auctions and Revenue Recycling Under Carbon Cap and Trade.” Testimony to House Select Committee on Energy Independence and Global Warming. Washington, DC. Green, Kenneth, Hayward, Steven F., Hassett, Kevin A. (2007). “Climate Change: Caps vs. Taxes“ Environmental Policy Outlook, AEI Online. Hassett, K. A., A. Mathur, G. Metcalf (2007). The Incidence of a U.S. Carbon Tax: A Lifetime and Regional Analysis, National Bureau of Economic Research. Working Paper 13554. 42 ENDNOTES 1 California Air Resources Board AB32 webpage 2 Climate Action Team 2006 Final Report. reports/2006-04-03_FINAL_CAT_REPORT.PDF 3 CARB AB32 Scoping Plan 4 Once a firm is given an allowance, using it is an implicit cost since the alternative is to sell the allowance for cash. 5 Energy Information Administration, Coal Prices Information Sheet 6 Letter from Congressional Budget Office Director Douglas W. Elmendorf to Committee on Ways and Means, “The Estimated Costs to Households From the Cap-and-Trade Provisions of H.R. 2454,” June 19, 2009. ftpdocs/103xx/doc10327/06-19-CapAndTradeCosts.pdf 7 Energy Information Administration. Energy Market and Economic Impacts of H.R. 2454, the American Clean Energy and Security Act of 2009 hr2454/execsummary.html 8 Kunkle, Cathy and Kammen, Daniel. “Draft Memo to the EAAC, ” August 11, 2009. 9 FEASTA’s website is. The Cap & Share website is. The author maintains a website describing a similar concept called Carbon Share at . 43 3 44 GETTING ON BOARD: HOW PUBLIC TRANSIT CAN PUT CALIFORNIA BACK ON TRACK D U S T I N M A G H A M FA R Dustin Maghamfar is a fourth-year graduate student at UCLA, pursuing a Juris Doctor and Master of Public Policy at the School of Law and School of Public Affairs. He has a B.A. in Government (with Honors) from Georgetown University. Maghamfar studies environmental law and policy, and focuses on emerging climate change policies. 45 3 California is in crisis.1 Amid what is often described as the worst economic situation since the Great Depression, 2 California is among the states hardest hit by home foreclosures. 3 The state suffers from the political inability to pass a budget and pay its bills, 4 has one of the highest unemployment rates in the nation, and has imposed mandatory furloughs on state employees.5 Highway and water system infrastructure throughout the state is crumbling, 6 and the state has declared a state of emergency for drought. 7 All of these daunting challenges must be addressed while California continues working to avoid the potentially severe impacts of climate change.8 Times of crisis can also be times of significant opportunity. The confluence of numerous challenges and demographic changes has created an opportunity for meaningful and long-lasting reform in land use and transit infrastructure in California. Through integrated policies, California can build a more sustainable society while putting people to work, improving public health, and reducing greenhouse gas emissions. As the economy begins to recover, the question becomes how will California move forward. Will the state fall back upon failed systems, or choose a stronger future? This chapter addresses the necessity of reform and innovation in the land use and transit arena. In Section I, the various challenges mandating the need for change are reviewed. Section II then surveys the synergistic benefits attainable through increased use of public transportation. Section III examines three elements of reform for public transit funding and transit-oriented development. First, Section III considers the potential impact of Senate Bill 375, a landmark bill addressing land use and transit planning in California. 9 Second, the section looks at public support for mass transit, particularly the success of local transit sales tax measures on the November 2008 ballot. Third, Section III reviews potential funding mechanisms and price signals to encourage transit use. 46 CURRENT AND FUTURE CHALLENGES M A N D AT E R E F O R M Proposition 42 was passed.1 5 Even when fully funded, Proposition 42 dollars are not required to go directly to mass transit projects. In short, Proposition 42 funding has not been reliable. 1 6 But this situation may be changing. California faces significant obstacles in the next fifty The legislature frequently relies upon shifting ear- years, many of which can be addressed by key reforms marked funds to the General Fund to help resolve an- and a strong focus on public transportation. A brief nual deficits. This practice may be coming to a forced survey of these challenges follows, before turning to end, however. Recent court rulings have struck down examine the role public transit can play. the legislature’s ability to shift money between the General Fund and transportation funds earmarked A N EC O N O M I C C R I S I S H E I G H T E N E D BY A P O LI T I CA L G R I D LO C K through the initiative process. 1 7 The California Transit Association sued the state for transferring over $5 billion from Propositions 116, 2, 42 and 1A to the General Fund. 1 8 In June 2009, the California Court of Appeal ruled that the challenged transfers were illegal. 1 9 With the refusal of the California Supreme Court to The budget situation that emerged in early 2009 in hear the state’s appeal, transit advocates claimed a sig- California could be considered the height of political nificant victory for protecting future transit funding. 2 0 theater, but for the devastating consequences of Nonetheless, questions remain. The court decision extensive delays and lack of will to resolve the should deter the legislature from diverting transpor- state’s structural deficit. 10 In the budget passed by tation funds in the future, but the court claimed no the legislature in February 2009, the state provided authority to order the legislature to restore the chal- zero dollars in funding for public transit operations lenged transfers to public transit accounts. 2 1 While by eliminating the State Transit Assistance (STA) transportation funding may largely be spared going program. 11 For the last three decades, the STA had forward, looming deficits foretell continued deep been the only ongoing source of daily operations budget cuts. 2 2 The court decision has no impact on funding. 1 2 The consequences of this budget decision the elimination of the STA program. As the Executive were stark: nearly every transit provider in the state Director of the California Transit Association stated, has increased fares and/or cut services. 13 the court decision “is one more obvious sign that the whole budget process needs serious reform.”2 3 Another perennial question in the budgeting process is whether Proposition 42 funding will be diverted Transit agencies throughout the state find themselves to the General Fund. Proposition 42 was passed by in line to receive funds for capital development from California voters in 2002 and mandates that sales taxes the American Reinvestment and Recovery Act (ARRA) from gasoline sales be directed to streets, roads and while facing significant deficiencies in operations highways projects and public transportation. 14 While funding due to the elimination of the STA program. 2 4 the 2008-09 budget maintained Proposition 42 funding, Additionally, the economic crisis has reduced sales and loopholes have allowed the legislature to divert those property tax revenues, further depleting operations monies to the General Fund in nearly every year since funds.2 5 Public transit recently set new ridership 47 records in the face of $4.00 per gallon for gasoline during the summer of 2008. 26 However, the state’s budgeting decisions have reduced public transit services. 27 The funding allocations seem contradictory in the face of California’s efforts to combat million metric tons of carbon dioxide equivalent (MMTCO2e). 3 1 CARB identified a further reduction in GHG emissions of one (1) MMTCO2e from the development and operation of a high speed rail system.3 2 climate change. SB 375 builds upon AB 32 as a means for achieving the C L I M AT E C H A N G E AND CLEAN AIR 5 MMT CO2e reduction identified in the scoping plan. The transportation sector is responsible for over 40% of California’s total GHG emissions.3 3 In passing SB 375, the legislature found and declared that reduction of GHG emissions from automobiles is not sufficient The California Legislature, in passing the California to obtain the AB 32 goals. 3 4 Instead, meeting the 2020 Global Warming Solutions Act of 2006, 2 8 aptly target under AB 32 will require reducing the number described the potential harms of climate change of vehicle miles traveled (VMT) by Californians, which to California: will in turn require changes to land-use decisions and Global warming poses a serious threat to the the expansion of existing and new mass transit. 3 5 economic well-being, public health, natural resources, and the environment of California. Reducing VMT will also aid the state in its efforts to The potential adverse impacts of global warming clean California’s notoriously polluted air.3 6 As include the exacerbation of air quality problems, a particular example of the air problems in California, a reduction in the quality and supply of water to the San Francisco Bay Area and the South Coast Air the state from the Sierra snowpack, a rise in sea Basin (which includes Los Angeles County) have levels resulting in the displacement of thousands failed to meet federal standards for ozone levels since of coastal businesses and residences, damage to 1989. 3 7 Ozone (smog) pollution—something with marine ecosystems and the natural environment, which most residents of those areas are intimately and an increase in the incidences of infectious familiar—is linked to serious health problems, diseases, asthma, and other human health-related including respiratory illness and premature death. 3 8 problems. 2 9 As described by the legislature, California stands to suffer extraordinary economic losses and a substantial drop in the quality of its residents’ lives if efforts are not taken to mitigate climate change. To address California’s contributions to climate change INCREASING P O P U L AT I O N A N D DENSITY and urge other governments to action, AB 32 directs In 1982, California’s population was approximately the California Air Resources Board (CARB) to reduce 24.5 million people3 9 and its density reached 159.1 California greenhouse gas (GHG) emissions to 1990 persons per square mile.4 0 In 2007, its population had levels by the year 2020. 3 0 CARB has identified in increased to 37.6 million people.4 1 The state’s density its scoping plan a goal of reducing GHG emissions rose to 234.4 persons per square mile. These trends from “Regional Transportation-Related GHG Targets” represent increases of 53% and 47%, respectively. 4 2 —that is, changes in land use decisions—by five (5) 48 The number of people in California is expected to In 2000, 71.8% of all Californians drove to work increase by more than 50% over its 2007 population alone;4 7 in Los Angeles the figure was slightly lower by 2050, rising to a projected 59.5 million. 4 3 Those at 70.4%. 4 8 An additional 15% of Angelinos carpooled, additional 25 million people will need somewhere while 6.3% took a bus, subway or rail. 4 9 Elisa Barbour, to live. Either cities will continue to sprawl or urban author of a study of commute times for the Public density will increase, with the critical fulcrum being Policy Institute of California (PPIC), told the media: the ratio between outward “greenfield” growth and urban infill. For example, the density of Los Angeles The decentralization of jobs and homes has County increased over 34% from 1982 (1,894 persons a complicated effect on commuting, leading per square mile) to 2007 (2,544 persons per square to both long, congested suburb-to-central city mile). As California’s population increases, its major commutes and relatively short suburb-to-suburb job centers will undoubtedly see an increase in density. commute times. … As policymakers invest in Density is an important variable in the ridership transportation, it’s critical to consider changing equation, and insufficient density is often blamed commute patterns because investment choices will in part for the underuse of certain transit lines. help shape public demand by influencing travel If regional development is planned in accordance with options and development patterns. 5 0 smart growth principles, funneling new residents into transit-oriented development, the challenge With the California population expected to grow of increasing population can be an opportunity for significantly over the next forty years, commute times increased transit and healthier communities. in Los Angeles and the rest of California can only The alternative is increasingly worse traffic congestion be expected to worsen without changes in land-use and commute times. decision-making and the development of new and/or increased mass transit services. LENGTHY COMMUTE TIMES According to the U.S. Bureau of the Census, as of 2004, Americans spent more than 100 hours per year commuting to their workplaces. 44 With an average one-way commute time of 26.5 minutes, California had the dubious honor of the fifth longest average commute in the nation. Continuing to use Los CALIFORNIA MUST TA K E A D V A N TA G E O F THE SYNERGISTIC BENEFITS OF PUBLIC TRANSIT Angeles—notorious not only for its air pollution but also its traffic—as an example, Angelinos faced an average commute of 29 minutes. 45 Approximately 3% Extensive benefits come with expanded public transit infrastructure and higher ridership. Perhaps the most of Los Angeles residents—more than 117,000 people important area is public health. In recent years, public —suffered commute times of more than 90 minutes health experts have returned their attention to the one-way, among the highest percentages of so-called interaction of people with their built environment, “extreme commutes” in the country. 46 with significant results. The design of our cities and the significant expansion of suburban sprawl have had 49 significant negative effects on the health of 2009 gas prices, transit riders in California save our communities. approximately $10,000 annually in San Diego and Los Angeles, and as much as $12,000 per year in San Sprawl and the resulting dependency on personal Francisco.5 7 Communities enjoy six-to-one economic vehicles has led to sedentary lifestyles, contributed returns on investments in public transportation, and to increasing obesity, and increased motor vehicle every $10 million put towards capital development or air pollution. 51 The more people who drive, the operating expenses generates $30 million specifically worse traffic becomes. Cars operate less efficiently in in increased business sales.5 8 According to the 2009 congestion, resulting in even higher levels of pollution. Urban Mobility Report, in 2007, public transportation use resulted in savings of 646 million hours of travel Re-orienting California development around public time, and 398 million gallons of fuel.5 9 Between 2005 transit begins the process of improving public health. and 2009, public transit use avoided $13.7 billion in Fewer cars on the road and fewer miles traveled means congestion costs.6 0 less congestion. This reduction in car use results in faster commutes. It lowers stress and produces more Transit and transit-oriented development (TOD) have efficient car travel and thus fewer emissions. The costs further benefits. The national security argument for of motor vehicle pollution, in terms of its impact on increasing average fuel economy is well established. It human health, are estimated to be between $29 billion holds equally true for reducing VMT. The fewer miles and $530 billion annually. 52 Transit riders walk more and get more exercise, helping to reduce obesity levels and improve the health of Californians generally. 53 driven, the less gasoline consumed, and the less foreign oil that needs to be imported into the U.S. Public transportation also reduces carbon emissions by 37 With 30% of Americans obese and obesity levels rising, million metric tons each year.6 1 Decreasing VMT has transit-oriented developments promote physically the additional benefit of reducing the overload of Cali- active lifestyles and are a smart priority for local fornia’s fragile highway infrastructure, thereby lower- governments as means to improve the health of ing the stress and burden on the system and saving the their citizens. 54 state money in maintenance and repair costs. Another improvement in public health comes simply Increasing transit use and TOD will also help preserve from the fact that riding public transit is significantly the ever-diminishing open space still left in California. safer than personal vehicles: taking the bus is 170 Expanding transit options where necessary and build- times safer, and overall, the number of fatalities, ing mixed-use complexes around existing transit will injuries and accidents on public transportation is make it easier to avoid further greenfield development 190,000 less than occurs from personal vehicle trips while accommodating California’s increasing popula- annually. 55 Additionally, the health and other benefits tion into vibrant urban centers. Lastly, and of particu- of public transportation helps to reduce the costs of lar importance in the current economic climate, health care in multiple ways, from healthier people investing in public transit creates jobs. needing less health care, to reducing the costs of nonemergency health care travel. 5 6 Expanding new transit infrastructure means new construction contracts and engineering work. There are substantial economic benefits that come Increasing service, whether new or existing lines, with increased use of public transportation. Based on creates new operator positions, as well as increased the average costs of driving, parking, and October needs in maintenance and control departments. 50 Investing in public transit only to restore transit form of dedicate revenue streams upon which transit services to the level Californians enjoyed two years providers can confidently rely. The adoption of price ago would create and preserve jobs by re-hiring signals to influence commuter behavior toward transit operators that had to be laid off and preventing further use is also important. service cuts. A study on the first ten weeks of ARRA’s investment in public transit projected the $8.4 billion invested would create over 250,000 jobs, with “green CHANGING THE jobs” going to blue-collar workers constituting 67% of R E G U L AT O R Y the total. 6 2 This discussion of the benefits of public transportation is not meant to be exhaustive. Rather, the goal is twofold: first, to demonstrate the wide range of benefits LANDSCAPE: SB 375 ENTERS THE SCENE that accrue with increased use of public transportation, and second, to demonstrate the significant domino SB 375 seeks to influence land-use and transit planning effect of public transit benefits. There is a positive decisions by directing federal and state transportation feedback effect as each category of direct benefits leads dollars towards sustainable development plans to extensive indirect benefits. The potential gains from that take a holistic approach to housing and transit increased transit ridership are vast but not always development, while enticing cities and developers well understood, and are worthy of committed to commit to sustainable growth through CEQA pursuit. The question then becomes how to realize incentives. Control over land use and zoning is these benefits. traditionally within the domain of local governments and is a power zealously guarded by those IMPLEMENTING PUBLIC TRANSIT AND LAND-USE REFORMS authorities. 6 3 As such, local councils hold significant power over patterns of development. Transit planning takes place at the regional level but with significant local involvement. Federal and state law mandates the existence of metropolitan planning organizations (MPOs) to plan Business as usual development will not lead to and coordinate the distribution of federal highway and sustainable communities, healthier Californians, or transit dollars, and state transportation funding, in a more fiscally stable state. Reform is necessary to urban areas, respectively. 6 4 Each MPO produces achieve the benefits that increased transit ridership a Regional Transportation Plan (RTP), which includes and transit-oriented development can provide. This planned projects and programmed funding. The section considers three avenues of reform essential to MPO overseeing the San Francisco Bay Area is the putting California on the path to a more secure future. Metropolitan Transportation Commission (MTC). The first path is legislative reform, with a landmark In Los Angeles the MPO is the Southern California bill—SB 375—already in force. The second is the need Association of Governments (SCAG).6 5 Decision- for public support, which is already strongly in favor making authority rests with MPO board members, who of expanded transit. Third, increased investments in are local officials serving in the additional role. 6 6 public transportation are needed—particularly in the 51 While the power of local governments is widely U N I F Y I N G T R A N S P O R TAT I O N debated in the academic literature, in California, cities AND HOUSING PLANNING have significant authority. They directly control new development in accordance with their occasionally Before the passage of SB 375, state-mandated revised general plans, and local officials affect transit transportation and housing plans were separate and funding decisions as board members of MPOs. distinct processes with the potential for significant The influence of cities in the state capitol should also efficiency gains through adoption of a unified, holistic not be underestimated. 67 approach. 7 3 SB 375 resolved this disconnect by The League of California Cities, representing city interests during negotiations, synchronizing the timing of RTP development and demanded revisions to SB 375 that would protect the preparation of housing plans. 7 4 The latter takes local control. 68 the form of housing elements in local general plans. These plans must incorporate regional housing needs Developers feared the loss of their suburban projects allocations (RHNAs) developed by the state to regions, and local officials worried about relinquishing and distributed by regional council of governments land use and transit planning powers to the state to localities.7 5 government. 6 9 Passage of SB 375 was eventually In addition to unifying the timing of the RTP and made possible by a “Coalition of the Impossible,” housing element development, SB 375 requires RTPs consisting of “builders, environmentalists, cities, housing organizations and transportation planners.” 70 to plan for RHNAs. The RHNA should be consistent The final version of SB 375 explicitly sought to avoid with the development projections used in the RTP. 7 6 usurping local powers and adopted amendments Given the projected population increases in California providing local governments with alternative means and the consequent increase in housing demand, the of compliance. It is highly unlikely SB 375 would have mutual consideration of housing and transit needs passed without these provisions. 71 should lead to an increase in sustainable development. CHANGING DECISION-MAKING T H E S U S TA I N A B L E C O M M U N I T I E S S T R AT E G Y THROUGH INCENTIVES One of the central components of SB 375’s planning SB 375 has three primary goals: 1) use the regional reform is a Sustainable Communities Strategy (SCS). 7 7 transportation planning process to achieve the The SCS is drafted by the MPOs with input from each emissions reduction goals established in AB 32; 2) region’s localities, and is subject to limited CARB offer streamlined environmental review under the approval for feasibility. 7 8 The SCS is a new component California Environmental Quality Act (CEQA) as of the RTP, and as such must build upon the federally- an incentive for sustainable development, and 3) mandated forecast of the region’s development over coordinate the allocation of regional housing needs the next two or three decades.79 This forecast must be with the regional transportation plan (RTP). 72 realistic. It cannot assume, for example, that growth Through a series of incentives, SB 375 provides the will occur in a manner wholly inapposite to local opportunity for unified regional planning decisions general plans. 8 0 across the climate change, housing and transportation arenas. SB 375 does not, however, require cities to Given that forecast of growth, the SCS must identify adopt this model of planning. areas to fulfill housing needs across the socioeconomic spectrum and the transit services necessitated by 52 that growth. 8 1 The resulting development plan, if targets. If the MPO finds that the target cannot be feasible, must be designed to achieve the region’s GHG feasibly attained, or if the ARB concludes the SCS reduction target, set by CARB as per AB 32. 82 The SCS will not achieve the necessary reductions, the MPOs must further quantify the projected GHG reductions must instead draft Alternative Planning Strategies and what shortfall, if any, will result relative to the (APS). The APS is not part of the RTP and therefore regional target. 83 is not subject to the internal consistency requirement, severely limiting its potential impact relative to an Perhaps the most important aspect of the SCS is that SCS. Accordingly, any measures or policies identified it is subject to the internal consistency requirement of by the APS will not influence the programming of the RTP. 84 Much like a city’s general plan, the various transportation funds in the RTP. components of the RTP—the action element, the financial element, and the SCS—must not conflict. It is unclear what effect an APS will have on regional For example, if the RTP plans for the expansion of development patterns. An APS does draw attention intercity rail but programs no money towards that to GHG emissions. But its lack of direct influence on project, the RTP is not internally consistent. It must transportation funding decisions calls into question be revised to be eligible for state and federal dollars. whether sustainable development will gain an edge in the fierce battles for transportation dollars. However, SB 375 mandates that the SCS is subject to the internal consistency requirement. 85 As such, the RTP’s funding if a specific project complies with the SCS or APS, new incentives become available to the project. and action plans must be consistent with and support the land-use and transportation plans articulated in the SCS. 86 CEQA INCENTIVES The practical effect of this requirement is that the RTP must funnel federal and state dollars to The California Environmental Quality Act is a power- the SCS’s plan, thus likely leading to increased public ful law that affects any project or development under- transportation and TOD, and making GHG reductions taken by or requiring approval from any California far more likely to occur. state or local government entity. 9 0 Preparation of CEQA documents typically costs in the hundreds of The SCS does, however, face key challenges in thousands of dollars, and the entire CEQA process can achieving its goal of effecting real change in take longer than a year in many cases. CEQA provides development patterns. First, the SCS does not for enforcement of its provisions by private citizens. 87 As a result, developers frequently find their projects supersede local plans. There is no requirement that cities amend their plans to be consistent with the SCS. 88 As the League of California Cities notes, “If delayed and pushed over-budget due to litigation expenses. CEQA has been a frequent target of a certain type of development pattern is unlikely to Republican state legislators and of developers since emerge from local decision-making, it will be difficult its inception. 9 1 for the regional agency to say that it reflects current planning assumptions.” 8 9 Therefore, if SB 375’s To encourage cities and developers to pursue TOD, SB incentives do not bring cities on board, the impact of 375 creates a set of CEQA incentives. 9 2 SB 375 creates the SCS will be limited. a new category of projects—Transit Priority Projects (TPP)—and offers three kinds of reduced CEQA review Finally, an SCS is required only if the MPO concludes to qualifying projects. 9 3 Of the most relevance here, that it is feasible to achieve the region’s GHG reduction TPPs must meet a minimum density requirement and 53 be located “within one-half mile of a major transit stop or high-quality transit corridor included in an RTP. 94 localities into particular planning decisions. Strong leaders with regional visions are needed to implement the goals of SB 375.9 5 It is unclear what effect the CEQA incentives will have on possible development. The first category is Second, the state could utilize the existing model widely considered nearly impossible to attain. But provided by the RHNA process. The state distributes there are potentially significant gains to be added from fair-share assignments to the regional council of the remaining incentives in both time and money. If governments, which then assigns specific housing cities and developers decide the CEQA incentives are development requirements to member cities. The cities valuable and choose to pursue them, the result could must amend their zoning to fulfill their RHNA. Should be greater support for and faster development of new SB 375 and its incentives prove ineffective, the state and/or expanded public transit service. could model SB 375 after the RHNA in two ways. I F I N C E N T I V E S F A L L S H O R T, ADOPT MEANS OF ENFORCEMENT First, California should mandate that city plans comply with an SCS. Initially, cities should have the discretion to choose how to revise their plans to be There is significant uncertainty in how much SB 375 consistent with the SCS. Second, if a city fails to do so will accomplish, and whether the CEQA incentives to the state’s approval, then the state should mandate will motivate developers and cities to align their plans an “SCS element” in the city’s general plans, just as with regional plans. Many questions remain, but of the state mandates housing elements. These steps particular interest is the extent to which local jurisdic- will force the cities to adhere to the regional planning tions will modify their general and specific plans to model, and thus increase the likelihood of sustainably incorporate transit-oriented development and thus developed regions with sufficient and well-designed interface with regional public transit development. public transportation. California cannot afford extensive delay in changing its patterns of developments. Incentive-based efforts were, and are, the appropriate place to begin. But if the incentives fail to effect significant change, the state must BUILD POPULAR SUPPORT seek a means of enforcement. Two potential changes to SB 375 would significantly strengthen the act. California voters approved tens of billions of dollars in expenditures on mass transit infrastructure and First, whether a MPO creates a SCS or APS, either operations in the November 2008 election. On the document needs to be part of the RTP and subject to state level, nearly 53% of voting Californians passed the internal consistency requirement. Thus, under both Proposition 1A. 9 6 Proposition 1A authorized the planning scenarios, federal and state transportation sale and expenditure of nearly $10 billion in bonds funds will be directed towards sustainable to fund the development of a high-speed rail system development plans. This requirement alone may not eventually to connect the four major metropolitan solve the problem, however, since local officials are the areas of California: Sacramento, the San Francisco MPO decision-makers and may not be inclined to force Bay Area, Los Angeles, and San Diego. 9 7 Regionally, voters approved three new transit-linked sales taxes, exceeding the required two-thirds supermajority for 54 tax increases in each case. These approvals came in With expanding transit service comes a need for despite of the California budget crisis and the then increased infrastructure capacity. In anticipation rapidly deteriorating global economic situation. of high-speed rail and expanding local rail service, both San Francisco and San Jose are developing In Los Angeles County, the Metropolitan new downtown transit centers. In San Francisco, Transportation Authority placed Measure R on the redevelopment has begun of the Transbay Transit ballot, seeking voter approval for a half-cent sales tax Center, which will host local rail, high-speed rail, bus increase to last for thirty years. 98 Nearly 68% of voting Los Angeles County residents approved Measure R. 99 lines, underground connections to BART, offices, retail stores, and a public park. 1 0 9 It is expected to generate $40 billion over its term. 1 0 0 Revenues will support dozens of projects across five The project also calls for the redevelopment of the major categories: rail expansion (including extending surrounding area, building commercial, retail, and the subway to West Los Angeles); street improvements; residential space, including affordable housing. traffic reduction; public transportation (generally Similarly in San Jose, the supporters of Measure B related to bus service), and quality of life projects (e.g., envision the redevelopment of the Diridon Train soundwalls). 101 Significant job creation is potentially entailed in these various programs. Station into the “Grand Central of the West.” 1 1 0 The greatly expanded station will provide capacity for inter-city and regional rail combined with local In the San Francisco Bay Area, voters approved two light-rail and bus service, central among nearby sales taxes to fund rail projects. Voters in Santa Clara entertainment and housing. County approved Measure B with 66.78% of the vote. 1 0 2 Measure B, a thirty-year one-eighth cent sales In July 2009, the PPIC released the results of its tax, will fund the operation and maintenance costs annual statewide survey of Californians’ views of extending Bay Area Rapid Transit (BART) to San on the environment. 1 1 1 Seventy-seven percent of Jose. 1 0 3 The BART extension will create a new transit Californians stated that they favor expanding mass hub in San Jose with connections to multiple transit transit and using existing roadways more efficiently, rail lines, including high-speed rail, local light-rail and as opposed to building more freeways. One important local busses, with easy access to Downtown San Jose. aspect to recall is that this popular support must be maintained once the public realizes that to get the Voters in Sonoma and Marin Counties approved Measure Q with 69.6% of the vote. 104 Measure Q expanded transit, some of their freeway lanes may become toll lanes, or the costs of parking may increase. increases the sales tax by one-quarter of one-percent Effective communication with the public of the to fund the construction and operation of a new rail benefits of each policy will be essentially to sustaining system seventy miles in length. 105 The Sonoma and growing public support. Marin Area Rail Transit, or SMART train, will bring passengers to the ferry terminal, where they can complete their journey to San Francisco. 106 SMART is expected to remove over 1.3 million car trips from Highway 101 per year. 107 Plans are already in development to build mixed-use TOD “transit villages” around the new SMART stations. 108 SB 375 has put the incentives in place, and there is demonstrated popular support for expanded transit infrastructure and operations. These are critical steps, but are unlikely to achieve success without also addressing funding and economic policies bolstering public transit. 55 INCREASE THE AMOUNT AND RELIABILITY OF FUNDING AND IMPLEMENT PRICE SIGNALS local, regional and state government, ranging from infrastructure maintenance to greater use of emergency services to higher health care costs. The direct and indirect economic benefits of public transportation accrue at every level of government and for individuals and communities, and thus in many instances increased use of public transportation is economically rational behavior. However, a price signal is needed to overcome market deficiencies, primarily the externalities of suburban sprawl and individual driving, and a lack of information.1 1 4 In an ideal world, in which the state was not facing When the price of gasoline reached $4.00 per gallon fiscal crises, transit advocates would wait for in summer 2008, consumers significantly adjusted the legislature to fix the structural deficit in the their behavior, increasing transit use and reducing California budget. They would then prioritize transit VMT. The rationality of an effective price signal, and and sustainable development in balanced budgets the significant benefits that accrue from more rational and put major funding behind the SCS and transit consumer behavior, transcends political lines.1 1 5 operations.1 1 2 However, there is no reason to believe that California’s recurrent budget crises will be Use of price signals deserves full consideration and, ultimately, implementation. resolved in the near term. Increasing the state taxes on gasoline should be part of The perpetually chaotic budgeting process creates the conversation.1 1 6 The California gasoline tax is not enormous uncertainty for transit planners and indexed to inflation and has not been increased since operators. Further exacerbating their fiscal positions, 1994. 1 1 7 “In real terms, California fuel tax revenue per the Los Angeles County Metropolitan Transportation vehicle mile traveled today is worth approximately 36 Authority and the Santa Clara Valley Transportation percent of what drivers paid in 1970.â€? 1 1 8 Increasing Authority rely on sales tax receipts for more than the gas tax both generates revenue and influences 60% and 75% of their funding, respectively. 113 Sales consumer behavior, leading to more efficient use tax revenues are volatile and highly susceptible to of roadways and associated economic and public economic downturns. health benefits. 1 1 9 However, the failed attempt to increase the gas tax during the February 2009 budget There are two primary goals funding reform should negotiations demonstrates that generating Republican attempt to achieve. First is the provision of reliable, support is highly unlikely. Nonetheless, the gas tax increased funding streams to transit providers. should be on the table. The second goal should be to send a price signal to drivers that will lead them to adopt more sustainable The gas tax is not a perfect solution but the price of behaviors. The majority of individual drivers do not gas has been demonstrated to be a powerful price calculate the full breadth of the externalities their signal. Criticisms of the gas tax include its regressivity driving imposes on their communities and ecosystems. and its declining returns in the face of increasing Driving imposes significant costs on communities, fuel efficiency. A tax based on VMT, using global 56 positioning satellite (GPS) or tolling technology, is As to regional planning, Senate Bill 406, proposed a frequently suggested but highly controversial idea, and passed by the legislature in 2009, would have even if more economically efficient than the gas allowed certain local or regional governmental tax. 120 As to the regressivity of the gas tax, this can be mitigated through refunds or lowering rates for the lowest tax brackets. 121 Revenue from the increased bodies to increase motor vehicle registration fees in their jurisdiction. The fees would have funded the development of Sustainable Community Strategies gas tax could thus be distributed to compensate those under SB 375.1 2 4 However, the bill was vetoed by hit hardest by the tax increase. It would also flow Governor Schwarzenegger in October 2009, on the toward infrastructure maintenance costs (lowered basis that such fee increases should be subject to voter due to VMT reductions, if the tax is set correctly) and approval. 1 2 5 toward transit operations. There are myriad other ideas for how to generate With the court decision in Shaw v. Chiang, Proposition revenue for public transit and to send price signals to 42 may become a reliable source of funding. Given the individuals.1 2 6 One option solely on the cost side is to budget challenges facing in the legislature, however, look within and seek to maximize the efficiency—and relying on the state for reliable transit funding comes minimize unnecessary costs—at transit providers. with high risks. Direct democracy has generated Internal audits could help streamline the provision of transit revenue on the local level, through super- transit services. Another funding option (without price majority approval of ballot items such as Measure signals) is to distribute revenues generated under B and Measure R, placed on the ballots by transit a cap-and-trade program for carbon emissions under providers. Sales taxes, as already noted, are highly AB 32 to support public transportation. 1 2 7 susceptible to economic downturns. Next, the cost of parking is an important policy subject The PPIC’s California 2025 report asserts that to local government control. UCLA Professor Donald county-level funding reduces flexibility in funding Shoup’s research, and particularly his seminal book, programming, favors projects designed to elicit The High Cost of Free Parking, examines the role of support of suburban voters, and serves county- parking prices with respect to transportation planning level purposes at the cost of regional needs. 122 The and land use decisions, and consumer behavior.1 2 8 approach of Measure B suggests county transportation Setting prices for parking too low, Shoup argues, authorities may be more conscious of planning on the results in excess vehicle travel as drivers look for regional level, an effort now strongly pushed forward open parking spots, resulting in higher VMT and the by SB 375. Additionally, targeting suburban voters extensive accompanying negative impacts. 1 2 9 Shoup may no longer be a barrier. Many of those voters now advocates that parking rates be set such that 15% of wish to live closer to work and Measures R and Q will spaces are available at any given time. The result is spur the development of new transit villages. Another both reduced VMT and higher revenue. 1 3 0 shortcoming of sales taxes is that, unlike user fees, everyone pays equally regardless of their transit use. Lower traffic congestion from circling drivers will Thus, the sales tax does not incentivize changes in help reduce delays in transit services. Additionally, by behavior with respect to driving and transit use. 123 internalizing the external costs imposed by subsidized parking in the form of higher prices, many drivers will likely be dissuaded from driving in the first place, 57 leading to higher transit ridership. Further, Shoup congestion when HOT lanes are implemented. In recommends that the additional revenue be reinvested addition, lower income residents, who are more likely in the area where it is collected. 131 Part of these to be transit riders, benefit from the investments made revenues could be used to support transit services in in local public transportation. Two of the explicit that area, for example, through contributions to the goals of the program are to change the behavior of transit provider for the cost of operating the line or commuters and generate revenues to support and increasing service frequency. Or the revenues could be increase transit options. 1 3 6 used to improve local stations in order to increase the desirability of the area. CONCLUSION ‘Whether for innovative parking management or high occupancy toll lanes, leveraging federal dollars California faces substantial transportation challenges. whenever possible is an important strategy for state The state and many of its largest urban areas and local governments to pursue. Mayor Villaraigosa have taken important steps toward sustainable of Los Angeles announced in October 2009 his development. It is up to political and citizen leaders intention to accelerate the rail projects approved as to take advantage of the opportunities for reform to part of Measure R dramatically. His “30/10” plan move the state forward in a healthier manner. SB 375 is would complete twelve rail projects in a decade, a groundbreaking effort to coordinate environmental, instead of over thirty years. 132 Leveraging federal development and transit-related concerns legislatively. dollars will be critical to the success of this ambitious It remains to be seen whether either more incentives or plan. Another avenue with respect to federal funding stricter mandates will be required for SB 375 to achieve is for California to lobby the federal government to its potential. allow current sources of federal funds, stimulus or otherwise, to be used for daily transit operations. Combining reformed transit funding with implementation of effective price signals is essential Los Angeles has already successful acquired federal to realizing the vast benefits associated with increased dollars to implement a test project of High Occupancy public transportation. With public support for mass Toll (HOT) lanes in 2011. 133 HOT lanes are an transit and more efficient use of existing roadways example of congestion pricing. Segments of two strong, it is up to the political and citizen leaders carpool lanes in the Los Angeles area will be converted to communicate the benefits of new reforms. By to HOT lanes. The toll for using the HOT lanes varies maintaining public support, moving forward with during the day, with the price set to keep traffic in the provisions of SB 375, and implementing economic the HOT lane moving at full speed. 134 In addition to the conversion of the carpool lanes to HOT lanes, the project also will increase bus service and vanpools. Toll revenues will first go towards the operation of the system, with remaining funds expected to “improve or enhance transportation services in the corridor where the toll is generated.” 1 3 5 HOT lanes are sometimes criticized as regressive and potentially creating an express lane for the wealthy. But research indicates that non-tolled lanes also experience a reduction in 58 reforms, public transportation supporters can usher in a better future for all Californians. 59 APPENDIX A: ACRONYMS IN THIS CHAPTER AB = assembly bill MTC = Metropolitan Transportation Commission APS = alternative planning strategy PPIC = Public Policy Institute of California ARRA = American Reinvestment SB = senate bill and Recovery Act BART = Bay Area Rapid Transit CARB SCAG = Southern California Association of Governments = California Air Resources Board SCS = sustainable communities strategy CEQA = California Environmental Quality Act SMART = Sonoma Marin Area Rail Transit GHG = greenhouse gas STA = State Transit Assistance program HOT = high occupancy toll (lanes) RHNA = regional housing needs allocation MTA = (Los Angeles County) Metropolitan RTP = regional transportation plan Transportation Authority MMTCO 2 e = million metric tons of 60 TOD = transit-oriented development carbon dioxide equivalent TPP = transit priority project MPO = metropolitan planning organization VMT = vehicle miles traveled ENDNOTES 1 The chapter was originally a term paper prepared for Public California Legislature in the California Global Warming Solutions Act Policy 233 in winter quarter 2009. It has been updated to reflect of 2006 of extensive threats to the “economic well-being, public health, developments as of October 2009. Because many transit-related natural resources, and [ ] environment of California.”). acronyms are used in this chapter, an Appendix with definitions is provided. 2 Hereafter referred to as SB 375. The text of SB 375 is available at “US Crisis ‘Worst Since 1930s’,” BBC News, 10 Feb. 2009; http:// news.bbc.co.uk/2/hi/americas/7882094.stm. 3 9 “Worst Foreclosure Activity Limited to Four States,” sb_375_bill_20080930_chaptered.html. 10 For an extensive discussion of the California state budget, the causes of the structural deficit and an analysis of both past and ConsumerAffairs.com, 6 Aug. 2008; recent negotiations, see Daniel J.B. Mitchell, “When Luck Runs Out: news04/2008/08/foreclosure_worst.html. Leadership – Present and Past – and the California State Budget,” 4 California Policy Options 2009 (2009): 29-72. For the consequences of See “California Budget Crisis Jeopardizes 20,000 Jobs,” CNN, 17 Feb. 2009;. budget.crisis/; see also “California Delays $3.5B in Payments,” 2. Feb. delayed budgets, see, e.g., “California Budget Crisis Jeopardizes 20,000 Jobs” and “California Delays $3.5B in Payments.” 2009; 11 budget_crisis/. Association, 12 Feb. 2009;; “Final 5 “‘Armageddon Scenario’ Has Arrived,” California Transit California Budget Protects Proposition 42 Funds,” Transportation Wyatt Buchanan, “Furloughs Saving Less than Expected, Study California;. Says”, San Francisco Chronicle, 16 Oct. 2009, cfm?an=1&subarticlenbr=245 (accessed 2 March 2009). Because many cgi-bin/article.cgi?f=/c/a/2009/10/16/BA271A68U4.DTL&tsp=1. acronyms are used in this chapter, Appendix A provides a listing for 6 the reader. Dan Walters, “California’s Highways are in a Sad State”, Sacramento Bee, 5 Oct. 2009; 12 story/2230727.html. Michael Gardner, “Ambitious Overhaul of State Transit’s Pain,” California Transit Association, 16 June 2009; Water System in Works”, San Diego Union-Tribune, 20 Oct. 2009;- 061609%20-%20Conference%20Committee%20Vote.pdf. overhaul-system-works/?california&zIndex=185610. 7 Samantha Young, “Schwarzenegger Declares Calif. Drought Emergency,” The Washington Post, 27 Feb. 2009;. washingtonpost.com/wp-dyn/content/article/2009/02/27/ AR2009022701972.html. 8 13 “Budget Crafters Pass Up Opportunity to Ease Public See “Aftermath Archive,” California Transit Association; (providing extensive details of the consequences of eliminating the STA throughout the state). 14 Office of the Governor, “Governor Schwarzenegger Announces Full Funding of Proposition 42 Transportation Funds,” California Climate Change Portal, “FAQs,” 29 April 2008;; see State of California, 11 May 2005;. also Cal. HEALTHY & SAFETY CODE § 38,501(a) (findings of the 61 15 “Opposing the Raid on Proposition 42,” Transportation “California’s Fiscal Health Continues to Deteriorate, Despite Many California;. Deep Cuts,” New York Times, Oct. 31, 2009;. cfm?an=1&subarticlenbr=243. com/2009/11/01/us/01calif.html. 16 23 California 2025: Taking on the Future, eds. Ellen Hanak Press Release, “Case Closed: A Resounding Victory for & Mark Baldassare (Public Policy Institute of California: 2005), 108; Transit Riders,” California Transit Association, Oct. 1, 2009; http://. 17 -%20Supreme%20Court%20Rejects%20Appeal%20of%20Transit%20 Jennifer Steinhauer, “California’s Fiscal Health Continues to Deteriorate, Despite Many Deep Cuts,” New York Times, Oct. 31, Case.pdf. 2009;; Shaw v. 24 Chiang, 75 Cal. App. 4th 577 (Ct. App. 2009). Faces ‘Armageddon’,” 23 Feb. 2009;. 18 Gary Richards, “Despite Stimulus Money, Bay Area Transit com/politics/ci_11751492. See also John King, “Bus Route Closing Press Release, “Court Rejects State Raids on Transit Devastates Disabled Couple,” 27 Mar. 2009;. Funding,” California Transit Association, June 30, 2009;. com/2009/POLITICS/03/27/st.louis.no.bus/index.html (providing an caltransit.org/files/resources/News%20Release%20063009%20-%20 example from St. Louis, Missouri, of necessary operations cuts despite Appeals%20Court%20Ruling.pdf. federal stimulus money limited to capital projects)”. 19 Shaw v. Chiang, 75 Cal. App. 4th 577, 615 (Ct. App. 2009). 25 Id. 20 Press Release, “Case Closed: A Resounding Victory for 26 “In 2008, 10.7 billion trips were taken on public Transit Riders,” California Transit Association, Oct. 1, 2009; http:// transportation, the highest level in more than 52 years.” “Economy Fact Sheet”, American Public Transportation Association (2009); -%20Supreme%20Court%20Rejects%20Appeal%20of%20Transit%20 Case.pdf. See also “Redevelopment Agencies File Lawsuit Challenging sheet.pdf. Unconstitutional $2.05 Billion State Raid of Local Development Funds,” Reuters, Oct. 20, 2009; 27 pressRelease/idUS232870+20-Oct-2009+PRN20091020 (discussing Faces ‘Armageddon’,” 23 Feb. 2009; the California Redevelopment Association’s final victory in court politics/ci_11751492. challenging $350 million in redevelopment agency funds to the state, and the filing of a subsequent suit challenging the $2 billion take in the February 2009 budget). 21 Press Release, “Court Rejects State Raids on Transit Funding,” California Transit Association, June 30, 2009;. caltransit.org/files/resources/News%20Release%20063009%20-%20 Appeals%20Court%20Ruling.pdf. 22 28 Hereafter referred to as AB 32. 29 CAL. HEALTH & SAFETY CODE § 38501(a). 30. 31 California Air Resources Board (ARB), “Climate Change Proposed Scoping Plan” (October 2008): 17; Due in large part to lower than anticipated tax revenues, that budget now has a $7 billion deficit for the current fiscal year, with potential growth to between $10 and $20 billion. How that deficit will be resolved is impossible to predict. Jennifer Steinhauer, 62 Gary Richards, “Despite Stimulus Money, Bay Area Transit cc/scopingplan/document/psp.pdf. 32 Id.; see also. 33 SB 375 § 1(a). 47 Elisa Barbour, Time to Work (Public Policy Institute of California: Feb. 2006), 9; 34 Id. at § 1(b) & (c). cacounts/CC_206EBCC.pdf. 35 Id. at § 1(c). 48 “Average Commute Time Up in the Southland,” ABC 7 News, 28 Feb. 2006; 36 Id. at § 1(d). story?section=news/local&id=3949576. 37 ARB, “Chronology of State Ozone Designations,” 3 July 49 Id. 50 Id. Lung Association, 2009;- 51 “Public health leaders are asserting—as had leaders 150 risks/overview.html. years earlier—that the built environment profoundly influences 2007;. 38 39 “State of the Air: 2009 Health Risks Overview,” American health. The focus this time is not urban tenements, but rather the Rand California, “Population and Demographic Statistics,” (May 2008);. 40 fragmented and sprawling communities that foster car dependency, inactivity, obesity, loneliness, fossil fuel and resource consumption, and environmental pollution.” Richard Jackson, “Environment Meets Rand California, “Community Statistics,” (July 2008);. Health, Again,” Science 315 (2007): 1337. 52 “The Route to Better Personal Health”, APTA;. 41 Id. at note 28. publictransportation.org/pdf/reports/better_health.pdf. 42 Id. at note 29. 53 43 “Quality of Life Fact Sheet”, APTA (2009); http:// publictransportation.org/takesusthere/docs/quality_of_life_fact_ State of California, Department of Finance, “Population sheet.pdf. See also Julia Griffin, “Fit to be Ride(ing): Public Transit Projections for California and its Counties 2000-2050,” (July 2007); Patrons Pretty Physically Active”, Miller-McCune Online Magazine, 31 March 2009;- Projections/P1/P1.php. public-transit-patrons-pretty-physically-active-1112. 44 54 U.S. Census Bureau News, “Americans Spend More Than 100 Hours Commuting to Work Each Year, Census Bureau Reports,” 30 Mar. 2005; archives/american_community_survey_acs/004489.html. 45 46 “The Route to Better Personal Health”, APTA;. publictransportation.org/pdf/reports/better_health.pdf. 55 “Transit Benefits”, Center for Transportation Excellence (2006); (based on 2004 data). Id. Id.; Rand California reports the population of the City of Los Angeles in 2004 was 3.9 million people. “Population and Demographic Statistics.” 56 “The Route to Better Personal Health”, APTA;. publictransportation.org/pdf/reports/better_health.pdf. 57 “Riding Public Transit Saves Individuals $9,062 Annually”, American Public Transportation Association (6 October 2009); http://. 63 58 “Facts on Public Transportation”, APTA;. publictransportation.org/facts/. 59 org/index.jsp?displaytype=§ion=about&zone=locc. League at 20. Specifically, the League demanded that Alternative Planning Strategies not be included in Regional Transportation Plans. The implications of “Public Transit Saved 646 Million Hours in Travel Delay in 2007”, American Public Transportation Association (8 July this amendment are discussed in detail below. 2009); 69 Pages/090708_transit_saved.aspx. Sprawl,” Los Angeles Times, 21 Aug. 2008;. 60 61 Margot Roosevelt, “Legislature Takes Aim at Urban com/2008/aug/21/local/me-sprawl21. Ibid. “Transit Benefits”, Center for Transportation Excellence 70 Tony Bizjak, “Fate of Steinberg Warming Bill Up in the Air,” The Sacramento Bee, 28 Sep. 2008; (2006);. story/1271584.html. 62 71 “Two Out of Three Jobs Created by Public Transit SB 375 is complex legislation that makes numerous intricate Investment Replace Jobs Hardest Hit by Economic Downturn”, APTA changes to the planning processes in California. The discussion herein (29 April 2009); will not attempt to analyze SB 375 in depth, but will instead focus jobs_impact.asp. on the key elements relevant to public transportation. For excellent 63 and extensive discussions of SB 375, see Prof. Cara Horowitz’s See, e.g., Richard Briffault, “Our Localism: Part I – The chapter earlier in this edition of California Policy Options; League, Structure of Local Government Law,” Columbia Law Review 90 (1990): Technical Overview, at. 57-58. SB%20375%20Implementation%20Final%209-19-08(1.1).pdf; and 64 John Darakjian, “SB 375: Promise, Compromise and the New Urban Association of Metropolitan Planning Organizations (AMPO);. Bill Fulton, “SB 375 is Now Law —But What Will it Do?,” California Planning & Development Report, Landscape,” UCLA Journal of Environmental Law and Policy, vol. 27, p. 371 (2009). (Oct. 1, 2008);. 72 League at 1-2. 65 AMPO;. 73 Id. at 14. 66 League of California Cities [hereafter “League”], “Technical 74 Id. resource_files/27223.SB%20375%20Implementation%20Final%209-19- 75 California Department of Housing and Community 08(1.1).pdf. Development,. 67 76 League at 14. as political interest groups in state lawmaking). 77 SB 375 § 4(b)(2). 68 78 League at 6-7. 79 Id. at 4. Overview of SB 375 v 1.1,” (Sept. 2008): 9; See Daniel Rodriguez, “Localism and Lawmaking,” Rutgers Law Journal 32 (2001) (arguing, inter alia, that local governments act “The League of California Cities is an association of California city officials who work together to enhance their knowledge and skills, exchange information, and combine resources so that they may influence policy decisions that affect cities.”. 64 80 Id. 97 “What is Proposition 1A?,” California High-Speed Rail Authority; 81 Id. at 5. proposition-1a.htm. 82 Id. 98. 83 84 “Measure R Information Guide,” MTA; Id. Id. at 8. 99. 100 “Measure R Information Guide,” MTA;. 85 Id. metro.net/measurer/default.asp. 86 Id. 101 87 “Measure R Project Index,” MTA;. net/measurer/project_index.html. I.e., general plans, specific plans, and zoning. 102 “Project Overview – Capital Funding,” Valley 88 League at 5-6. Transportation Authority;. 89 Id. at 5. 103 90 2000, pays in part for the construction of the extension. CAL. PUB. RES. CODE § 21000 et seq. CEQA: Summary,. 91 Id. A previous sales tax measure, Measure A, passed in 104 “What is SMART?”, Sonoma Marin Area Rail Transit;. Wyatt Buchanan, “Whitman Would Suspend AB32”, San 105 Id. 106 Id. 107 Id. projects that do not meet the transit-oriented requirements of TPPs. 108 William Jason, “SMART, Creative Housing Reach See id. Tentative Agreement on Railroad Square,” North Bay Business Francisco Chronicle, 17 Sept. 2009; blogs/nov05election/detail?blogid=14&entry_id=47872. 92 93 League at 12. SB 375 also creates incentives for SCS/APS consistent Journal (18 Oct. 2007); 94 CAL. PUB. RES. CODE § 21155(b). BUSINESSJOURNAL/71018009/1209. 95 See Mitchell, at 60-61. 109 96 Transbay Transit Center;. org/transbay/. votes_for_against.pdf. 110 Gary Richards, “BART Backers Pop Open Champagne, Celebrate Vision for San Jose’s Grand Central Station,” San Jose Mercury News (21 Nov. 2008). 65 111 Mark Baldassare et al., Californians & the environment, (Public Policy Institute of California: 2009); content/pubs/survey/S_709MBS.pdf. 112 This is not meant to suggest that throwing money at California: July 2009), 2; R_709LBEHR.pdf. 120 Louise Bedworth and Ellen Hanak, Planning for a Better Future: California 2025 – Transportation, (Public Policy Institute of transit providers will automatically lead to realizing all of the benefits California: July 2009), 3; of public transit discussed earlier. Transit funding must be utilized R_709LBEHR.pdf. intelligently to maximize ridership and benefits to constituents. In addition to traditional ridership modeling, the coordinated regional 121 planning envisioned by SB 375 should guide the deployment of Hold Up Higher Gasoline Taxes?”, Resources for the Future, June 22, increased transit funds. 2009;- 113 Sarah E. West, “Should Distributional Considerations Distributional-Considerations-Hold-Up-Higher-Gasoline-Taxes.aspx. SANTA CLARA VTA ADOPTED BIENNIAL BUDGET 122 California 2025 at 147-48. book.pdf; LA MTA ADOPTED BUDGET FY2008 at II-6 (2006), available 123 Louise Bedworth and Ellen Hanak, Planning for a Better at Future: California 2025 – Transportation, (Public Policy Institute of adopted_fy08.pdf. California: July 2009), 2; FISCAL YEARS 2008 AND 2009 at 35 (2007), available at. vta.org/inside/investor/financial/statements/fy08and09_budget_ 114 R_709LBEHR.pdf. For one columnist’s discussion on the difficulty of this challenge, see David Lazarus, “U.S. Public Transit Improvements Will 124 be a Tough Sell,” Los Angeles Times, Aug. 5, 2009;.. latimes.com/2009/aug/05/business/fi-lazarus5. 115 See, e.g., Charles Krauthammer, “At $4, Everybody Gets Rational,” Washington Post, June 6, 2008;. washingtonpost.com/wp-dyn/content/article/2008/06/05/ 125 The legislative counsel’s digest of SB 406 is available at: The veto message for SB 406 is available at: http:// vt_20091012.html. AR2008060503434.html (noted conservative columnist Krauthammer 126 advocates for higher energy taxes and a price floor of $4 on gasoline, directed by Brian Taylor.. with accompanying reductions in payroll taxes). 116 Ellen Hanak, Paying for Infrastructure: California’s Choices 2025, (Public Policy Institute of California: Jan. 2009), 10-11;. 127 See, e.g., UCLA Institute of Transportation Studies, The Scoping Plan for AB 32, which discusses the proposed cap-and-trade system in detail, is available at. arb.ca.gov/cc/scopingplan/scopingplan.htm. 128 Professor Shoup’s research is available at. 117 California 2025 at 147. bol.ucla.edu/. 118 California 2025 at 141. 129 119 Francisco Chronicle, June 3, 2005; Louise Bedworth and Ellen Hanak, Planning for a Better Future: California 2025 – Transportation, (Public Policy Institute of 66 Donald Shoup, “The High Cost of Free Parking,” San article.cgi?file=/c/a/2005/06/03/EDGFGD1VQ61.DTL. 130 Ibid. One such pilot project is SFpark, in San Francisco.. 131 Ibid. 132 Ari B. Bloomekatz, “Villaraigosa Has Bullish Plan for Rail Transit Projects,” Los Angeles Times, Oct. 29, 2009; http:// latimesblogs.latimes.com/lanow/2009/10/villaraigosa-has-bullishplan-for-la-rail-transit-projects.html. 133 Metro ExpressLanes, studies/expresslanes/index.htm. 134 135 136 Ibid. Ibid. (click on “News & Info”). Ibid. 67 4 68 HARNESSING THE MARKET TO DISCOURAGE SPRAWL IN CALIFORNIA PHILIP J. ROMERO 1 Philip J. Romero is Dean of the College of Business and Economics at California State University Los Angeles, and a principal in the Forward Observer and Third Century Solutions public policy consulting firms. As chief economist to the governor of California in the 1990s, Romero designed market-harnessing changes in public policy that contributed to the state’s turnaround in the mid 1990s, from last to first in the nation in economic performance. The author or co-author of six books on policy and economic topics, he earned his PhD from the RAND Graduate School. His latest book is A Boomer ’s Guide to Preserving Your Wealth from Washington, forthcoming in 2010. 69 4 Urban planners have long attempted to mandate reductions in “sprawl”, but they often run afoul of both consumer preferences for detached homes and existing land use policies (exclusionary zoning). A better approach would be to work with the market, not against it. A period of deep recession presents an ideal opportunity to put in place new policies to avoid repeating past mistakes. Most of the overbuilding in California in the first half of the decade occurred on the urban fringe. Thousands of excess homes led to one of the nation’s highest foreclosure rates, which aggravated an already steep economic downturn. This overbuilding wasted not only economic resources, but also natural resources. Policy innovations which can encourage denser infill development can help make the next boom more economically and environmentally responsible. “Smart districts,” modeled after redevelopment areas (RDAs), would allow some fraction of tax revenues generated inside the district to be retained for reinvestment in infrastructure or amenities for districts that commit to higher density development. The critical assumption is that richer amenities and infrastructure will attract private investment, and thereby encourage faster economic growth. This chapter estimates the economic impact of such districts if implemented statewide. Based on the historical experience of California’s redevelopment areas, it is reasonable to assume that the average smart district will, conservatively, accelerate economic growth within its boundaries by 4.6% to 8.3% per year. If implemented on a moderate to large scale, this additional growth will translate to an increase of 1,300 to 12,300 jobs per year; $95 to $885 million in personal income per year; and $124 million to $1.1 billion in added gross state product per year. Critics may argue that this faster growth comes at the expense of smart districts’ parent (surrounding) jurisdictions, because those parents “subsidize” the 70 districts by allowing them to keep a portion of locally- in exurban communities, so sprawl can cause economic generated revenues. In fact, such “subsidies” are in the as well as environmental and social damage. parents’ interest: The accelerated economic growth is estimate to generate one to three dollars of added reve- Attempts by land-use officials to mandate “smart nue per dollar of subsidy. This 100% to 300% return on growth” or “transit oriented development”—i.e., investment is far above any creditworthy jurisdiction’s growth in which the new construction is at higher typical borrowing rate, even in a credit crunch. densities than existing urbanization, to facilitate transit and pedestrians and make automobiles less Land-use mandates are largely ineffective and have necessary—have often failed. Sometimes failure significant adverse environmental side-effects. occurs because the high-density urban environments If, instead, market incentives are used to encourage beloved of smart growth advocates are appealing to such higher density development, they will eliminate only a small segment of the market. 3 Often failure the usual tradeoff between environmental and occurs because existing zoning mandates maximum, economic benefits. Further, using a market mechanism not minimum densities; these regulations are termed minimizes the chance of failure that has followed “exclusionary” zoning because their proscriptions on so many “new urbanist” and “transit oriented higher densities effectively price non-incumbents out development” schemes which fundamentally rely of the market. 4 So anti-sprawl advocates are working on mandates (coercion). Smart districts can help against powerful forces. make California’s inevitable future growth more responsible—and also more prosperous. Those forces in California shifted development inland from the exclusionary (and consequently expensive) coast. This shift fueled not only environmental CONVENTIONAL POLICIES TO C O N TA I N S P R A W L degradation from sprawl, but also rapid increases in housing prices in the first half of the decade, especially in the state. The result was an industry crash which helped cause a deep general recession. A period of deep recession presents an ideal opportunity to put in place new policies to avoid “Sprawl”—the horizontal spread of urbanized areas repeating past mistakes. Most of the overbuilding into formerly rural land--has become a bugbear in in California in the first half of the decade occurred numerous land-use planning debates. Where once the on the urban fringe. Thousands of inland excess opponents of sprawl were mainly concerned about homes led to one of the nation’s highest foreclosure aesthetics, the list of charges against it has grown. The rates, which aggravated an already steep economic reduction in walking opportunities and increased de- downturn. This building wasted not only economic pendence on automobiles (and longer commutes for resources, but also natural resources. Policy working parents, leaving them less time to attend to innovations which can encourage denser infill their children) has associated sprawl with a variety of development can help make the next boom more pathologies. These negative impacts include air pollu- economically and environmentally responsible. tion, climate change, obesity, reduced social cohesion, and even reduced educational performance.2 Further, the housing bust that began in 2007 largely originated 71 A DIFFERENT APPROACH since have been copied in most other states, may be declared in any “blighted” area. 7 Once an RDA is declared, thereafter some fraction of the property taxes generated within its boundaries, above the amount Only a fraction of housing buyers prefer to live in generated in a base year (i.e., “incremental”), may high-density environments. Zoning mandates are a be retained for reinvestment inside its borders. The very blunt and sometimes counterproductive instru- retention is a departure from the usual practice of ment for steering the market to provide such environ- transferring those revenues to the parent, city, county, ments. Thus, a superior alternative is to work with the and state. 8 Proponents argue that the reinvestment market, not against it. There are many ways to inter- is necessary to provide the RDA, which is generally vene to change incentives and encourage individual in an economically unattractive location (if not consumers or developers to pursue smarter-growth literally “blighted”) a fighting chance to achieve rates development. This chapter examines the economic im- of economic growth similar to or higher than the pacts of one approach, dubbed “Smart Districts.” surrounding area. The more extravagant advocates argue that RDAs are necessary to propel the outsized 5 Smart districts are inspired by a very common economic growth needed to overcome the area’s policy mechanism: use of the tax code to encourage disadvantages. desired behavior, or to discourage the opposite. There are many examples. For instance, the deductibility Opponents of redevelopment argue that RDAs add of charitable contributions on income taxes has little to economic growth, and mainly provide a tax undoubtedly contributed to the United States’ position subsidy to favored developers—of, for instance, sales as having the highest rate of charitable donations tax-generating properties such as retail shopping malls (as a share of income) in the industrialized world. and auto dealerships. The economic criticisms, at least, seem weak. Based on the sample of RDAs used in The boom in sales of hybrid automobiles in the middle the analysis in this chapter, economic activity inside of the 2000s was facilitated by a generous tax credit redevelopment districts (as captured by the assessed that led Toyota, for example, to maintain a lengthy value of all real property in the district’s boundaries) waiting list for its Prius. Subsequently, the 2009 expands at a rate between 2% and 5% faster than the “cash for clunkers” program, which used a subsidy surrounding county. Since nominal growth (i.e., not similar to a tax credit to encourage trade-ins of fuel adjusted for inflation) of GDP statewide in an average inefficient vehicles in favor of more efficient new year varies between about 3% and 7%, 9 growth rates models, exhausted after only a week of operation within RDAs are between half again to more than its first tranche of funding that was intended to last double that of non-RDA areas. four months. In principle, some tax incentive, on either the demand side (homebuyers) or the supply side (developers) should encourage changes in development patterns to reduce future sprawl. SMART DISTRICTS 6 Under the Smart District concept, RDA-like districts There are numerous ways such incentives could would be established, but with different eligibility be designed. The Smart District idea borrows from criteria. To be eligible for smart district designation, an existing practice: redevelopment areas (RDAs). instead of the subjective and inevitably controversial RDAs, which were first innovated in California and “blight”, land use authorities in the governing 72 jurisdiction would commit to (and zone for) higher office use, some residents may live close to work. All density development inside the district than in the residents would have an opportunity to experience the surrounding region. For the purpose of this discussion, vibrant urban living epitomized by Greenwich Village we will assume that the density difference must be or Soho in New York, South of Market or North Beach a least a factor of two—that is, new development in the in San Francisco, or the Pearl District in Portland, district much generate twice the dwellings per acre as Oregon. While such environments are clearly not the area outside the district. In practice, any density for all tastes, they tend to be attractive to what Prof. differential is possible, and should be based on market Richard Florida has termed “the creative class.” research as to what level buyers will accept. The creative class refers to writers, artists, software Designation could be made by local governing bod- engineers, and multimedia specialists who are typi- ies (e.g., city councils), or there could be a statewide cally well-educated and therefore have above-average competitive process, as with enterprise zones. Further- incomes (and spending). In their early and late careers more, the district’s location must be “landlocked”— they are often without children, and thus more at- that is, surrounded by already-urbanized area, so that tracted to such environments. “Creative class” eco- new development “infills” among existing urbaniza- nomic strategies have become fashionable, especially tion. Clearly, these criteria and the establishment pro- in many left-leaning large cities. While some observers cess can be refined. Other eligibility criteria may be doubt their effectiveness, 1 0 it seems evident that they added as this concept is legislated. will succeed for some market segment. Smart districts would allow cities to encourage the development of “Smart growth” (anti-sprawl) proponents should find environments to attract a share of this market. this idea promising. Through increased densities, they can encourage pedestrian/transit friendly ECONOMIC environments with all the advantages the advocates profess. “Transit-oriented development” (TOD) is CONCERNS a fashion in land use circles, but rarely are TODs designed holistically, in a way that intelligently encourages transit use. Smart districts do so not Smart districts’ attractiveness to prospective residents with regulatory mandates, which rarely can trump (and therefore to developers) will be substantially the market and often are counterproductive, but by enhanced through tax preferences. RDAs provide giving the market a gentle inducement in the desired a model: Smart districts can be permitted to retain direction. Transit stops will likely be a normal feature some fraction of the incremental revenues generated of smart districts, since they will enhance the districts’ by development within the district boundaries. For attractiveness to developers. RDAs, the revenues in question are property taxes, but in principle, the concept could apply to any type of Within these districts economic growth can be district-generated tax revenue. For example, it could accelerated, at least theoretically. Residents’ recurring also include sales taxes collected at a point of sale in living costs will be lower (because of less frequent the district, or personal or corporate income taxes need for automobile trips, a particular advantage at collected from resident individuals and businesses in a time of high gasoline prices and slow or negative the district. economic growth). If development inside smart districts includes mixed residential, commercial, and 73 The fiscal arrangements between redevelopment areas greater economic growth than would occur without and parent cities and counties remain controversial, the district. Thus, the theory goes, these districts will with the parents arguing that they are responsible for have economic as well as land-use benefits. a range of expensive services that aren’t fully covered by the share of district-generated taxes they are The empirical estimates are based on the historical permitted to receive. In an attempt to limit abuse, state experience of redevelopment areas in California. law puts a ceiling on the number of years an RDA These RDAs are the closest existing analogues to smart can exist. 11 By the same token, governance needs districts. Economic growth was computed for a sample careful design to assure accountability for the funds of 22 RDAs,1 3 and compared to economic growth spent within the district. Alternative governance in the surrounding county to determine the degree models, including special districts such as business to which RDAs actually accelerated growth. 1 4 The improvement districts, may be a more promising added growth attributable to RDAs was then adjusted governance approach than the RDA model, although (subjectively) to approximate the differences, positive this author approves of a long sunset provision to and negative, between smart districts and RDAs. encourage capital investment (perhaps 50 years). Why do RDAs grow faster than the rest of the state? Any retention of revenues by the district represents It is not because they are initially endowed with an implicit subsidy by its parent jurisdictions (which favorable characteristics—quite the opposite. would otherwise have received those revenues). From A reasonable assumption is that the added infrastruc- their parents’ perspectives, the burden of proof is on ture and amenities that retained incremental tax the district to demonstrate the remaining revenues that revenue makes the RDAs a more attractive location for parent jurisdictions receive are more than they would private investment. That investment then raises the have received if the district did not exist. In other value of nearby property as it raises local economic words, smart districts need to demonstrate that they activity and incomes. The evidence summarized below accelerate economic growth, and thus revenue growth. seems to confirm this assumption. OBJECTIVES AND HOW SMART A N A LY S I S DISTRICTS ARE This chapter evaluates the economic consequences of creation of one or more such smart districts in California. Its purpose is to approximately estimate the DIFFERENT FROM REDEVELOPMENT economic benefits if some fraction of revenues gener- AREAS ated inside a district were allowed to be retained for reinvestment, such as on public amenities (e.g., parks) or on infrastructure. 1 2 The assumption is that smart While RDAs are the closest extant model, they are an districts with more extensive endowments of these imperfect proxy for projecting the economic impact of things will be more attractive to desirable residents, smart districts. This section summarizes some of the and therefore to developers. As residents and devel- key differences. opers respond to these incentives, they will generate 74 Negative differences (i.e., reasons why smart districts’ to the historical record of the median of the sample economic impact would be less than RDAs) RDAs (which is lower than their mean). We consider 1. A 1998 review of RDAs by the Public Policy this a conservative assumption, because we believe Institute of California (PPIC) found that the that the positive differences noted above are of greater fastest-growing districts in its sample were magnitude than the negative ones. Therefore, readers those that contained considerable undeveloped should treat the estimates that follow as a credible land. 15 They were essentially development, lower bound on actual economic effects—that is, not redevelopment districts. By contrast, all smart districts’ actual effects will likely be higher smart districts would be established in already- than those presented. developed areas, so the value they could add will be more limited than those RDAs that had Another rough analog is enterprise zones (EZs). These a completely undeveloped base. are special areas in which companies which locate 2. To be attractive to their target market, smart inside a zone are taxed at a lower rate than they districts could not be zoned for quite as wide would be otherwise, in order to attract businesses to a range of uses as can RDAs. For example, it is depressed areas. EZs’ economic effectiveness have also unlikely that industrial uses would attract the been disputed. But EZs have a great handicap relative desired residents. to smart districts: they are usually located (when not abused) in disadvantaged areas; whereas developers Positive differences 3. RDAs start with significant handicaps, since they will only locate smart districts in areas they believe can have competitive advantages for attracting residents. are typically established in troubled (“blighted”) So again, it is reasonable to assume that smart districts areas. By contrast, the areas for which smart will have superior economic performance to EZs. districts would be best suited are those that can readily be made attractive to residents and, Nevertheless, not all smart districts will succeed. The therefore, profitable for developers. landscape is littered with planning schemes based on 4. Smart districts that attract residents of above- mistaken assumptions about the market’s response average incomes (creative class) will be the to urban designs. Later sections of this chapter will wellsprings for substantial economic activity discuss findings for two groups of scenarios: (a) where through those residents’ spending. 60% to 90% of smart districts are “successful” (i.e., 5. Smart districts that are mixed-use—which grow at the rate projected), and where only 20-50% will likely be the common pattern—will have succeed.1 6 Even the lower number assumes that the considerable retail activity as residents patronize jurisdictions that create a smart district do so only stores and restaurants near (by design, within after considerable market research. transit or walking distance) their homes. 6. The likely absence of industrial uses in these districts precludes the negative impact FINDINGS on neighboring property values that often accompanies industrial development. Over the period between 1996 to 2002 (two years at roughly the same point—early in a recovery--in two For the purposes of this chapter, we will assume that California economic cycles), economic growth in the the net effect of the above differences means that the sample of redevelopment areas (RDAs) exceeded that average smart district will add growth at a rate equal of their surrounding counties by a mean of 5.3% and 75 a median of 2.1% per year. If a typical district was per- By way of background, RDAs’ share of total state mitted (as RDAs are under AB 1290) to keep 67% of its assessed value declined from 49% to 9% in the years incremental property tax revenues (and conservatively from 1996 to 2002. 1 7 considering only property tax revenues in this fiscal impact analysis), the parent jurisdictions would see Table 1 summarizes the four scenarios. 100% to 300% more revenues than the subsidy they provide to the district: a return on their “investment” Table 1. Scenario Summary of 100 to 300%, depending on whether the historical mean or median rate of added annual growth is used. S ce na ri o % of S ta te A sse sse d Va l ue % of S m a r t Di s t r i c t s In other words, it would take between 15 years and 25 of S ucce ss i n S m a r t D i stri cts A ssum ed S u c c e s s f u l revenues from economic growth attributable to the 1. Ea r l y /Hi g h 1% 90% RDAs to equal the revenue they retained). 2. Ma t ure /Hi g h 10% 60% 3. Ea r l y /Mod . 1% 50% 4. Ma t ure /Mod . 10% 20% years for the investment to break even (for the added Appendix A displays the results of our findings about how much added economic growth has been associated with RDAs historically, and Appendix So we will assume that 0.9% (1% x 90%) of the state’s B outlines the return on investment and breakeven assessed value is located inside successful smart computations to parent jurisdictions. districts under Scenario #1; 6% in #2; 0.5% in #3, and 2% in Scenario #4. To apply these to smart districts, we specified the following scenarios: 1. Early implementation/high success: Smart districts contain 1% of the state’s development, and 90% of these are successful. SPECIFIC ECONOMIC BENEFITS OF SMART 2. Maturation/high success: DISTRICTS Smart districts contain 10% of state development; 60% of these are successful. 3. Early implementation/limited success: To recapitulate, our analysis assumes that assessed Smart districts contain 1% of state development, value within smart districts will grow at an annual and 50% are successful. rate of between 2.1% and 5.3% faster than the 4. Maturation/limited success: overall economy. Most long-term projections of the Smart districts contain 10% of the state’s California’s economy expect it to grow between development, and 20% of these are successful. 2.5% and 3% per year. So a successful smart growth district’s assessed value will grow between 4.6% and The scenarios make the plausible assumption that as 8.3% per year. We will assume that other measures smart districts scale up and proliferate throughout of economic activity, such as employment, personal California (i.e., go from containing 1% in early income, or output (gross state product), grow at implementation to 10% of state assessed value in roughly the same rate as assessed value. Baseline maturity), the probability of success will drop. That is, statistics for assessed value, gross state product, the most promising locations for districts will probably employment, and personal income are shown in Table be used first; and the program will reach diminishing 2. These data are from 2005, the latest year for which returns later. authoritative state data were available when this 76 chapter was first drafted. Skeptics may argue that the numbers in Table 3 are Table 2. 2005 Statewide Baseline Values high, because they implicitly assume that accelerated As s es s ed Value: $ 3 ,1 9 3 ,6 2 3 mi l l i on ( 2005) growth in smart districts does not come at the expense Gro s s St at e Product: $ 1 ,5 5 0 ,7 5 3 mi l l i on ( 2004) of slower growth elsewhere in the state outside the Per s o n al In come: $ 1 ,1 8 4 ,9 9 7 mi l l i on ( 2003) districts’ boundaries. The premise is reasonable: some E m plo ym en t : 1 6 ,4 6 0 ,0 0 0 j obs (2 0 04) within-district growth merely reflects a shift from outside of districts to inside. But since this analysis Source: Depar tment of Finance, California Statistical Abstract, 2005 ed. is based on the historical experience of RDAs, it assumes no more and no less such shifting than RDAs As mentioned, economic aggregates are assumed to encountered historically. scale with property values. Clearly this is not always true; for example, property values often fall farther in CONCLUSION a recession or rise faster in a boom than does, say, employment or personal income. But over the long term it is reasonable to expect a fairly stable relationship. Creation of special “smart districts” in California—in With this in mind, Table 3 displays estimates of the an- which district status is granted to areas that agree to nual benefits of smart growth districts (i.e., accelerate permit higher densities than surrounding areas in growth) under our four scenarios. exchange for the right to keep a fraction of the revenue generated therein—can have economic benefits in addition to non-economic ones. Depending upon the Table 3. Growth in Economic Aggregates pace at which districts are created and on their success for Smart District Scenarios in the marketplace, smart districts could be responsible Sc enar io Asse sse d Va lu e for annual increases in gross state product of between An n u a l g row th i n: $124 million and nearly $1.2 billion. These increases In Su cce ssf u l Sma r t Dist rict s Jo b s Pe rs. In com e Output ( G S P ) may not seem large in a state economy that grows by over $30 billion per year (in a normal year). But with 1 0.9 % 1 2 ,3 0 0 $885 M $1,158 M 2 6.0% 8,200 59 0 M 772 M 3 0.5 % 3 ,3 0 0 237 M 310 M 4 2.0% 1,300 95 M 124 M Assumes that average growth in smar t districts is between 4.6% (scen a r i o s 3 a n d 4 ) a n d 8 . 3 % ( s c e n a r i o s 1 a n d 2 ) p e r y e a r, b a s e d o n t h e range revealed by our analysis of RDA experience. Relative relationships among scenarios may not be quite consistent due to rounding. GSP = Gross State Product, the sum of all goods and services produced in California. this output growth will come new jobs—between 1,300 and 12,300 per year. If market incentives, as opposed to land-use mandates, are used to encourage higher density development, they will eliminate the usual tradeoff between environmental and economic benefits. Further, using a market mechanism minimizes the chance of failure that has followed so many “new urbanist” and To put these numbers in perspective, median household income in California was $49,320 in 2003, “transit oriented development” schemes which rely on 18 coercion. Smart districts can help make California’s so smart districts have the potential to stimulate inevitable future growth more responsible—and also enough added personal income for 2,000 to 18,000 more prosperous. families—per year. 77 Added Economic Growth Attributable to Sample Redevelopment Districts, 1996-2002 C o u n t y Dist rict A sse sse d Va l ue A sse sse d Va l ue A s s e s s e d Va l u e 1996- 7 ( $) 2002- 03 ( $) G ro wt h /Y r Fresno Mari posa $79,933,610 N A --Me rg e d ? Fresno K i ngsburg $33,500,350 $54,886,007 7 . 3 % Fresno Al l county R DAs $2,333,148,652 $4,314,811,785 9 . 2 % County PI growth LA Puente- Merced $39,675,937 N A LA Burbank $514,681,000 $605,751,923 2 . 4 % LA Cul v er Ci ty $1,687,686,440 $2,762,642,108 7 . 3 % LA Santa Fe $111,588,136 $138,642,595 3 . 1 % LA Beacon Street $64,373,000 $88,948,000 4 . 7 % LA Li ttl e Toky o $271,498,000 $254,939,000 - 0 . 9 % LA Al l county R DAs $76,176,672,787 $112,346,729,359 5 . 7 % County PI growth Mari n San R afael $1,175,247,100 $1,720,575,389 5 . 6 % Mari n Al l county R DAs $1,479,376,877 $2,821,946,543 9 . 7 % County PI growth Orange Buena Park $247,451,975 $1,005,488,960 2 2 . 2 % Orange Al l county R DAs $21,391,900,403 $34,527,411,331 7 . 1 % County PI growth Pl acer R osev i l l e $184,379,039 $417,573,339 1 2 . 4 % Pl acer Al l county R DAs $492,080,055 $2,201,547,532 2 3 . 9 % County PI growth R i v ersi de County Proj # 1 $53,586,155 N A --me rg e d ? R i v ersi de Coachel l a # 3 $115,607,457 $137,067,443 2 . 5 % R i v ersi de Moreno Val l ey $1,061,085,739 $1,141,558,437 1 . 0 % R i v ersi de Sy camore Cy n $130,749,364 N A R i v ersi de Al l county R DAs $21,999,073,915 $38,530,626,124 County PI growth 78 8 . 3 % APPENDIX A Per s onal In co me Pe rso n a l In co me Pe rso na l I ncom e Ne t RD A 1996-7 ($M) 2002-3 ( $M) G ro w th/ Yr e f f e ct 2. 1% $14, 430 $ 2 0 ,6 5 1 5 .3 % - 2. 5% 2. 4% - 1. 7% - 0. 2% - 5. 8% $222, 773 $ 3 1 1 ,2 8 5 4 .9 % 0. 5% $11, 395 $ 1 6 ,1 9 0 5 .1 % 16. 2% $77, 499 $ 1 1 6 ,2 3 8 6 .0 % 4. 1% $6, 153 $ 1 0 ,7 5 1 8 .3 % - 4. 7% - 6. 1% $27, 565 $ 4 4 ,6 2 7 7.1% 79 San Bern. I nl and Val l ey $1,883,372,936 $2,243,838,469 2 . 5 % San Bern. Chi no $264,282,224 $1,198,120,736 2 4 . 1 % San Bern. Proj . # 3 $268,565,027 $436,440,856 7 . 2 % San Bern. Al l county R DAs $23,641,375,869 $34,118,323,742 5 . 4 % County PI growth San Di ego San Marcos # 1 $702,654,378 $1,035,809,595 5 . 7 % San Di ego Al l county R DAs $15,567,409,305 $27,657,118,641 8 . 6 % County PI growth San Fran R i ncon- So Bch $305,494,000 $1,240,786,000 2 2 . 2 % San Fran Al l county R DAs $3,062,046,000 $6,968,034,458 1 2 . 5 % County PI growth San Mateo E P Al to R av enswo od + 101 $60,650,900 $259,232,398 2 3 . 1 % San Mateo Foster Ci ty $786,659,191 $1,456,232,925 9 . 2 % San Mateo Al l county R DAs $5,108,275,087 $10,940,509,244 1 1 . 5 % County PI growth S Cl ara San Jose $7,680,817,524 $18,732,943,658 1 3 . 6 % S Cl ara Al l county R DAs $12,340,697,586 $27,878,019,206 1 2 . 3 % County PI growth Sol ano Vacav i l l e $393,020,156 $1,442,373,628 2 0 . 4 % Sol ano Al l county R DAs $4,951,438,003 $7,181,406,264 5 . 5 % County PI growth Stani sl aus Modesto $693,844,712 $872,354,117 3 . 3 % Stani sl aus Al l county R DAs $2,697,073,479 $4,082,751,742 6 . 1 % County PI growth Yol o Woodl and $203,725,248 $243,635,594 2 . 6 % Yol o Al l county R DAs $1,938,474,773 $2,975,074,296 6 . 3 % County PI growth Note: “PI ” = persona l i nc ome 80 Su mma ry o f e f f ects ( a dde d g row th/ yr) Me dia n Ne t RDA e f f e ct 2. 05% P e r ye a r Me a n Ne t RDA ef f e ct 5. 31% P e r ye a r 2. 5% 24. 1% 7. 2% $29, 450 $ 4 4 ,7 7 2 6 .2 % - 1. 1% $65, 881 $ 1 0 4 ,6 1 4 6 .8 % 16. 7% $28, 832 $ 4 1 ,8 9 7 5 .5 % 18. 5% 4. 6% $26, 952 $ 3 6 ,9 4 1 4 .6 % 8. 2% $54, 169 $ 7 8 ,1 6 5 5 .4 % 20. 4% $8, 009 $ 1 2 ,4 5 6 6 .5 % - 2. 5% $8, 036 $ 1 1 ,9 2 0 5 .8 % - 2. 6% $3, 568 $ 5 ,0 8 1 5 .2 % A u t h o r ’s c a l c u l a t i o n s b a s e d o n d a t a f r o m : S t a t e C o n t r o l l e r ’s O f f i c e , Community Redevelopment Agencies Annual Report, 1996-97 and 2002-03; and Department of Finance, California Statistical Abstract, 2005. 81 Smart districts, like redevelopment areas, retain thereafter at 8.3% or 4.6% per year. 1 9 The “Parent’s a portion of locally-generated revenues and “pass Cumulative Subsidy” column shows the accumulated through” the rest to parent jurisdictions. Since absent revenues foregone by the parent jurisdictions—i.e., such districts, the parent(s) would receive all revenues, that subsidize the district. The “Extra Revenue” districts can be considered to be receiving a “subsidy” column indicates those revenues received by the from the parent(s). This subsidy has been one of the parent jurisdiction which would not exist but for the sources of opposition to redevelopment areas. accelerated growth created because of the district. The “Parent’s Cumulative Benefit” column accumulates the But as the saying goes, it takes money to make money. prior column. When “Parent’s Cum Benefit” reaches Revenues that are retained by a district to accelerate the level of “Parent’s Cum Subsidy”, the parent economic growth will also accelerate tax revenues. jurisdiction has broken even. That year is shown in The fair question to ask is: Do the added revenues from bold within the table: it occurs after 15 years in the that acceleration equal or exceed the subsidy provided “high” scenario and 25 years in the “low” scenario. (through foregone revenue) by the parent(s)? If they do, then the parent is earning a positive return on Finally, return on investment is calculated by its “investment”. discounting all cashflows, subsidy and “extra revenue”, to account for the time value of money, then Typically investment analyses compute the increased comparing the net present value (NPV) of the sum of revenues resulting from some up front investment, each, computed over 30 years.2 0 We used a discount and compare the former to the latter. A “return on rate of 7%, which is approximately the rate of most investment” (ROI), expressed as a percentage, captures local jurisdictions. Dividing “cum benefits” by “cum the excess revenues generated over and above the subsidy” produces the return on investment (ROI): upfront cost. The ROI is usually compared to the 103% in the low growth scenario, and 304% in the rate at which the jurisdiction borrows money. If the high growth scenario. Both ROIs are far above any investment’s ROI is greater than the jurisdiction’s creditworthy California jurisdiction’s borrowing rate, borrowing rate, the investment is worthwhile even in a credit crunch. Thus, smart districts are (the investor/jurisdiction makes a profit). a good investment to the parent jurisdiction, which gets back two to four dollars in added revenue for The table in Appendix B outlines the investment computation for a hypothetical district under two scenarios, high and low growth, based respectively on the mean and median growth acceleration achieved historically by redevelopment areas. In the “high” scenario, smart districts grow at 8.3% per year, vs. 4.6% in the “low” scenario. Starting from an initial illustrative assumption of $10 million in tax revenues (67% retained by the district—i.e., “subsidized”— and 33% passed through to parents), revenues grow 82 every dollar they forego for “subsidy”. 83 Computation of Return on Investment to Parent Jurisdictions P a re nt J uri sdi cti on ROI C om puta ti on ( dol l a rs i n m i l l i o n s ) A s s ume d p a s s -t hroug h r a t e : 33.0% A s s ume d e c onomi c ( & re v e nue ) g rowt h r a t e — -hi g h 8.3% A s s ume d e c onomi c ( & re v e nue ) g rowt h r a t e — -l ow 4.6% D i s c ount r a t e : 7.0% LOW GROWTH SCENARIO Year Dist rict Pa re n t Re ve n u e s 1 P a re nt’s P a re nt’s P a re n t ’s Re ve n ue s Re ce i ve d re vs C um S ubsi dy Extra Re v Cu m B e n e f i t $ 3 .3 0 $ 6 .7 0 $10.00 $3.30 $0.00 $0.00 2 $ 3 .4 5 $ 7 .0 1 $10.46 $6.75 $0.31 $0.31 3 $ 3 .6 1 $ 7 .3 3 $10.94 $6.91 $0.32 $0.63 4 $ 3 .7 8 $ 7 .6 7 $11.44 $7.08 $0.34 $0.97 5 $ 3 .9 5 $ 8 .0 2 $11.97 $7.25 $0.35 $1.32 6 $ 4 .1 3 $ 8 .3 9 $12.52 $7.43 $0.37 $1.69 7 $ 4 .3 2 $ 8 .7 8 $13.10 $7.62 $0.39 $2.08 8 $ 4 .5 2 $ 9 .1 8 $13.70 $7.82 $0.40 $2.48 9 $ 4 .7 3 $ 9 .6 0 $14.33 $8.03 $0.42 $2.90 10 $ 4 .9 5 $ 1 0 .0 4 $14.99 $8.25 $0.44 $3.34 11 $ 5 .1 7 $ 1 0 .5 0 $15.68 $8.47 $0.46 $3.80 12 $ 5 .4 1 $ 1 0 .9 9 $16.40 $8.71 $0.48 $4.29 13 $ 5 .6 6 $ 1 1 .4 9 $17.15 $8.96 $0.51 $4.79 14 $ 5 .9 2 $ 1 2 .0 2 $17.94 $9.22 $0.53 $5.32 15 $ 6 .1 9 $ 1 2 .5 8 $18.77 $9.49 $0.55 $5.88 16 $ 6 .4 8 $ 1 3 .1 5 $19.63 $9.78 $0.58 $6.45 17 $ 6 .7 8 $ 1 3 .7 6 $20.54 $10.08 $0.61 $7.06 18 $ 7 .0 9 $ 1 4 .3 9 $21.48 $10.39 $0.63 $7.69 19 $ 7 .4 1 $ 1 5 .0 5 $22.47 $10.71 $0.66 $8.35 20 $ 7 .7 6 $ 1 5 .7 5 $23.50 $11.06 $0.69 $9.05 21 $ 8 .1 1 $ 1 6 .4 7 $24.58 $11.41 $0.72 $9.77 22 $ 8 .4 9 $ 1 7 .2 3 $25.71 $11.79 $0.76 $10.53 23 $ 8 .8 8 $ 1 8 .0 2 $26.90 $12.18 $0.79 $11.32 24 $ 9 .2 8 $ 1 8 .8 5 $28.13 $12.58 $0.83 $12.15 25 $9.71 $19.72 $29. 43 $13. 01 $0. 87 $13.02 26 $ 1 0 .1 6 $ 2 0 .6 2 $30.78 $13.46 $0.91 $13.92 27 $ 1 0 .6 3 $ 2 1 .5 7 $32.20 $13.93 $0.95 $14.87 28 $ 1 1 .1 1 $ 2 2 .5 6 $33.68 $14.41 $0.99 $15.86 29 $ 1 1 .6 3 $ 2 3 .6 0 $35.23 $14.93 $1.04 $16.90 30 $ 1 2 .1 6 $ 2 4 .6 9 $36.85 $15.46 $1.09 $17.99 $214. 74 ROI : 1 0 3 % 84 NPV: $105. 74 Tota l *L ow * B rke ve n APPENDIX B Year s To Cove r Su bsidy Fro m Pa re n t Ju risidict io n s 25 At m ean RDA ef fect (added growth per y ear) 15 HIGH GROWTH SCENARIO At m edian RDA ef fect (added growth per y ear) Ye a r Dist rict P a re nt Re ve n u e s 1 P a re nt’s P a re nt’s P a re n t ’s Re ve nue s Re ce i v e d re vs C um S ubsi dy Extra Rev Cu m B e n e f i t $ 3 .3 0 $6.70 $10.00 $3.30 $0.00 $0.00 2 $ 3 .5 7 $7.26 $10.83 $6.87 $0.56 $0.56 3 $ 3 .8 7 $7.86 $11.73 $7.17 $0.60 $1.16 4 $ 4 .1 9 $8.51 $12.70 $7.49 $0.65 $1.81 5 $ 4 .5 4 $9.22 $13.76 $7.84 $0.71 $2.52 6 $ 4 .9 2 $9.98 $14.90 $8.22 $0.77 $3.28 7 $ 5 .3 2 $10.81 $16.14 $8.62 $0.83 $4.11 8 $ 5 .7 7 $11.71 $17.47 $9.07 $0.90 $5.01 9 $ 6 .2 5 $12.68 $18.92 $9.55 $0.97 $5.98 1 0 $ 6 .7 6 $13.73 $20.50 $10.06 $1.05 $7.03 1 1 $ 7 .3 2 $14.87 $22.20 $10.62 $1.14 $8.17 1 2 $ 7 .9 3 $16.11 $24.04 $11.23 $1.23 $9.41 1 3 $ 8 .5 9 $17.44 $26.03 $11.89 $1.34 $10.74 1 4 $ 9 .3 0 $18.89 $28.19 $12.60 $1.45 $12.19 15 $10.08 $20. 46 $30. 54 $13. 38 $1. 57 $13.76 1 6 $ 1 0 .9 1 $22.16 $33.07 $14.21 $1.70 $15.46 1 7 $ 1 1 .8 2 $24.00 $35.81 $15.12 $1.84 $17.30 1 8 $ 1 2 .8 0 $25.99 $38.79 $16.10 $1.99 $19.29 1 9 $ 1 3 .8 6 $28.14 $42.01 $17.16 $2.16 $21.44 2 0 $ 1 5 .0 1 $30.48 $45.49 $18.31 $2.34 $23.78 2 1 $ 1 6 .2 6 $33.01 $49.27 $19.56 $2.53 $26.31 2 2 $ 1 7 .6 1 $35.75 $53.36 $20.91 $2.74 $29.05 2 3 $ 1 9 .0 7 $38.72 $57.79 $22.37 $2.97 $32.02 2 4 $ 2 0 .6 5 $41.93 $62.58 $23.95 $3.21 $35.23 2 5 $ 2 2 .3 7 $45.41 $67.78 $25.67 $3.48 $38.71 2 6 $ 2 4 .2 2 $49.18 $73.40 $27.52 $3.77 $42.48 2 7 $ 2 6 .2 3 $53.26 $79.50 $29.53 $4.08 $46.56 2 8 $ 2 8 .4 1 $57.68 $86.09 $31.71 $4.42 $50.98 2 9 $ 3 0 .7 7 $62.47 $93.24 $34.07 $4.79 $55.77 3 0 $ 3 3 .3 2 $67.66 $100.98 $36.62 $5.19 $60.96 NPV: $148. 70 $601. 05 ROI : 304% Tota l *Hi g h* B rke ve n 85 1 This research was originally supported by the California Building Industry Association. (CBIA). The author acknowledges helpful comments from the following: Tim Coyle and Richard Lyon of CBIA; and Joe Rodota of Forward Observer. Mandy Zimmerman of Forward Observer provided research assistance. 2 The sprawl debate is far too extensive to recount here. A useful contrarian summary is Bruegmann, Robert, Sprawl: A Compact History, University of Chicago Press, 2005. Note that while there is some scientific evidence for most of the side effects of sprawl listed in this paragraph, many of these studies’ findings are disputed and subject to refinement in future research. For perspective on the importance of findings about the effects of sprawl, see Levine, below. 3 Kotkin, Joel, “The War Against Suburbia”, Wall Street Journal, Jan. 14, 2006; and “The Ersatz Urban Renaissance”, Wall Street Journal, May 15, 2006.. 4 An excellent summary of the effects of exclusionary zoning, and how the existence of such rules implies that the “market vs. planning” paradigm is flawed, is Levine, Jonathan, Zoned Out, Resources for the Future Press, 2006. 5 So-named in deference to advocates of “smart growth.” 6 The language in the foregoing sentence implies indifference about whether incentives are supply-oriented or demand-oriented. But in fact unless they affect demand behavior, any supply-side incentives’ effect will be only temporary. If developers are encouraged to build condominium buildings that buyers won’t buy, the developer will lose money, nothwithstanding any incentive. Thereafter they will eschew “smart growth” development unless they are confident that buyers will support it. 7 The definition of “blight” is relatively flexible, and over time has occasionally—critics would say “frequently”--been abused. The California legislature has attempted to tighten the RDA system up in this and other ways. In addition, the U.S. Supreme Court’s 2005 Kelo 86 ENDNOTES vs. New London decision, which affirmed the ability of a city to declare Stanislaus counties). Our sample included 25 districts, although only a region “blighted” and exercise eminent domain to displace residents 22 could be used because three districts merged or were dissolved in in favor of private development, has sparked considerable interest in the years between 1996 and 2002. tightening up the conditions under which “blight” can be declared. Certainly a smart districts program should have more rigorous 14 eligibility standards to limit the opportunities for abuse, by either for economic activity) within each RDA’s boundary at equivalent local governments or the developers who often exert influence. points in two economic cycles: 1996-97 and 2002-03. Each year was 8 We recorded the assessed value of all real estate (as a proxy roughly two years after an economic trough. Statewide, on average, In California, the fraction of revenues that must be “passed each dollar of assessed property value was the foundation of 42 cents through” to higher jurisdictions was mandated by AB 1290 of 1993. per year of economic activity in 2002. (Author ’s calculations based While the “pass through” computation is complex, the average rate is on annual reports of the state controller.) Economic growth for the 33% of RDA-generated property tax revenues. See Dardia, Michael, surrounding area was estimated based on county personal income Subsidizing Redevelopment in California, January 1998, Public Policy data from the Department of Finance’s California Statistical Abstract, Institute of California, for a summary of fiscal issues associated 2005-06. Personal income was used as an economic measure because with RDAs. gross state product data is only available at the county level with very 9 long lags. The economic growth in the sample RDAs and surrounding This result is described in Appendix A and discussed below. 10 counties is displayed in the Appendix. . 15 See Dardia, footnoted earlier in this chapter. urban pied-a-tierre as a second home) and twentysomething slackers 16 “Succeed” is defined as generating enough new revenue than true job creators. to parent jurisdictions (a district’s city, county, and the state) to Kotkin has been outspoken in arguing that many “new urbanist” environments attract more empty-nest retirees (who buy an 11 compensate for the loss of revenues that are instead retained by the The City of Industry, a “city” that could not exist without RDAs, at this writing is facing opposition to its attempt to extend the district. life of its RDAs in order to offer tax incentives to lure a sports stadium 17 within its boundaries. Agencies Annual Report, 1996-97. 12 18 Department of Finance, California Statistical Abstract, 2005. of time necessary for districts’ economic growth to compensate their 19 The tax revenues in question would almost certainly parent jurisdictions for implicit subsidies. included property taxes, but could include other taxes generated by Fiscal impacts are outside the scope of this chapter, beyond a rough calculation (reported in the Appendix) estimating the length 13 California State Controller, Community Redevelopment economic activity, such as income or property taxes, if smart districts The random sample attempted to span the range of urban environments in which SMART districts might be contemplated: were so designed. dense city (Los Angeles or San Francisco), inner suburbs (e.g., 20 Marin, Orange, or San Mateo counties, or north San Diego county), retained by the smart district—i.e., “subsidized” by its parent fast-growing edge cities (Placer, Riverside, San Bernadino, and Yolo jurisdiction—will generally be spent of fixed investment counties), and fast-growing diminishing agricultural areas (Fresno and (e.g., infrastructure), which has a long lifespan. A thirty-year horizon was used because the revenues 87 5 88 PA S S I N G A G U N CONTROL LAW IN CALIFORNIA: A CASE STUDY OF THE CRIME GUN I D E N T I F I C AT I O N A C T W I L L I A M PA R E N T * William Parent is the Associate Dean for Programs and Initiatives at the UCLA School of Public Affairs. Before coming to UCLA, he was at Harvard University’s John F. Kennedy School of Government where he was the Executive Director of the Innovations in American Government Program. * This chapter is based on a case study supported by a generous contribution by the David Bohnett Foundation. 89 5 In early February 2007, newly-elected California State Assemblyman Mike Feuer was approached by gun violence prevention activists Amanda and Nick Wilcox. They asked if he would sponsor a bill which would require that semi-automatic handguns sold in California include a newly-tested “microstamping” technology, which could be used to trace shells to the guns that fired them. There was no such requirement anywhere in the country. The Wilcoxes had worked on a failed attempt at the same law the previous session. But Feuer, even though he had a strong reputation on gun control during his six years as a Los Angeles City Councilman, was reticent. First impressions are important for a freshman legislator. He had an ambitious agenda in a wide range of policy areas. Feuer didn’t want to get pigeonholed as a singleissue assemblyman. It was the kind of bill that would require many hours of his time to pass, distracting from the rest of his agenda. And, perhaps most important, he didn’t want to fight a highly visible, losing battle first time out. AN INITIAL A LT E R N AT I V E SPONSOR The Wilcoxes had not originally planned on asking a freshman legislator to carry the bill. Their first hope had been Senator Darrell Steinberg. At the time, Steinberg was a freshman senator. But he had completed three accomplished terms in the Assembly and was preparing for a potential leadership role in the Senate. Steinberg had worked closely with the Wilcoxes on a range of issues helped with the successful passage of Proposition 63, a mental health initiative. 90 BECOMING Initially, there was an assurance to the Wilcoxes that Steinberg was “99 percent sure” he would carry the ACTIVISTS bill. However, they got a call from the Senator ’s chief of staff that he would not, just weeks before the deadline for submitting new legislation. The Wilcoxes turned to Kay Holmen, the Los Angelesbased president of the California Chapters of the Brady Campaign against Gun Violence. She, in turn, approached Feuer, and pitched microstamping and the Wilcoxes. “The issues of mental health and gun violence came to us, we didn’t go to them,” the Wilcoxes say. After Laura’s death, Nick and Amanda, raised as Quakers and long-time contributors to the Brady Campaign, devoted themselves to improved mental health treatment and gun violence prevention. Just a month after the shooting, they organized a vigil at an annual THE KILLING OF LAURA WILCOX Nick and Amanda Wilcox were not the kind to be easily deterred. Their 19-year-old daughter, Laura, valedictorian of her high school, had been shot and killed six years before. The shooting was a random incident, occurring as she worked as a fill-in during winter break at the Nevada County Mental Health Center. She was then a sophomore at Haverford gun show at the Nevada County Fairgrounds, which Thorpe had been known to attend. A year later, the Wilcoxes pushed the California Department of Justice to send undercover agents to the gun show. The agents found banned weapons for sale, unlicensed dealers, and weapons sold without background checks or ten-day waiting periods as required by California law. Arrests were made, and the Wilcoxes were eventually successful in closing down the show. College in Pennsylvania and had been an intern at the mental health center the previous summer. On the afternoon of January 10, 2001, Scott Alan Thorpe, 41, delusional, with a history of resistance to his family’s pleas to get mental health treatment, walked in to the Nevada Mental Health Center. There he shot and killed Laura Wilcox, who was working as a receptionist, Pearlie Mae Feldman, 68, a mental health caregiver, and severely injured Judith Edzards, 49. Thorpe then went to a local restaurant and shot two more people, killing one, Mike Markle, 24, the manager. After Thorpe was arrested, he explained to the police how the mental health center had angered him and how the restaurant had been trying to poison him. He believed he had settled the matter and asked the police when he could go home. T H E C A M PA I G N FOR “LAURA’S LAW” Over the next two years, the Wilcoxes were also instrumental and persistent in moving “Laura’s Law” through the California legislature and having it signed by Governor Gray Davis. The law allows involuntary outpatient treatment of mental illness patients if they are a threat to themselves or others. Laura’s Law was modeled after a similar New York state “Kendra’s Law.” Kendra was a young woman who was pushed in front of a subway train by a mentally-ill man. Laura’s Law proved difficult to implement without funding. In response, the Wilcoxes worked for the passage of Proposition 63, a state surtax on those with income above $1 million to support treatment for the 91 mentally ill, passed by voters in 2004. Proposition 63 close. “Mike’s not a bullshitter,” Nick Wilcox said. was sponsored by Darrell Steinberg when he was in “He got right to counting the votes.” the Assembly. Following the election, there were a lot of new “We’re effective because of what happened and moderate and conservative Democrats, along with because we’re not paid,” Nick Wilcox once told a more conservative Republican leadership. Together, a reporter. “We’ve discovered that every legislative Feuer, Marcus, and the Wilcoxes focused and door was unlocked.” Through their involvement speculated on the new Senate. They shared their with the inter-related California Chapters of the knowledge of the members and opinions on how they Brady Campaign (formerly the Million Mom March would lean. They agreed on the names of five key Chapters), they had learned of microstamping swing senators. That was enough for Feuer. He would technology. The Wilcoxes saw it as a tool for finding sponsor the bill, but he had conditions. armed criminals at large. It would also be a deterrent against “straw purchasers” who buy and resell When Mike Feuer was defeated for City Attorney quantities of guns, often under the radar and often at after being termed out as a city council member, the gun shows. The microstamp could help identify the National Rifle Association (NRA) put his picture original purchaser of a gun through spent shells left at on the front page of its national website, with the a crime scene, a deterrent to illegal reselling. headline, “We Beat Mike Feuer.” As a city councilman, Feuer had developed a national reputation for writing The Wilcoxes had worked with Assemblyman Paul anti-gun laws. These laws included bans on high- Koretz (D-Los Angeles), Feuer ’s predecessor who had capacity magazines and easily concealable weapons, been termed out, on the microstamping bill a year a requirement for background checks on gun store earlier. They had served as volunteer lobbyists on its owners, limits of purchases by a single customer to behalf in the corridors of the state capitol, where they one gun per month to prevent straw purchasers from had become well known and respected by legislators buying and reselling large quantities of guns, and and staff alike. One such staffer was Rebecca Marcus, a law requiring trigger locks on handguns. who had previously worked for Johan Klehs, an East Bay legislator known for his knowledge of tax policy, Feuer had worked to convince neighboring counties who carried a firearm bill in 2006. Klehs had just to enact the same laws and penalties as Los Angeles termed out and Marcus had just signed on to be chief- and convened a statewide summit in conjunction with of-staff to Mike Feuer, where she was attracted by the Women Against Violence on women and gun violence. freshman legislator ’s broad and ambitious agenda. He had developed a range of tactics and strategies against the gun lobby. Finally, he knew that the gun THE DECISION FOR FEUER lobby had a range of tactics and strategies to employ against his initiatives. Feuer told the Wilcoxes that he would author the bill if it were framed as a law enforcement bill, not Confronted with the plea and story of Nick and as a gun control bill. In addition, he insisted that Amanda Wilcox, for Feuer the decision to sponsor the Wilcoxes and their allies would have to do the came down to whether it was winnable. In the heavy lifting. The previous bill had carried the previous session, the votes on microstamping were title: “Semiautomatic Weapons—Unsafe Handgun 92 Requirements Microstamping,” which limited its firing a gun, the intense pressure caused by the firing appeal to gun control advocates. In terms of heavy leaves any marks present in the chamber etched onto lifting, the previous sponsor, Paul Koretz, had served the shell. Matching these random marks in shells to three terms in the Assembly. He was able to achieve models of guns and specific guns, a process called more politically with less effort than a freshman such ballistic fingerprinting, has long been a tool in forensic as Feuer, who would need more help. The Wilcoxes investigations. Lizotte realized than the microstamping agreed and promised they would organize support technology he was developing for metal parts could be from law enforcement as they had with the Koretz applied to great effect in ballistic fingerprinting. bill. They were also delighted when Feuer assigned Rebecca Marcus, whom they remembered from Johan The method he and his colleagues developed was to Kleh’s office, to work with them. engrave a code with laser technology onto the face of the firing pin. When a trigger is pulled, the firing pin On February 23, 2007, the last day possible to snaps into the back of the bullet casing, hitting a small introduce new legislation, AB 1471, the “Crime Gun circular “primer.” The blow ignites an explosion of Identification Act” was filed by Feuer. The Wilcoxes gunpowder, launches the lead tip out of the barrel of prepared a strategy to obtain endorsements from the the gun, and forces the shell back against the firing pin membership of the California Police Chiefs Association at the primer. That force, Lizotte found, can effectively (Cal Chiefs). A lawyer by training, Feuer set out to forge symbols from the firing pin onto the primer. build his case and understand the technology. Using microscopic code, a spent shell could be used to identify the make, style and serial number of the gun. M I C R O S TA M P I N G TECHNOLOGY GUN LAWS IN CALIFORNIA Microstamping is largely the invention of a Manchester, New Hampshire engineer named Todd Lizotte. Lizotte California, according to the Brady campaign, leads describes himself as a conservative Republican gun the nation in gun control regulation. In 2007, the state owner, member of the NRA, and an advocate for scored a 79 out of a possible 100 on the Brady national Second Amendment rights. He listed Sarah Palin on report card. Over the years, the state has banned his Facebook page as a person he admires. assault weapons, .50 caliber rifles, and “unsafe” guns that have no load indicators in the chambers or flunk In 1993, he and a number of colleagues at ID Dynamics a drop test. It has required guns to be purchased from in Londonderry N.H. were working on ways of licensed dealers and the maintenance of records of imprinting microscopic serial numbers on metal parts. handgun purchases. California required users to Such numbering is used in the automobile, aerospace, obtain a safety certificate with a written test and and medical industries to help track stolen parts and a safe-handling demonstration. It mandated safety and assist in the investigation of crash sites. As a gun locking devices, limited handgun purchases to one enthusiast, Lizotte saw a connection. per month per person; and imposed a ten-day waiting period, and required a universal background check. Lizzotte understood that when a cartridge case, or shell, is forged into the bullet chamber in the act of 93 For both gun control and gun rights advocates, California is seen as a bellwether state. Active and resourceful lobbies locate in Sacramento and myriad local chapters THE POSITION OF THE GOVERNOR of volunteer organizations monitor local developments. The NRA, for instance, does not disagree with One of the major unknowns for Feuer and his allies the Brady assessment. But it argues that the Brady re- was where Governor Arnold Schwarzenegger would port card demonstrates that jurisdictions with the most come down on the bill—if it reached him. While they restrictive gun laws (California, New York, District of had good relations with the governor ’s public safety Columbia) have the highest homicide rates. staff, the staff was not able to make any commitments on behalf of the governor. He would make the decision Many of the state laws concerning guns in California if and when the bill came to his desk. were first enacted in at the city and county level. Since the mid-1990s, California local governments have When Arnold Schwarzenegger first ran for Governor, passed more than 300 gun-related ordinances. Lower he was a candidate who, in his acting role as The courts in California have consistently upheld the Terminator, had walked into a gun store, picked out authority of local governments to regulate firearms, a 12-gauge auto loader, a .45 long slide, a phase plasma somewhat mitigating the tension inherent to what rifle, and an Uzi 9 mm machine gun, and, leaving, shot owning a gun means in rural settings with strong the guy behind the counter. As governor, however, he hunting cultures, versus urban settings with higher proved to be more moderate while still considering crime rates and strong gang cultures. himself a proponent of the right to bear arms. Gun control laws are, generally, weakest at the federal Schwarzenegger had previously signed bills to level, where, for instance, a Clinton era ban on assault prohibit the sale of .50 caliber sniper rifles, to prohibit weapons was allowed to lapse by the subsequent Bush the sale of ammunition to minors, and to require administration. They are strongest at the local level. owners of guns seized at domestic violence incidents For example, in 2005, San Francisco voters adopted to undergo background checks. He had also signed proposition H, an ordinance to prohibit the possession, bills to require the state to keep records of guns manufacture, sale, distribution, and transfer of reported stolen from dealers and to allow a defendant handguns in the city. to be charged separately for each assault weapon or .50 caliber rifle he or she possesses (a Koretz bill). Local communities in California have prohibited At the same time, however, the governor had vetoed gun dealers from operating in residential areas or a bill that would have required dealers to store near schools and required dealers to obtain liability ammunition where it would be inaccessible to the insurance. They have required dealers to have public. He vetoed another that would have required background checks (a Feuer initiative while on the LA gun violence prevention education in schools. City Council) and prohibited the sale or possession on firearms on public property (the Wilcox gun show Another factor affecting the fate of the microstamping initiative). Finally, they have required gun owners to bill was that it was competing with two other high- notify police of lost or stolen firearms. As a result, the profile gun bills. AB 362 by Assemblymember Kevin stakes are high at the state level on gun legislation. DeLeon (D-Los Angeles) would require background The California State Assembly has tended to be more checks for purchasers of ammunition. AB 334, by restrictive than the Senate and, of course, the governor Assemblymember Lloyd Levine called for mandatory has final veto power. 94 reporting of lost or stolen guns. For Feuer and his a magazine in the handle of the gun. The recoil of allies, while they supported AB 362, they were aware a single shot ejects the fired cartridge from the pistol’s that having two major pieces of gun technology chamber and loads an unfired round from a magazine legislation passed and signed by the governor in one into the chamber for the next shot. year would be a difficult hurdle. Many semi-automatic pistols are also double action, SPECIFICS OF THE BILL meaning that the first pull of the trigger requires greater effort than subsequent pulls in the same firing. A semiautomatic is more deadly and more accurate than a revolver. Unlike a revolver, it leaves shell casings behind. Most important, it is not a gun commonly used in hunting, home protection, or sport The text of Feuer ’s AB 1471 read—in part—as follows: target firing. Rather, it is the weapon most commonly used in gang shootings and by police. Existing law defines unsafe handguns as failing to pass certain tests, or lacking certain features, as Another interesting phrase in the bill was later added specified. This bill would, commencing January 1, in the Senate: “...the Attorney General certifies that 2010, expand the definition of unsafe handgun to this new method is also unencumbered by any patent include semiautomatic pistols that are not designed restrictions.” In the 1980s, Sacramento was scandalized and equipped with a microscopic array of characters by an investigation known as “Shrimpgate,” in that identify the make, model, and serial number of which undercover FBI agents bought the support the pistol, etched into the interior surface or internal of legislators for a bill that would benefit a single, working parts of the pistol, and that are transferred fictitious seafood company. This sting operation, by imprinting on each cartridge case when the firearm which led to the conviction of five legislators and is fired. By expanding the definition of “unsafe four legislative aides made legislators wary of any handgun,” the manufacture, sale, and other specified legislation that could benefit a single patent holder. transfer of which is a crime, this bill would expand the Todd Lizotte solely held the patent on microstamping scope of an existing crime, and thereby impose a state- technology. In addition, the phrase “unencumbered by mandated local program. any patent,” had no real legislative or legal precedent, and therefore no specific legal meaning. AB 1471 was identical to the Koretz bill when it was first filed. In April, however, it was amended to require microstamping to appear in “two or more places” on the interior parts of the gun, not just one. O B TA I N I N G SUPPORT The Feuer bill contained a number of provisions and assurances that had been worked out by Koretz with Amanda and Nick Wilcox had left Mike Feuer ’s multiple stakeholders during the session before. office with the charge to do the heavy lifting and A key element was that it applied only to semi- to stick to the script of the bill being seen as law automatic pistols. A semi-automatic pistol is defined enforcement legislation. The previous year, California as one that fires one cartridge and reloads the next for Brady Campaign chapters had developed a support each pull of the trigger. Bullets are stored in list for the Koretz bill that included 45 police chiefs. 95 That list had to be rebuilt. Each endorsement took from being killed.” He also worked more closely with multiple contacts—a letter, several phone calls, and the inventor, Todd Lizotte, and Joshua Horowitz, the executive director of the Washington DC-based their local chiefs. In addition, the Wilcoxes and their Coalition Against Gun Violence. The Coalition, which allies tried to get to chiefs in areas where there were included the Brady Campaign, co-sponsored the bill no chapters, particularly in the districts of key swing along with the Brady campaign. senators. Along the way, however, it became apparent that the NRA had persuaded a number of chiefs who supported the Koretz bill to withhold support from the COMMITTEE WORK Feuer bill. The first hearing for the bill was before the Assembly Meanwhile, Mike Feuer turned to his Los Angeles Public Safety Committee. Feuer ’s office and the allies from his City Council days, where he had Wilcoxes on behalf of the Brady Chapters submitted worked closely with Los Angeles County Sheriff Lee information sheets and letters of support. The analysis Baca, who had also supported the Koretz bill. At prepared for the hearing was drawn from the Wilcox Feuer ’s request, Baca’s staff members went through material as well as a letter they had drafted submitted the recent homicide files. They looked for cases where, by Fresno Police Chief Jerry Dyer. Todd Lizotte was if shells left as a murder scene had been microstamped, flown out from New Hampshire to testify and he was it would have made a significant difference in solving joined by Joshua Horowitz. the crimes. And they found many such cases. From Feuer ’s perspective the hearing went well in “On July 28, 2005, a 14 year-old boy and his 18 year- terms of giving some momentum to the bill. The gun old brother were shot and killed in a mini-mart near lobby was principally represented by Kathryn Lynch, their home. Police found four shells at the scene. No a Sacramento lobbyist. Lynch’s testimony centered leads,” Feuer would testify. Later “a man coming home largely on the technology as flawed and unproven as from work was flagged down by a woman apparently a law enforcement tool. But that appraisal seemed to in distress. When he went to help her, two men tried to be contradicted by the support of a significant number rob him. When he ran, they shot and killed him. Three of police chiefs and sheriffs who had signed letters and shell casings. No leads.” on behalf of AB 1471. Such stories allowed Feuer to put human faces on the “Mike Feuer was excellent in the Assembly Public story. “These are not isolated incidents,” he would Safety Committee,” Amanda Wilcox said. “He was add. “In 45 percent of the homicides in California, passionate, articulate, prepared, and methodically no arrests are ever made, and the perpetrators, often built his case. The whole room listened.” The members of violent gangs, are left to roam the streets, legislative hearings, Feuer pointed out, were important putting all of us at risk.” in terms of events to mobilize support and to engage in direct dialogue. “All of the hearings went pretty much As Feuer delved deeper into the technology he also as expected,” Feuer said. “People said the things one became more careful not to promote microstamping would expect them to say.” The real political action as a perfect solution to the problem of gun violence. would be later, outside of Sacramento, in the districts “This is not a panacea,” he would say, “but it will of the swing senators and in the media across the state solve some gun crimes and prevent some people and beyond. 96 EXTERNAL WORK While the Feuer bill was under consideration, the Brady campaign was reorganizing its California operation. Its one paid staff person was leaving. Brian Malte, the Washington DC-based director of state legislation “liked big, high visibility initiatives” and, unlike most of the players in Sacramento, he viewed himself performing on a national stage. Additionally, for the national Brady campaign, California was to be just the first state in the country to require microstamping; there were 49 more. for the Brady Campaign, stepped in to play a larger role in developing strategy for passage of the bill. Instead of immediately hiring a replacement, Malte advocated using the salary savings to hire a professional contract lobbying firm that would work on the microstamping bill. Malte and the Wilcoxes interviewed four such firms. They chose Political Solutions, a Sacramento organization noted for its political ties to THE GUN LOBBY FIGHTS BACK Heading into May 2007, the microstamping bill was beginning to gain momentum. At the Assembly Appropriations Committee, James Jacks appeared in Republican as well as Democratic leaders. support of the bill, surprising members of the gun Political Solutions offered its services at a reduced rate. good ties to Republicans. Feuer had also taken the Staffers Tami Miller, whose portfolio largely consisted of real estate and land-use clients, and James Jacks, who had worked for former Governor Pete Wilson and then Secretary of State Bruce McPherson, became the principal lobbyists. “Political Solutions was my top choice,” said Amanda Wilcox. “They were prepared, smart, easy to talk to, and I felt a very good connection. I knew that we needed someone who would appreciate and value the work of the chapters. Tami, in particular, became emotionally invested in the bill. She told me that whenever she heard or thought of lobby that the other side had a lobbyist, and one with unusual step of arranging meetings with the boards of the two major state law enforcement organizations, the California Police Chiefs Association and the Police Officers Research Association (PORAC). For the NRA and its allies, it began to appear that this battle would be a tougher fight than was the Koretz bill. The gun lobby had prevailed in the previous session by arguing against microstamping on the grounds that the technology was unproven in the field. It would be prohibitively expensive for manufacturers. Laura’s story, she was deeply impacted.” It would raise costs for law enforcement because they At the time, the Wilcoxes believed they were hiring Most crimes, they argued, are committed with stolen a firm to concentrate on one Senate vote, Michael Machado, a centrist Democrat in a politically-diverse microstamped guns would be much more expensive. guns and the shells would simply trace back to the original owners, leading to their false arrests. district. (Another Political Solutions staff member had previously worked in Machado’s office.) In addition, the firm would focus on Governor Arnold Schwarzenegger. Soon, however, Feuer, Rebecca Marcus, the Wilcoxes, Political Solutions, and Brian Malte began to develop a larger, national strategy. They knew the governor 97 THE UC-DAVIS STUDY through the media and the law enforcement community, the NRA and other opponents of the bill used their previous case against the bill, fueled by the UC-Davis study, to win support. They operated One of the most persuasive arguments for the gun lob- through myriad blogs, online discussion boards, and by was that the microstamps could be easily removed conservative talk radio. The opposition points were or altered. These were the arguments that had pre- reiterated with passion and even vehemence. Petitions vailed the previous year. They had a working formula, and letter-writing campaigns were organized by gun and soon, an unforeseen ally in their argument. manufacturers and retailers. Soon, the UC-Davis study became the lead story. On May 3, 2007, a team of researchers at University of California-Davis Forensic Science Graduate Program released a report critical of microstamping based on testing the technology with a range of firearms. The study, which a University press release said was C O M B AT I N G T H E UC-DAVIS REPORT commissioned by the California legislature, was conducted by a graduate student Michael Beddow Feuer immediately enlisted Todd Lizotte and sought under the supervision of Professor Fred Tulleners. to refute the charges, not to the UC-Davis faculty Tulleners was director of the forensic science who conducted the study, but to the Chancellor of graduate program at UC-Davis and former director the University, Larry N. Vanderhoef. Lizotte, while of the California Department of Justice crime labs in maintaining his Second Amendment support and Sacramento and Santa Rosa. membership in the NRA, had become an articulate and scientifically-based defender of his technology for this Beddow’s study sought to evaluate the “durability use. From legislative testimony to pro-gun discussion and longevity of an array of micro characters laser- boards on internet blogs, he continually and calmly machined onto firing pins, the legibility of the imprint refuted the opponents of the technology. of the micro-characters on ammunition, and the ease with which micro characters can be intentionally Lizotte was especially knowledgeable about the defaced or obliterated.” After tests, the study laser-based imprints and their reliability, which was concluded that microstamping was “flawed” and that at the core of the UC-Davis study. “I am not going “at the current time it is not recommended that into detail on what the encoded geometric is,” Lizotte a mandate for implementation of this technology in all wrote on a blog site, Gun Debate Critic. “However semiautomatic weapons in the state of California be I will state that if someone attempted to file off the made. Further testing, analysis and evaluation is (sic) code and left only five percent of the original encoded required.” The new study seemed to confirm surface, that five percent will still retain 100 percent of the charges that the technology was unreliable and the actual code.” that the microstamps could be erased or altered. The California Chapter of the NRA, gun trade and “Todd Lizotte was selfless and generous throughout business associations, and sporting organizations this whole process,” Feuer said. Indeed, when Lizotte quickly disseminated the UC Davis findings to the was informed of the sole-source concern, he said he media and law enforcement organizations. would gladly give up his patent rights, offering it While the proponents of the bill worked largely for free to manufacturers who used the technology. 98 “Nick and I met first met Todd when he came to the First, this is an “Author ’s Report” and was Public Safety Committee hearing (earlier in the year),” posted by California Policy Research Center Amanda Wilcox said. “He told us he strongly believes (CPRC), which funded the study, before CPRC’s that inventions that have important public benefit usual academic peer review and state legislative should be in the public domain. He mentioned Jonas briefings, which violates CPRC’s own policy. As Salk, who never got a patent for the polio vaccine.” well, public release of the report and issuance of a press release by UC Davis was premature. THE VANDERHOEF LETTER Second, contrary to the press release, the Legislature did not commission the study. The study was faculty-initiated with the CPRC. The UC-Davis study had proved to be a major problem Finally, I understand that you have concerns for advocates of the Feuer bill. They had been counting about the relevance of the specific contents of this on an endorsement from the California Police Chief’s study to your pending legislation, especially with Association at its May 24th meeting, but the UC-Davis respect to (1) the age and kinds of guns used in study derailed it. Feuer, however, prevailed upon the the study as compared to those that are covered in UC-Davis administration. Two weeks after the study your legislation, (2) the technology tested in the was released, Chancellor Vanderhoef, in a highly study as compared to the technology called for in unusual step, publicly released a letter to Mike Feuer the legislation, and (3) differences in the amount tending to undermine the findings and formally of microstamping examined in the study compared apologized for the study. to the amount of microstamping required in your legislation. While the accuracy of the findings can Dear Assemblyman Feuer: and must be assessed by the upcoming peer review, the press release should have not connected the I am writing to provide corrections and clarifica- study results with the legislation. tion about a recent press release, one that references an issue of significant legislative interest, I regret the issuance of this press release, issued by the University of California, Davis. premature posting of the report, the implication that the study pertains to your legislation, and the The release, dated May 3, 2007, relates to inaccurate statement about the legislative origins a UC Davis research project authored by two UC of the report. Please accept my apologies for Davis faculty members and a UC Davis graduate complicating, rather than elucidating, student regarding “microstamping” of some a sensitive public policy issue on which you handgun and rifles. This study is entitled, “What have taken statewide leadership. Laser Machining Technology Adds to Firearm Forensics: How Viable are Micro-Marked Firing Sincerely, Pins as Evidence?” I understand that you have authored legislation this session on this issue. Larry N. Vanderhoef Unfortunately, the release surely will have created Chancellor some misimpressions. With this background, I would like to set the record straight: 99 REGAINING MOMENTUM the Senate and with the Governor. “The thing that surprised me most when I got to Sacramento was the animosity between the Assembly and the Senate,” Feuer said. “I quickly learned that nothing The Vanderhoef letter turned back the tide of opposi- is guaranteed.” tion to the Feuer bill. The Wilcoxes were able to use the letter to persuade Cal Chiefs to agree to consider their In the Senate, they had identified five key potential endorsement at a later date. And because the letter was swing votes: Michael Machado (D-Linden), Dean so unusual—a chancellor casting doubt on the research Florez (D-Shafter), Ron Calderon (D-Montebello), of his own faculty—it was a convincing piece of evi- Gloria Negrete McLeod (D-Montclair), and Denise dence for legislators, the media, and even the national Moreno Ducheny (D-San Diego). “We knew that audience following the bill. Ducheny was against us, Amanda Wilcox said. “Tami and James connected with Calderon, who was A further boost came when Congressman Xavier an ‘aye’ and Negrete McLeod, who was a ‘no.’ We Becerra (D-Los Angeles) and U.S. Senator Edward M. needed one more vote. We were a little concerned Kennedy (D-MA), who was also the California First about Senator Joseph Simitian (D-Palo Alto) and Lady’s close uncle, announced that they planned to arranged patch-through calls to him, and we file federal microstamping legislation in Congress the arranged more calls to Machado and Florez.” following year. The California Brady chapters also organized a Lobby Day on May 23, 2007, where Police At this point, Brian Malte, Kay Holmen, the Wilcoxes, Chief Ken James, Chair of the Cal Chiefs Firearms Tami Miller, James Jacks, Rebecca Marcus, and Joshua sub-committee, spoke with several legislators. The Horowitz began having weekly conference calls. Other event was a success, and also had the important effect staff from the Brady Campaign and Coalition Against of proving to the Political Solutions staff that the Gun Violence listened in. As the summer progressed, volunteers they with which they were working were representatives from the offices of Senator Kennedy effective and professional. and Representative Becerra also joined the calls. Malte emerged as the point person in the discussions, AB 1471 was brought to a vote on the Assembly constantly pushing the group on obtaining more floor on May 30, where Feuer and his allies had been favorable media coverage, placing op-eds, and meeting confident they had the votes. The bill passed 44-29, with newspaper editorial boards. The group also along party lines. “Tami and James had done their job picked a target date for the Senate vote around which of counting the votes correctly and Mike Feuer did to coordinate. It planned a demonstration of the a great job at rebutting the opposition on the floor,” technology in Los Angeles for late August. Amanda Wilcox said. Small and medium successes continued to occur THE SUMMER OF THE S T R AT E G Y T E A M throughout the summer. To Feuer ’s surprise, the board of the Police Officers Research Association (PORAC), which had subjected him to mostly skeptical questions, voted to endorse the bill. The Bakersfield Californian, with a large conservative readership, ran an editorial All along, Feuer and the Wilcoxes knew that the major in support. So, too, did The Los Angeles Times. challenge for the bill was not in the Assembly, but in A supportive op-ed submitted by the Fresno Police Chief was circulated widely. 100 S E N AT E W O R K The Wilcoxes and the Political Solutions staff continued to work on the Senate and cleared three hurdles with committee staff and Senate President Pro Tem, Don Perata. These hurdles involved 1) providing assurance that the bill would not contribute to prison overcrowding (a required provision of crime-related legislation), 2) adding language to defuse the sole-source concerns, and 3) convincing the senate president’s staff that AB 1471 was the Brady Campaign’s very top priority piece of gun legislation. In addition, they were also successful, along with Feuer, in persuading Perata to co-sponsor the bill. Meanwhile, the Wilcoxes concentrated on Senator Machado in particular. They spent time with one of Machado’s close friends in the Senate, Tom Torkalson (D-Antioch) and his staff, connecting back to the Brady Campaign’s strong chapter in Contra Costa, in Torlakson’s district. One Friday, they drove through Machado’s district and visited all of its police stations unannounced, speaking to a number of captains and dropping off literature. In time, they would have the endorsements of the Stockton, West Sacramento, Davis, Woodland, and Suisun City chiefs. Feuer, whose name had now become synonymous with the microstamping bill, recalled his nervousness, no doubt with the UC-Davis study in mind, as he realized he had not yet seen a demonstration of it himself. “I remember driving to the Training Academy thinking, “This thing had better work, or my political career is going to go right down the drain. I’ll be a laughing stock.” With the media and the public officials looking on, an LAPD police officer fired bullets from guns outfitted with microstamping technology. Lizotte then examined the shells under a display microscope so everyone could see the identifying markings made by firing the gun. It worked; Feuer exhaled. “The Los Angeles County Sheriff’s Department Homicide Bureau has hundreds of unsolved cases where the only evidence left at the scene of the crime were expended bullet casings,” Sheriff Baca said in a press release. “If these casings had imprinted information on them from the firearm, our investigators would have an exceptional chance of solving these heinous crimes.” Another compelling speaker at this even was Tim Heyne, president of the Ventura County Brady chapter. Heyne’s wife and best friend had been shot, spent shell casings were scattered over his wife’s body, and there were no leads on the gunman until he killed D E M O N S T R AT I N G THE TECHNOLOGY Feuer had also developed an ally in Los Angeles Police Chief William Bratton, a powerful figure with a national constituency and a friend of the Governor. In August, through Bratton, Feuer arranged for the media demonstration of the microstamping technology with Todd Lizotte to be held at the Los Angeles Police department shooting range. Los Angeles Mayor Antonio Villaraigosa, Sheriff Baca, and LAPD Chief of Detectives Gary Brennan were all present. another person the next day. T H E S E N AT E V O T E The California State Senate has 40 members; it takes 21 votes to pass a bill requiring a simple majority vote. (Budgets and bills with tax increases require 26 votes under a 2/3 rule). Around September 1, 2007, the Wilcoxes learned that Senator Florez would vote with them. He would be the 21st vote. The Bakersfield Californian editorial and the endorsement of Police Chief Dyer seemed to have played a role. They had to keep it a secret, however. If the opposition found 101 out, there would be full-scale campaign to get the for freshman Assemblymembers, said, “You better vote back by the NRA. The microstamping team have the votes, we are doing this right now.” started to work to have the bill put before the Senate as it finished the session with all the aye votes on the “Tami was in the hall, watching the floor vote on the floor. At that point, however, Senator Edward Vincent monitors and the gun lobby was watching on a dif- (D-Inglewood) a supporter of the bill, had to leave ferent monitor down the corridor,” Amanda Wilcox Sacramento to tend to a family matter. said. “When Florez voted ‘aye’ they (the gun lobbyists) looked shocked. When Machado voted ‘aye’ they start- Over the next days, they put the full press on Sen. ed blaming each other.” But when they got to Senator Machado, who had voted against the Koretz bill the Joseph Simitian he didn’t vote. Perata came back at the previous year. Feuer met with Machado and explained end and called Simitian’s name, and he gave the 21st the new bill in detail. By this time, they had secured “aye.” AB 1471 had passed the Senate 21-17. the five police chiefs from his district, run radio ads, and pressed Machado’s friend Sen. Torlakson, who On September 10, the bill went back to the Assembly would also be the floor manager for the bill in the for a concurrence vote because of language changes Senate. They enlisted lobbyists Machado trusted made by the Senate. There was considerable debate on from the Friends Committee on Legislation and the the floor, but Feuer held all of the previous ‘ayes’ from Lutheran Office of Public Policy. When the Lutheran the initial vote. The bill was on its way to the governor. Policy lobbyist left Machado’s office, they reported that the NRA was waiting to go in. On Tuesday, September 4, they received word that Machado would be an “aye.” They immediately PUSHING THE GOVERNOR informed Senator Perata that they were ready. There was confusion on the floor over another bill, however, “When the bill came out of both houses of the and the vote was delayed another day. legislature, I still had no idea at all whether the governor would sign this thing or not,” said Feuer, On Wednesday, September 5, they were ready again, who, as it turned out, also represented Arnold only to learn that another supporter, Senator Ellen Schwarzenegger ’s Brentwood neighborhood. Corbett (D-San Leandro), was at a funeral. Another “Everything we did for the Senate vote,” said Amanda delay. On Thursday, finally, they had all of their votes Wilcox, “was also for the Governor ’s benefit—the on the floor. It was at the end of session and Perata editorials, the LA demonstration, and the long support was taking bills out of order, a common legislative tac- list. By the time AB 1471 reached the Governor ’s tic as Senators came and went from the chamber. Feuer desk, we had 97 names, including 65 police chiefs and and Rebecca Marcus watched from the gallery. The sheriffs, five law enforcement organizations, a DA, Wilcoxes and the volunteers were watching the votes three mayors, six cities, the state Superintendent of on their computers. Across the country in Virginia at Instruction, and 15 different advocacy organizations.” a school event for this son, Brian Malte was listening to the floor debate on his Blackberry as the Wilcoxes Over the summer Feuer, Marcus, Political Solutions, put their phone next to their computer speakers so he and the Wilcoxes worked very closely with Chris Ryan could hear. When Perata returned to the chamber, he and Tom Sawyer, the Governor ’s public safety staff. turned to Feuer and, in a tone senior Senators reserve Ryan and Political Solutions had a previous long and 102 mutually-respectful relationship. Ryan and Sawyer California’s embrace of the innovative crime- took meetings with the Wilcoxes, Todd Lizotte, Feuer, fighting tool over reflexive gun lobby opposition and the Emeryville Police Chief Ken James, who would set an example for other states, and also chaired the Cal Chiefs firearms committee. (“Wear for Congress, which certainly needs more than your uniform, with gun” he was told.) Feuer had a push. Nearly six months after the massacre at also, through the Brady organization, been working Virginia Tech, a bill to tighten the system for with an editorial writer for The New York Times. preventing people with serious mental problems On September 24, the newspaper ran a lead editorial from purchasing guns still languishes. supporting AB 1471, an extraordinary boost for a piece of state legislation 3,000 miles from Times Square. For California, the new law offers a real chance to save lives and bring more perpetrators of violent An Opportunity for Mr. Schwarzenegger crime to justice. Mr. Schwarzenegger ’s choice should be easy. California’s Republican governor, Arnold Schwarzenegger, has a laudable record of splitting In the next weeks, the Governor, or his wife, or his with his party’s orthodoxy to support pathbreaking staff heard from New York Mayor Michael Bloomberg, state initiatives on global warming and stem cell Senator Edward Kennedy, Chief Bratton, and a list of research. Now Mr. Schwarzenegger has a chance celebrities close to Schwarzenegger from his movie to make Californians safer, and set a new national days, in support of the bill. Ambivalent as he was standard, by signing into law the Crime Gun about gun control, Schwarzenegger had respect for Identification Act of 2007. Mike Feuer. And he had strong feelings about crime victims, especially young crime victims. The measure would make California the first state to require that all new semiautomatic weapons be equipped with technology known S I G N AT U R E as microstamping, which imprints microscopic markings as a gun fires. That would allow police In the end, those around the Governor felt he was to quickly match bullet casings found at a crime motivated most by the argument of justice for victims scene to the weapon that shot them, a valuable new and their families. He was moved by the story of tool for solving gun crimes and for deterring gun what happened to Laura Wilcox at the Nevada traffickers who supply violent criminals. County Mental Health Center and the dedication of her parents on behalf of the bill. On October 14, 2007, The technology is relatively inexpensive. And the Governor Schwarzenegger signed AB 1471, The Crime new law gives manufacturers until 2010 to retool. Gun Identification Act, into law. “While I appreciate Mike Feuer, the Democratic Assemblyman who and understand that this technology is not without is the author of the bill, notes that more than 40 limitations” a statement from the Governor read, percent of homicides in California go unsolved “I am signing this bill to provide law enforcement with yearly for lack of evidence. The national record an additional tool for solving crimes. I encourage all is not much better, explaining the bill’s broad stakeholders to work on improving this technology.” support from law enforcement. There is no real With his signature, the bill became law. explanation, save the fierce opposition of the gun lobby, for why no Republican voted for the bill. 103 6 104 S TA G N A N T W A G E S : CALIFORNIA’S INTERIOR M E T R O P O L I TA N AREAS MICHAEL MANVILLE 1 Michael Manville is a research fellow at UCLA’s Lewis Center for Regional Policy Studies. He received his PhD from UCLA and has published research on economic development, transportation and land use, and urban revitalization. M AT T H E W P. D R E N N A N 2 Matthew P. Drennan, an economist, is a Visiting Professor in Urban Planning, UCLA, and Professor Emeritus, Cornell University. Most of his research focuses on the economic transformation of metropolitan areas. His latest book, The Information Economy and American Cities, was published by Johns Hopkins University Press. 105 6 From 1979 to 2007, real wages of the inland agricultural areas of California suffered a marked economic deterioration relative to California’s large coastal metropolitan areas. 3 This chapter documents that relative decline and investigates possible explanations for wage divergence in California over the same period. It concentrates on twelve small inland Metropolitan Statistical Areas (MSAs) that, at first glance, would not seem to be candidates for economic distress. Eleven of these twelve areas compose one of the most productive swathes of farmland in the United States, if not the world. The San Joaquin Valley, which comprises eight of these metropolitan areas, exports more agricultural products than any U.S. state—other than California. And all 12 of these MSAs have been growing rapidly in population. Yet compared to the large coastal metropolitan regions of Los Angeles, San Diego, San Francisco and San Jose, real wages in these twelve MSAs are falling behind. Even as their populations have boomed, their wages have stagnated. In some cases, wages actually declined in real terms. At the end of the 1970s, these areas lagged behind the large coastal metros. From 1979 to 1999 the gap between these areas continued to widen. There was some recovery 1999 to 2007, but the gap is nonetheless still huge. It is not a surprise that wages in small metropolitan areas are less than wages in large ones. All twelve interior MSAs have populations well under one million. Larger places have greater congestion, longer journeys to work, and higher land prices. These factors raise the cost-of-living and exert upward pressure on wages (O’Sullivan 2007). But in the period after 1979, the percentage difference between average wages in the interior and the coast grew sharply. Figure 1 shows that from 1969 to 1979, real average wages for the twelve interior places in our study were low but moving in line with real average wages in 106 the four coastal metropolitan areas. Both inland and coastal areas were depressed in that stagnant decade. In the 1980s, however, real wages on the coast and in POSSIBLE SOURCES OF THE WAGE GAP the interior began to diverge. During the 1990s, the gap widened dramatically. There was a slight shrinking of The twelve metropolitan areas that are the focus of the gap after 1999, but the discrepancy is still large. this chapter are shown on Table 1. In 1969, ten of these The coastal MSAs’ average wage of almost $61,000 in twelve MSAs had a lower average real wage than any 2007 is almost $26,000 higher than the interior MSA’s of the four coastal MSAs. The two exceptions, Redding average wage. It is this gap that the chapter addresses. and Stockton, had a slightly higher real wage than San Diego. None were as high as Los Angeles, San Most of the analysis that follows makes use of the Francisco, and San Jose. average annual wage as the key metric, as reported by the U.S. Bureau of Economic Analysis, Regional During the next three decades, wages in the twelve Economic Accounts, for all MSAs. This measure is the inland MSAs grew more slowly than in three of the wage per job, including full-time and part-time work, four large coastal MSAs—Los Angeles is the exception. and excluding the self-employed (proprietors and part- Wages in Hanford-Corcoran and Madera grew about nerships). The average wage is used because wages the same or slightly more than the Los Angeles growth: are the largest and most explicitly spatial component 13.2 percent. The interior growth rates over those 38 of personal income, and personal income is in turn a years ranged from a high of 15.4 percent (Madera) good (albeit imperfect) measure of material well-being. to a low of -10.0 percent (Redding). In contrast, the Disparities in income, therefore, are in many ways the growth of the four coastal MSAs ranged from a high result of disparities in wages. Understanding wage of 43.7 percent (San Jose) to a low of 13.2 percent (Los divergence helps in understanding why people in Angeles). Average real wage growth in the 12 interior some California locations are materially better off than MSAs combined was only 6 percent, while in the four people in others. large coastal MSAs it was 30 percent. The next section discusses possible explanations Why might this pattern have developed? The wage for the growing wage differences across California. data suggest that in the last decades of the twentieth It pays particular attention to the importance of century, these quite different places became less, rather education and industrial mix in determining those than more, alike. A further puzzle is that falling wages differences. The coastal and interior MSAs in are often associated with outmigration (Drennan California are then shown to be markedly different 2008), but people are flowing into, rather than out of, in their industry mix. They also differ in the nature California’s interior MSAs. of their immigration and in the education level of their populations. The final section provides some Table 1 also shows that the interior MSAs have mostly conclusions relevant to policy. outstripped the coastal MSAs in population growth. The interior MSAs grew, on average, by 134 percent from 1969-2007, while the four coastal MSAs averaged 57 percent. In part, this divergence is an artifact of the large differences in population between the coastal and interior regions. All four coastal MSAs have well over 107 Table 1. Average Real Wage & Population by MSA, 1969 and 2007 S o u r c e : B E A MSA Ave ra ge Re a l Wa ge 1969 2007 P opul a ti on P e rce nt C ha ng e , 1969- 2007 1969 Wa g e Pop ul a t i on 2007 4 L a rg e Coas tal M SAs L o s Angeles 43,849 50,520 8,366,706 1 2 , 7 8 4 , 6 1 2 1 3 . 2 % 52.8% S a n Dieg o 3 6 ,7 3 2 4 7 ,6 1 1 1,340,989 2,959,734 22.8% 120.7% S a n F r an cis co 4 4 ,2 6 2 6 4 ,2 8 7 3,088,491 4,216,125 31.1% 36.5% S a n J o s e 4 5 ,7 2 5 8 1 ,1 5 8 1,051,545 1,786,355 43.7% 69.9% S im ple aver ag e o f 4 4 2 ,6 4 2 6 0 ,8 9 4 3,461,933 5,436,707 30.0% 57.0% 787,179 7.2% 141.8% 1 2 Small Inter ior M SAs B a k e r s f ield 3 6 ,4 5 0 3 9 ,2 6 4 325,549 C h ico 3 3 ,8 5 1 3 3 ,2 2 7 101,057 218,185 -1.9% 115.9% E l C en t ro 2 9 ,5 6 4 3 3 ,0 5 9 73,604 160,830 10.6% 118.5% F res n o 3 3 ,1 5 1 3 5 ,6 5 3 408,304 894,748 7.0% 119.1% H a n fo rd-Co rco r an 3 0 ,5 3 0 3 5 ,1 4 0 65,647 148,232 13.1% 125.8% M a d er a 2 8 ,5 9 3 3 3 ,7 8 5 41,079 145,654 15.4% 254.6% M erced 2 9 ,9 2 6 3 2 ,7 1 2 101,255 244,218 8.5% 141.2% M o d e s t o 3 3 ,5 1 8 3 7 ,0 3 4 191,271 509,068 9.5% 166.2% R ed din g 3 8 ,5 9 1 3 5 ,0 8 0 76,290 179,068 -10.0% 134.7% S t o c k t o n 3 7 ,1 6 7 3 8 ,4 0 7 284,769 667,886 3.2% 134.5% V isa lia-Po r t er ville 2 8 ,7 9 0 3 1 ,2 1 5 185,701 419,172 7.8% 125.7% Yu b a Cit y 3 4 ,1 0 0 3 6 ,5 0 7 86,435 163,302 6.6% 88.9% S im ple aver ag e o f 12 3 2 ,8 5 3 3 5 ,0 9 0 161,747 378,129 6.4% 133.8% ’ one million residents, while none of the interior places P O P U L AT I O N do. The interior areas range in population from 148,000 (Hanford-Corcoran) to 895,000 (Fresno). Nevertheless, Economists have long recognized that large places the population growth in the interior is striking, given have advantages over small ones. Gunnar Myrdal, in the slow wage growth over the same period. his cumulative causation growth model (1957) argued that larger places have initial advantages that lead to What can account for not just California’s self-sustaining growth. In core-periphery models, an wage divergence, but also for its peculiar form, initial concentration of economic activity at the core is characterized by sharp increases in population even not easily overcome by the periphery (Krugman 1991; as wages stagnate or decline? Four factors may have Fujita et al 2001). Scale economies and agglomeration played a role: population, industrial specialization, economies also favor larger places, pushing up labor human capital, and immigration. productivity and thus wages (Henderson, 1988). 108 Famed 18th century economist Adam Smith noted or technical, and require at least a bachelor ’s degree that market size, which is highly correlated with (Drennan and Lobo 2009). These jobs also tend to population, permitted industrial specialization. pay well (McCall 1998), either as a result of greater “There are some sorts of industry…” he wrote, “which efficiency, or—as James Galbraith (1998) has argued— can be carried on nowhere but in a great town.” because some knowledge-sector firms have quasi- (Smith 1776, p. 17). Size allows specialization because monopolistic power. Such power enables them to large places have bigger consumer and labor markets, reward their workers with wage premiums. and because large populations allow for ease in the coordination of talent (Becker and Murphy 1992). For purposes of this chapter, the important fact is Specialization, in turn, better enables learning and that in California the transition into the knowledge expertise, and these facilitate the transmission of ideas economy has not taken place evenly. California has (Anas, Arnott and Small 1998). always had spatial disparities in both the location of knowledge industries and the college-educated INDUSTRIAL S P E C I A L I Z AT I O N people they employ. Between 1970 and 2000, these discrepancies widened. It is reasonable to suspect that this disparity would play some role in the divergence of California’s wages. The set of industries that stimulate wages and those H U M A N C A P I TA L that depress wages changes over time. (Detroit once prospered because it manufactured automobiles; now it suffers for the same reason.) In the period In the United States, individuals with a college examined, the California economy, as did the national education or higher earn better wages than those who economy, underwent a significant transition. It shifted have not completed college. Moreover, the premium away from the production of goods and toward the paid to college graduates has been increasing over production of information and ideas (Glaeser 1994). time (Levy and Murnane 1992; Katz and Murphy 1992). The reasons for this trend are numerous. This transition—from “mill-based to mind-based” However, the favored explanation among economists (Bluestone, 2000) economic activity—resulted in is that technological change is “skill-biased,” i.e., that a decreased emphasis on many traditional urban it disproportionately benefits the educated. industries, such as manufacturing. Instead, there was increased emphasis on non-routine service sector work These effects could be compounded by the erosion of that requires formal higher education, such as law, various institutions that have traditionally protected medicine and the arts. These latter industries, which the wages of the less-educated. Unionization rates have been dubbed the “knowledge” economy, differ have fallen steadily over the past several decades from older goods-based urban industries in the types and the real value of the minimum wage declined of jobs they offer, the level of the wages they pay, throughout the 1980s and 1990s (Card and DiNardo and the requirements for employment in them 2002; Lee 1999). In a spatial context, places with high (Drennan 2002). proportions of educated residents can be expected to have higher average wages than places with low At the national level, almost half the jobs in the proportions of educated people (Drennan 2002; knowledge industries are managerial, professional, Glaeser 2004). 109 I M M I G R AT I O N productivity, then the average wage could rise even as wages at the bottom fall. Immigration’s influence on wages is a source of both academic and popular debate (Borjas and Katz 2005; Card 2005, Lowenstein 2005). California has D I F F I C U LT I E S W I T H more immigrants than any other state. Perhaps THE COMMON more importantly, it has more Mexican-origin immigrants and more undocumented immigrants, E X P L A N AT I O N S than any other state. At one point in the 1990s, it was estimated that California had fully 43 percent of the nation’s undocumented immigrants. Mexican-origin All of these potential explanations overlap. immigrants generally, and undocumented Mexican Take, for instance, the hypothesis about industrial immigrants in particular, lie at the heart of most specialization. It could be argued that the large debates about immigration’s impact on wages. coastal MSAs transitioned more successfully into the knowledge economy while the interior MSAs remained Intuitively, immigration offers an explanation for the more specialized in relatively declining industries. simultaneous economic decline and population ex- This rather straightforward argument is, however, pansion in inland California. If poor immigrants from difficult to prove. rural Mexico and Central America are drawn to the interior by the prospect of agricultural jobs, they could The first problem is that industrial specialization is drive up the population while at the same time de- hard to measure. Some industries can be categorized pressing the average wage. But it is far from clear that as knowledge-based as opposed to goods-based. But it immigration could reduce a region’s average wage. is hard to tell with available data whether the earnings generated by those industries in any given place are Even those researchers who argue that immigration export oriented. depresses wages do not argue that it drags down earnings in the entire regional labor market (Friedberg It is standard practice in economic development and Hunt 1995; Lazear et al 2007). Rather they worry analysis to assume that productivity and wage that immigrants will depress the earnings of the increases in a metropolitan area are largely determined unskilled native born, such as high school dropouts by that area’s ability to sell goods and services to (e.g., Borjas and Katz 2005). Although this assertion is outside individuals and firms. Yet it is difficult controversial (Card 2005; Lang 2006), assume for to separate the export-oriented components of an a moment there is some validity to it. industrial sector from the locally-oriented components. Earnings from law, for instance, could come from Given that assumption, immigration could decrease family attorneys doing local work or corporate lawyers the wages of the low-skilled native born and who sell their services nationally or globally. The latter nevertheless increase the average wage region- represents a movement into the knowledge economy; wide. For example, immigrant domestic labor in the former probably does not. some metropolitan areas enables native-born college educated women to increase their time commitment to The second problem is that industrial structure is hard work. If the gains to the skilled outweigh any losses to separate from other factors. Population size, as to the unskilled, and the overall result is increased mentioned, often drives industrial specialization. 110 And industrial specialization is itself tremendously difficult to disentangle from educational attainment. To a strong degree, industrial structure and labor force skill are jointly determined. The presence of skilled people can help incubate skilled industries. INDUSTRIAL CHANGE AND WAGE DISPERSION And the presence (or absence) of skilled industries helps determine both the skill levels of in-migrants. While bearing these qualifiers in mind, it is possible Educated people flock to places with a high demand to speculate as to how industrial change may have for skilled work. Industry structure also determines contributed to wage divergence in California. investments in skill that are made by locals. Education is the principal input to knowledge industries. One of the starkest differences between There are exceptions, of course. Skill level varies both California’s coast and its interior can be found in levels within and across industries so that labor-force skill of educational attainment. does not track perfectly with industrial structure. Indeed, there is some evidence that traditionally low- California has, on the whole, a larger share of skill industries are reorganizing to include high-skill college educated residents than the nation. Yet the jobs (Gibbs et al 2004). Nevertheless, information- great majority of these residents have, since the intensive industries tend to have more high-skill, 1960s, lived on the state’s coast. Probably, and not high-wage jobs. More than anything else, knowledge coincidentally, until 2003, all of California’s major industries are built on skilled people (Drennan 2002; research universities were also in coastal metropolitan Nelson 2005). areas. Since 1970, the gap in the level of educational attainment between the coast and the interior has This observation raises a third potential problem: widened, even as education has grown more important skill is often measured by educational attainment, as a determinant of earnings. but educational attainment is an imperfect proxy for ability. Productivity varies tremendously across In the years between 1969 and 1979, across all 26 of people who have earned a college degree. Unmeasured California’s metropolitan statistical areas, the simple differences between similarly-educated people might correlation between the metropolitan average wage have a strong impact on productivity and thus wages. and the share of adults with a bachelor ’s degree or more was 0.27. For the time period 1989-2000, Lastly, discussions about immigration’s impact on however, that correlation increased to 0.75. Yet during wages become hard to separate from discussions about that same time levels of educational attainment in the industrial structure and about education’s impact on coast and the interior continued to diverge. wages. Immigration is not monolithic. California’s foreign-born population includes both urbane highlytrained software engineers and the illiterate rural poor. Location of skilled and unskilled immigrants will be determined in part by the job opportunities available POSSIBLE WAGE GAP E X P L A N AT I O N S in different places. The economic impact of unskilled immigrants is, after all, driven more by their being Given the facts presented so far, three possible unskilled than by their status as foreign-born. reasons can be suggested for the observed wage gap between the large coastal MSAs and the small 111 interior MSAs of California. First, changes in ter transmission of ideas and knowledge. Naturally, all metropolitan industrial structure closely track changes three explanations may also be valid; they are not mu- in metropolitan educational attainment. Second, the tually exclusive. All posit that skilled people are more effects of education and industrial upgrading can both productive in larger places and that this increased pro- positively influence the level of the average wage. ductivity enhances the average wage. Third, it might be true that population size will interact with both industrial structure and educational attainment, and have a positive impact on the average wage. That is, there may be a wage benefit associated with a large MSA and a wage benefit associated with an educated populace. But there may also be additional independent effect that is generated by having educated people in a large place. Larger places, in other words, might obtain more from their educated people, in terms of productivity. Three reasons can be suggested why this phenomenon might occur. THE INDUSTRIAL STRUCTURE O F C O A S TA L AND INTERIOR M E T R O P O L I TA N CALIFORNIA The first explanation is unobserved differences across the college-educated. Large places, because they Industrial specialization is measured by focusing offer more labor-market opportunities and more only on those industries that are believed to produce consumption opportunities, might simply attract the traded goods and services. Those are industries whose most productive college-educated workers (Shapiro, output could bring in revenue from other places or that 2006). If the most productive people migrate toward could be in competition with non-local firms for local the most desirable places, productivity and wages will markets. As noted above, whether these industries are be higher in those places. export-based or not is impossible to determine with the data used. Local industries producing non-traded The second explanation is specialization. As noted goods and services are viewed as endogenous to urban earlier, using available data, it is difficult to tell if growth and therefore not a source of differences in earnings from knowledge industries are actually part growth across urban places. of a region’s export base. However, it is reasonable to believe that a greater share of knowledge-sector Using an industry taxonomy developed by Drennan earnings in larger places represents specialized, (2002), the traded goods and services industries are export-based activity. Thus the interaction of divided into two parts. The industries in each of educational attainment and/or knowledge sector our groups are two-digit North American Industrial earnings with population size might represent Classification System (NAICS) industries. a greater degree of export activity. The first category created is goods production A final possible explanation, which is closely related and distribution, or GP&D. This sector consists of to specialization, is that the interaction of size and in- farming and related activities, mining, manufacturing, dustrial structure (or size and educational attainment) wholesale trade, and transportation and warehousing. could proxy for the benefits of agglomeration; the bet- GP&D is, essentially, the group of traditional economic 112 activities that drove almost all urban external trade THE KNOWLEDGE through the first half of the twentieth century. SECTOR GP&D has become less important with the rise of what is labeled the knowledge industries (information, The dominant industries in the knowledge sector are finance and insurance, professional and technical the producer services—high-wage industries such services, educational services, health, and finally arts as finance, insurance, computer software, business and entertainment). These industries are the more consulting, law, engineering, architecture and other recent component of traded goods and services. They professional services. These industries essentially are notable for being a steadily-growing share of sell knowledge to firms, governments, and non-profit the U.S. economy, while the goods production and organizations. Previous research on urban industrial distribution sector is—for the most part—a contracting structure has shown that the largest metropolitan share (although many of the GP&D industries continue areas tend to be specialized in knowledge industries, to grow absolutely). particularly producer services. Smaller metropolitan areas tend to be specialized in goods production and distribution industries (Black and Henderson 1999; Drennan 2002; Drennan and Table 2. Earning by Traded Goods and Services Industries, 2006 Lobo 2009). Data from the U.S. Bureau of Economic Analysis show that in 2003, almost 80 percent of All U.S. 4 Coa s t a l 12 Interior metropolitan producer services earnings were MSAs MSAs MS A s generated in metropolitan areas with populations of one million or more. But these areas contained only 54 E ar ning s (Millio n s o f $) 7,583,998 809,035 84, 132 percent of the country’s metropolitan population. Share of earn in gs b y t ra d e d go o d s & se r vice s in d ustri e s Table 2 shows that in 2006, the export bases of the interior metropolitan areas were not just smaller but F ar m in g , f o re stry & rel ated 0 .4 % 0 .2 % 8.2% also qualitatively different from the export bases M in in g 0 .9 % 0 .3 % 1.5% of the coastal metropolitan areas. For comparison M an u f act u r in g 1 1 .6 % 1 2 .7 % 8.7% purposes, Table 2 also shows figures on traded goods Wh o les ale t r a de 5 .1 % 4 .4 % 3.8% and services for all U.S. metropolitan statistical areas Tr an s po r t at ion & warehousi ng 2 .4 % 2 .4 % 3.7% in 2006 (this is NAICS data). In general, traded 2 0 .4 % 1 9 .9 % 25.8% goods and services account for roughly one-half of All g o o ds producti on & di st. metropolitan earnings (Henderson 1988), and this In f o r m at io n 3 .8 % 6 .3 % 1.4% generalization holds for all U.S. metropolitan areas F in an ce & in surance 8 .2 % 8 .0 % 3.4% (54 percent of earnings) and for the four coastal Pro f es s io n al & techni cal serv i ces 1 0 .2 % 1 3 .7 % 4.0% California metropolitan areas (55 percent). For the E du cat io n 1 .3 % 1 .3 % 0.5% 12 interior metropolitan areas, however, the share is Healt h care & soci al assi stance 9 .2 % 7 .3 % 10.1% markedly lower: 46 percent. Ar t s , en t er t ainment & recreati on 1 .1 % 1 .8 % 0.5% 3 3 .8 % 3 8 .4 % 19.8% All k n o w ledge i ndustri es Coastal MSAs are also far more specialized in the knowledge sector, while the interior areas are more Source: BEA specialized in goods production and distribution. 113 The knowledge sector accounts for over 38 percent of large shares in farming, forestry and related activities earnings in the four large metropolitan areas, while plus mining (which includes oil and gas extraction). the goods production and distribution sector accounts These economic activities constitute almost ten percent for 20 percent. The opposite is true for the twelve of earnings in the inland metros, compared with inland areas, which derive only 20 percent of earnings one percent for all U.S. MSAs and well under one from the knowledge sector and 26 percent from goods percent for the coastal MSAs. These activities are also production and distribution. characterized by concentrations of low-skilled workers and low pay. For all U.S. MSAs, goods production and distribution accounts for 20 percent of earnings, while the The only portion of the knowledge sector where the 12 knowledge sector accounts for about 34 percent. Thus, interior metros have earnings shares that surpass the the two sets of California places—inland and coastal coast and nation is the health care and social assistance —sit at opposite ends of the national distribution with industry. This is, unfortunately, one of the low-wage respect to the knowledge sector. The coastal places industries of the knowledge sector. Thus the 12 inland have an above-average concentration of knowledge metropolitan areas have the worst of both worlds. sector earnings while the inland areas have a below- Their economies are in general heavily biased toward average share. GP&D. But their concentration is not in the one area of GP&D—manufacturing—that pays moderate to high THE GOODS PRODUCTION AND wages. They are under-represented in the knowledge sector but over-represented in one area of that sector that pays poorly. DISTRIBUTION I M M I G R AT I O N A N D SECTOR E D U C AT I O N GP&D share among the inland metropolitan areas Compared to the coastal metropolitan areas and is not just larger but also differently-composed to California as a whole, individuals in the twelve than the shares in both coastal California and U.S. interior MSAs are poorer, less educated, and more metropolitan areas as a whole. The largest part of likely to be Hispanic. They are not, however, more the goods production and distribution sector in all likely to be immigrants. Table 3 shows the percentages U.S. MSAs and in the four California coastal MSAs is of the population in 2000 that were Hispanic, foreign- manufacturing. Manufacturing accounts for between born, and foreign-born from Mexico for the twelve 12 and 13 percent of earnings in both sets of places. interior MSAs. It shows them for the coastal places, The manufacturing sector is also the portion of GP&D too, as well as the state and the nation. that pays the highest wages. Of the four coastal MSAs, Los Angeles has by far the In the twelve small inland MSAs, however, largest share of Hispanics: 41 percent. High as that is, manufacturing accounts for less than nine percent six of the 12 interior MSAs have even higher shares. El of earnings. The high share of GP&D in the interior Centro is 72 percent Hispanic. Only two of the interior comes not from manufacturing but from unusually places have lower Hispanic shares than San Francisco’s 114 low share of 18 percent. Those are Chico, 11 percent, and Redding, six percent. The coastal places and the interior places, however, are not much different in their shares of the foreignborn. Coastal MSAs range from a high of 35 percent (Los Angeles) to a low of 22 percent (San Diego). Interior MSAs range from a high of 32 percent (El Centro) to a low of four percent (Redding). Thus, Los Angeles has a greater share of foreign born than any of the 12 interior places, as does San Jose. Table 3. Characteristics of Individuals in 12 Interior and Four Coastal MSAs, 2000 Pe rce n t Pe rce n t P e rce nt F ore i g n Hisp a n ic Fo re ign Bo rn B orn f rom Me xi co B ak er s f ield 3 8 .4 1 6 .9 74.4 Ch ico 1 0 .5 7 .7 44 E l Cen t ro 7 2 .2 3 2 .2 94.1 F res n o 44 2 1 .1 66.4 Han f o rd-Co rcoran 4 3 .6 1 6 79.5 M ader a 4 4 .3 2 0 .1 86.4 M erced 4 5 .3 2 4 .8 69.9 M o des t o 3 1 .7 1 8 .3 62.2 Reddin g 5 .5 4 23.9 St o ck t o n 3 0 .5 1 9 .5 51.5 V is alia-Po r t er v i l l e 5 0 .8 2 2 .6 82.4 Yu ba Cit y 20 1 3 .2 51.6 Lo s An g eles 4 1 .4 3 4 .7 44.5 San Dieg o 2 6 .7 2 1 .5 48.2 San F r an cis co 1 7 .8 2 7 .4 38.9 San J o s e 24 3 4 24.4 Calif o r n ia 3 2 .4 2 6 .2 44.3 U n it ed St at es 1 2 .5 1 1 .1 29.5 S o u r c e : U . S . C e n s u s , 2 0 0 0 MEXICO AS A P O P U L AT I O N SOURCE The dramatic difference among the two groups of places is shown on the last column of Table 3, the percent of the foreign born from Mexico. The twelve interior MSAs have far higher shares of foreign-born from Mexico than the four coastal MSAs with a few exceptions. Only two of the interior places have shares below that of the coastal place, San Diego, with the highest share: 48 percent. Indeed, ten of the twelve interior MSAs have well over half of their foreign born from Mexico, ranging from 52 percent (Stockton) to 94 percent (El Centro). Almost all of the California places listed in Table 3 have shares in each category far above the national shares. 115 OTHER CHARACTERISTICS CONCLUSION Figure 1 showed that wage divergence in California began in earnest sometime in the 1980s, and Table 4 presents social and economic characteristics accelerated in the 1990s. The analysis in this chapter from the 2000 Census for the four coastal MSAs and offered some explanation for this fact. It has been the twelve interior MSAs compared with California well documented that in the period covered, and the United States. Here the differences are stark. metropolitan economies of the United States were The twelve interior places are far less educated, less becoming more concentrated in the knowledge likely to be in the labor force, and poorer. In the coastal sector. They were becoming less concentrated in the MSAs, shares of the adult population with a bachelor ’s goods production and distribution sector, especially degree or more range from a high of 40 percent in San the large metropolitan economies. As recently as Jose to a low of 26 percent in Los Angeles. None of the 1970, the goods production and distribution share of 12 interior MSAs have as high a share as Los Angeles, metropolitan economies was about double the share of ranging from a high of almost 22 percent in Chico to the knowledge sector (Drennan 2002). a tie for low of 10 percent in three places: El Centro, Hanford-Corcoran, and Yuba City. By contrast the Table 2 shows that the sectoral mix has been reversed California share is almost 27 percent and the national and that the shift in the nation’s metropolitan share is 24 percent. economies was mirrored in California. As the knowledge economy (and its primary input, formal Labor-force participation in the four coastal places education) became more important in the 1980s and is well over 60 percent, except Los Angeles at almost 1990s, its influence on wages grew. In the nation, the 62 percent. In the twelve interior places only four knowledge sector is heavily concentrated in MSAs locations - Fresno, Modesto, Stockton, and Visalia- with populations above one million. In California, Porterville - are at 60 and 61 percent. El Centro is the all such large metros are on the coast, excluding lowest at 49 percent. the state’s capital, Sacramento. Thus, the increasing dominance of the knowledge sector across the nation The facts brought out in Table 3 and 4 are consistent favored the large coastal MSAs of California. with previous research suggesting that immigrants to the interior are for the most part poorly-educated rural Mexicans who work poverty-wage agricultural jobs RETURNS TO SKILL (Taylor and Martin 1997, Taylor, Martin and Fix 2006). Again, however, the influence of immigration on the The returns to skill help explain why coastal wages wage is more likely to be a result of the immigrants’ grew much faster than interior wages. But they do not skill levels and the opportunities available to them. It necessarily explain why wages in the interior MSAs is not a result of their place of origin per se. showed such anemic growth and even decline over 38 years. Nor does this study shed light on the variation of wages within a given metropolitan area. Certainly, MSAs such as Los Angeles and San Francisco have their share of economic distress, which a high regional average wage can mask. Future research should use individuallevel wage data to assess more closely the economic well-being of individuals within these regions. 116 Table 4. Social and Economic Characteristics in Large Coastal and Small Interior MSAs, 2000 M S A Pe rce n t w it h BA L a bor F orce P e rce nt i n P e rce nt House hol ds Not o r High e r De gre e P a r ti ci pa ti on Ra te P ove r ty S pe a ki ng Eng l i sh a t Hom e 4 Larg e Coa st a l Lo s An g eles 2 6 .2 % 61.7% 16.2% 51.2% San Dieg o 2 9 .5 % 65.0% 12.4% 33.0% San F r an cis co 3 8 .8 % 65.8% 9.1% 35.0% San J o s e 4 0 .4 % 67.1% 7.5% 45.4% 12 S mall Inte rio r B ak er s f ield 1 3 .5 % 56.5% 20.8% 33.4% Ch ico 2 1 .8 % 56.8% 19.8% 12.5% E l Cen t ro 1 0 .3 % 49.4% 22.6% 67.8% F res n o 1 7 .5 % 59.9% 22.9% 40.8% Han f o rd-Co rcoran 1 0 .4 % 51.1% 19.5% 36.7% M ader a 1 2 .0 % 53.5% 21.4% 37.0% M erced 1 1 .0 % 59.5% 21.7% 45.2% M o des t o 1 4 .1 % 61.2% 16.0% 32.4% Reddin g 1 6 .6 % 57.3% 15.4% 6.5% St o ck t o n 1 4 .5 % 59.8% 17.7% 33.7% V is alia-Po r t er v i l l e 1 1 .5 % 59.8% 23.9% 43.8% Yu ba Cit y 1 0 .3 % 57.6% 20.8% 21.9% Calif o r n ia 2 6 .6 % 62.4% 14.2% 39.5% U n it ed St at es 2 4 .4 % 63.9% 12.4% 17.9% Source: U.S. Census 2000. Figure 1. Average Real Wage, Coastal & Interior MSAs, 1969-2007 (2007 $) 60,00 0 4 Coastal MSAs 12 Coastal MSAs Av era g e Re al Wa g e 50,00 0 40,00 0 30,00 0 20,00 0 10,00 0 0 1969 1979 1989 1999 2007 117 THE POLICY DILEMMA AT T R A C T I N G From a policy perspective, the small interior KNOWLEDGE MSAs of California present a dilemma. Declining INDUSTRIES regions usually undergo natural, albeit painful, corrections when their residents leave (Pritchett 2004; Christopherson et al. 2004). In inland California, One approach for policymakers in the interior is however, falling real wages have been accompanied to attract knowledge industries. But attracting by surging population growth. Whether this growth such industries will be of limited benefit to the is harmful is a difficult question. A large portion of unskilled workers who currently live in the interior. the population growth in the interior seems to be the Furthermore, even assuming that programs to create result of unskilled immigration. It is possible that or attract knowledge industries work is a large the presence of unskilled immigrants prolongs the assumption, given that industrial incentive programs interior ’s dependence on primary production activities are often quixotic (Fisher and Peters 1998; 2004). like agriculture, which pay low wages. But there is Frustrating though it may be to admit, after decades little reason to think that a decreased dependence on of study academics still have few good answers about primary production will usher in a new industrial why certain industries locate in certain places. regime. Nor is there any reason to believe that having fewer unskilled residents will prompt an in-migration To a certain extent industrial location reflects little of educated citizens. more than historical contingency. Industries start in one place and tend to stay there, e.g., Hollywood. Indeed, one of the interior ’s problems may be that Exogenous demand shocks can either catapult these the two forms of traded goods and services share industries and the places that host them forward so few inputs. In 1969, the large coastal MSAs had (such as computers in Silicon Valley) or send them sizeable GP&D industries, but they also had large spiraling into decline (automobiles in Detroit). When (for that time) stocks of educated people and nascent industrial geography is something that everyone can knowledge agglomerations. When manufacturing and explain after the fact but no one can predict before, other goods production industries contracted, these there is little guidance for policymakers. There is an MSAs were able to move more easily into producer obvious political appeal of programs designed to services and other parts of the knowledge sector. But turn wayward regions into high tech centers but their the less-skilled, less educated individuals in GP&D efficacy is uncertain. occupations were not necessarily able to move into knowledge industries. BOOSTING E D U C AT I O N Another approach is to focus on education. Certainly higher education is a long-term answer for the young in California’s interior. However, anyone endorsing education as a solution for these areas should be aware that individuals in declining places will, once 118 educated, probably leave. Those who are educated will benefit. But the places from which they depart will not. Nevertheless, economic development in California should be first about helping people and only second about helping places. T H E I M M I G R AT I O N CHALLENGE The people-place distinction is perhaps most acute in the case of immigration. It seems likely that the low levels of educational attainment in California’s interior reflect, at least in part, a steady influx of poorly-educated immigrants. So it is possible that immigration has had an indirect influence on wages in the interior. But a proper analysis of immigration requires consideration of its impact, not just on the places that receive the immigrants, but also on the immigrants themselves. In 1999, the per capita income in Mexico was about $4,500. In rural areas of Mexico it was much lower. Thus, almost every immigrant who came to the twelve interior MSAs in California was made better off as a result. But where immigration makes people better off, it can make places relatively worse off. The arrival of poor people increases the poverty rate, even if immigrants, once they arrive, are less poor than they once were. Anti-poverty benefits of immigration are international, but immigration’s costs—both economic and political—are often local. Resolving this tension will be a challenge for California in general, and for its interior in particular. 119 Anas, Alex, Richard Arnott and Peter Small. 1998. Urban Spatial Drennan, Matthew P. and Jose Lobo. 2009. Traded Goods and Structure. Journal of Economic Literature 26: 1426-1464. Services: Diversity and Specialization in United States Cities Beyond Manufacturing. Urban Studies, forthcoming. Becker, Gary and Kevin Murphy. 1992. The Division of Labor, Coordination Costs, and Knowledge. Quarterly Journal of Economics. Fisher, Peter S. and Alan H. Peters. 1998. Industrial Incentives. 107 (4): 1137-1160. Kalamazoo, MI: WE Upjohn Institute for Employment Research. Black, Duncan, J. Vernon Henderson. 1999. Spatial Evolution of _________. 2004. The Failures of Economic Development Incentives. Population and Industry in the United States. American Economic Journal of the American Planning Association 70(1): 27-37. Review, 89(2): 321-327. Friedberg, Rachel and Jennifer Hunt. 1995. The Impact of Immigrants Bluestone, Barry and Mary Huff Stevenson. 2000. The Boston on Host country Wages, Employment and Growth. Journal of Economic Renaissance. New York: Russell Sage. Perspectivse 9 (2): 23-44. Borjas, George J. and Lawrence F. Katz. 2005. The Evolution of the Fujita, Masahisa, Paul Krugman and Anthony J. Venables. 2001. The Mexican-born Workforce in the United States. National Bureau of Spatial Economy: Cities, Regions, and International Trade. Cambridge, Economic Research, Working Paper 11281. MA: MIT Press. Card, David. 2005. Is the New Immigration Really So Bad? Economic Gibbs, K., L. Kusmin and J. Cromarte, J. 2004. Low-Skill Jobs: Journal, 115(11): 300-323. A shrinking share of the rural economy. Amber Waves. November 2007. <. Card, David and John E. DiNardo. 2002. Skill-biased Technological htm>. Change and Rising Wage Inequality: Some problems and puzzles. Journal of Labor Economics, 20 (4): 733-778. Galbraith, James. 1998. Created Unequal: The Crisis in American Pay. New York: Free Press. Card, David and Ethan G. Lewis. 2005. The Diffusion of Mexican Immigrants During the 1990s: Explanations and impacts. National Glaeser, Edward L. 1994. Cities, Information and Economic Growth. Bureau of Economic Research, Working Paper 11552. Cityscape 1(1): 1-47. Christopherson, Susan, Matthew P. Drennan and Rolf Pendall. 2004. Glaeser, Edward L. 2004. Review of ‘The Rise of the Creative Class.’ Transition and Renewal: The Emergence of a Diverse Upstate Economy, Regional Science and Urban Economics, 35(3): 593-596. Center on Urban and Metropolitan Policy, Brookings Institution. Henderson, J. Vernon. 1988. Urban Development: Theory, Fact and Drennan, Matthew P. 2002. The Information Economy and American Illusion. Oxford: Oxford University Press. Cities. Baltimore: Johns Hopkins University Press. Katz, Lawrence F. and Kevin Murphy. 2002. Changes in Relative Drennan, Matthew P. 2008. The Great Lakes Economy. Politique Wages 1963-1987; Supply and Demand Factors. Quarterly Journal of Americaine, forthcoming. Economics 107(1): 35-78. 120 REFERENCES Krugman, Paul. 1991. Geography and Trade. Cambridge, MA: MIT Smith, Adam. 1776 [1937]. The Wealth of Nations. New York: The Press and Leuven, Belgium: Leuven University Press. Modern Library, Random House. Lazear, Edward. 2007. Immigration’s Economic Impact. President’s Taylor, Edward and Philip Martin. 1997. The Immigrant Subsidy and Council of Economic Advisers. U.S. Agriculture: Farm employment, welfare, and poverty. Population and Development Review 23(4): 855-887. Lee, David S. 1999. Wage Inequality in the United States During the 1980s: Rising dispersion or falling minimum wage? Quarterly Journal Taylor, Edward, Philip Martin and Michael Fix. 2006). Poverty Amid of Economics 114(3): 977-1023. Prosperity. Washington, DC: Urban Institute Press. Levy, Frank and Richard J. Murnane. 1992. U.S. Earnings Levels U.S. Bureau of the Census. 2006 and 2007. American Fact Finder. May and Earnings Inequality: A review of recent trends and proposed 2007. <>. explanations. Journal of Economic Literature 30(3): 1333-1381. U.S. Bureau of Economic Analysis (BEA), Regional Economic Lowenstein, Roger. 2006. The Immigration Equation. New York Times Accounts. April 2009. <>. Magazine. July 9. ENDNOTES McCall, Leslie. 1998. Spatial Routes to Gender Wage (in) Equality: Regional wage restructuring and wage differentials by gender and education. Economic Geography. 74(4): 379-404. 1 UCLA Lewis Center, 3245 Public Policy Building, Myrdal, Gunar. 1957. Economic Theory and Underdeveloped Regions. Los Angeles, CA 90095, Phone: 323-333-0149, Fax: 310-206-5566, London: Gerald Duckworth. Nelson, Marla K. 2005. Rethinking Agglomeration Economies in the Central City: The public accounting industry in Chicago and 2 Minneapolis-St. Paul. Journal of Planning Education and Research. UCLA, 3245 Public Policy Building, Los Angeles, CA 90095, 24(3): 331-341. Phone: 310-825-0587, Fax: 310-206-5566, Email: mattd@ucla.edu O’Sullivan, Arthur. 2007. Urban Economics, 6th edition. New York: McGraw-Hill Irwin. 3 Visiting Professor, Department of Urban Planning, An earlier more technical version of this paper was published in the Berkeley Planning Journal, Vol. 21, 2008. Pritchett, Lant. 2004. Boomtowns and Ghost Countries: Geography, Agglomeration and Population Mobility. Working Paper Number 36. Washington: Center for Global Development. Shapiro, Jesse. 2006. Smart Cities: Quality of Life, Productivity, and the Growth Effects of Human Capital. The Review of Economics and Statistics 88(2), 324-335. 121 7 122 S H A D E S O F G R AY D A N I E L J . B . M I T C H E L L* Daniel J.B. Mitchell is a professor-emeritus at UCLA. He formerly held faculty appointments at the School of Public Affairs and the Anderson Graduate School of Management where he held the Hosu Wu endowed chair. Mitchell is a former president of the North American Economics and Finance Association, now known as the International Banking, Economics, and Finance Association. His research and publication have been in the areas of labor markets, international economics, and California policy issues. * Professor-Emeritus, UCLA Anderson Graduate School of Management and UCLA School of Public Affairs. Address: c/o Anderson Graduate School of Management, UCLA, 110 Westwood Plaza, Los Angeles, California 90095-1481. Email: daniel.j.b.mitchell@anderson.ucla.edu. 123 7 “Sometimes you will fail and be blamed for things you had absolutely nothing to do with.” —Former Governor Gray Davis Keynote speech to Columbia University Law School graduation, May 21, 20091 Gray Davis, the 37th governor of California, took office in 1999 in a period of prosperity. Unlike his two predecessors, Pete Wilson and George Deukmejian, both of which became governor in periods of budget crisis, Davis—thanks to what would eventually be known as the dot-com boom—was initially blessed with state revenue. By the time he ran for re-election in 2002, he was dealing with a major fiscal problem that eventually led to his recall a year later. His successor, Arnold Schwarzenegger, promised to fix the state’s budget problems and without a tax increase. Yet Schwarzenegger found himself mired in another budget crisis during his second term. Given that later history, in hindsight can Davis be blamed for the fiscal problems that led to his recall? Not surprisingly, there is not a clear-cut answer to that question. But it can be said that the style of Governor Davis’ leadership left him vulnerable to crisis. It can be said that despite the prosperous times in which he was initially elected, the state’s proneness to budget crises was apparent. And, it can be said that his successor was naïve about the difficulty of changing the institutional structure of the budget process. DIFFERENT PERSONALITIES “I have prepared my whole life for this moment.” 124 —Governor-Elect Gray Davis Shortly before taking office 2 Davis and Schwarzenegger were very different in background and personality. Davis, a Democrat, was a lawyer by training and was a career politician. 3 He served as chief of staff to Governor Jerry Brown and subsequently became a state assemblyman, controller, and then lieutenant governor. In the 1998 Democratic primary, Davis ran against two wealthy and selffinanced candidates, seemingly as the dark horse in the race. Yet his two rivals managed to defeat each other and Davis emerged as the winner in the primary. Davis based his campaign on his political experience and promised that his focus, if elected governor, would be on education. In the November general election, he easily defeated his Republican opponent, AttorneyGeneral Don Lungren. Arnold Schwarzenegger ran in the 2003 recall as an outsider—not a politician—who would clean up state politics. Although it was his movie career that made him a high-profile candidate, he emphasized his business background which would allow him to rid the state of governmental waste and inefficiencies. Because he was wealthy, Schwarzenegger argued, he would not have to depend on special interests. Schwarzenegger was most successful in terms of public approval when he displayed optimism and humor—and least successful when he seemed combative. In contrast, Davis retained the image of a somewhat stand-offish career politico. Despite these sharp differences in public personas, Governor Schwarzenegger ended up facing a budget crisis at least as severe as the one that defeated Davis in the recall. After a series of ballot propositions related to the budget were rejected by voters in a May 2009 special election, words such as “Armageddon” and images of California driving off a cliff were regularly used. UP AND DOWN: A BUDGET SUMMARY OF THE DAVIS YEARS “Their job is to implement my vision. That is their job.” —Governor Gray Davis discussing the role of the legislature 4 Table 1 provides data on budget proposals made during Governor Davis’ period in office. Except for proposals made in 2003, the proposals are the initial ones made in early January for the coming fiscal year beginning the following July 1. For 2003, the table shows both the January and the “May revise” proposal; the May revise of 2003 was the last proposal made by Governor Davis because of the recall in October of that year. Proposals are not the same as the adopted budget ultimately passed by the legislature. But they do show the intentions of the governor. Yet they can be misleading. The table indicates that Governor Davis repeatedly— until the very end—submitted budgets that were expected to deplete the General Fund reserve. (We avoid the words deficit and surplus to describe these changes in the reserve because budget proposals are not confined on the receipt side to revenue but rather also include “transfers” from outside the general fund, including borrowing.) However, Governor Davis was not necessarily being profligate. During the dot-com boom, revenue kept rising faster than forecast, even relative to what was projected half way through the ongoing fiscal year. (Table 1 shows that projection as well as the proposal for the next fiscal year.) In the late 1990s, revenue from capital gains related to stock market and employee stock option capital gains poured into the state treasury. Although spending was being ramped up, in effect the legislature could not keep up with the inflow. 125 Table 1: General Fund Budget Proposals By Governor Gray Davis ($ Billions) Ja n u a ry 1999 J a nua ry 2000 Estimate Proposal E s t i m a t e P ro p o s a l for 1998-99 f o r 1990-00 f or 1999- 00 f or 2000- 01 R ev en u e & Tr an s f er s $5 6 .3 $ 6 0 .3 $65.2 $68.2 E x p e n dit u res 58.3 6 0 .5 65.9 68.8 -2.0 - 0 .2 + 1 .1 +0 .9 C h a ng e in Res er ve E n d o f F Y Res er ve -0.7 -0.6 + 3.0 + 2.4 - - - - - - - ---------------------------------------------------------------------------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Ja n u a ry 2001 J a nua ry 2002 E st ima t e Pro po sa l Esti m a te P roposa l for 2000-01 for 2001-02 for 2001-02 for 2002-03 * T h e D a v i s a d m i n i s t r a t i o n t re a t e d a l o a n f o r e l e c t r i c i t y p u rc h a s e s i n 2 0 0 0 - 0 1 R ev en u e & Tr an s f er s $7 6 .9 $ 7 9 .4 $70.9* $79.3 re p a i d by r a t e -p a y e r s i n 2001-0 2 i n c o ns i s t e nt l y. I t wa s t re a t e d a s p a r t o f re v- E x p e n dit u res 79.7 8 2 .9 78.4 78.8 e nue a nd t r a ns f e r s i n t he Ja nua ry 2 0 0 2 estimate for 2001-02 but not included C h a ng e in Res er ve -2.8 - 3 .4 -7.5 + 0.5 a s a n e x p e n d i t u re i n p r i o r p re s e n t a t i o n s . T h i s t re a t m e n t h a s b e e n c o r re c t e d i n t h e E n d of FY Reserve +6.6 +3.1 +1.5 +2.0 t a bl e a bov e . - - - - - - - ---------------------------------------------------------------------------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Ja n u a ry 2003 Ma y 2003 E st ima t e Pro po sa l Esti m a te P roposa l for 2002-03 for 2003-04 f o r 2 0 0 2 - 0 3 for 2003-04 **Ex c l ud e s p roc e e d s f rom p rop o s e d R ev en u e & Tr an s f er s $72 .2 $ 7 3 .1 $70.8 $70.9 b o r ro w i n g o f $ 1 0 . 7 b i l l i o n p ro p o s e d f o r 2002-03. E x p e n dit u res 7 6 .8 7 5 .5 78.1 70.4 * * * I n c l u d e s p ro c e e d s f ro m p rop o s e d C h a ng e in Res er ve* * -4.5 - 2 .3 -7.3 + 0.5 b o r ro w i n g o f $ 1 0 . 7 b i l l i o n p ro p o s e d f o r 2002-03. E n d o f F Y Res er ve* * -2 .1 - 4 .5 -9.3 -8.8 na = not a p p l i c a bl e . E n d o f F Y Res er ve na na + 1.4 + 1.9 w i t h Proposed Borrowing*** N o t e : D e t a i l s n e e d n o t s u m t o t o t a l s d u e t o r o u n d i n g . S o u r c e : C a l i f o r n i a L e g i s l a t i v e A n a l y s t ’s O f f i c e . 126 And during the upswing, Davis may well have dependent on short-term borrowing to finance its counted on positive budget “surprises” to develop deficiency in the general fund. Governor Davis then after his preliminary January proposals. proposed refinancing California’s debt through a legally-questionable long-term borrowing scheme Chart 1 shows the end-of-fiscal-year reserve as which his successor essentially adopted and legalized a percent of expenditures for that year. Note that via two ballot propositions in 2004. at the peak, the reserve was roughly one eighth of general fund spending, a “rainy-day fund” target that It is not surprising that a governor ’s popularity would Governor Schwarzenegger later tried to mandate via be enhanced by a good economy and generous budgets a ballot proposition in May 2009, but failed. The chart and that the reverse would occur in Hard Times. also shows how fast even such a large reserve can However, as will be described below, during the good be dissipated. years the leadership style of Governor Davis and his cool relationship with legislators in both parties In a little more than a year, the reserve went from brought him few allies. When the recall threatened, roughly one-eighth positive to one-eighth negative! in large part because of the budget crisis that had Toward the end of the period shown, the state was developed, he had few friends to which he could turn. Chart 1: End-of-Year General Fund Reserve as Percent of Annual Disbursements 14 12 10 8 6 4 2 0 -2 -4 -6 -8 -10 -12 -14 1997- 98 1998- 99 1999-00 2000-01 2001-02 2002-03 127 TA K I N G O F F I C E about how to deal with the lawsuit —left by Wilson— defending Proposition 187. Prop 187 attempted to deny “Too many families of every ethnicity have thrown up state services to illegals and was largely struck down their hands in frustration, concluding they have no through litigation. 7 choice but to send their kids to private or parochial school. I say enough is enough. The time has come to It also soon became apparent that Davis had a strong restore California’s public schools to greatness!” tendency toward micro-management and against del- —Governor Gray Davis 1999 inaugural address 5 egation, even delegation to top appointees. This tendency was initially explained by his press secretary as simply matter of administrative start-up. “It’s impor- The threat of an eventual budgetary debacle that tant that the people he appoints understand where he would lead to his 2003 recall was not part of Governor wants to go,” the aide said.8 But in fact the tendency Davis’ thinking when he took office. As in all bubbles, persisted throughout the Davis era, leading to paraly- there was much rationalizing in the financial press sis of decision making and to a lack of support for the as to why the stock market—especially the dot-coms governor when the recall challenge developed. —could go on rising at a rapid pace indefinitely. The fact that many dot-com startups seemed unable to In the early years, however, Davis’ micro-managing turn a profit was a matter of discussion, but was often style was something to joke about. “We have a simple dismissed as a sign that the new technology was in the policy,” he said. “I’m the only one elected in this early stages of maturing. Profits justifying the current administration.”9 But even then, Davis’ need for stock prices would surely appear in the future. micro-managing showed up in the form of unfilled vacancies in many state positions. “The governor In 1999, a book entitled Dow 36,000 appeared, 6 has spent a tremendous amount of time on the encapsulating this mania. The book’s argument appointment process,” an aide explained. 1 0 That was ran that the business cycle was disappearing. Stocks precisely the problem. generally were not as risky as was once the case and therefore were undervalued, according to its authors’ analysis. Once stocks came to be perceived THE FIRST BUDGET: as essentially riskless by the market, the Dow-Jones 1999-00 Industrial Average could rise to 36,000. Davis’ 1999 inaugural address focused heavily on “I am disappointed that I do not have more resources improving education, his major campaign theme. But to allocate to programs that I want, but I have to bring he also pledged to end “wedge issue politics,” a slam this budget into balance.” at his predecessor, Pete Wilson, who was in attendance at the ceremony and who had won re-election in 1994 —Governor Gray Davis announcing his first budget 1 1 in part on the issue of illegal immigration. Thus, Davis—from the start—exhibited a combativeness that When it came to his budget proposals for 1999-00 un- impeded his relations with the legislature and even veiled a few days after the inauguration, education his own top administrative officials. Later in the year, was again the centerpiece with proposals ranging from for example, there was a high-profile spat between pre-school programs to higher education. A general Davis and Lieutenant Governor Cruz Bustamante theme would be that there would be more money for 128 education but on the other hand there would also be conservative through such gestures as refusing paroles more accountability for student outcomes. Davis sug- to convicted murderers. gested that parents should sign formal contracts with schools to enhance their children’s academic advance- Despite Davis’ centrist balancing, Republicans in ment. Shortly after the budget announcement, the gov- the legislature preferred tax reductions to his new ernor was photographed reading “The Little Engine programs. On the tax day April 15th, they called for That Could” to elementary school students, a symbolic scene that later was repeated for national television. 12 various tax cuts, including eliminating the Vehicle License Fee (“car tax”), a property tax on cars collected by the state for local governments. The state would Overall, however, the new budget was based on then compensate local governments for the resulting revenue projections that were conservative. Senate losses in revenue. Under former Governor Wilson, Republican leader Ross Johnson noted that the stock a staged reduction of the car tax had already been set market was bringing in capital gains and termed in place, but not total abolition. Davis’ projections as “pessimistic.” 13 Groups that might have expected more generous results from T H E M AY a Democrat expressed disappointment over the tightfisted proposals. 1999 REVISE Public-sector unions noted that the budget contained allowances for only modest pay gains. Teachers’ union By the time of the 1999 May revise, revenue projections spokespersons were cautious about the governor ’s had been raised by $4 billion since the January budget proposals for tests and performance reviews. Local proposal. Governor Davis now proposed various officials complained that revenues allocated for their infrastructure project— something that business level of government were inadequate. However, interests supported—although in the past many such budget director Tim Gage said the governor “didn’t projects were financed by earmarked taxes and trust want to be overly optimistic and miss the mark on the funds rather than the general fund. More money high side.” 14 would go to schools—including bonuses for teachers —and there would be bigger pay raises in the revised In effect, Davis was positioning himself as fiscally plan for state workers. prudent. Since the actual budget would not be adopted before the May revise, any positive revenue surprises Some tax cuts were included but these would be could then be incorporated. Positive surprises began delayed beyond the budget year. That proposal became to accumulate as soon as February when Legislative a sticking point for Republicans. GOP assembly Analyst Elizabeth Hill pointed to good economic news leader Scott Baugh said his members “will not accept and projected further revenue increases as a result. that there is no place for taxpayers at this bountiful By March, larger-than-budgeted pay raises for table.” 1 5 Assemblyman Tom McClintock threatened state employees were negotiated by the Davis that an initiative would be put on the ballot to abolish administration. Apart from direct pay increases, Davis the car tax, a tax he characterized as “outmoded shored up his relationship with organized labor— and mean-spirited.”1 6 McClintock’s partner in this private sector as well as public—by agreeing both endeavor would be People’s Advocate, the group that to improved state labor standards and to upgraded was eventually to sponsor the 2003 recall. The notion labor standards enforcement. But he also tilted of a bountiful table was reinforced shortly after the 129 May revise when the Legislative Analyst projected still A DEAL IS more revenue than Davis had assumed in his revision. REACHED Governor Davis was anxious to bring in a budget deal on time—in principle even by June 15, the date the The legislature did not quite meet the June 15 deadline legislature is supposed to be finished with it. Such but seemed close to reaching a deal with Republicans, a timely enactment would be seen as a change from the a few of whose votes were needed to reach the notable delays that had characterized the Wilson era. required constitutional two-thirds supermajority. As Chart 2 shows, Pete Wilson had only one on-time Essentially, Republicans bargained for further tax cuts budget; his predecesso—George Deukmejian—had at the margin, such as adding truckers to the car tax experienced only two major delays, both in times of cut, and for a credit for research and development for budget crisis. With the threat of a car tax initiative and business. The budget was enacted on June 16, one day with pressure from legislative Republicans in mind, after the official deadline but well before the start of Davis agreed to a reduction in the car tax. That cut was the new fiscal year on July 1. However, it took until later to figure in the 2003 recall when he temporarily June 30 for the governor to sign off on the budget and reversed it. announce various line-item vetoes totaling over a half Chart 2: Days of Budget Delay Beyond June 30 Until Signing 2003-04 (Dav is) 2002-03 (Dav is) 2001-02 (Dav is) 2000-01 (Dav is) 1999-00 (Dav is) 1998-99 (W ilso n ) 1997-98 (W ilso n ) 1996-97 (W ilso n ) 1995-96 (W ilso n ) 1994-95 (W ilso n ) 1993-94 (W ilso n ) 1992-93 (W ilso n ) 1991-92 (W ilso n ) 1990-91 (Deukmejia n ) 1989-90 (Deukmejia n ) 1988-89 (Deukmejia n ) 1987-88 (Deukmejia n ) 1986-87 (Deukmejia n ) 1985-86 (Deukmejia n ) 1984-85 (Deukmejia n ) 1983-84 (Deukmejia n ) 0 130 5 10 15 20 25 30 35 40 45 50 55 60 65 70 billion dollars, a sign of the detail-orientation that Calendar 1999 came to a close with various groups characterized Governor Davis. pushing for ways to spend the funds that the stock market kept adding. Republicans wanted more tax As part of the accord, Davis had the legislature cut out cuts. The California Teachers Association (CTA) the chairing role of the Lieutenant Governor—who had threatened to sponsor a ballot initiative to earmark feuded with him over the Prop 187 litigation—in a new more money for schools unless it was delivered commission to deal with the upcoming 2000 federal legislatively in the next budget. Infrastructure Census. The governor ’s vetoes included various improvements, accelerating the opening of UC- “pork” projects in Republican districts which GOP Merced, student fee reductions in public universities, legislators insisted they had been promised as part of all were being on the table for potential funding. the budget negotiations. Davis spokesperson denied the governor had gone back on his word. YEAR TWO: Davis himself said that he couldn’t let Republicans PROSPERITY keep all the pork they wanted while cutting pet projects desired by legislative Democrats. But the controversy created a climate of mistrust. Republican senator Jim Brulte noted that “we work here on a system of good faith and trust” and that that Republican leaders “California is flush.” —Governor Gray Davis presenting his budget for 2000-01 1 9 believed that Davis “did not keep his word.” 1 7 As the new calendar year opened, much of the preIt was not only Republicans who expressed concerns budget debate revolved around education funding. about the governor. Various education bills supported CTA wanted per-pupil spending raised to the national by Davis were before the legislature. The Davis average. But the Davis administration resisted administration put pressure on balking Democratic anything that costly. One advisor to the governor legislators in ways they considered inappropriate. argued that voters were not interested in abstract After the governor was quoted as saying it was the numerical goals. “We polled it and focus-grouped it job of the legislature to implement his vision, some during the campaign… It’s simply not where people legislative Democrats made their unhappiness semi- are,” the advisor noted. 2 0 Davis preferred particular public. Senate president John Burton simply said targeted education programs such as special rewards he had “a different point of view on the matter.” 18 for good teachers, increased teacher training in state Meanwhile, another gubernatorial feud with higher-education institutions, rewards for college Democratic state controller Kathleen Connell was grads to go into teaching, and such. also being reported. Competing with possible spending on education was While times were good, however, such conflicts were a court decision voiding a fee on out-of-state cars largely the concerns of state political junkies, not the brought into California, mainly by newcomers to the general public. Davis was able to cultivate his image state, ostensibly for their “smog impact.” The fee had as a tough-minded centrist with a bent for improving been imposed in the Wilson budget crisis of the early education and fighting crime. And by the fall of 1999, 1990s and would now have to be refunded to those it was apparent that revenues were again who had paid it. Governor Davis also had spending exceeding projections. objectives related to social welfare programs. The goals 131 included pay raises for state-paid home care aides While Davis supported the idea of cutting the hurdle and expansion of health insurance for children of the for voter approval of school bonds to 55 percent, working poor. Davis also supported a ballot measure he did not endorse a related proposal that would scheduled for March 2000 that would reduce the allow voter approval of transportation taxes by only popular vote required for school bonds to be approved 55 percent. The governor did eventually support from two thirds to 55 percent. the idea of limited use of general fund revenue for transportation projects and a bond measure for THE JANUARY PROPOSAL transportation to be put to voters. Yet it was hard to adhere to a posture of fiscal restraint in the face of continuous positive budget surprises. Only a few days after Davis formally presented his When the budget proposal was unveiled in early January proposal for 2000-01, Legislative Analyst January 2000, public discussion continued with Elizabeth Hill projected that revenues would in fact be educational interests pressing to increase per-pupil $3 billion higher than he had forecast. The chair of the spending. Republicans were pushing for more tax cuts Senate’s Republican caucus Jim Brulte (who was soon than the governor had suggested and asking for more to become minority leader) commented that “we can funding to be returned to local governments. In two do everything Governor Davis wants, as well as what respects, Davis seemed to be returning to his early we’d like to do.”2 1 Since Republican votes would be apprenticeship as chief of staff to former Governor needed to pass a budget even in prosperous times, it Jerry Brown. Brown accumulated a large reserve in the would be hard to say “no” to their agenda when there general fund—often viewed as a factor in the passage was money around for so much else. of Proposition 13 which drastically cut property taxes in 1978. Angry property taxpayers saw their tax bills Apart from the governor, there was recognition—at rising at the local level while the state enjoyed a large least in some quarters—that a budget based heavily and growing reserve. on the rapidly-advancing stock market could suffer a sharp reversal if the capital gains went away. Davis also wanted to add funding to the reserve. But it was tough to keep from partying in the face He was aware that relative to the 1970s, the state of the substantial revenue inflows. State School had become more dependent on the stock market to Superintendent Delaine Eastin—a Democrat but like generate capital gains tax revenue. Any reversal in others in a tenuous relationship with the governor—in the market could undermine state finance. Perhaps particular pushed for more educational spending than sensitive to Davis’ concerns, Assembly speaker Davis had proposed.2 2 During the spring, the spat Antonio Villaraigosa proposed a ballot initiative that over education funding continued. There was debate would halt scheduled cuts in the Vehicle License Fee over how many dollars would be required to bring (car tax), with the money to go for education. state per-pupil spending to the national average. And CTA continued gathering signatures for its ballot Jerry Brown was also famous for his disdain of the large-scale public works projects that had characterized the era of his father, Governor Pat Brown. In 2000, Davis was criticized for failing to address transportation and congestion adequately. 132 initiative to force such spending. GANN AGAIN? One possible check on the growing demands for state F R O M M AY R E V I S E TO FINAL DEAL spending was the long-irrelevant Gann Limit. In the aftermath of Prop 13, voters passed Prop 4 (dubbed The notion of a total income tax exemption for teachers the son of Prop 13), which capped state spending ac- did not find a warm reception in the legislature, partly cording to a formula. The Gann Limit quickly became because of concerns that other professions might irrelevant due to the recession in the early 1980s that also demand similar treatment. CTA was not keen brought down spending well below the limit. on the exemption idea, fearing it would stir voter resentment against teachers. Other ideas were floated Gann resurfaced briefly in the form of a required tax such as a limited tax credit or a cut in teacher pension rebate during Governor George Deukmejian’s second contributions. How a more general income tax rebate term in the late 1980s when the limit was hit. But that would be handled was also a sticking point. episode triggered Prop 98 of 1988 which earmarked funding for K-14 via two formulas and partly gut- It was argued that an income tax rebate would be ted Gann. The gutting was completed two years later partly diverted to the federal government since state by another initiative—Prop 111—that also added an income taxes are deductible from income declared additional formula to Prop 98. A final blow was the on the federal income tax. Democrats pushed for an recession of the early 1990s, which—as had the reces- alternative sales tax rebate of some type. Republicans sion of a decade before—brought down state spending. wanted a guarantee that future scheduled cuts in the However, with the recovery in the late 1990s and the Vehicle License Fee (car tax) would not be impeded by stock-market related revenue surge, it appeared that other elements in the budget. The wrangling over tax even gutted Gann might become a constraint. cuts and rebates led to delays beyond the official June 15 deadline for the legislature to enact a budget. With hindsight, it appears that the Gann limit was ultimately exceeded although no one knew at the With Republicans focused on the car tax, eventually time and no explicit Gann-mandated tax rebate ever the tax rebate plan was scrapped and an increased resulted. Nonetheless, the revival of Gann did have the effect of putting a constraint on the eventually- the car tax previously scheduled for 2004 was shifted enacted 2000-01 budget. The constraint arose into the 2000-01 budget. In a move to make the car particularly because Davis—shortly before the May tax cut visible, motorists would receive rebate checks revise—acceded to additional education funding. back in the mail for part of the tax they paid. (This He made a deal with CTA in which the union’s cumbersome process was later abandoned after several proposed ballot initiative was dropped. months of rebates by an equivalent straight-forward rate reduction.) With that issue settled, the legislature With more educational spending, there was less room passed the budget and it was signed with ceremony for the many other proposals and demands that were —after vetoes totaling $1 billion by the governor— surfacing. The May revise combined the deal with an on June 30. The vetoes kept the total budget, i.e., income tax rebate which was not technically linked general fund plus special funds, just below $100 to Gann. A final cherry on the budget sundae was billion. Several budget-related bills were signed later a proposed exemption of school teachers from the including various teacher incentives. income tax. 133 WARNING LIGHT The solution developed for San Diego ratepayers was a short-term transitional patch whereby rates In 1996, an elaborate electricity plan for California would rise more gradually through a borrowing was adopted with bipartisan support in the legislature arrangement. It did not include a re-evaluation of the as well as support by Governor Wilson. The theory entire deregulation plan to see if other problems lay was that competition in electricity supply could bring ahead. Various issues competed for Davis’ attention down the costs of power. Generation (power supply) in summer 2000 such as creating a César Chavez would be separated from distribution. Customers, holiday for the state and deciding how the state would both residential and commercial, would buy from the celebrate the 150th anniversary of statehood. There cheapest source. Retail prices would be controlled were pressures to enlarge the Cal Grant funds for and capped until the former generating/distribution college tuition and controversy over a possible state regulated monopoly firms divested themselves of their law to resolve labor disputes for police and firefighters generation capacity. Despite the appealing theory, through an arbitration process. there are many practical issues in any deregulation scheme, once the plan moves from general concept to Also competing for the governor ’s attention was the specific details. aftermath of a scandal that had led to resignation of Insurance Commissioner Charles Quackenbush, a bill Unlike other markets, electricity demand and supply related to racial profiling by police, reduction of fees must match exactly, moment by moment. Insufficient at state parks, political jockeying surrounding various supply can cause equipment failures at both the sup- ballot measures destined for the November election, ply and demand ends. So there must always be enough and nursing home regulation. One of these measures power, something that can only be ensured either by would be the ballot proposition that would reduce having excess capacity or by quickly cutting off power the voter approval hurdle for school bonds from (blackouts) to some customers. The electricity market two thirds to 55 percent. 2 3 In short, it was easy for can be subject to manipulation unless the deregulation the warning light flashed in San Diego on electricity plan includes a new version of regulation to prevent deregulation to be ignored, especially if all important artificial withholding of power and ensure sufficient and not-so-important decisions ended up in the supply and capacity. As it turned out, California’s de- governor ’s office. regulation plan was flawed and was famously manipulated on the supply side. And there was so much good news to announce, including a reduction in the sales tax beginning on Governor Davis was not responsible for the original de- January 1, 2001, triggered by the state’s revenue boom regulation plan, since it was signed into law by his pre- and extra payments to schools for education of the decessor. However, Davis’ tendency to micro-manage disabled, a matter that had been in litigation for years. and his aversion to delegation meant that his adminis- The projections for 2001-02 also were rosy, according tration could overload in a crisis situation. San Diego to the legislative analyst and the Department of Gas and Electric was the first major utility to divest Finance. “Extra revenue in the billions,” was how the itself of its generating capacity and so was free to raise forecast as of November 2000 was characterized by the its rates. San Diegans saw their electric bills soar in July Department of Finance spokesperson.2 4 2000, leading to a public outcry. That outcry should have been a warning sign that there were problems with However, there also were suggestions that maybe the larger deregulation scheme outside of San Diego. some of the revenue should be spent to shore up the 134 electricity deregulation scheme which had already Despite the growing electricity crisis, Governor Davis caused the San Diego uproar. A spokesperson for stuck to his educational theme in framing his budget Governor Davis said that the governor was pondering proposals for 2001-02. Traditionally, word is leaked the matter but that “it’s premature to discuss any about key features of the January budget message specific budget proposal.” 25 And a spokesperson in advance. For 2001-02, there was to be expansion for a trade group of electricity producers suggested of teacher training and recruitment, a pay premium that the state could better spend its money on public for math teachers, and enhanced math education. schools, roads, and tax relief. If California were to The academic year would be expanded for middle change its approach to deregulation, the unstable schoolers. At the higher education level, construction political environment would discourage investment of the new UC-Merced campus was due to start. in new power plants, the spokesperson for generating interests argued. 2 6 Republicans also had plans. Assemblyman Keith Richman (R-Northridge), who was later to be involved Some forecasters did suggest caution. The UCLA in developing Governor Schwarzenegger ’s ill-fated Anderson Forecast in December 2000 indicated that 2007 universal health plan proposal, suggested an economic slowdown—but not a full recession—lay expanding children’s health insurance coverage. But ahead. And two of the three big private electrical Republicans more generally wanted tax cuts. Yet utilities—Pacific Gas and Electric (PG&E) and despite partisan debate on the budget, electricity could Southern California Edison—were straining under the not be ignored. deregulation plan. Because they had not divested all of their power plants by then, they could not raise retail rates. But the wholesale price of electricity had reached POWER CORRUPTS a level at which they were operating at a loss, buying high and selling low. At a hearing of the state Public By early January 2001, there was talk of an imminent Utilities Commission in late December, PG&E reported PG&E bankruptcy which could result in the inability that “we are out of credit and we are close to being of the company to buy electricity in the deregulated out of cash.” 27 The spectacle of repeated blackouts in California was about to begin. marketplace. (The firm did file bankruptcy in April.) There was also discussion of seizing power plants through eminent domain. And there was talk of THE 2001-02 BUDGET PROPOSAL the state having authority to turn on power plants ostensibly closed for maintenance. Federal assistance was not forthcoming. Washington, D.C. was by that time in the midst of the transition from Democrat Bill Clinton to GOP President George W. Bush. The new regime was not disposed to offer assistance. “Make now mistake: We will regain control over the power that’s generated in California and commit it to the public good… Never again will we allow out-of- At the same time as electricity was taking the focus state generators to threaten to turn off our lights with away from the budget, there were signs that the dot- the flip of a switch.” com boom was ending and the California economy —Governor Gray Davis January 2001 State of the State speech 28 was weakening. The large general fund reserve that the state had built up was likely to decline according to the legislative analyst, due to those developments. 135 And with PG&E and Southern California Edison ous fiscal situation.3 0 And despite state intervention running out of cash to buy electricity, the state stepped in electricity supply, the lights kept going out. in to buy power for them through the Department of Water Resources, effectively reselling it to the utilities As Table 2 indicates, Davis’ approval ratings took and consumers at a loss. a hit during the electricity crisis. Then, as the budget situation deteriorated, his ratings remained low. By The terms of these newly-negotiated state power early 2003, when his removal from office by the recall contracts were kept secret, officially to obtain the best became a serious possibility, his ratings essentially price. Contract secrecy became yet another matter of had tanked. controversy. Plans were proposed for a bond issue that would repay the state for its loss-producing power purchases through higher electricity bills in the future. T H E M AY 2 0 0 1 However, there were delays in coming to an agreement REVISE on the details of the bond. At one point, state controller Kathleen Connell—with As the date for the 2001 May revise proposal for whom the governor had feuded in the past—refused 2001-02 approached, it had become clear that the to transfer state funds for electricity purchases. The dot-com boom had turned into the dot-com bust. The governor wanted the bond to be floated quickly so outlook for continued positive surprises in tax receipts that the draw on the state treasury would end before on capital gains had reversed. Now the outlook was the beginning of the new fiscal year. Nonetheless, for a loss of such revenues and negative surprises. wrangling over the bond and about electricity in general delayed the bond beyond 2000-01. Memories in Sacramento began to turn to the early 1990s, when a national recession and the end of the The Davis administration’s position was that the state Cold War caused a major state budget crisis. Legisla- could afford such electricity purchases in the interim tive Analyst Elizabeth Hill projected the January bud- period before a bond was issued, given its budget sur- get proposal would produce a negative reserve by the plus. Yet as my colleague Werner Hirsch and I pointed end of 2001-02 unless cuts in it were made. The con- out in a February 2001 op ed in the Los Angeles Times, cerns were not confined to Sacramento, however. the budget was in fact already in deficit. Expenditures were in excess of revenue, a bad position to be in, even As Table 3 shows, state bond ratings were lowered apart from the electricity purchases, when the business in April by Standard & Poor ’s (S&P)—the first of cycle seemed to be peaking. multiple downgrades during the Davis era. Wall Street was watching both the deteriorating economic outlook A deficit at the peak could only become larger in an and the drain on the state treasury from electricity economic decline. Davis’ finance director responded purchases. The electricity bond proposal passed in in a letter to the editor that there was no deficit, de- May. But without a two-thirds urgency vote, the bond spite the figures to the contrary on the Department of sale had to wait 90 days, thus pushing it into 2001-02. Finance’s own website. 29 Given a budgetary environ- In the end, Davis authorized an emergency short- ment that the legislative analyst termed “one of the term loan in June—effectively a borrowing against most unusual and challenging set of circumstances in the flotation of the longer-term bond. The state was recent history,” California was moving into a precari- borrowing against future borrowing. 136 Table 2: Voter Attitudes Toward Governor Gray Davis Vo t e r Appro va l* M ar. 1999 Au g . 1999 Oct . 1999 Table 3: California General Obligation Bond Ratings Fa vo r Re ca ll 5 4 % Apr. 1 - 6 , 2003 59 Jul . 1 - 1 3 54 Aug. 1 0 -13 ------------------------------------------------------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 55** D ur i ng 53** 1999 57** ------------------------------------------------------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - J u n . 2000 61 Sep. 2 5 -28 Au g . 2000 56 Sep. 2 9 -O c t . 1 J an . 2001 57 - - - - - - - - - - - - - - ------------------------------------ D ur i ng M ay 2001 36 Actual El e c t i on Re s ul t 2000 Fav or R e c a l l Dec. 2001 38 J an . 2002 39 Apr. 2002 39 McCl i ntoc k J u l. 2002 41 Camej o A a 3 58** Sep. 3 - 7 38 A A - Ja n. 1999 Moody’s & P o o r ’s 51** 62 F i tch A s of S ta n d a rd 46% * F eb. 2000 Sep. 2001 A+ A A ( F e b.) A A - ( Au g.) A a 2 ( S e p.) A A ( Se p.) 55.4% ------------------------------------------------------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Schwarz e ne g g e r 48.6% During Bustama nt e 31.5% 2001 13.5% 2.8% A a 3 ( Ma y ) A + ( Ap r.) A 1 ( N ov.) ------------------------------------------------------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Sep. 2002 39 D ur i ng Apr. 2003 24 2002 J u l. 2003 23 ------------------------------------------------------------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Au g . 2003 22 D ur i ng 2003 A ( D e c .) B B B ( D e c .) A ( D e c.) A 2 ( F e b.) B B B ( J u l.) * Reg is t ered v oters. A 3 ( A ug.) * * Lik ely vo t ers. Ba a 1 ( D e c.) Source: California Field Poll at: California Secretary of State at: h t t p : / / w w w. s o s . c a . g o v / e l e c t i o n s / s o v / 2 0 0 3 _ s p e c i a l / r e c a l l _ q u e s t i o n . p d f h t t p : / / w w w. s o s . c a . g o v / e l e c t i o n s / s o v / 2 0 0 3 _ s p e c i a l / g o v. p d f Note: Interim warnings by the rating agencies that may have been issued between rating changes are not included. Downgrades are in italics. S o u r c e : C a l i f o r n i a S t a t e Tr e a s u r e r. A v a i l a b l e a t : h t t p : / / w w w. t r e a s u r e r. c a . g o v / r a t i n g s / h i s t o r y. a s p bond would repay the state for its power purchases, When the May revise did come out, it included various the state would still run a deficit and pull down its cuts. However, Governor Davis tried to preserve as reserve. As a result, state bond ratings were lowered much of his January education proposals as possible. by Moody’s. Republicans criticized the governor ’s “I’m not going to let our commitment to education plan as fiscally imprudent. And the legislative analyst backslide,” he said. 31 But in fact the education proposals were trimmed. For example, the proposed warned that even the slimmed down May revise would lead to a negative reserve. lengthening of the middle school academic year was retained, but the number of added days was reduced. Governor Davis, however, denied that the reserve would go negative. “Reserves are for rainy days… Even with the various May revise spending cuts We’re getting out our umbrella,” he said. 3 2 By June, relative to January, and assuming that the electricity state Senator Steve Peace (D-El Cajon)—later to 137 become Davis’ finance director—said the slim reserve After a lack of success in the Assembly on the trailer projected by the governor ’s May revise “ain’t going to bills, the Senate took up the budget and a new deal last ten days in a softening economy.” 33 was cut in the upper house. Not surprisingly, the June 15th technical deadline Under the eventual Senate budget plan, the sales tax for the legislature to pass a budget came and went increase formula was modified but in a way that it without a deal. Cuts were made, however, in various would still trigger the 0.25 cent hike on January 1, legislative proposals. Lengthening of the middle 2002. In addition, among other inducements, a propo- school year was dropped, for example. A sticking point sition would be placed on the March 2002 ballot ear- was the 0.25 cent cut in the sales tax which would end marking the sales tax on gasoline (not to be confused automatically by formula on January 1, 2002 due to with the gas tax itself) for transportation. The Senate’s revenue declines. Republicans wanted the reduced rate passage of the budget with the ballot measure broke to continue, i.e., to override the existing formula and the stalemate in the Assembly over the trailer bills. The keep the cut in place. With a legislative stalemate, the governor signed the budget after vetoing about half new fiscal year began on July 1 without a budget. a billion dollars of spending. Particularly hit by vetoes were community colleges, although some funding was N E G O T I AT I N G T H E 2001-02 BUDGET later restored. In theory, a reserve in the general fund of $2.6 billion was forecast for the end of 2001-02. But in fact, a substantial negative reserve resulted. A series of events delayed flotation of the electricity It took until July 26th for a budget deal to be reached bond, including the September 11th terrorist attacks - and signed into law. Assembly speaker Robert which also made the economic outlook more uncertain. Hertzberg (D-Sherman Oaks) suggested that the Drops in revenue below forecast levels added to the Republicans were holding back on a budget deal to precarious fiscal climate. By October, the governor told “embarrass the governor” by depriving him of an state department heads to plan for major budget cuts. on-time budget. 34 There was discussion of delaying the formula-linked sales tax rise, rather than blocking it entirely as Republicans had wanted. 35 Another A hiring freeze was ordered. By November, Davis was calling for mid-year spending cuts and freezing various funds over which he had control. possibility was changing the formula in some way. Eventually, enough Republican votes to reach the Borrowing to deal with state deficits was raised as two-thirds hurdle were obtained in the Assembly by a short-term solution to what was now acknowledged dropping the sales tax issue and offering a deal for as a budget crisis. There began to be discussion of rural districts that benefited agriculture and other having the state issue Revenue Anticipation Warrants” interests there. (RAWs), that would allow borrowing across the fiscal years, i.e., from 2001-02 to 2002-03, particularly since Once a budget had passed the Assembly, it was the electricity bond was on indefinite hold at the thought that the process would be easier in the Public Utilities Commission. Another possibility that Senate since only one Republican vote was needed. began to be discussed was borrowing against future However, various trailer bills linked to the budget in tobacco settlement revenue. the Assembly failed to obtain sufficient Republican approval, thus delaying the process there. 138 Given the budget and electricity meltdowns, various Despite the revenue problem, the governor did not Republican candidates for governor in the November propose new taxes in his January budget proposal. 2002 election began to surface, as Davis looked more But various fees were to increase. The proposal and more vulnerable to a challenge. Included on acknowledged that a deficit would in fact be occurring the list were Los Angeles Mayor Richard Riordan, during the current (2001-02) fiscal year but assumed Secretary of State Bill Jones, and businessman nonetheless that 2002-03 would end with a slight William Simon, Jr. 36 All of the candidates pointed to positive reserve. However, some of that reserve would California’s fiscal problems and attributed them to consist of borrowed tobacco money and of borrowings Davis’ lack of prudence. “Spending like a drunken from other sources including delayed payments to sailor,” was Riordan’s description. 37 Riordan was state pension plans. widely viewed as the most effective opponent in a race against Davis. But he was also seen as someone The January budget plan assumed various funding who might have trouble—because of his centrism—in would flow from the federal government that in fact winning a Republican primary. might not be forthcoming. And the legislative analyst suggested that required payments to K-14 education BUDGETING FOR 2002-03 IN AN ELECTION YEAR under Prop 98 were underestimated in the Davis proposal. By late February, she also estimated that his revenue forecasts were significantly overoptimistic. The only good news was that California’s electricity usage was constrained by the state’s economic slump, making it unlikely that a renewed period of blackouts would occur. “With the same resolve we demonstrated during the energy crisis, we will squarely confront the current economic downturn and its consequences.” PRIMARY EVENTS —Governor Gray Davis 2002 State of the State address38 Republican gubernatorial hopeful William Simon characterized the Davis budget as “shell games and With revenues adversely affected by recession, the fuzzy math.” 3 9 Foreshadowing a favorite proposal of need to conserve cash became an element in budget- Arnold Schwarzenegger when he became governor, ing. State Treasurer Phil Angelides proposed a restruc- Simon pushed for a large rainy-day fund to cushion turing of state debt so that debt service would be more the state budget from economic downturns. Senate back-loaded, i.e., that outflows for debt service would president John Burton, while officially favoring Davis’ be delayed. Potentially complicating state budgeting re-election, managed to be photographed hugging was the above-mentioned ballot proposition (Prop 42) Republican Richard Riordan and made various off- that was scheduled to appear on the March 2002 ballot handed criticisms of the governor. And as bad revenue as part of the earlier budget deal for 2001-02. Prop 42 news accumulated, the governor had to scrap his earmarked the sales tax on gasoline for transportation teacher bonus program as part of midyear budget cuts. rather than the general fund and when put to the electorate passed by a wide margin. It is not unknown for incumbent California governors seeking re-election to try and influence the selection of the other party in the hopes of facing a weaker opponent. 139 However, such cross-party efforts can be risky. Still, the state was likely to run short of cash ab- Governor Pat Brown, seeking a third term in 1966, sent some solution. Part of the problem was that the thought Ronald Reagan was his preferred opponent electricity bond had not yet been floated and it was on the assumption that a movie actor would not unclear when it could be issued. Controller Kathleen be considered by voters as a serious candidate. As Connell announced there would need to be an issuance it turned out, Reagan was a strong contender and of Revenue Anticipation Warrants (RAWs), short-term defeated Brown. Intervention in the other party’s borrowing that crosses the fiscal year. By the May re- primary, in short, can lead to unintended results. vise, the governor was proposing to undo past cuts in the Vehicle License Fee (car tax) for a one-year peri- Nevertheless, Gray Davis thought that Riordan, od—although delayed until after the November elec- as a centrist candidate, would be his strongest rival tion. A tobacco tax would be part of the package. And among the Republicans and ran TV ads to undermine there would be cuts in Medi-Cal and other programs. him. Ostensibly, the ads criticized Riordan as a flip-flopper on the abortion issue. However, the ads Legislative Democrats pushed for increased income tax were intended to emphasize that Riordan, although rates in the higher brackets, but Republican support a Catholic, was taking a pro-choice position. Davis was was not available for such a tax hike. However, the undoubtedly right about Riordan being the strongest Senate, which required only one Republican vote candidate in 2002 and his strategy did help Simon beat to obtain the needed two thirds, did pass a budget Riordan in the March primary. (Jones came in third.) with a jump in the car tax for one year, a tobacco However, Davis’ intervention in a Republican primary tax, and other revenue raisers. The one Republican was remembered in the 2003 recall as a political who provided the vote—Senator Maurice Johannsen manipulation to the governor ’s ultimate detriment. (R-Redding)—was subsequently excluded from Republican caucus meetings in early July. The deal PRELUDE TO A S U M M E R S TA L E M AT E with him reportedly involved not closing a private prison in his district and other considerations.4 1 In the Assembly, however, four Republican votes were necessary and no budget was passed when fiscal 200203 began on July 1. Given the squeeze on state revenue, various publicsector unions pushed for a tax increase. However, in an election year, Governor Davis was reluctant to endorse such a strategy. In addition, a tax increase would require a two-thirds vote in the legislature—an A LONG HOT S U M M E R O F D E L AY unlikely outcome. But by April, Davis was discussing the possibility—as something he didn’t want to do In the background of the stalemate were the but could not rule out—of suspending Prop 98’s impending gubernatorial and other elections in guaranteed funding for K-14. “I don’t want to go there November. William Simon was having trouble in right now,” the governor said. 40 There was also talk of delaying the opening of UC-Merced. fundraising and there was controversy over his unwillingness to release his tax returns. And Governor Davis had a scandal simmering about state computer contracting with Oracle Corp. The California state auditor also criticized inefficiencies in the management 140 of state prisons. As the heat of the campaign was 2006. But Schwarzenegger wasn’t shy about his increased, the duration of the budget delay also ambitions. “That is my favorite job in a political arena. increased. Eventually, the state was to go over two Being CEO of a state—that, to me, is interesting.” 4 3 months without a budget, a record not to be exceeded again until the summer of 2008 under Governor By August, although various proposals on the Schwarzenegger. budget were debated in the legislature – including a major increase in the tobacco tax - none seemed The new fiscal year began with the usual warnings close to breaking the stalemate. Without a budget, that certain payments could not be made without an state employees were still receiving their full pay enacted budget, and with conflict between Governor although a legal challenge to paying them more than Davis and Controller Connell over what payments the minimum wage had been mounted. Various would be made. A legislative analyst’s report other providers of state services were not being paid suggested that if the current trajectory of revenues and at all and Cal Grant scholarships were also delayed. spending were continued, the state would face deficits Republicans charged that Davis was “alarmingly over a multiyear period, i.e., that economic growth disengaged” from the budget process. 4 4 alone was not expected to repair the problem. In late August, Assembly Republicans and Democrats As the budget stalemate persisted, Governor Davis’ seemed to be moving towards a deal. It involved popularity with voters was certainly not enhanced. certain changes in business taxes that would bring in However, Republican gubernatorial opponent Simon more revenue in the short term (although less in the seemed to be having difficulties convincing prospec- future), various spending cuts, and some cosmetic tive voters that he would do a better job than Davis deferrals of expenditures into the next fiscal year. But or even in raising funds to support a campaign to tell the deal also involved a possible ballot proposition them so. There were reports that Simon was under an that would earmark a portion of the general fund for IRS investigation concerning his income taxes and infrastructure improvements. In the end, agreement a tax shelter he had used of uncertain validity. But he was reached in the Assembly, but without the continued to refuse to make his returns public, saying infrastructure proposition. The Assembly version of he would do so only if elected. As pressure mounted the budget was then passed by the Senate. on the issue, Simon eventually allowed reporters to see the returns, but not to copy them. In signing the budget in early September 2002, Davis called the process of negotiations “an arduous and On the other hand, a Field poll suggested that Prop difficult task.” Gubernatorial rival Simon charged that 49 scheduled for the November 2002 enjoyed strong the new budget was “a fabrication that was neither public support. 42 Prop 49 earmarked funding for balanced nor fiscally responsible.” 4 5 However, by after-school activities and was supported by actor that time Simon was looking increasingly to be a likely Arnold Schwarzenegger. Schwarzenegger was loser in November, albeit with Davis seen by voters as interested in possibly running for governor in some being only the less bad of a poor choice. future election. His political advisors had suggested sponsoring a ballot initiative to introduce him to the public as a serious figure. At the time, no recall was envisioned so the earliest Schwarzenegger could have been contemplating a run for the governorship 141 THE 2002 GENERAL ELECTION Democratic legislative candidates. Democrats lost two seats in the Assembly and one in the Senate, thus making it more difficult for them in future budget or tax debates to obtain the needed two-thirds majority. Davis refused to attend a debate in mid-September, leaving Simon to debate the Green Party candidate. On the other hand, the election led to internal feuding (Both major party candidates did debate in October.) within the GOP. State Republican chair Shawn Steel He vetoed a bill that would have allowed illegal complained that big business had engaged in immigrants to obtain drivers’ licenses, even though a “betrayal” of the party by underfunding Simon and the bill might have attracted some Latino voters. (The McClintock. Steel vowed the GOP would no longer license issue arose again in the 2003 recall when Davis support tax breaks for large corporations. 4 7 signed a similar bill, hoping to attract Latino votes). A Simon TV ad purported to show a photo of Davis It was soon apparent after the election —if it had accepting a campaign check inside a state office, an act not been before—that the 2002-03 budget was in fact which would have been illegal. But it turned out that in deficit and that more fiscal difficulties lay ahead. the location was in a private home and therefore legal, “There is no easy way out of this predicament,” the a revelation that ended up casting a negative light on legislative analyst said in mid-November.4 8 Governor Simon rather than Davis. Davis called a special session of the legislature in December to deal with the unraveling budget and On Election Day, Davis won 47 percent to Simon’s 42 recommended midyear spending cuts and layoffs. percent (with the remainder going to third parties). Student fees were raised at UC and CSU campuses. Such a narrow winning margin was not a good The resignation of finance director Tim Gage was showing for an incumbent—especially one who had announced with the explanation that he needed to spent roughly twice as much on his campaign as spend more time with his family. And the state’s credit his particularly weak opponent. The apparent voter rating was cut by Standard & Poor ’s and by Fitch. unhappiness of 2002 would ultimately be reflected in the 2003 recall. 4 6 Of more immediate significance The election—while a win for Davis—also turned him to the budget was a very narrow victory by into a lame duck due to term limits. Davis’ lack of Democrat Steve Westly over Republican state senator close relations with other elected Democrats surfaced Tom McClintock for controller. The conservative even before the election when Lieutenant Governor McClintock, had he won, might well have refused to Cruz Bustamante, running for his own re-election, float the Revenue Anticipation Warrants (RAWs) that raised the Oracle computer contracting scandal in were needed by the time of the next budget. (For odd a TV ad. In the post-election period, Bustamante—who reasons, RAWs are floated by the controller rather than became the de facto Democratic alternative in the 2003 the Treasurer.) In the official tally, the two controller recall—said of Davis, “I’m not his yes man.”4 9 candidates were separated by less than 17,000 votes. After the election, various politicos had a meeting The Schwarzenegger-backed Prop 49 earmarking funds with the editorial board of the Sacramento Bee. Davis’ for after-school activities, in contrast, was adopted campaign advisor Gary South chastised Republican by a margin of over one million votes. Just as Simon state senator Jim Brulte at the meeting over the lack of was not seen as a viable vehicle for addressing voter viable GOP candidates for office at the statewide level. concerns about the budget, so—too—were some 142 “You have no candidates. Now, I know what you’re going to do; you’re going to get somebody, By pushing revenue and programs down to the local oh, Schwarzenegger, he’s rich, he’s famous, he’s level, the proposal avoided Prop 98’s requirement that got a wife who’s a Kennedy… (But) running an new state revenue—such as would accrue under the initiative campaign like Proposition 49 is not even governor ’s tax increase proposal—be partly earmarked in the same ballpark as running for governor… He for K-14 education. Despite the budget squeeze, an might think it is… But it’s not.” 50 expansion of Healthy Families was proposed, i.e., covering more working poor children with public DAVIS’ FINAL BUDGET: 2003-04 health insurance. But there were cuts in other social welfare programs. Additional but uncertain revenue from Indian gaming was projected. The governor suggested the Regents should invest UC pension funds in home construction to create jobs and affordable housing—a suggestion that went nowhere. “I’m greatly honored to be able to lead California for the next four years. There’s no question I’ve been tested by adversity, but I’m stronger and tougher and One proposal that Davis did not make at the time, more determined to do a good job.” but that was already percolating in Sacramento, was —Governor Gray Davis interviewed in early January 2003 51 triggering a hike in the Vehicle License Fee (car tax). When the car tax had been cut earlier—taking money away from local governments which the state then Unlike what was possible at the beginning of his first backfilled—a trigger provision had been included. term, Governor Davis could not promise major new The trigger would raise the tax back up if there were gains in education as his fifth year and second term insufficient state funds for the backfill. In the prior year, in office commenced. There was talk about obtain- Davis had proposed raising the car tax but his proposal ing additional support from the federal government, then was not accepted in the earlier budget deal. protecting homeland security (post 9-11), and creating jobs by releasing previously-authorized bond funds It was unclear exactly who would pull the trigger for infrastructure. In his State of the State address, the or exactly how a determination of insufficient funds governor asked for more authority to make midyear would be made. Later in 2003, however, as the recall budget cuts, a proposal which Republican legislators loomed, the car tax trigger became a major campaign supported but to which Senate President John Burton issue. But in January, the governor made a point of responded with “not in my lifetime.” 52 Davis vowed to reject any budget that did not contain structural re- enacting a bill that would clarify the trigger. However, form (the precise nature of which was not spelled out). there was pressure from local governments to hike the car tax. Jerry Brown, then mayor of Oakland, suggest- When his January budget proposal was released for ed that Davis “with the stroke of a pen” could raise the 2003-04, it contained proposals for income tax, sales tax, car tax so that “we can restore vital police services.” 5 4 and tobacco tax increases. Senate minority leader Jim Brulte, however, quickly declared that he was “not going to vote for a tax increase.” 53 A new wrinkle in the For local governments, the issue wasn’t the car tax per se but that the governor was proposing that the proposed tax plan was that the revenue would be shift- state stop paying the backfill while not raising the ed down to counties—framed as fiscal “realignment”— tax. It appeared that Davis—realizing that the car tax along with responsibilities for various state services. was a major issue for Republicans—was resisting the 143 possibility of such an increase. He may have hoped to i.e., what would happen if no budget changes were have a car tax increase as fiscal bargaining chip later in made. If the projection is exaggerated, but offset by the process. Or he may have hoped that by siding with equivalent cuts in spending, the budget predicament is the Republicans at this stage of the process he might made more dramatic, possibly influencing legislative make them more cooperative later. cooperation. There is no net effect on the projected outcome, but the large gross dollar magnitude might But keeping the car tax off the table proved difficult. jar the legislature into going along. Legislative Analyst Elizabeth Hill criticized the governor for depriving local governments of the Another part of the problem was the time dimension. backfill. “The state made a policy decision to give tax Multiyear projections are routinely compared with the relief (when the car tax was cut), and we think that one-year general fund budget, thus producing the same entity of government that makes the decision a large and shocking comparative number. This about tax relief should bear that burden.” 55 apples-and-oranges approach—multiyear vs. one year —may simply confuse the process of fiscal decision- By late January, the Assembly had proposed a bill making. It is certainly questionable whether sowing that would make midyear spending cuts in 2002-03, confusion produces legislative cooperation or better but effectively linked the cuts to Davis pulling the car eventual results. tax trigger. Davis indicated he would veto such a bill, saying he wanted a “total budget solution” instead. 5 6 Davis was not the first governor to use the apples-and- However, he did not rule out the possibility that the oranges approach to budget presentation approach trigger would eventually be pulled under existing nor, as it turned out under Schwarzenegger, the last. law if the budget problem worsened. Eventually, the Nonetheless, the debate over the size and presentation governor and the controller produced a legal opinion of the fiscal problem created a credibility issue for the that the car tax increase could be triggered by an governor. Lack of any obvious budget agreement in opinion of the finance director. With that opinion February led Moody’s to join the other two rating agencies on the record, the legislature then approved some in downgrading California bonds, the first of three midyear spending cuts. such downgrades by that agency during calendar 2003. AN ENDANGERED GOVERNOR? At about the time the car tax veto was becoming the focus in Sacramento, recall papers were served on the governor, charging him with “gross mismanagement of California Finances.”5 8 Initially, the threat of a recall was not taken very seriously by the Davis Both the legislative analyst and legislative Republicans administration. Serving such papers is merely the first argued that Davis’ proposal for a midyear correction step in the recall process, allowing a voters’ petition to of 2002-03 and for the coming 2003-04 had overstated be circulated. the problem, perhaps to dramatize the real dilemma and pressure the legislature. The new finance director Two prior recalls against Davis had been in fact been —former state senator Steve Peace—attributed served by groups angry over immigration and about alternative projections to a “green eyeshade debate” electricity, but those efforts had dissipated. Recalls had over methodology.57 The controversy centered around also been filed against all earlier governors going back estimates of the so-called “workload” projections, to the mid-1930s, except for two, without success.5 9 144 “This is the sort of thing that they do all the time,” said Gary South, a Davis political advisor. 60 News of the 2003 recall being served when it first surfaced did as the budget situation deteriorated. Moreover, it was considering filing still another initiative earmarking a tax increase for education. not even make the front page of the Sacramento Bee, although it was reported on an interior page. Other public sector unions had potential gripes with the governor. As part of collective bargaining By mid-February, however, the possibility of a recall proposals made by the Davis administration in March began to taken more seriously, although Davis 2003, came a suggestion for furloughs—unpaid reportedly told state attorney general Bill Lockyer as involuntary days of leave—a device used in the 2008- late as May that the recall would not qualify. 61 While 09 budget crisis. Some state unions with contracts the link back of the recall to some Republicans was already in effect were asked to reopen them for apparent, Davis was also vulnerable because of limited concessions. As might be expected, there was little allies within his own party. 62 Early on, however, union enthusiasm for such proposals. Republican legislative leaders were leery of endorsing the recall. Groups such as the California Business When an elected official is served with a recall, he Roundtable opposed a recall as late as June. or she can provide a response before the petition is authorized for circulation. Governor Davis, rather than Anyone—including a Democrat—could run for ignore the effort (one option for such an official), chose governor if a recall made it on to the ballot so the to argue that the recall was the product of sore losers result might be substituting one Democrat for another. in the 2002 election and of right-wingers who were A new Democrat would not be termed out in 2006 and blaming him for a national recession. His response might prove to be more popular than Davis. In the became part of the material petition circulators would early stages of the recall, key Democrats eschewed have to include in future signature gathering. It any ambitions to run. But, of course, they could eventually became part of the official voter pamphlet always reverse course (as Lieutenant Governor Cruz when the recall appeared on the ballot. Bustamante ultimately did). Assembly minority leader Dave Cox initially opposed the recall; “There’s It was unclear until late April whether the recall a difference between being incompetent and corrupt,” proponents would have sufficient resources to mount he said. 63 Nonetheless, the threat of a recall gave a credible petition drive. Up to that point, they did traditional Democratic allies some leverage over the not have the substantial resources needed to pay for governor on budgetary matters. gathering the required signatures. Although there was talk of using the Internet to circumvent the need to The president of the California Teachers Associa- hire sufficient paid signature gatherers, it appeared tion (CTA) pointedly noted, when asked about the unlikely that a spontaneous uprising via the Internet recall, that “Gray Davis is not popular with the CTA, could succeed. However, Congressman Darrell Issa or teachers.” 64 The CTA tended to be affiliated with (R-Vista), who had become independently wealthy in Democrats but could be pragmatic about choosing al- the car alarm business, decided to contribute to the lies. CTA had in fact supported Arnold Schwarzeneg- recall campaign in the hopes of becoming governor. ger ’s Prop 49 the previous November which won voter approval. Prop 49 earmarked funding for after-school Issa turned out to be a more serious gubernatorial can- (and therefore school-related) activities. And CTA was didate in his own mind than in the voters’. Despite his anxious to defend Prop 98’s school funding guarantees success in the car alarm business, he had in his youth 145 been arrested for car theft, although the charges were into the debate. There were already proposals on dropped. More recently, in sensitive the post 9-11 pe- the table to sell state bonds in order to cover state riod, he had charged that airline officials had kept him public pension obligations. Borrowing for a specific off a plane to Saudi Arabia due to racial profiling of expense within the budget is not much different in his Middle Eastern background. The airline in question concept from borrowing for general expenses. But said he had simply arrived for the flight too late. These it was thought that such a bond would avoid the controversies dogged his abortive campaign. constitutional requirement that voters approve general obligation debt increases. But once serious financing had entered the campaign via Issa, it became a real threat to Davis and began to color the budget process. 65 More and more attention Adding to the pressure to come up with new borrowing was the fact that borrowing that had had to be devoted to the recall in an administration already been built into the current year ’s budget in the which insisted on gubernatorial attention to form of a tobacco settlement bond. But in April that everything. As Republican legislators were pulled bond was indefinitely delayed. There were concerns towards support of the recall, they had less incentive at that point that cigarette maker Philip Morris might to produce an on-time budget or otherwise cooperate be forced into bankruptcy due to a pending lawsuit. with the governor. Arnold Schwarzenegger began Such a bankruptcy would make a debt security that to loom as a threat in a possible recall, even before was dependent on tobacco company revenue difficult he formally announced his candidacy. At a dinner to float. celebrating the 25th anniversary of Prop 13 in June, Schwarzenegger quipped, “I just forgot our state Moreover, an important element of the January budget governor ’s name, but I know that you will help me —realignment, i.e., pushing revenue and programs to recall him.” 66 the local government level—was called into question by the Legislative Counsel. A purpose of realignment, THE BORROWING SOLUTION as noted earlier, was to reduce state education obligations under Prop 98, which would otherwise accrue under the governor ’s tax increase proposal. In short, the more that alternatives to general borrowing of the type the Republicans were proposing were Since Republicans were rejecting a tax increase – stymied, the more attractive their rollover borrowing but were not willing to specify a cuts-only package appeared, simply by default. to resolve the budget dilemma—they needed an alternative plan. Essentially, the only way out for them Davis’ own Department of Finance began to flirt was to propose to borrow, a “rollover of a deficit” as with the rollover idea in early May, shortly before Senate minority leader Jim Brulte termed it. 67 Such an the May Revise, although the governor indicated that approach had been used by Republican Governor Pete he was still “not prepared to say” whether or not he Wilson during the budget crisis of the early 1990s. supported the idea.6 9 Ultimately, however, rollover became part of the governor ’s approach. And the idea When the borrowing option fully surfaced, Davis was inherited and adopted by Davis’ successor, Arnold initially was reluctant to consider it and termed Schwarzenegger, after the recall election. the Republican plan as based on “fuzzy math. 68 Nevertheless, the borrowing idea steadily crept 146 T H E M AY 2 0 0 3 REVISE Not surprisingly, given the growing magnitude of the budget problem and the complicating fact of the recall movement, there was no budget agreement at the end of June. And the legislature remained polarized. When the May Revise for 2003-04 was released, it had Two moderates, Republican assemblyman Keith largely dropped the realignment approach, probably Richman (Northridge) and Democratic assemblyman because of the legal uncertainty over whether it would Joe Canciamilla (Pittsburg), tried to put together a avoid Prop 98’s claim on any added state revenue. compromise budget. But they ended up isolated from Governor Davis included a rollover element as their more partisan legislative colleagues. proposed by the Republicans, but continued to include various tax increases including a half-cent hike in Adding to the turmoil was an opinion of the the state sales tax. Given the two-thirds requirement Legislative Counsel that the car tax trigger could not needed for tax increases or for the budget more in fact be pulled, since it was based on the state having generally, however, it was unclear how Davis expected “insufficient” funds for the backfill. Her view was his new proposal to fly. Davis did assume that the that if there was any money left in the general fund car tax would be increased by the trigger mechanism, sufficient to cover the backfill, the tax could not be something not requiring a two-thirds vote in his view. automatically raised. That opinion gave support to Republicans who threatened a court challenge to The legislative analyst provided a cautious note, but a hike in the car tax. Meanwhile, the fact that RAWs indicated that, if everything went exactly as planned, had been floated in June would keep the state in cash the governor ’s rollover plan could work. However, any well into the summer—reducing the incentive to come borrowing plan would have to persuade Wall Street to a quick budget compromise. to finance the rollover. Wall Street was already being asked for a short-term loan in the form of Revenue Anticipation Warrants (RAWs), which were secured in mid-June. S TA L E M AT E A N D CIRCUS A budget stalemate beyond July 1 would create investor doubts over a more extensive rollover. Once the state began its fiscal year without a budget, And the rollover plan—if it entailed long-term the usual forces were set in motion. State controller borrowing—would have to deal with the constitutional Steve Westly warned that certain payments could not requirements that general obligation borrowing must be made absent a budget. Moreover, a recent court be for specific projects—not normal operations—and decision would lead to state workers being paid only must be approved by a vote of the people. An attorney the minimum wage, he indicated, with the rest of their with the conservative Pacific Legal Foundation pointed pay held up until a budget was enacted. The gridlock to the constitutional issue in an op ed, probably on the budget occurred despite the fact that by the intended as a warning that the Foundation would time the new fiscal year began, the governor and both likely file a legal challenge to any borrowing plan it parties in the legislature were in favor of a rollover considered unconstitutional. 70 borrowing plan, pegged at $10.7 billion. However, Republicans did not want to impose a tax increase to pay off the loan; Democrats wanted an earmarked tax hike tied to it. 147 Early in the new fiscal year, the recall moved from up on the recall election ballot, assuming the recall a possibility to a near-certainty. On July 7, recall occurred. It became Prop 54. In addition, there would organizers announced that they had collected enough be a ballot proposition (Prop 53) earmarking a portion signatures to force an election and that the secretary of the general fund for infrastructure, a leftover from of state Kevin Shelley would be receiving the petitions the budget deal for 2002-03. (Props 53 and 54 were shortly. Although a Democrat, Shelley was anxious to defeated in the special recall election.) be viewed as acting impartially and efficiently, perhaps with a future career goal in mind. And he generally Davis’ finance director Steve Peace attracted unwanted was so perceived in handling the recall’s mechanics. media attention by screaming “We need a budget” at Shelley’s goal, however, meant that Davis could not a Republican assemblyman and was reportedly in tears hope the recall would somehow be delayed or derailed at the time. He also denounced some Democrats who because a Democrat was the state’s chief election had inadvertently strategized about the budget near officer. (Ironically, like Davis, but a year and a half an open microphone as “a group of fringe Democrats later, Shelley’s political career also came to a sudden having a goofy conversation.”7 2 When the recall was halt when he resigned in the midst of a campaign officially certified on July 23, Davis said he was going funding scandal.) to fight it “like a Bengal tiger.” 7 3 A recall organizer characterized the atmosphere in Sacramento: “Set up a Even though the recall campaign had officially ended tent; the circus will come.” 7 4 Standard & Poor ’s cut its once the signatures were gathered, Darrell Issa rating of California bonds to BBB. continued to air anti-Davis ads on the radio, now focused on his own candidacy for governor should Davis be ousted. Yet Issa’s opinion poll results put him BUDGET DEAL behind other Republican possibilities. Various lawsuits were filed to block the recall, but in the end—despite Announcement of the recall certification seemed to some legal obstacles—it was certified and plans for the expedite legislative budget negotiations. On July 24, an election went forward. The date of the election was set outline of a deal was reported, although a final version by the Lieutenant Governor as October 7. Even before was not sent to the governor until July 29. It contained a budget was ultimately signed, voters were bending a rollover but—in a partial victory for Republicans toward the recall option. —without a tax increase. Their victory was partial because a business tax credit was eliminated and By the third week in July, there was both a focus on various fees were increased. Nevertheless, the ultimate the budget and various distractions apart from the package contained more cuts than Democrats had recall, all of which created a chaotic atmosphere. Big wanted and the deal tilted toward the Republican student fee increases were approved for UC and CSU side. The opening of the new UC-Merced campus was in anticipation of whatever budget was ultimately delayed. Governor Davis signed the budget on August approved. Some Democrats were proposing to ask the 2, despite his earlier pledge not to sign any budget that state Supreme Court to overturn the two-thirds budget failed to contain structural reform. He vetoed less than and tax rules, citing a vaguely-related case in Nevada. $1 million of spending. An initiative, defeated in 2004, was also circulating aimed at cutting the two-thirds hurdle to 55 percent. 7 1 An elaborate, and legally questionable, strategy was Another initiative, which would outlaw the state’s developed as part of the budget accord to enable keeping racial statistical records, was likely to end a rollover bond flotation. A half-cent of the sales tax 148 normally going to local governments would be cut. The state would raise its part of the sales tax by half a cent and semi-earmark that revenue to pay off the THE BUDGET BECOMES A LEGACY bond. An equivalent amount of property tax would be taken from school districts and used to compensate “I have to stay focused. Believe me, I do not like (the local governments for their half cent loss. The state recall). But that and a dollar will get me a cup of coffee.” —Governor Gray Davis 7 5 would then reimburse the school districts for their loss of property tax revenue that had been given to the locals. This three-step approach—known as the “The public doesn’t care about figures. They have heard “triple flip”—allowed sales tax earmarking without figures for the last five years. Figures and drafts and a sales tax net hike. By itself, however, it did not percentages. And all kinds of things. What people want resolve the constitutional issues of floating bonds for to hear is are you willing to make the changes? Are you general operations and without a vote of the people. tough enough to go in there and provide leadership”? —Recall candidate Arnold Schwarzenegger7 6 After the recall, when Governor Schwarzenegger adopted the rollover approach from Davis, he retained Once a budget was signed, increased public attention the triple flip—which had the inadvertent effect of was drawn to the recall. In a recall election, voters first making future state expenditures contingent on the indicate whether they favor or oppose recalling the of- ups and downs of local property tax receipts. But ficial involved. Then, regardless of their personal vote Schwarzenegger dealt with the constitutional issues by on the recall question itself, they choose among com- putting the matter to the voters in the form of Props peting candidates (other than the targeted official). If 57 and 58 of 2004. He also raised the level of the bond the recall succeeds, the candidate with the most votes authorization well above Davis’ $10.7 billion which takes the office and the targeted official is removed; gave him a future cushion of borrowing ability should there is no runoff. It is possible, therefore, for just un- another fiscal crisis arise. der 50% of the voters to oppose the recall and for some candidate with well under 50% to be elected as the In contrast with Schwarzenegger ’s later rollover, replacement. As Table 2 shows, in the end, the recall Davis’ version sought to avoid the constitutional passed with 55.4% of the vote and Schwarzenegger constraints by creating an entity outside the general received a respectable 48.6%, well ahead of any rivals. fund. The legislature would use the entity to repay the bond by appropriating money annually Organized labor largely backed Governor Davis in to service the debt, technically on a discretionary opposing the recall effort. Funds were allocated to tie basis. The uncertain legal argument was that since up signature gathering firms recall proponents might the legislature formally did not have to appropriate use by paying them to circulate a petition—of no legal the funds (the half-cent revenue), the bond did not significance—in support of Davis. The Democratic represent constitutional “debt.” It is unlikely that strategy of not fielding a candidate soon eroded and such an approach could have succeeded since a court Lieutenant Governor Cruz Bustamante ultimately put challenge to the constitutionality of the bond would his name on the ballot after U.S. Senator Diane Fein- have scared off potential investors. That is, even if the stein made it clear she would not run. (Insurance elaborate scheme was eventually found constitutional, Commissioner John Garamendi announced he would the uncertainty posed by litigation in real time would run but then reversed himself and left the Democratic likely have killed it as a practical matter. field to Bustamante.) 149 The Democratic strategy became “no” on the recall Green Party candidate Peter Camejo focused on tax but (just in case it succeeded anyway), “yes” on increases on the wealthy and reducing fees at UC and Bustamante. Congressman Darrell Issa, who had CSU. As did Huffington, he favored raising taxes on funded the recall campaign, tearfully dropped out and commercial property. Because of the ease of getting on Arnold Schwarzenegger dropped in. Schwarzenegger the recall ballot, well over 100 minor candidates were announced his candidacy on the Tonight Show, and listed, some apparently running for the fun of it and appointing former Governor Pete Wilson as his others to attract publicity. campaign co-chair. Democrat Bustamante, who ultimately came in second When Schwarzenegger became a candidate, Richard in the recall, promised to reduce the car tax and Riordan—whose campaign a year for the Republican substitute taxes on higher-income individuals and nomination had been undermined by Davis—bowed on tobacco. If the legislature would not approve his out as a potential candidate. William Simon—the “tough love” budget program, he suggested he could Republicans’ losing gubernatorial candidate in 2002 go directly to the voters through a ballot proposition —was in the recall race for a time, but also bowed out to implement his plan. 7 7 Schwarzenegger did not eventually as did Peter Ueberroth. Ueberroth was well propose a detailed fiscal plan. But did say that he known in Los Angeles for successfully supervising the would undo Davis’ car tax increase and that he would 1984 Olympics. But his leadership of Rebuild L.A., an propose a constitutional spending cap, a concept he organization set up after the Los Angeles Riot of 1992, raised repeatedly—and without success—during his was not the success his Olympic efforts were. two terms in office. Conservative state senator Tom McClintock was Schwarzenegger quickly distanced himself from the only significant Republican left—other than economic advisor and famous financier Warren Buffett Schwarzenegger—for voters to choose by the time of who criticized Prop 13’s effect on property taxes. And the recall election. Although McClintock was arguably he promised there would be no new taxes, except in the most knowledgeable about the state budget, he emergencies. He was dogged by allegations of sexual never proposed an overall plan for fixing it. But he harassment and made various apologies for past did propose zeroing out the car tax—not just undoing behavior during the later days of the campaign. Davis’ car tax increase—and imposing a spending cap on the state. However, Schwarzenegger generally characterized himself as a practical centrist who favored abortion Independent columnist Arianna Huffington entered rights—despite his Catholic background—and gun the campaign but eventually dropped out towards control. As a wealthy businessman, he would not the end. Her campaign centered on ridding state need support of special interests, Schwarzenegger government of “special interests.” She argued for argued. But his definitions of special interests seemed shifting toward higher corporation taxes and higher confined to unions and Indian gaming tribes. Other taxes on commercial property—a position that would commercial interests did contribute to his campaign require modification of Prop 13—but favored undoing and continued to do so during his governorship. Davis’ car tax increase. In an era when use of the Schwarzenegger promised to institute an “audit” of Internet for political campaigns was still developing, the state government to uncover inefficiencies. her website included amusing animated cartoons. 150 FA S T F O R W A R D : Governor Davis had to take stands on the various bills crossing his desk during the recall campaign. He signed a bill allow drivers’ licenses for illegal THE BUDGET CRISIS immigrants although he had vetoed a similar bill in OF 2008-09 AND the past. Opponents charged that the governor was desperately seeking Latino votes. (And the legislature BEYOND quickly repealed the license law after Schwarzenegger took office.) “Our elected officials in Sacramento are facing Davis signed a hastily-drafted employer-mandated a budget crisis unseen in this state since the health insurance plan (which voters subsequently Great Depression, and it was entirely avoidable… repealed in a 2004 referendum). Republicans charged California’s future is in danger.” that the Davis administration was signing off on —Candidate Arnold Schwarzenegger during the 2003 recall campaign 7 9 state union contracts without obtaining sufficient pay concessions. Meanwhile, a court decision blocked sale of a pension bond without a vote of the people. And “It’s abundantly clear that just because you change Davis’ rollover bond mechanism was challenged in governors you don’t change the financial condition of court—as expected—by the Pacific Legal Foundation the state.” on constitutional grounds. —Former Governor Gray Davis commenting on the 2009 budget crisis8 0 Anything that suggested the budget was not yet under control was unfavorable for Davis. Moreover, On taking office, Arnold Schwarzenegger was in many the unpopular car tax hike went into effect October 1, respects the complete opposite of Gray Davis. He was only a few days before the October 7 recall election. ebullient, optimistic, and—of course — After the recall succeeded and Schwarzenegger took a celebrity, not someone initially elected, as Davis was, office, the first official action he took was repealing with a reputation as a competent, professional public the car tax hike. Although as governor he periodically administrator. But Schwarzenegger could be unfocused defended that action, it immediately worsened the with too many goals, albeit popular goals. budget situation he inherited. And the car tax repeal continued to be an issue into the next budget crisis Davis came into office focused on education. He of 2008-09, when the car tax was again raised. But on retained that emphasis as long as the budget was flush. the night he won office in the recall, Governor-elect However, Davis’ tendency to micromanage produced Schwarzenegger promised the voters that “I will not a variant of lack of focus—since it is impossible to fail you, I will not disappoint you, and I will not let handle everything once difficulties are encountered. you down.” 78 Thus, early warning symptoms of the electricity crisis were missed. And the evolving budget crisis of the early 2000s eventually overwhelmed everything else, despite early denials by the governor ’s finance director that anything was amiss. 151 A RENEWED BUDGET CRISIS on environmental issues, hydrogen highways, and greenhouse gases. That agenda won him international acclaim and even an invitation to address the United Nations. But neither the state budget nor proposals for The budget crisis of the early 2000s was clearly state health care could be passed at the UN. the major factor in the recall of Davis and Schwarzenegger ’s election as his replacement in In the end, the health plan failed—in part due to 2003. Initially, because he inherited that crisis, wandering gubernatorial attention. There was only Schwarzenegger did focus on fiscal affairs, putting a narrow window of opportunity to pass a potentially- the Davis borrowing plan into effect but doing so costly health plan before renewed budget pressures through clearly legal means. Schwarzenegger used his became apparent. And the window had closed by the initial popularity to win voter approval of the needed time a full plan was readied for legislative action in (one-time) constitutional changes in 2004 under late 2007. The plan was passed in the Assembly but Propositions 57 and 58 to permit the borrowing. But rebuffed in the Senate as too risky to enact in the face the new governor took to feuding with the legislature of a deteriorating fiscal situation. the following year, putting a series of initiatives before the voters in 2005 as part of his “Year of Reform.” By 2008, a renewed California state budget crisis was Only one of these propositions was directly linked to well underway. 8 3 Continued fiscal deterioration the budget. And all failed at the ballot box while the led to a budget stalemate— and no budget—during governor ’s popularity plummeted. 81 the summer of 2008. During that summer, Governor Schwarzenegger dropped his opposition to a tax in- Part of the problem in 2005 was that during crease and advocated one. Ultimately, the stalemate Schwarzenegger ’s campaign for the two 2004 lasted two and a half months, exceeding even the two- borrowing propositions, he oversold what they could month record delay set under Davis. Moreover, the accomplish to the public. Voters were assured that the new budget, enacted in mid-September 2008 without two measures would solve the state’s fiscal problem the governor ’s proposed tax increase, quickly unrav- and that afterwards the state would be able to “throw eled. GOP opposition to Schwarzenegger ’s tax pre- away the credit card.” Instead, the state lived off the scription blocked the tax proposal he initially made. reserve that resulted from 2004 borrowings, aided by the improved economy, until 2007. A midyear revision of the 2008-09 budget was enacted in February 2009, this time raising taxes as well as cut- After the stinging rebuff he suffered the Year of Reform ting expenditures. The February deal also included an campaign of 2005, and with the 2006 gubernatorial early budget for 2009-10. However, the enacted budget election coming up, Schwarzenegger switched to was partly dependent on a series of budget proposi- promotion of the construction state infrastructure—to tions that voters largely rejected in May 2009. That be financed by more borrowing. A seemingly no-cost rejection and continued economic deterioration led to expansion of infrastructure appealed to the electorate new negotiations for a revised budget for 2009-10. and the governor was re-elected by a strong margin. In 2007, the gubernatorial theme became adoption of California began the new fiscal year (2009-10) with the a state universal health care program, promoted as old February budget still in place. In contrast to prior self-supporting, but in fact with some budget risks. 82 However, Schwarzenegger ’s attention in 2007 was also 152 years, when there was no budget on July 1, the state was authorized to spend. But it lacked the cash to pay for all the authorized programs. By early July, the state were. Despite this expectation, by 2009, the nation controller began issuing registered warrants (IOUs) was treated to pundits pointing to California as instead of cash for some payments. A budget revision ungovernable. Metaphors of sinking ships and cars deal reached in late July ostensibly fixed the renewed running off cliffs were common as were references to fiscal problem. It involved real cuts but much de facto failed states and third-world countries. and overt borrowing, questionable expected sales of state assets, and dubious savings and forecasts. One The fact that different governors ended with similar Democratic advisor rationalized the outcome on the results suggests a structural interpretation. But typi- grounds that it was necessary to “distinguish be- cally, the structures to which reference is made are tween the best possible solution and the best solution institutional in a political sense. The usual suspects possible.” 84 But the fear was that there had been no fundamental solution. are Proposition 13, the two-thirds vote requirements for new taxes and budget enactment, term limits, voter mandated spending and spending formulas, gerry- In particular, the new deal seemed unlikely to produce mandered legislative districts, and polarized political a positive or even zero reserve, given further economic parties. And so the remedies suggested generally re- decline. Litigation was threatened by local govern- volve around political solutions such as new corrective ments as the state dipped into their treasuries. Not all initiatives or even a constitutional convention. elements of the ostensible solution passed. The prison budget was to be cut in the face of legally-questionable inmate overcrowding but the specifics of how a re- A N U N D E R LY I N G duced prisoner population was to be accomplished REALITY was left to be determined. In effect, the legislature dared a federal court to make the reductions. Although the Obama administration was trying studiously to Despite the tendency to focus on them, political avert its gaze from California’s fiscal drama, the pos- institutions are not created exogenously. There may sibility (or hope) remained that there would eventually well be a more fundamental economic reality beneath be federal assistance of some type. those institutions. Going back to gold rush days, California generally grew faster than the rest of the S I M I L A R R E S U LT S U.S. But California became an elderly state in the late 19th and early 20th centuries, along the lines of Florida today. People came from the cold Midwest to retire We started with the obvious question of whether in the sunshine, or at least to live out their days in a leadership matters in California. As outlined below, warm climate. With many folks thinking about the Gray Davis and Arnold Schwarzenegger had very hereafter, the state produced religious innovations, different types of personalities, backgrounds, and quack remedies, and invented the commercial leadership styles. Yet the Schwarzenegger budget cemetery. It also produced wacky “pensionite” crisis of 2008-09 seemed similar to the Davis crisis movements that cemented the state’s image as a place of the early 2000s. Voters had apparently thought where oddities were the norm. that by recalling Davis and replacing him with Schwarzenegger, they would resolve the state’s budget But at the same time, the nice weather had attracted woes. The man on the white horse would ride in and movie making and airplane manufacture in the south defeat the bad guys in Sacramento, whoever they in the early twentieth century. And in the Bay Area, 153 two guys named Hewlett and Packard were tinkering growth resumed. 8 5 But by the end of the 1980s, with electronic equipment in a garage in the late 1930s. the Soviet Union was dissolving and aerospace in With the impetus of World War II, which brought California was substantially downsized, removing a veritable population explosion to the California to a base of high-wage jobs from the state. Immigration work in military production, California became —reflecting developments in Mexico and others parts a youth culture. After the War, returning GIs came of the world—brought in new job-seekers, but biased back to stay. And after a pause, military needs of the toward the low-wage end of the scale. Cold War, augmented by the hot Korean and Vietnam Wars, kept federal money flowing to the state’s A new downturn and budget crisis was left by aerospace industry. Deukmejian to his successor, Governor Pete Wilson, first elected in 1990. Wilson wrestled with a budget California continued to experience rapid growth crisis for much of his initial term.8 6 And he often compared with the U.S. as a whole. Land and housing focused on illegal immigration as fiscal burden for was cheap. Suburbs could be built on low-cost farm the state. Much of his successful re-election campaign land. The growth provided tax revenues to expand in 1994 centered on the immigration issue and on freeways and water projects, to fund a highly regarded Prop 187, an initiative aimed at barring use of public K-12 educational system, and to create new public services by illegal immigrants. colleges and universities. By the mid-1960s, California became the largest state in the nation. As Chart 3 shows, California never really recovered from the recession of the early 1990s. The problem Growth comes at a cost, however, particularly in that had developed by the late 1970s finally became the face of heightened environmental sensitivities. apparent once the growth accompanying the end-stage Concerns arose about air and water pollution, of Cold War military spending was removed. Relative congestion, and the quality of life for those already in to the old trend, job growth in the state lagged, even California. Whereas Governor Pat Brown in the 1960s during recovery and even during the dot-com boom is remembered for infrastructure expansion, his son and the later housing boom. California, in short, Jerry Brown was elected governor in 1974 touting “an has been enmeshed in a decades-long process of era of limits.” As population growth pressed against converting from a state characterized by supernormal land and housing supply, property values rose. So did growth to a more average state. property tax assessments and bills, leading to Prop 13. Various “slow growth” movements followed, limiting Voter expectations about public services have lagged new development. A major water project was rejected in recognizing this underlying shift. In the context of by voters in the early 1980s. direct democracy, the result is a string of uncoordinated actions by initiative which mandate spending and California experienced a budget crisis in the early weaken the legislature. While voters tend to see the 1980s. However, that period was also the era of governor as a kind of CEO who can fix the resulting President Reagan’s “evil empire” which gave a new fiscal strains, a weakened legislature inherently weak- fillip to aerospace activity and temporarily masked ens the governor. Ultimately, it is the legislature that the underlying shift. The budget crisis was eventually has to act on budgets and other state programs. resolved under Governor George Deukmejian when 154 Chart 3: California Nonfarm Employment History & Forecast Vs. 2.3 % Trend from 1990:3 22000 20,000 T ho usand s 18,000 16,000 14,000 12,000 10,000 8000 1986 1991 1996 H i s t o r y & F o re ca s t 2001 2006 2011 2 . 3 % Tre n d L i n e Source: UCLA Anderson Forecast (June 2009). A ROLE FOR LEADERSHIP Some governors have pointed to underlying causes but not the whole picture. As noted, Jerry Brown’s “era of limits” suggested the rising cost of growth and a structural shift. But when it came to the major political consequence of the shift, Prop 13, Brown was either distracted or bemused and—in the end— flipflopped from opposition to the proposition before it passed to support afterwards. 8 7 Deukmejian took the taxpayer revolt as a given and the last gasp of the Cold War helped pull the California economy back on track. In any case, he had little incentive to look for an underlying shift that was being temporarily obscured. and ultimately did navigate the state out of the budget crisis of the early 1990s. But his preferred remedy, in effect state control of immigration via Prop 187, was doomed to fail since immigration control is the province of the federal government. Subsequent litigation largely voided Prop 187. Finally, neither Gray Davis nor Arnold Schwarzenegger focused on underlying trends. Davis came into office during the dot-com boom when, despite the employment lag shown on Chart 3, the budget position of the state was temporarily strong. Ultimately, Davis viewed his fate as a function of the short-term business cycle. “Nobody seems to understand that the economy is like the tide,” he complained. “When you’re in high tide no one thinks low tide is coming.”8 8 Wilson looked at the demographic element as an underlying cause of California’s budgetary problems 155 Schwarzenegger tended to point to the political symptoms of the underlying shift. His suggested political reforms, such as a larger rainy-day fund, would help at the margin. But his communications skills were never pointed toward acquainting the public with the difficulties the underlying economic shift entailed and the implications for public policy. Probably, his natural tendency toward optimism made it difficult to contemplate the idea that California had become a normal state in terms of its growth potential. The Bad News is that California’s virtuous circle of growth leading to revenue to supply the infrastructure for more growth began coming to an end in the 1970s. The state’s size help obscure that reality. California politicians often point to the fact that if the state were a country, it would be the 6 th or 7th largest in the world. But apart from electoral votes, size doesn’t matter. The Good News is that being average is not a terrible fate—if only California could find a leader to make the challenges of the transition explicit. Perhaps voters now realize that expecting a man (or a woman) on a white horse to fix the state’s fiscal problem is unrealistic. The question is whether whoever emerges from the 2010 gubernatorial election will be willing to acquaint voters with the idea of California as a normal state. 156 157 1 Available at- 2009/18213/2009-keynote-address. 2 PBS NewsHour. February 11, 1999. Transcript available at CA_2-11.html. Quoted in Dan Smith. “For Davis, dream comes alive today.” Sacramento Bee, January 4, 1999. 3 12 13 Quoted in Steven A. Capps. “No frills first budget from Davis.” Sacramento Bee, January 9, 1999. The narrative in the material that follows is taken mainly from press information, mainly the Sacramento Bee. Footnote references are 14 confined mainly to direct quotes. status quo.” Sacramento Bee, January 12, 1999. 4 15 Quoted in Dan Smith. “Friction grows between Davis, Quoted in John Jacobs. “Gray Davis’ first budget: Distinctly Quoted in Steven A. Capps. “Davis tells how he would use Democratic lawmakers.” Sacramento Bee, July 22, 1999. surplus.” Sacramento Bee, May 15, 2009. 5 16 Available at Quoted in Dennis Love. “Initiative backers hope to drive car documents/inaugural_37.html. tax into ground.” Sacramento Bee, May 21, 1999. 6 17 James Glassman and Kevin A. Hassett. 1999. DOW 36,000: The new strategy for profiting from the coming rise in the stock market. New York: Times Business. 7 Davis inherited a lawsuit challenging the almost-complete voiding of Prop 187 by a court. Bustamante wanted Davis to drop Quoted in Steven A. Capps. “Davis reneged on budget deal, GOP says.” Sacramento Bee, July 2, 1999. 18 Quoted in Dan Smith. “Friction grows between Davis, Democratic lawmakers.” Sacramento Bee, July 22, 1999. Wilson’s appeal. Davis followed a strategy of agreeing to “mediation” 19 of the dispute – which essentially would result in the state agreeing to billion budget.” Sacramento Bee, January 11, 2000. Note: The $88 accept the court decision. billion figure in the headline refers to the entire budget, not just the 8 Quoted in Steven A. Capps. “Davis offers ‘prudent’ $88 general fund. Michael Bustamante quoted in Dan Smith. “Davis underlings squirm under his iron-grip leadership.” 20 Sacramento Bee, February 21, 1999. with funds, critics urge.” Sacramento Bee, January 6, 2000. 9 21 Quoted in Dan Smith. “On the job nearly 100 days, Davis quieting critics.” Sacramento Bee, April 11, 1999. 10 Hilary McLean quoted in Stephen Green. “Key jobs in state Quoted in Steven A. Capps. “No frills first budget from Davis.” Sacramento Bee, January 9, 1999. 158 Quoted in Steven A. Capps. “State budget picture gets even rosier – Projection for surplus up $3 billion.” Sacramento Bee, January 14, 2000. Brulte succeeded minority leader Ross Johnson who stepped remain unfilled – critics.” Sacramento Bee, October 31, 1999. 11 Garry South quoted in Amy Chance. “Back education plans down unexpectedly in late April 2000. 22 Eastin reportedly had favored a Davis rival in the 1998 gubernatorial primary. Dan Walters. “Davis doghouse gets crowded.” Sacramento Bee, January 27, 2000. ENDNOTES 23 An earlier ballot measure in March 2000 sought to reduce the 33 Quoted in John Hill. “Cut budget by $1 billion, Peace says.” hurdle to a simple majority but it failed. Sacramento Bee, June 6, 2001. 24 34 Sandy Harrison quoted in Steven A. Capps, “State expects budget surplus – Revenues increase for fifth year in a row.” Sacramento Bee, November 16, 2000. 25 Phil Troustine quoted in Steven A. Capp, “Senator seeks $2 Quoted in Jim Sanders. “Cox-led GOP puts its dukes up.” Sacramento Bee, July 1, 2001. 35 The trigger under a 1991 law would be pulled if the reserve in the general fund fell below four percent. The eventual compromise billion to stabilize power rates.” Sacramento Bee, November 21, 2000. described below dropped the figure to three percent. 26 36 See Steven A. Capp, “Senator seeks $2 billion to stabilize Simon was the son of a former U.S. Secretary of the power rates.” Sacramento Bee, November 21, 2000. Treasury, giving him name recognition. 27 37 Roger Peters quoted in Carrie Peyton. “PUC weighs power hikes – Hearing starts with utility pleas.” Sacramento Bee, December 28, 2000. 28 Quoted in Dan Smith. “Davis offers power fix – He urges greater state role to end ‘energy nightmare.” Sacramento Bee, January 9, 2001. 29 Werner Z. Hirsch and Daniel J.B. Mitchell. “Surplus? California is running a deficit.” Los Angeles Times, February 12, 2001. Quoted in Emily Bazar. “Riordan blasts Davis over spending.” Sacramento Bee, December 8, 2001. 38 Quoted in Dan Walters. “Davis’ State of State address sounds more like a campaign speech.” Sacramento Bee, January 9, 2001. 39 Quoted in Herbert A. Sample. “Davis rival airs plan to end deficits.” Sacramento Bee, January 12, 2002. Finance director Tim Gage’s letter to the editor denying that there 40 was a deficit appeared on February 23, 2001. Although the figures Prop. 98 funds.” Sacramento Bee, April 16, 2002. have been revised by the Department of Finance since that time, they continue to show a deficit. 30 41 Quoted in John Hill and Dan Smith. “Davis fears lack of Dan Walters. “Behind scenes of budget battle, squabbling erupts within parties.” Sacramento Bee, July 3, 2002. Elizabeth Hill quoted in “California’s wild ride – Budget analyst charts the risks ahead for lawmakers.” Sacramento Bee, 42 February 27, 2001. (Editorial). But there’s early support for a pair of school measures.” Sacramento 31 Amy Chance. “Voter initiative trailing, poll finds – Bee, July 18, 2002. Quoted in John Hill. “Budget plan shrinks – Davis responds to an uncertain economy but preserves a boost in education funding.” 43 Sacramento Bee, May 15, 2001. – Schwarzenegger puts his muscle behind after-school measure.” 32 Quoted in Gary Delsohn. “Prop. 49 would aid schoolkids Sacramento Bee, October 6, 2002. Quoted in Daniel Weintraub. “Davis gambles big on his state budget proposal.” Sacramento Bee, May 17, 2001. 159 44 Op ed by Assembly Republican leader Dave Cox. “Leadership from Davis missing in budget impasse.” Sacramento Bee, August 18, 2002. 45 Davis and Simon quoted in John Hill. “Davis quietly 57 Quoted in Dan Walters. “Davis’ credibility dented again by conflict over deficit number.” Sacramento Bee, January 17, 2003. 58 The charges and the governor ’s response can be found in the official recall ballot pamphlet available at approves budget.” Sacramento Bee, September 6, 2002. voterguide/english.pdf. 46 59 Davis reported spent $77.8 million on his campaign Governors Earl Warren and Goodwin Knight were not compared to Simon’s $36.4 million. Source: Margaret Talev. “Davis targeted with recalls. The first governor to be targeted was Frank raised record amount.” Sacramento Bee, February 1, 2003. Merriam. A brief history can be found in Margaret Talev. “Recall 47 attempts old hat in state.” Sacramento Bee, June 9, 2003. Quoted in Margaret Talev. “State GOP chief seeks to punish big business.” Sacramento Bee, December 10, 2002. 48 Gary South quoted in Alexa H. Bluth. “Lots of recall talk aimed at governor.” Sacramento Bee, February 5, 2003. Elizabeth Hill quoted in John Hill. “Huge budget gap looms again.” Sacramento Bee, November 15, 2002. 49 60 61 Margaret Talev. “Fighting back – Davis arrives late at idea that the recall drive is serious.” Sacramento Bee, August 3, 2003. Quoted in Margaret Talev. “No. 2 seeks his own place in spotlight – Bustamante is even willing to ding Davis in the process.” 62 Sacramento Bee, November 21, 2002. of People’s Advocate – the filer of the recall – to coordinate. 50 See Margaret Talev. “Davis recall is gaining traction.” Sacramento Bee, Quoted in “Postmortem on an election.” Sacramento Bee, November 17, 2002. 51 Quoted in Margaret Talev. “Davis will ask Bush to ease the state’s pain.” Sacramento Bee, January 6, 2003. 52 Quoted in Amy Chance. “As both parties dig in, epic budget battle looms.” Sacramento Bee, January 9, 2003. 53 Quoted in Margaret Talev. “Davis’ budget plan likely faces series of makeovers.” Sacramento Bee, January 12, 2003. 54 California Republican party chair met with Ted Costa February 11, 2003. 63 Quoted in Margaret Talev. “GOP leader Cox says he won’t back Davis recall try.” Sacramento Bee, February 19, 2003. 64 Wayne Johnson quoted in Margaret Talev. “Davis recall is gaining traction.” Sacramento Bee, February 11, 2003. 65 About 900,000 of the 1.6 million signatures turned in were reported to have been obtained by paid signature gathering firms. So about 700,000 were gathered by volunteers. About 900,000 were needed to qualify the recall and many signatures on voter petitions Quoted in Ed Fletcher. “Governor holds line against fee turn out to be improper and are rejected. Thus, without the paid hike – He rejects Jerry Brown’s tax increase is needed to fight crime.” signature gatherers, a pure volunteer effort was unlikely to succeed. Sacramento Bee, January 23, 2003. Data from Daniel Weintraub. “Facts and fiction about the California 55 recall election.” Sacramento Bee, October 7, 2003. Quoted in Alexa H. Bluth. “Study backs Davis budget proposal.” Sacramento Bee, February 20, 2003. 56 Quoted in Dale Kasler, “Buffett interview ignites controversy.” Sacramento Bee, August 16, 2003. Quoted in John Hill, “Davis: I’ll veto auto fee hike.” Sacramento Bee, February 5, 2003. 160 66 67 Quoted in Alexa H. Bluth. “GOP wants to roll over portion of state’s deficit.” Sacramento Bee, February 17, 2003. 68 Quoted in John Hill and Alexa H. Bluth. “Budget proposal Quoted in Alexa H. Bluth and Margaret Talev. “Wall St. 80 Quoted in “Just in: Kennedy whacks Davis, more on gov 81 Daniel J.B. Mitchell. “‘They want to destroy me’: How California’s fiscal crisis became a war on ‘big government Harold Johnson, “Does ‘Casserly’ mean anything today?” Sacramento Bee, July 1, 2003. 71 State sank into budget morass.” San Francisco Chronicle, money.” Calbuzz.com, July 2, 2009. warns state of borrowing’s risk.” Sacramento Bee, May 8, 2003. 70 Quoted in Carla Marinucci and Matthew Yi. “How Golden June 28, 2009. unveiled by GOP.” Sacramento Bee, April 30, 2003. 69 79 During the budget crisis of 2008-09, such a lawsuit was filed unions.’” WorkingUSA, vol. 9 (March 2006), pp. 99-121. 82 Daniel J.B. Mitchell. “Something different in the air? The collapse of the Schwarzenegger health plan in California.” by former UCLA Chancellor Charles Young. WorkingUSA, vol. 11 (June 2008), pp. 198-218. 72 83 Quoted in Alexa H. Bluth. “Davis fiscal chief loses cool over Daniel J.B. Mitchell. “Division of labor: California’s renewed failure to pass a budget.” Sacramento Bee, July 23, 2003. budget crisis splits the union movement.” Forthcoming, WorkingUSA. 73 84 Quoted in Margaret Talev and Laura Mecoy. “Recall petitions certified – Historic vote to be held by early October, Shelley says.” Sacramento Bee, July 24, 2003. 74 David Gilliard, director of Rescue California, the pro-recall group, quoted in Margaret Talev and Laura Mecoy. “Recall petitions certified – Historic vote to be held by early October, Shelley says.” Sacramento Bee, July 24, 2003. 75 Quoted in Margaret Talev and Laura Mecoy. “Recall petitions Sacramento Bee, July 24, 2003. Quoted in Daniel Weintraub. “Poised Schwarzenegger is vague on fiscal details.” Sacramento Bee, August 21, 2003. 77 85 Daniel J.B. Mitchell. “‘I never knew it could be like this’: Lessons from the 1980s for California’s budget crisis.” Municipal Finance Journal, vol. 29 (Winter 2009), pp. 101-124. 86 Daniel J.B. Mitchell. “‘Duke, Is there perhaps something you budget.” Southern California Quarterly, vol. 90 (Winter 2008-2009), pp. 379-418. 87 Daniel J.B. Mitchell. “When luck runs out: Leadership – past the present – and the California state budget” in Daniel J.B. Mitchell (ed.), California Policy Options 2009. Los Angeles: UCLA School of Public Affairs, 2009, pp. 29-72. John Hill. “Bustamante unveils plan to fix state fiscal woes.” Sacramento Bee, August 20, 2003. 78 but it’s our mess.” Los Angeles Times, July 23, 2009. forgot to tell me?’: Pete Wilson’s first-term struggle with the California certified – Historic vote to be held by early October, Shelley says.” 76 Rick Simpson quoted in George Skelton. “Budget’s a mess, 88 Quoted in Wyatt Buchanan. “Ex-Gov. Davis reflects on fiscal crisis.” San Francisco Chronicle, July 3, 2009. Quoted in Margaret Talev. “It’s Arnold – Schwarzenegger coasts to victory as Davis is ousted in historic vote.” Sacramento Bee, October 8, 2003. 161 8 162 CALIFORNIA’S V O L AT I L E TA X E S : HEALING A SELF-INFLICTED WOUND JERRY NICKELSBURG Jerry Nickelsburg is a Senior Economist with the UCLA Anderson Forecast. He received his PhD from the University of Minnesota and has written extensively on public policy, econometrics and the California Economy. He has held positions at The Board of Governors of the Federal Reserve, University of Southern California, Douglas Aircraft, FSI, The Boeing Company, and is a Fulbright Scholar. 163 8 Those who think California lacks seasons miss the well-defined season of discord in Sacramento’s halls of government. The drama of the fiscal budget season is made all the more complex and interesting by its reliance on revenue estimates; estimates which are at best a moving target. Revenue “shortfalls” for the combined 2008-09 and 2009-10 fiscal years were described at times as $12 billion, as $40 billion dollars and as $60 billion.1 This was a huge margin of error when one considers that the 2007 fiscal year general fund was $103 billion. Regardless of the forecast one uses the adjustments in spending, borrowing and taxation are huge. How does it happen that the state has been faced with budget adjustments of this size on four different occasions this decade? It stretches credulity to lay the blame solely on irresponsible spending. Rather, spending is typically multi-year and implicit in the approval of spending is a forecast of revenues sufficient to sustain that spending. 2 The systemic volatility in California’s revenues make these revenue forecasts unreliable. In this chapter, the source of that systemic problem is analyzed. One solution to alleviate volatility in California tax revenues is proposed. The solution proposed is clearly not the only route to less volatility, but rather a vehicle to demonstrate what must be done if California is to avoid a continuation of the repetitive severe revenue shortfalls of the 2000s decade and earlier. 164 REPETITIVE CRISES, PROP 13, AND GOVERNMENT SPENDING of the economy, an analysis of this side of the equation is more a study in political science than economics. The revenue side also has a political element: defining the structure through which revenues will be raised. But once defined, the amount of revenues is not in the direct control of the political structure. There is, of course, no clear answer as to whether or The crisis of the late 2000s had a familiar ring to not there is sufficient energy in California for reform. it. Steven Hayward of the National Review called it Only time will tell if the body politic is ready to force California’s “once-a-decade crisis” (although there fundamental change. But we can better understand 3 were in fact two crises in the 2000s). Citing the what the issues are, and how they affect the prospects budget problems of Governors Reagan, Wilson and for future crises in Sacramento. especially Davis, he points to the current crisis as a particular home-grown California malady. Much has been made of the spending side of the equation REVENUES and, indeed, California’s 2/3 majority requirement for approval of budgets, legislation by referendum, The most important issue is on the revenue side. and locked-in expenditures. These components of If revenue streams grew at a known constant rate each state budgeting create friction in the system which year, it is unlikely that there would be the kind of makes spending and taxation changes all the more chaos seen during the crises of the 2000s. Such a Polly- challenging. anna world would not eliminate all of the problems as the executive and legislature branches of government Robert Wassmer ’s 2006 study of the recurrent crises would still have conflicts over their own priorities and concluded that Proposition 13 of 1978 has made with voter initiative priorities. And there would still the problem one of expenditure management by be an inconsistency between the time horizons of state Sacramento. By sharply cutting local property taxes, business and those of political careers. But without the Prop 13 forced a reliance on a pro-cyclical state wide swings in revenue engendered by the existing tax 4 revenue stream. Dan Walters of the Sacramento Bee system, California would not have the fiscal disasters stated “whether the state’s fiscal problem is too much it regularly develops. spending or too little revenue, of course, is much like beauty or art, largely dependent on the eye of the beholder.” 5 But there is more to it than just that. EXPENDITURES PROPOSITION 13 As noted, it is common blame fiscal swings on Prop 13. Indeed there are a number of studies of California’s fiscal problem which assume that a discrete break in The expenditure side is a political decision. Califor- the pattern of fiscal affairs occurred in 1978 with the nians through their legislators, governor, and ballot passage of Prop 13. 6 “If only property taxes could propositions make explicit decisions on what to spend have risen, we would have had more revenue than we state revenues. While dictated somewhat by the health have today,” is a common refrain. Of course, states 165 with higher property taxes have other taxes which are projected expenditures. In that sense, they are not real lower, so this conclusion does not necessarily follow. data. They are guidelines for the budget process which Although property taxes in California are lower than are based upon forecast assumptions by state gover- average for U.S. states, they are not much lower. nors, legislatures and independent revenue boards. Prop 13’s restrictions on property assessments and Moreover as events change, so do the estimated tax rates should not be confused with property tax shortfalls. The underlying phenomena these shortfall revenues. Suppose we were to assume that Prop 13 estimates are trying to capture are actual expenditures restrictions on property tax assessments and property and revenues. Each will be affected by decisions made tax rates did not exist and that California’s general by state government based upon projected shortfalls. fund were supported entirely by property tax receipts (although property taxes are in fact local). Then Revenues could be greater due to new taxes and revenue would have fallen by 29% from its peak in expenditures could be less due to spending cuts. fiscal year 2006 to fiscal year 2009 compared to the 17% Nevertheless, the volatility of the underlying data, decline in actual revenue experienced. 7 particularly with respect to tax revenue, ought to characterize the shortfall/budget adjustment process. Although there is some truth in the view that property If actual tax revenue were growing at a constant taxes are a tool which, under certain circumstances, rate, and therefore not volatile, one would not expect could be used to stabilize the state budget, they are budget crises to appear. Similarly, if underlying tax clearly not the source of the volatility problem. As will revenue is highly volatile, one would expect to see be shown, the volatility of tax revenues is, as Gamage either expenditure smoothing over time or recurrent suggests, traceable to California’s income tax. But the budget crises. relationship is more subtle than he finds and—as it turns out—it is not a construct of Prop. 13. 8 The total volatility of general fund tax revenue is given by the sum of the volatility of each of the taxes V O L AT I L I T Y A N D RELIANCE ON D I F F E R E N T TA X BASES that make up the general revenue adjusted for the co-variation of the taxes. If a state hypothetically relied on three taxes—sales, income, and property— mathematically this could be represented as: Va r i a nc e ( g e ne r a l f und ) = Va r i a nc e ( I nc ome Ta x ) + Va r i a nc e ( S a l e s Ta xe s ) + Va r i a nc e ( Prop e r t y Ta x e s ) + 2x Cov a r i a nc e ( I nc ome Ta x a nd Sa l e s Ta x) + 2 x C o v a r i a n c e ( I n c o m e Ta x a n d P ro p e r t y Ta x ) + 2x Cov a r i a nc e ( S a l e s Ta x a nd Prop e r t y Ta x ) The National Conference of State Legislatures prepares a study of forecast impending budget “shortfalls” (that Fluctuations in general fund revenues from Income is, projected shortfalls if nothing were to be done) for Taxes, Property Taxes and Sales Taxes are normally 9 each state each year. California is in the unenviable positively correlated and thus the Covariance terms position of making the top-10 list more often than oth- add to the variability. So, it is not just the reliance on er states. These projected shortfalls result in the budget a particular tax that matters. The structure of the tax crises we continually experience, but shortfalls are can induce more or less variability than the inherent simply the difference between projected revenues and variability of the underlying tax source. Prop 13 broke 166 the link between economic conditions and property fornia for local government revenue on property taxes. assessments and lowered the overall variability of If the state government makes transfers to the local California’s local property tax collections. governments in lieu of property taxes, then while the state does not rely on property taxes for its own TA X S T R U C T U R E revenue generation, property tax revenues could still have an important impact on the state budget. And, in fact, California is in the top-10 states when it The tax structure of California can be compared to comes to transfers to local governments. In the years other states using the data from the U.S. Bureau of immediately following Prop 13’s passage, California the Census and shown in Figures 1-5. 10 These data are consistent in definition across states, although ran deficits in part to pick up the slack in local government revenues with increased state transfers. 1 2 revenue categories are not exactly the same as used by the California Department of Finance. Although But, California is the only one of the top-10 states the California’s shortfalls are blamed by some on to appear in either the fiscal 2008/2009 or the fiscal Proposition 13, an examination of state reliance on 2009/2010 National Conference of State Legislator ’s property taxes shows that most states do not utilize fiscal stress list. Indeed the Los Angeles Times property taxes as a source of revenue. reported that local governments were finding that by not moving assessments each year with the swings in P R O P E R T Y TA X the current market value of properties, Proposition 13 has been a stabilizing factor in property tax generation. 1 3 So, from the revenue side, California’s California, like most states, does not have a state budget woes are not about Prop 13. property tax per se. There are certain levies which flow through the state government, but they are not revenue sources for state expenditures. These are included in the Census data and incorporated here for completeness. (It appears that the so-called “car tax,” a kind of property tax on motor vehicles, is treated in these data as California state revenue, although the state remits the proceeds to local governments.) As can be seen from Figure 1, for all but a handful of states, property taxes are insignificant. 1 1 One could argue, correctly, that state finance and local finance are difficult to separate. What happens in local government finance affects the state budget indirectly even if there is no direct linkage. Looking at property taxes across the country, we find that local governments typically rely on property taxes for the majority of their revenue. California’s property tax reliance is lower than the national average, but not by much, although about 2/3rds of the states rely more heavily than Cali- 167 Figure 2. Local Gov’t % of Tax Revenues Figure 1. State Gov’t % of Tax Revenues From Property Tax, 2006 From Property Tax, 2006 Minnesota Alabama Louisiana Arkansas Ne w M e x i co M a r yl a n d Ok l a h o m a Ke n t u ck y Ne w Yo r k Wa s h i n g t o n C o l o r a do Missouri Te n n e s s e e G e o rg i a Arizona Ne v a da Utah West V irginia Ohio Neb raska S. Carololoina N or th Dakota Missouri I llinois V irginia Georgia Louisiana Pennsylvania W isconsin New Mexioc Kansas Maine Mary land Nevada A lab ama A laska Florida A rizona California Kentucky Michigan A rkansas W y oming Washington Montana Vermont New H amp. 0% 5% 10% Source: U.S. Depar tment of Census 168 15% 20% 25% 30% California Oh i o D e l a w a re P e n n s yl v a n i a V i rg i n i a South Dakota No r t h C a ro l i n a W yo m i n g Ore g o n Ne b r a s k a Hawaii Ka n s a s Alasaka F l o r i da We s t V i rg i n i a Il l i n o i s Io w a Te x a s S o u t h C a ro l i n a No r t h D a k o t a In di a n a Ida h o Minnesota M i ch i g a n M i s s i s s i ppi W i s co n s i n Ve r m o n t Mass. Montana R h o de Is l a n d Ne w J e r s e y C o n n e ct i cu t Maine Ne w H a m p. 0% 20% 40% 60% 80% 100% 120% Figure 3. Local Gov’t % of General Revenue From State Transfers, 2006 H aw a ii Color a d o Flo r id a Te x a s S outh Dako ta Neb ra ska Mary la n d I llin o is Misso u r i Georgia New Jer sey Tennessee S outh Carolin a New H a mp . Ma in e Connect ic u t Rhonde Isla n d New Yo r k A la ska Io w a Uta h I ndia n a V irgin ia Kansa s Washingto n Nor th Da ko ta A laba ma W yomin g Louisia n a P ennsylva n ia Ore go n Id a h o Mon ta n a Nev a d a Oh io Oklaho ma A rizo n a Ma ss. Nor th Caro lin a Kentu c ky Mississip p i W iscon sin Mich iga n Califor n ia West V irgin ia Minneso ta Delaw a re New Mex ic o A rkansa s Verm o n t 0% 10% 20% 30% 40 % 5 0 % 6 0 % 7 0 % 8 0 % 169 SALES AND I N C O M E TA X E S There are two other important taxes to examine as potential sources of recurrent revenue problems in California: sales and use taxes and income taxes. Sales and use taxes are a major source of revenue for many states. This tax tends to be volatile because it relies heavily on consumer durables such as automobiles, home improvements, and home construction. While the sales tax in California is a major source of revenue, accounting for about 35% of state tax receipts, California is in the bottom quintile of states relying on this revenue source. So the answer to California’s recurrent budget crises does not seem to lie in sales and use taxes. If this were the problem, then the state would not be continually making the top-10 list for states with fiscal stress. Figure 4. Reliance of State Revenue on Sales and Use Tax % of Total Ore g o n D e l a w a re Montana Mass. Ne w Yo r k Ve r m o n t Ne w H a m p. V i rg i n i a California Ok l a h o m a C o l o r a do No r t h C a ro l i n a W i s co n s i n M a r yl a n d G e o rg i a M i ch i g a n Minnesota Ida h o Maine Ne w J e r s e y Ke n t u ck y Oh i o P e n n s yl v a n i a Missouri Ka n s a s Il l i n o i s Io w a Utah Ne b r a s k a Arkansas R h o de Is l a n d C o n n e ct i cu t In di a n a Alabama S o u t h C a ro l i n a M e w M e x i co We s t V i rg i n i a No r t h D a k o t a Louisiana Arizona Hawaii M i s s i s s i ppi Te n n e s s e e 0% 10% 20% 30% 40% 50% 60% 70% 80% Source: U.S. Depar tment of Census 170 The last tax we want to examine for volatility is the income tax. In general, state income taxes are more variable and less predictable than other taxes. on Income Tax % of Total 14 California relies heavily on income taxes for its revenue generation, fifth in the nation. In the top-10 states measured by reliance on income tax about half appeared once on the stress list for either fiscal 2008 or fiscal 2009. The correlation is not perfect, but there is at least some indication that reliance on income taxes might be causal to swings in tax revenues. We should note that there are quite a few states on the stress list which have average or less-than-average reliance on income taxes as well. This fact just points out the difficulty of ferreting out California’s atypical shortfall situation. State tax revenue structures not only differ widely from each other and over time, and so does the character of their tax base. Figure 5. Reliance of State Revenues Te n n e s s e e Ne w H a m p. No r t h D a k o t a M i s s i s s i ppi Louisiana Ne w M e x i co Ve r m o n t Hawaii Arizona Arkansas We s t V i rg i n i a Alabama ‘ P e n n s yl v a n i a Ke n t u ck y Ok l a h o m a Io w a S o u t h C a ro l i n a M i ch i g a n C o n n e ct i cu t Il l i n o i s Montana Ka n s a s Ne b r a s k a R h o de Is l a n d Missouri Oh i o D e l a w a re Utah Ida h o Maine In di a n a Ne w J e r s e y Minesota M a r yl a n d W i s co n s i n G e o rg i a No r t h C a ro l i n a California C o l o r a do V i rg i n i a Ne w Yo r k Mass. 0% 10% 20% 30% 40% 50% 60% 171 70% V O L AT I L I T Y A N D I N C O M E TA X STRUCTURE marginal tax rate of the highest income tax bracket less the marginal tax rate for those earning $10,000 of taxable income per year. California has the highest degree of progressivity in its income tax at just under 6%.1 5 Going from lower progressivity to higher progressivity, we see a pattern emerging. Although the To explore the volatility issue further, we want to relationship is not perfect, revenue variability tends to consider five factors for each state: 1) the variability increase the more progressive is the income tax system. of income, 2) the extent to which each state relies on (There are smaller spheres towards the bottom and income taxes, 3) the progressivity of the income tax, larger sphere towards the top). 4) the highest income tax bracket, and 5) the variability of general fund tax revenue. Consider the top-10 To round this analysis out, we look at the final states as measured by the variability of the state’s variable, the marginal tax rate paid by taxpayers in inflation-adjusted personal income over the period the highest income tax bracket. After adjusting for the 1990-2006. The top-10 states divide into two categories “millionaire’s tax” of 1%, California’s highest marginal (except Hawaii); extractive industry states (Texas, rate is 9.3% for general revenue. 1 6 The numbers Oklahoma, Louisiana, Colorado and Nevada) and on the chart next to each sphere are the highest tax innovation, knowledge, technology, and finance-driven bracket’s marginal tax rate. For Massachusetts, this states (Massachusetts, Connecticut, New York, and number is adjusted to include that state’s higher tax California). Texas and Nevada do not have income on capital gains. For similar progressivity of the tax taxes and, hence, the volatility of income is not directly system, the higher the top bracket, the more variable is reflected in general fund revenue. revenue. Moving from left to right and bottom to top, we find that the spheres become bigger the larger is Figure 6 illustrates the results of the analysis. Spheres the progressivity of the tax system. They also become on the chart represent the variability of taxes. The larger bigger the higher is the highest tax bracket. the sphere the more variable is total tax revenue. The horizontal axis reflects the reliance on income taxes. It is interesting to note that even among the states with the highest variability of income, the variability of RELIANCE ON TOP EARNERS taxes is unrelated to the reliance on income taxes for revenue generation. Moving from less reliance to more The striking thing about the volatility analysis is that reliance (left to right on Figure 6), one sees that the it is not variability in income per se that is a problem. size of the spheres does not change in any regular way. Colorado, Oklahoma, Massachusetts and New York New York, for example, has a small sphere though it re- all have highly variable income. But because they lies on income taxes for more than 60% of its total tax rev- have little to no progressivity and fairly low marginal enue. Louisiana, in contrast, has a large sphere and relies tax rates, even a 65% reliance on income taxes does on income taxes for less than 30% of its total tax revenue. not create the kind of budget stress that California experiences. To be sure, these states can have episodes The vertical axis of Figure 6 is the progressivity of of revenue shortfall. But overall, their tax revenues are the tax system measured by the difference in the much more stable than California’s. 172 Figure 6. Variability of Tax Revenue and Tax Structure—Larger Spheres Correspond to Higher Tax Variability 7.0% P ro g resi v i t y o f Inc o m e Tax 6.0% CA 9.3% 5.0% LA 6.0% 4 The bottom line here is that California relies heavily on levies on the income earners with the highest variance taxing the highest income bracket for its tax revenue, in income. And the covariance between fluctuations in and that bracket has a highly variable income. The the income of the highest earners and those in lower reason why incomes are highly variable in California brackets is relatively small. So the higher the income and Massachusetts and, to a lesser extent, the finance- tax burden on highly-compensated Californians, the heavy New York and Connecticut, is that these states worse the volatility problem becomes. foster the early stages of companies. They are states with knowledge communities, substantial research and innovation, and a critical mass of scientists, engineers, and entrepreuers. So Google, Yahoo and other internet companies, new propulsion technologies, innovations in medical technology, and the like generate a stream RELIANCE ON INDIVIDUALS WITH VARIABLE INCOMES of income which is uneven year to year. It is profits and capital gains which fluctuate substantially and not the income of firefighters or factory workers. 17 California, having decided on a tax structure which, in a state with a highly variable income base, relies most heavily on taxing the portion of that base which is the More formally, the variance of income taxes is the sum most variable. The result, not surprisingly, is a highly of the variances of the income taxes from each tax variable stream of revenue from which to fund state bracket plus the covariances of tax revenues between and local expenditures. It is the tax structure—which each pairing of brackets. The structure of the California amplifies the variability of income—that is the root of economy is such that the highest tax bracket imposes the “once-a-decade-crisis” in the state’s budget. 173 THE EVOLUTION THE INCOME/DEFICIT OF CALIFORNIA’S R E L AT I O N S H I P V O L AT I L E TA X REVENUE There are two important things to notice about the relationship between the change in the growth of real personal income and ex poste deficits. The first is that the passage of Prop 13 did nothing to change the California has had a progressive income tax system since 1935. 18 Available data on deficits and surpluses relationship. The deficits after Prop 13 were a little larger, but only because the state chose to increase (Figure 7) go back only to 1948, but that is sufficient transfer payments to local governments. In other to see the impact of this system on California gen- words, Prop 13 did not change the revenue side of the eral fund revenue volatility. Up until 1967, there was equation, just the spending decisions. no correlation between personal income growth and deficits and surpluses, nor was there a clear relation- Second, the deficits are becoming worse. The ship with the rate of change of that growth. Personal large deficits of Governor Davis’ and Governor income would grow and California might have a defi- Schwarzenegger ’s administrations are reflective of cit, but equally likely, it might have a surplus. That a changed California economy. Prior to 2000, California situation changed in 1967. Governor Reagan signed was a state that relied heavily on final assembly into law an increase in the personal income tax rates manufacturing by large companies. The filling in of in 1967 as a way of closing the deficits run during the coastal California’s urban centers, the recessions of prior administration of Governor Pat Brown. The tax 1990 and 2001, the opening of trade with China, and increase was supposed to be temporary and put into the productivity improvements of the past 20 years place the most progressive state income tax system in ended that chapter in California’s economic history. As the country. But that shift toward high progressitivity aptly put by Dr. Bruce Yandle of Clemson University: is still reflected in the California tax system. 19 “California’s economy continues to be transformed An examination of changes in real personal income by globalization. Previously prosperous industries growth (after adjusting for inflation) and actual are faltering, while new ones flourish. This (ex poste) budget deficits reveals a clear relationship. transformation has been largely driven by the rise With three exceptions from 1967 through 2009, every of the knowledge economy, in which knowledge is time personal income growth slowed, California ran the source of competitiveness. In this new economy a deficit. Every time personal income growth it is science, research, technology and innovation increased, California ran a surplus. which are central to economic prosperity.” 2 0 The three exceptions include two years when the top The California of today is one based on knowledge marginal tax rate jumped temporarily to 13%, thereby communities, innovation and entrepreneurship. Over offsetting the potential losses in revenue. And there 40% of the venture capital invested in the U.S. finds its was one year in which the decrease in personal income way to California business.2 1 And these businesses, growth was very small. What this fiscal history tells us from Google to Tesla and beyond, generate stock is that the highly progressive income tax system Cali- options, bonuses, and entrepreneurial profits during fornia employs to fund state government is the source good times but not during lean times. So tax revenue of the state’s volatility in general fund revenues. 174 Figure 7. Per Capita California Real Budget Deficit and Change in FY Real Personal Income B a s e d o n A u t h o r ’s C a l c u l a t i o n s : $400 10% Change In Real Personal Income (Right Scale) 8% $300 6% $200 4% 2% 2000$ 0% $0 % CHG . $100 - 2% - 4% -$100 Real Budget Deficit Per Capita (Left Scale) - 6% -$200 - 8% - 10& 2008 2006 2004 2002 2000 1998 1996 1994 1992 1990 1988 1986 1984 1982 1980 1978 1976 1974 1972 1970 1968 1966 1964 1962 1960 1958 1956 1954 1952 1950 1948 -$300 D a t a S o u r c e s : h t t p : / / b e a . g o v / , h t t p : / / w w w. d o f . c a . g o v / b u d g e t i n g / b u d g e t _ f a q s / i n f o r m a t i o n / , h t t p : / / w w w. d o f . c a . g o v / r e s e a r c h / d e m o g r a p h i c / r e p o r t s / from the top tier of income earners is now much more Davis administration, large deficits were blamed on variable than in the past as a direct result of the new excess spending. After the recall election in 2003, California economy. 22 Governor Schwarzenegger along with the legislature crafted a budget to close the gap left by Davis. As C A P I TA L G A I N S officially recorded for a time thereafter, the budget was in surplus. But the surplus was illusory as it involved borrowing, transfers, and one-time In a report on tax revenues, the Legislative Analyst’s measures. But by California’s fiscal accounting a Office noted that capital gains began to be an seeming surplus appeared. Politicians in Sacramento, increasingly important part of the taxable income base although agreeing that reform was needed, wiped in the late 1990s. 23 There is an aspect of the California budget crisis that is tied up in the spending side, but their collective brow in a sigh of relief, and continued business as usual until the fiscal crisis reappeared. there is also an important part which is generated by the nature of the tax structure. Thus, regardless In late July 2009, a new budget fix was enacted. of which political party is in power and regardless The revised budget was in surplus on paper, using of what decisions politicians and voters might make Sacramento accounting newspeak. But will the pain about spending, without a change in the way in which experienced have been enough to force reforms in California seeks to raise revenues, the amplified crises revenue generation? If not, California will have in revenues will continue. wasted a perfectly good disaster for a second time in the 2000s and can expect a similar crisis in budgeting A closer examination of ex poste deficits over the in the future. past decade yields a disturbing fact. During the . 175 R E F O R M I N G T H E TA X SYSTEM: A MODEST PROPOSAL Even though Prop 13 is clearly not the cause of California’s recurrent budget crises, wouldn’t elimination of Prop 13 give the legislature more tools to fix the problem? The answer is decidedly no. What Prop 13 does is stabilize the property tax base. With restrictions on the annual increase in assessed property values limited to the rate of inflation or 2%, whichever is lower, most properties in California will not be reassessed upwards to market values during boom times in the housing market. Nor will they be reassessed downward as market values fall during bust times. Under Prop 13, only properties actually sold are reassessed at current market value. Over long periods, housing will likely appreciate preserve the stability of the tax base. This increase would move the mill rate up to a higher rate, but in the spirit of Prop. 13 prohibit it from rising year to year. Since the current property tax is a local levy, the added revenue from the rate increase would have to be redirected in some fashion to the state’s general fund. The second provision of tax reform would then be to lower income tax rates for each income tax bracket. The combination—increased tax revenue from a more stable base and decreased tax revenues from a less stable base—will decrease the overall volatility of the total tax revenue. To see the impact of this approach, consider the following exercise. Over the period 1990 to 2006, reduce all income tax brackets by 40%. To compensate for this raise the mill rate for property taxes from 100 to 170 and redirect the added revenue to the state’s general fund. Finally, keep all provisions of the tax code including Prop 13 restrictions on assessed value in place. at a rate higher than the rate of inflation and, therefore, higher than the Prop 13 limited increase in assessments. A home is an investment as well as CHARTING THE R E S U LT a provider of shelter services. As an investment, it needs to earn an effective inflation-adjusted rate of return (after taking account of tax benefits and depreciation) at least as great as the next best alternative. Prop 13 actually stabilizes the revenue base and is thus a potential solution to California’s revenue crises. This simple shift of the source of some of the revenue for the general fund would have had a dramatic effect on the volatility of the taxes throughout the 1990-2006 period. But the shift is revenue neutral in the sense that the aggregate amount of taxes collected in the hypothetical example is virtually identical to the actual RAISING THE P R O P E R T Y TA X R AT E Consider an increase in the property tax mill rate. The current mill rate is at 100 (1% of assessed value). By retaining all of the provisions of Prop 13 with a constitutional amendment permitting an increase in the mill rate we could increase tax revenue and 176 tax collected. We can see the results clearly in the volatility analysis of Figure 8. The volatility of California’s general revenue shrinks dramatically (the size of the lined sphere in the chart labeled CA**, relative to the size of the CA sphere in the upper right-hand corner). In fact, due to the stability of the Prop 13 protected annual increases in property tax revenue, the volatility falls much more Figure 8. Variability of Tax Revenue and Tax Structure—Larger Spheres Correspond to Higher Tax Variability 7.0% P ro g resi v i t y o f Inc o m e Tax 6.0% CA 9.3% 5.0% LA 6.0% 4.0% CA** 5 than one would otherwise expect. The hypothetical changes make capital gains, entrepreneurial profits, has California volatility about the magnitude of those bonuses and Initial Public Offerings (IPOs) a much states with flat taxes and high income volatility in more important part of state revenue and a much more spite of the fact that California would have retained volatile source of state revenue. a progressive, albeit less progressive, income tax system. This simple exercise shows the power of For California to move away from its legacy of shifting the locus of the tax base away from its current recurrent fiscal crisis, it must address the source center of gravity and suggests many possibilities for of the problem rather than treat the symptoms as avoiding the recurrent revenue crises which plague they appear. The suggestion here is to transfer the California and threaten its ability to govern itself. tax burden to a legislated stable source of revenue such as the property tax. That approach is one way CONCLUSION to accomplish the goal of reduced volatility without giving up some of the social goals inherent in the state’s progressive tax system. There are many ways California’s recurrent budget crises have been shown to impose the kind of stability that Prop 13 provides to be a function of the highly progressive income tax on potential revenue bases. These alternatives include system put in place in 1935 and left largely unchanged various kinds of wealth taxes and income-smoothing since modified in 1967. The changes in the California schemes. However, absent reform—and regardless of economy—moving from a traditional manufacturing the political party in power—a repeat of the Governor economy to knowledge and service-based economy— Davis/Governor Schwarzenegger budget deficit dance have made income tax revenue more volatile. These will occur in the future. 177 1 State Budget 2009-10, State of California, Department of Finance,. 2 Sheffrin, Steven M. 2004. “State Budget Deficit Dynamics and the California Debacle.” Journal of Economic Perspectives, 18(2): 205–226. Boylan, Richard T., Political Distortions in State Forecasts, Public Choice, September, 2008. Boylan finds systematic forecast error correlated with elections which compounds the revenue forecast problem for multi-year programs. 3 Steven Hayward, The Once A Decade Crisis, California can get well – and stay well – through sensible, though politically difficult reforms, National Review, September, 2003 4 Robert W. Wassmer, The “Roller Coaster” of California State Budgeting After Proposition 13,Conference on Intergovernmental Relations and Fiscal Conditions, Andrew Young School of Policy Studies, Georgia State University, April 2006. 5 Dan Walters, In California Budget Circles, What Goes Around Comes Around, Sacramento Bee, July 28, 2008. 6 See, for example, “The Roller Coaster of California State Budgeting After Prop 13,” Robert W. Wassmer, Andrew Young School of Policy Studies Symposium. 2006. Citrin, Jack (2009) “Proposition 13 and the Transformation of California Government,” California Journal of Politics and Policy: Vol. 1 : Iss. 1, Article 16. Gamage, David Scott, “Coping through California’s Budget Crises in Light of Proposition 13 and California’s Fiscal Constitution”, After the Tax Revolt: California’s Proposition 13 Turns 30, Jack Citrin & Isaac Martin, eds., IGS – University of California, Berkeley, 2009. 178 ENDNOTES 7 16 See the previous footnote concerning the millionaire’s tax. aspx; home price estimates from the Federal Housing Finance Agency– 17 Vasche, Jon David and Williams, Brad, Revenue Volatility in House Price Index FHFA HPI California. State Tax Notes, Vol. 36. No. 1, April 4, 2005. General revenue estimates from the Legislative Analyst’s Office,. e=215&Type=compare&Area1=CA&Area2=&Area3=. 8 9 Legislative Analyst’s Office, State of California, “Perspectives on Gamage (2009) ibid. The State’s Revenue Structure,” Presentation to the Committee On The 21st Century Economy, January 2009, National Conference of State Legislatures, State Budget Update, June 2008. 10 18 Census of Government Finances and Annual Survey of Government Finances, U.S. Census, estimate/historical_data.html 11 12 13 handouts/fo/2009/revenue_structure_perspectives.pdf David Doerr, “Conformity, The Impossible Dream,” Cal-Tax Digest, 1997. 19 Michael New, “Morning In California: Reagan’s Governorship Transformed American Politics,” National Review, U.S. Census, ibid. June 10, 2004, new200406100853.asp. Citrin (2009) ibid. Cara Mia DiMassa, Property Tax Funds Rise as Housing 20 Bruce Yandle, “The New Knowledge Economy: Increasing Competitiveness in the California Economy,” George Mason Market Falls, LA Times, July 9, 2008 University, 2008. 14 21 Randall G. Holcombe and /Russell S. Sobel, The Relative Variability of State Income and Sales Taxes Over The Revenue Cycle, Atlantic Economic Journal, June, 1995. 15 In 2004, Proposition 63 instituted a “millionaire’s tax” in California in which is a surcharge of 1% for those whose annual The Money Tree Report, Price Waterhouse Coopers, https:// 22 Jerry Nickelsburg, “Report to The Commission on The 20th Century Economy,” (PowerPoint Slides) Los Angeles, 2009, http://. adjusted gross income exceeded $1 million for mental health spending. The variability of tax revenue analyzed here is general fund revenue. Mac Taylor, “California’s Fiscal Outlook,” Legislative Analyst’s Office, The millionaire’s tax is put into a special fund to support county November 2008, operated mental health clinics and does not generate general fund outlook_112008.pdf revenue. Therefore, it is not included in the tax progressivity numbers. 23 Legislative Analysts Office, Revenue Volatility In California, 2005, volatility_012005.htm. 179 9 180 RECOVERY IS C E R TA I N F O R CALIFORNIA —WHEN IS NOT CHRISTOPHER THORNBERG Christopher Thornberg is a Founding Principal of Beacon Economics. He is the chief economic advisor to California State Controller John Chiang and is widely recognized as one of the nation’s leading economic forecasters. He received his PhD in Business Economics from the Anderson School of Management at UCLA. 181 9 The year 2009 was rough. The national economy contracted by close to 4% from the second quarter of 2008 to the second quarter of 2009. This was the single worst pullback in GDP over the course of one year since the 1930s. The downturn was led by a 28% decline in business investment, and a 1.7% decline in real consumer spending. But now the recession is over, or so said Newsweek on the cover of its July 27, 2009 edition. Good news indeed as far as it went. In this chapter, we first review the national economic outlook. California is roughly an eighth of the national economy and cannot remain isolated from overall U.S. trends. We then turn to the specifics of the California outlook It is true that the third quarter of 2009 saw the U.S. expand at a pace in the 3 to 4% range, based on preliminary numbers available at this writing. That was a good number, driven by across the board gains. There were small gains in housing, a surge in consumer durables spending driven by the “cash-for-clunkersâ€? program, government subsidized new car purchases for old-car trade-ins, rationalized by improved gas mileage. There was also a slowing of the inventory burn-off. Business investment spending on equipment and software remained flat, although we continued to see economic losses in non-residential construction. That sure sounded as if the recession was over. LABOR MARKET LAGS Unfortunately, the labor markets did not agree that the recession was over—indeed the figures as of fall 2009 remained positively ugly. Unemployment hit 9.8% in September 2009; total job losses to that point came to 7.2 million (-5.2%) since the employment peak hit in December of 2007. But it was hardly surprising that the nation continued to experience the loss of jobs and increasing unemployment. Labor markets are typically lagging indicators, and given the economic turmoil of 182 the last year it was hardly surprising that we contin- for housing was the increase in home sales seen over ued to see negative results in these indicators even if the summer of 2009. And with this surge in buyers, the big negative growth figures had come to an end. prices also started to stabilize. The Case-Shiller home price indexes showed increases in 17 of the 20 local M I X E D R E S U LT S I N OTHER MARKETS markets tracked, as well as in their national index. FINANCIAL MARKETS Other indicators at this writing showed at best some On the other side of the equation are the figures stabilization—but hardly numbers that seem to imply coming out of the financial markets. Last year—after the US is on the rebound. Instead they painted a pic- the collapse of Lehman—the financial markets became ture of an economy stuck in neutral. Data on consumer completely unglued. Risk spreads went through the spending have been mixed lately. Auto sales, which roof as multiple financial institutions teetered on the had leapt to over 1.1 million in August as a result of edge of bankruptcy. The nation was warned of an the cash for clunkers program dropped back to below impending economic apocalypse unless extraordinary 800,000 on a seasonally-adjusted basis in September. actions were taken—to the tune of something over $2 Similarly retail sales apart from autos were still 7% trillion and counting at this writing, with little sign below where they were at their peak in July 2008. that much of this public funding will ever come back to the taxpayer. The industrial portion of the economy as of fall 2009 could also be described, at best, tepid. Factory orders, How fast things can change! The remaining two major industrial production and exports all showed slight investment banks, JP Morgan and Goldman Sachs, improvements by that time. However, the levels were have paid off their federal TARP money and have been still considerably lower than what we saw even 18 posting profit figures that are close to record levels. months earlier and the trends were nothing close to Taking the cue, the Dow crossed the 10,000 mark in what we might call a rebound. Capacity utilization was October 2009, even though corporate earnings were still below 70%, the lowest level it had been at since still in the tank. the Federal Reserve started collecting the data. Factory orders, one of the leading indicators of manufacturing Similarly the debt markets were also calming down production, were up 3% (in nominal dollars) from the by fall 2009. Risk spreads have come down across the trough hit in March 2009, but still were 24% below board to levels not seen since prior to the first financial where they were in July 2008. cracks that occurred in the third quarter of 2007. The BAA-AAA (high risk – low risk) bond interest-rate The housing market also experienced some stabiliza- spread fell from 340 basis points to only by October tion by fall 2009, although here the signs were even 2009. Will the real economy please stand up? more tenuous. Housing starts increased slightly from the record low levels of a few months earlier. Still, the 509,000 unit pace (seasonally-adjusted annual rate) seen in September 2009 remained at a record low for any housing cycle until 2009. The one bit of good news 183 THE REAL ECONOMY THE BORROWING OUTLOOK BINGE So what next for the U.S. and California economies? Instead, the pressure on the financial system was Forecasting is a perilous business at the best of times. the direct consequence of a massive borrowing and We base our assessments by marrying an incomplete spending binge than began in the U.S. economy back understanding of the current economy with lessons in the mid-1990s. Consumer savings rates dropped from the past that may or may not be analogous to from 8% to 1% of disposable incomes, asset values our present circumstances. This process in the context across the spectrum rose to levels completely out of of the slump of 2008 and beyond is made even more whack with fundamentals (of which housing was only difficult by the fact that public policy continues to shift a part). And a massive increase in the use of leverage rapidly. However, one thing is for sure; as of fall 2009, all created a situation in which the U.S. economy was the U.S. economy had not yet burned off the excesses eventually going to stumble—and stumble hard. that pushed the economy into the downturn in the first place. As such, the economy in 2010 and subsequently These large imbalances that drove this recession have will continue to be at best turbulent and at worst stuck not been erased. Instead, they have all moved only in the slump that began in 2008. partially back towards balance. The current growth in the U.S. economy as of late 2009 is largely due This view certainly contradicts the rebound in the to massive fiscal and monetary policy responses. financial markets which in turn seemed so out of Consider these root problems in turn: real estate, sync with the more direct measures of economic banking, and consumption. performance. The standard mantra that continues to echo across the media is that the financial markets are a leading indicator of the economy. Unfortunately, R E A L E S TAT E such faith in the ability for the markets to see what mere mortals cannot flies in the face of historical facts. The stability seen in the housing market as of fall Remember that the markets were bubbling along near 2009 was driven not by fundamentals but by policy all-time highs even after the U.S. economy entered decisions. For example, buyers enjoyed record-low a recession in 2008. interest rates due to the Fed’s policy of “quantitative easing.” Money was being created and used to buy Unfortunately, we—like Ben Bernanke, chairman of debt issued by Fannie and Freddie, the two major the Federal Reserve—are less inclined to believe that mortgage lenders that were nationalized. Similarly, the U.S. economy will rebound rapidly in 2010 from the Federal Housing Administration (FHA) expanded the great downturn of 2008-2009. The roots of this its presence in the market during 2009, guaranteeing downturn did not start with the collapse of Lehman a record number of mortgages. Lastly, a tax credit was and the financial markets. Thus, a recovery in the instituted for first-time homebuyers. financial markets does not imply that the pressures on the real economy are finished. All of these programs were set up with a limited lifespan. Chairman Bernanke has to worry about the possible future inflationary pressures created by the expansion of the money supply. The FHA’s portfolio 184 was seeing record increases in delinquencies as of fall fact that most mortgage servicers and banks have 2009. The government may need to reach into its wallet little incentive to modify the mortgages—the process to bailout out this institution as well as its banking is expensive and fraught with moral hazard. Only the counterpart, the Federal Deposit Insurance Corporation larger banks have really played ball and this is because (FDIC), to the tune of hundreds of billions of dollars. they have larger political fish to fry. The big banks And even though the housing industry was pushing wanted to deflect the push for strong re-regulation of strongly for an extension of the homebuyer tax benefit, the banking sector. the Obama administration seemed reluctant to extend it due to concerns about the federal budget deficit. Of course, home sales were up; some homebuyers rushed in to snap up those few bargain deals that have In any case, it is only the last two or three months of made it onto the market. Yet it is not clear whether the such a program that really create the desired result pool of potential buyers will be large enough to handle of expanding sales. It is the impending end of such the mass of foreclosed homes soon to hit the market. a program that makes it work in the first place! That mass will probably total 2 million to 4 million Potential homebuyers rush to take advantage of the homes over 2010-2012. program before it expires. The largest issue, however, is mortgage foreclosures. THE BANKING Although much has been made of the various SECTOR homeowner rescue plans, they have had little to no impact on the pace of people going into foreclosure. Instead, they have only slowed the process down. In the banking sector, profits were good in the first According to the Mortgage Bankers Association, the quarter of 2009—almost $8 billion for the industry delinquency rate on mortgages rose to 6.4% in the as a whole. But this result was largely due to very second quarter of 2009, driven largely by the increase easy Fed policy and the changes in the Financial in the number of loans that were 90 or more days Accounting Standards Board (FASB) rules. There is an behind on payments. The second quarter numbers entire cottage industry forming around helping banks from the Mortgage Bankers Association showed “value” their assets in such a way as to avoid being that 5.6% of mortgages were seriously (60 days or taken over by the FDIC. And despite these efforts, more) delinquent on payments, roughly 2.5 million the news became grim again in the second quarter. households. The pace of new foreclosures stayed According to the FDIC, the banking sector lost $3 above 1% at the time. A further 4% of mortgages were billion in the second quarter of 2009 and the number of already into the foreclosure process, but without troubled banks rose above 400. having finished the process. Papering over a problem does not clean it up. The The mortgage programs in place have largely failed peak in loan write-downs occurs after a recession has because they rely on owners being financially ignorant ended. The ratio of loan loss reserves to delinquent —not realizing that changing the monthly payment loans (the so-called coverage ratio) as of the latest data without changing the principal balance is hardly available at this writing is still vastly too low given helpful when you are 20% “under water,” i.e., the that the worst is yet to come. Loan losses were already mortgage debt exceeds the value of the house. In at a record high in fall 2009, with the overall collapse addition, the programs did very little to change the in asset prices back toward long-run norms. 185 There will be at least $1 trillion in additional losses the cyclical. The other half was due to the rebate and tax sector will have to absorb before we can truly say the programs put in place at the start of 2009. sector is healthy again. Yes, as noted earlier, interestrate spreads on risky debt have come down—too much What happens in 2010 and beyond when the stimulus in our opinion. It is likely that 2010 will be a record tax cuts and rebates go away, along with the Bush tax year for defaults and loss ratios are likely going to cuts of 2003? Buyers will once again find themselves be steep. with insufficient savings and spending will need to decline again. As for the closing trade deficit, it has THE CONSUMER been driven by rapid declines in business spending, not by declines in consumer spending. This outcome is neither sustainable nor healthy. Investment must rise Lastly, we have the consumer, who was largely and consumer spending must fall. These changes must responsible for the economic meltdown that started in occur and eventually U.S. public and private spending 2008 (not the failure of Lehman Brothers, as is often must fall back in line with reality. But the process will claimed by various Wall Street executives trying to not be easy. justify their multibillion-dollar bailouts). Before the economic slump began, personal savings rates were CHANCES FOR A running at an unsustainably low 1% of income, owing to the false sense of wealth created by the 15-year-old national asset bubble. The subsequent decline in U.S. QUICKER RECOVERY consumer spending is truly historic, setting off the chain reaction that created two of the worst back-to- But what of the financial market rebound? back quarters for U.S. real growth. Unfortunately it is our opinion that the markets, rather than being a leading indicator, have been no indicator Savings rates grew from 1% to 5% in a fairly short of much of anything. Instead the markets seem to have time period. The mirror of the savings deficit, the become largely unhinged from economic reality since foreign trade deficit, also closed sharply, with imports the mid-to-late1990s. We saw rapid increases in the plunging even more than exports. This adjustment is equity markets from 1997 to 2000 and from 2003 to exactly what needs to happen in order for the economy 2007 that led to disastrous consequences when these to regain proper footing. bubbles finally broke. But once again, the story is not that clean. Savings in Little has changed on Wall Street. The incentives, the United States rose from $127 billion to $546 billion the major players, and the regulatory framework that (real, seasonally-adjusted annual rate) from the first allowed such excesses all still remain in place. And quarter of 2008 to the second quarter of 2009. This the growth in asset prices as of this writing seems as rise would be impressive, given that incomes fell by contrary to the fundamentals of the economy as ever $250 billion, but in fact only $177 billion of the $800 before. A larger question is why, after two massive billion gap between savings and income came from bubbles, the American public seems willing to dive declines in spending—less than one-quarter. It was tax back into what seems to be yet another false promise cuts ($460 billion) that comprised most of the change. of a bull stock market. Remember that the four most Some of this decline in the tax stream was due to the dangerous words in economics are “this time progressive nature of taxes that makes the flow hyper- it’s different.” 186 There are some potential changes in the economy that The U.S. economy grew the wrong way from the mid- may lead to better economic outcomes. Asia has turned 1990s to 2007, with too much consumer spending and around faster than most anyone thought, a develop- not enough saving, too many imports and not enough ment particularly significant for California and its exports. Rebuilding the economy around a sustainable international trade gateways. Underlying economic path will simply take time. Patience is the word that resilience, a smaller reliance on leverage (Asia learned all American’s must learn to appreciate. the lesson the US is learning today back in 1997), and strong stimulus efforts by central governments with THE CALIFORNIA large reserves have helped Asian economies pull through the large decline in U.S. imports. If the U.S. S I T U AT I O N dollar falls another 10 to 20%, we could see a surge in U.S. exports that would do much to help the economy. There is little doubt that the Golden State lost some Another potential boost to the economy could come of its luster during 2009. As grim as the national from business spending. In the old economy, business downturn had been, California has was that much spending followed capacity utilization and profits, in worse. Unemployment in the state crossed the 12% turn driven by consumer spending. Faster depreciation mark during 2009, compared to 10% for the nation. of information technology capital and an overall This development shouldn’t surprise us. The state has quicker shift in technological changes could force always been a boom-bust economy as it is exposed to companies to invest again even if consumer spending the cyclical portions of the economy at a greater than remains weak. Again, the operative intuition here is normal level. those four most dangerous words in economics: “This run, we would still remain on an unsustainable path California Ja n 09 Sep 07 through the next presidential election. But in the long Ma 06 3.00 Ja n 05 tion in the short run—perhaps even pushing them 5.00 Sep 03 could cure many problems for the Obama administra- 7.00 May 02 ciation-fueled economy of 2004 to 2007. Such an event 9.00 Ja n 01 my returns to the unbalanced consumer, asset appre- 11.00 Sep 99 lead to a third outcome, one in which the U.S. econo- 13.00 Ja n 97 Oddly enough, the current rally in the markets can Figure 1. Unemployment Rates May 98 time it’s different.” United States and the next time the crash will be that much worse. Figure 2. CA Taxable Sales $130 to heal and for growth to occur in the proper direction. $80 Q 1- 0 9 $90 Q 1- 0 8 the plant back heavily. But it will still take some time Q 1- 0 7 $100 Q 1- 0 6 wrong way. The gardener may then decide to prune Q 1- 0 5 $110 Q 1- 0 4 $120 However, if the plant is left untended it may grow the Q 1- 0 3 to be carefully pruned to grow in a certain way. $140 Q 1- 0 2 economy can be thought of as a plant that is meant $150 Q 1- 0 0 put in place? The answer is absolutely not. The U.S. Q 1- 9 9 Isn’t there any quick solution the government can 187 CYCLICAL VULNERABILITIES OF CALIFORNIA hard. Lastly, some portions of the state, particular in the Bay Area, are heavily exposed to swings in business investment. When spending on equipment and software collapsed in the U.S. during 2009, firms in that region suffered. JOB LOSS Take housing. Parts of the state have been rightly characterized as “ground zero” in the housing market meltdown. Nearly 30% of subprime and Alt-A As of September 2009, the state had lost approximately mortgage money generated through the residential one million jobs or about 6.6% since the peak in 2008, mortgage back security markets landed in California, and the losses continue at this writing. To put this driving prices up more than anywhere else in the loss in perspective, California lost 2.5% of its payroll nation. There were places in the Inland Empire where workforce in the 2001 recession, 2.8% in the recession well over half of all mortgages were subprime or of1982, and 4.1% in the 1991 downturn. Alt-A. Price appreciation reflected the excess liquidity; prices in the state nearly tripled between 1998 and The Table 1illustrates how the downturn has been 2006. When the crash came, it hit California very hard, reflected inside the state economy. The table shows as did its impact on consumer spending. Taxable sales the changes in employment from June to June for the in the state were down 22% from the peak as mid-2009. 2007-2009. The downturn in the state started in 2007, as this year is when the first noticeable slowing of The state is also heavily dependent on exports—not employment occurred. Most sectors were performing just of goods but also of services such as licensing normally, but the collapse of the housing bubble (particularly in technology and entertainment) and hit construction and financial services (primarily tourism. The collapse in exports hit the state very mortgage brokers) quite hard. Figure 3. US Exports (Nominal Index) Figure 4. Change in CA Payroll Emplloyment (Smoothed) 125 120 115 110 105 100 95 90 85 80 60 40 20 0 -2 0 -4 0 -6 0 188 J ul 09 Oct 08 Ja n 0 8 Ap r 07 Jl 06 Oct 05 Ja n 0 5 Ap r 04 J ul 03 Ja n 0 2 A ug 09 May 09 Fe b 0 9 Nov 08 Oct 02 S erv ic es Go o d s A ug 08 Ma y 08 Fe b 0 8 Nov 07 A ug 07 -8 0 -1 0 0 Table 1: California Payroll Employment by Sector 9-08 t o 9-09 9-07 t o 9-08 9- 04 to 9- 07 To t al No n f ar m - 7 3 2 .7 - 2 5 6 .4 210.9 Co n s t r u ct io n - 1 4 4 .0 - 1 2 0 .1 5.7 Nat u r al Res o urces - 2 .0 1 .7 1.5 Du r able M an u f - 9 6 .1 - 2 8 .2 -15.3 No n -Du r able Manuf - 2 5 .2 - 1 3 .8 -5.4 Wh o les ale Tr ade - 3 6 .5 - 1 2 .1 21.1 Ret ail Tr ade - 1 1 0 .2 - 5 2 .3 23.0 Lo g is t ics - 2 5 .3 - 7 .9 8.8 In f o r m at io n - 3 4 .4 2 .6 1.3 F in an ce - 3 1 .1 - 4 6 .7 -5.8 Real E s t at e - 1 0 .7 - 8 .5 1.8 Pro f Sci Tech - 4 7 .9 2 0 .5 46.4 M an ag em en t - 1 4 .3 - 2 .1 -7.8 Adm in Su ppo r t - 6 9 .0 - 4 6 .4 16.1 E du cat io n - 1 .3 9 .0 Healt h Care 1 3 .1 3 8 .5 30.9 Acco m m o dat ion - 4 6 .7 - 5 .8 34.8 Ar t s En t er t ainment - 4 .9 3 .6 5.5 Ot h er Ser vices - 1 7 .3 - 2 .2 3.5 F eder al Go v 0 .3 1 .7 -1.4 St at e Go v 7 .2 - 4 .6 10.4 Lo cal Go v - 3 4 .3 1 6 .5 26.5 9.8 The second stage of the current downturn was driven by a slowdown in consumer spending. Between 2007 and 2008 the weakness in construction and finance in the state spread to wholesale and retail trade, in addition to administrative services where temporary employment services lie. Then, in the 2009, the downturn shifted to a general economic malaise. Business spending contracted sharply as did exports. Suddenly the job losses shifted to manufacturing, information and profession services. Those local economies that had avoided the worst of the start of the downturn suddenly took a sharp hit. San Jose, for example, saw one of the largest increases in unemployment in the state over the course of 2009, as can be seen on Table 2. Problems in the consumer economy spilled over into the rest of the state’s economy during 2009. Everything from professional services to local government to information jobs, took a hit. The only stable sectors were state and federal employment, and education and health. While at this writing there is still positive job growth in this last category, it has slowed sharply. SIGNS OF RECOVERY? Table 2: Umemployment Rates for Selected Regions Se p t . 2009 Lo w e st Ra t e Be f ore Re ce ssi on Calif o r n ia 1 2 .2 4 .8 E as t B ay 1 1 .5 4 .2 In lan d E m pire 1 4 .3 4 .8 Lo s An g eles 1 2 .7 4 .5 Or an g e Co u n ty 9 .4 3 .3 Sacr am en t o 1 2 .2 4 .5 San Dieg o 1 0 .4 3 .9 San F r an cis co 9 .4 3 .7 San J o s e 1 2 .0 4 .3 When will the state start to pull out of the slide? As of late 2009, the rise in unemployment seemed to slow as did the rate of job loss. Payroll-based employment figures tend to miss turning points because of the methodology used to compile the estimates. So these figures may be overstating the problem. On the other hand, new claims for unemployment insurance remain quite high. Overall, there was a mixed message from labor-market indicators. 189 R E A L E S TAT E A N D CONSTRUCTION News from the residential real estate front was slightly better as of late 2009, although there are still problems to work through. The price bubble in California was one of the largest in the nation, with prices rising from a median of $150,000 in 1996 to $300,000 in 2003 to $500,000 in 2006. This era was a time of prosperity for the state. But even so, the increases implied that the market. The three major home finance institutions, Fannie , Freddie, and the FHA, more or less dominated the conforming market during 2009. Yet Fannie and Freddie were propped up by quantitative easing on the part of the Federal Reserve—a strategy that will eventually need to be reversed to prevent inflation. As for the FHA—it has become the new subprime lender with a portfolio that is experiencing rapid increases in delinquencies. When the bailout finally becomes necessary, we can expect that these activities will be curtailed. ratio of home prices to median homeowner incomes rose from 2.5 to 6. Even with lower interest rates, this situation meant that the proportional costs of owning Figure 5. Median Home Price an average home in the state doubled for the average 6 0 0 ,0 0 0 household—clearly an unsustainable consequence. 5 0 0 ,0 0 0 4 0 0 ,0 0 0 3 0 0 ,0 0 0 market grew to such unsustainable levels and then 2 0 0 ,0 0 0 was hit so hard. Thirty percent (by value) of all sub- 1 0 0 ,0 0 0 Q 3-05 Q 2-07 Q 1-09 Q 3 -0 4 Q 1 -0 6 Q 4-03 Q 1 -0 3 Q 1-02 Q 2-00 Q 3-98 Q 4-96 by the massive wave of foreclosures rippling through Q 1-95 Q 1-88 went to buy homes in California. Sadly was evidenced Q 2-93 0 Q 3-91 prime and Alt-A mortgages generated in the nation Q 4-89 There is little mystery as to why California’s housing the state. Figure 6. Median Home Price 2009. New low prices, along with tax breaks and low to Median Homeowner Income interest rates, contributed to the rise in sales. Over 7 the summer, sales in California were up 25% over the 6 the state were up by 7% from the second to the third quarter of 2009. But is this recovery real? First, there is the state economy. With unemployment at 12% and rising in 2009, weak wage growth and uncertainty will keep many buyers wary. Second, there is the mortgage 190 Q 1 -0 9 Q 3 -0 1 Q 1 -0 0 Q 3 -9 8 Q 1 -9 7 0 Q 3 -9 5 rose even more from the bottom. Median prices for 1 Q 1 -9 4 and San Diego rose modestly. For San Francisco, prices 2 Q 3 -9 2 The Case-Shiller home price indexes for Los Angeles 3 Q 1 -9 1 the mortgage markets. Prices suddenly started to rise. 4 Q 3 -8 9 properties, which is not surprising given the issues in 5 Q 1 -8 8 previous June. Many of these sales were of foreclosed Q 3 -0 7 There was a surge in home sales in the state in summer FORECLOSURES TO COME Why haven’t the numerous federal and state workout plans been effective? Because all rely on trying to Lastly, the foreclosure crisis is far from over. The pace incentivize mortgage services to modify the payment of foreclosures slowed in the summer of 2009, but this in some way in order to make payments affordable. was due more to the moratoriums injected into the This approach seems reasonable on the surface, but process by state regulation rather than any change even a small scratch reveals numerous problems. in the market. According to Dataquick, the number of foreclosures fell from 50,000 to 40,000 (seasonally First, an owner who is deeply underwater remains adjusted) from the fourth quarter of 2008 to the first underwater even if the monthly payment is reduced. quarter of 2009, whereas the number of defaults went Most owners quickly realize that their credit score will from 70,000 to 120,000. heal faster than their negative equity. Why should they remain in a situation of owing more on a house than it Even more startling are the latest data available at is worth, when they can simply walk away from this writing from the Mortgage Bankers Association. the liability? They show that 9% of all mortgages in California were delinquent on payments and another 6% were Second, at least at this writing, a large majority of loan somewhere in the foreclosure process. Put another modifications have fallen back into default within way, 400,000 to 500,000 California households were six months. Lenders are starting to realize that some behind in their payments and most if not all were homeowners view modifications as simply another likely underwater. way of maintaining rent-free housing for another year. Lastly, many mortgage servicers have little financial That fact suggests that a large proportion will motivation to spend the financial resources necessary eventually go into foreclosure and then put onto the to deal with troubled mortgages on a case-by-case market by the bank that held the mortgage. Why basis. The servicers simply administer the mortgages; hasn’t that occurred already? The various homeowner they don’t actually hold them. Without any financial workout plans and moratoriums at the state level have stake in the results, why hire the massive workforce simply bottled the process up. But the wave is coming. necessary to address the situation? Figure 7. NOD’s and Foreclosures in California 1 4 0 ,0 0 0 No t i ce o f D e f a u l t 1 2 0 ,0 0 0 F o re cl o s u re s 1 0 0 ,0 0 0 8 0 ,0 0 0 6 0 ,0 0 0 4 0 ,0 0 0 2 0 ,0 0 0 Q 3- 0 9 Q 1- 0 9 Q 3- 0 8 Q 1- 0 8 Q 3- 0 7 Q 1- 0 7 Q 3- 0 6 Q 1- 0 6 Q 3- 0 5 Q 1- 0 5 Q 3- 0 4 Q 1- 0 4 Q 3- 0 3 Q 1- 0 3 Q 3- 0 2 Q 1- 0 2 0 191 Figure 8. Non-Residential Permit Values $ 2 .5 such write-downs be cheaper than going through the $ 2 .0 Fe b 0 8 Apr 0 9 A p r 09 proportion (25%) of mortgages that are delinquent self- Se p 0 8 Jan 04 a cram-down. Evidence has shown that a sizable F e b 08 $ 0 .0 S e p 08 otherwise whole loan when other owners also request $ 0 .5 Jul 07 cash through such “cram-downs,” they will lose on an $ 1 .0 Dec 06 are afraid that for every mortgage on which they save Ma y 0 6 potential secondary implications are enormous. Banks $ 1 .5 Oct 0 5 foreclosure process? They likely are cheaper, but the Bi l l i o ns outstanding principals on the mortgages. Wouldn’t Ma r 0 5 being more proactive in simply writing down the Au g 0 4 Another question is why mortgage holders are not heal; that is, they become current without action on the part of the bank. Giving a break to some homeowners high level—led to the current crisis. In non-residential, the crisis is quieter, as banks primarily desire is not to acknowledge the financial losses on their loan pool for Jul 07 speculation which pushed prices up to unsustainably D e c 06 in residential—easy leverage generating crazy Ma y 06 similarly grim as of late 2009. The same issue as O c t 05 As for the non-residential markets, things were Ma r 05 provided by banks. 1 6 ,0 0 0 1 4 ,0 0 0 1 2 ,0 0 0 1 0 ,0 0 0 8 ,0 0 0 6 ,0 0 0 4 ,0 0 0 2 ,0 0 0 0 A ug 04 paying once they hear cram-downs are being actively Figure 9. Residential Permits (Units) Ja n 04 would induce others who would not default to stop Single-Family Multi-Family as long as possible. But the stresses are clear. Vacancy rates were rising as of fall 2009; rents were falling in all major markets, as Table 3 demonstrates. Table 3: Non-Residential Vacancy Rates and Rents With all these issues, the construction markets remain very weak. Non-residential building permits have Va ca n cy Askin g Re n t fallen over 50% during 2009, and there was little sign Q 3-07 Q3-09 Q3-07 Q3-09 of any recovery. Similarly, single family building E a st B ay 16.9 % 2 0 .6 % $ 2 6 .5 $ 2 2 .6 permits remained around 2000 per month, down from I n la n d E m pire 11.3 % 2 7 .5 % $ 2 2 .9 $ 1 9 .1 12,000 to 14,000 per month in 2004 and 2005. Despite L o s An g eles 11.7 % 1 7 .5 % $ 3 1 .0 $ 2 8 .5 the state tax credit for the purchase of new homes, O r a ng e Co u n t y 14.3 % 2 1 .1 % $ 2 9 .6 $ 2 4 .1 there was little activity in new home construction. S a c r am en t o 12.8 % 1 9 .5 % $ 2 2 .1 $ 2 0 .4 The small amount that did occur did help put a few S a n Dieg o 12.8 % 1 9 .6 % $ 3 0 .1 $ 2 6 .5 construction workers back on the job. But the small S a n F r an cis co 14.2 % 1 9 .4 % $ 3 5 .0 $ 2 9 .9 magnitude suggests a highly dubious use of taxpayers’ S a n J o s e 14.4 % 2 2 .2 % $ 3 1 .3 $ 2 9 .1 money; the credit basically a bailout for developers. 192 WILL THE SUNSHINE EVER RETURN? Table 4: Annual Growth Rates in Real Economic Output, 1997 to 2008 The big question then for California is whether or C a l i f orni a U.S. A l l i nd us t r y t ot a l 3.6% 2.7% Pr i v a t e i nd us t r i e s 3.9% 2.9% downturn. As with past downturns, the state’s critics A g r i c ul t ure 3.3% 3.1% —both internal and externa—have started beating Mi ni ng -5.6% -1.1% the drum of long-term decline. Much has been made Ut i l i t i e s 2.8% 1.7% of California’s poor business climate in recent years, Cons t r uc t i on -1.0% -1.7% when the state will recover in the wake of this sharp with some justification. The state is notoriously over- D ur a bl e g ood s 8.6% 4.5% regulated and has leveraged high taxes on certain N ond ur a bl e g ood s 1.3% -0.4% sectors. Add to this problem the more general issues W hol e s a l e t r a d e 3.2% 2.8% of governance and it is easy to find reasons to criticize Re t a i l t r a d e 5.0% 4.5% California. At one point in 2009, the Economist entered L og i s t i c s 2.0% 2.5% the fray, with its top U.S. article asking whether Texas I nf or ma t i on 7.9% 6.9% would soon replace California as the flagship state of F i na nc e a nd i ns ur a nc e 4.7% 4.0% the U.S. economy. Re a l e s t a t e a nd re nt a l 3.5% 2.6% Prof e s s i ona l a nd t e c hni c a l 5.7% 5.5% Ma na g e me nt of c omp a ni e s -4.6% -0.5% 1.1% 2.0% But just as in 2001, the claims of California’s demise are highly exaggerated. Clearly the state is in a fair A d mi ni s t r a t i v e s e r v i c e s degree of trouble; it has suffered worse than many Ed uc a t i ona l s e r v i c e s 2.9% 2.2% other places. But it is Beacon Economics’ opinion that He a l t h c a re 3.8% 3.1% once this cycle has been worked through, not only A r t s a nd re c re a t i on 2.3% 2.3% will growth return, it will return at a pace that again A c c ommod a t i on a nd f ood 3.5% 2.5% exceeds the nation overall. O t he r s e r v i c e s 0.5% 0.3% G ov e r nme nt 1.9% 1.1% CALIFORNIA’S POTENTIAL This suggestion may sound Pollyannaish. But consider that California, as hard as it might be to believe, has been one of the growth engines of the U.S. economy over the past decade. Table 4 provides real growth rates for California’s economy by sector, relative to the nation overall, from 1997 to 2008. The table is full of surprises. Overall, the state economy outgrew the U.S. economy by one full percentage point annually 193 during this period (3.6% versus 2.7%). The state grew faster (or declined slower) than the nation in almost every sector. The state only underperformed relative to national averages in three categories: logistics, administrative services, and management of companies and enterprises. This first sector may be a shock to those who have envisaged the Ports of Los Angeles and Long Beach as large drivers of growth in the economy. The greatest contributor to growth during this period was durable goods manufacturing, which accounted for almost one-fifth of California’s output growth. Manufacturing, particularly in information technology, is doing well despite the decline in jobs. This seeming paradox is explained by the substitution of capital, particularly computerization, for labor. Following manufacturing is real estate (the rental side, not the construction portion of the business), professional services, information, and retail trade. Real gross state product is not the only place we can see the success of the California economy. Personal income overall and per capita income have been growing faster here than in the nation overall, as have payroll employment and population growth. Why? Many reasons. The state is ideally located to take advantage of expanding trade with Asia and South America. It has a climate and a landscape that draws tourists and long-term residents to the state. It is home to some of the finest technical schools in the world that spin off many enterprises. And it is the center of two of the most important industries in this digital age: entertainment and information technology. The past is the past and the future is the future. While we have succeeded well prior to the Great Recession, that fact is no assurance of future growth. To understand this point, we have to consider the nature of the downturn. 194 ADVERSE SHOCKS There are two types of changes that can affect the growth of a regional economy. The first is a cyclical hit caused by a temporary pullback or an over-expansion in growth that has been caused by some change in exogenous demand conditions. Once the imbalance works its way through the system, the economy moves back onto a normal long-run trend and begins to grow at a normal pace again. The second type of shock is structural - when an industry that is important to a local economy is permanently downsized. When a structural shock occurs, it can take years for an economy to find steady footing and fill the hole left by the collapsed industry. In short, the long-run trend line is altered. The 2001 downturn was of the first type. During the late 1990s, a tremendous amount of capital poured into California chasing the pipe dream of the “New Economy.” This heated up the state’s economy to an unsustainable level, particularly in the San Francisco Bay Area. Unemployment fell to almost zero, as incomes reached ridiculously high levels. It was almost as if there was a new gold rush. Unfortunately, when the gold ran out, the economy went through the typical painful process of withdrawal. But nothing fundamental had changed in the state. Information technology is still one of the most important growth industries in the world economy and the Bay Area is still the capital of that world. Once things returned to proper levels, growth continued. Most of the “decline” in the state was nothing more than a return to the long-term stable growth path—as can be seen on the chart of real income generated in California. Similarly, the downturn in the early 1980s was also cyclical, although here it was a negative cycle. The overall U.S. economy contracted and the reduction in demand caused the California economy to suffer losses. But the hit was temporary, and once the recession was over, the economy started to grow again at a rapid pace—until it caught up with its normal long-run growth trend. Figure 10. Real State Personal Income 1 4 .4 14 1 3 .8 1 3 .6 1 3 .4 1 3 .2 2 0 08 . 1 2 0 06 . 3 2 0 05 . 1 2 0 03 . 3 2 0 02 . 1 2 0 00 . 3 1 9 99 . 1 1 9 97 . 3 1 9 96 . 1 1 9 94 . 3 1 9 93 . 1 1 9 91 . 3 1 9 90 . 1 1 9 88 . 3 1 9 87 . 1 1 9 85 . 3 1 9 84 . 1 1 9 82 . 3 1 9 81 . 1 1 9 79 . 3 13 1 9 78 . 1 Log Va lu es— Mill i on s o f D o l l a r s , $ 2 0 0 9 1 4 .2 195 A STRUCTURAL SHIFT I N T H E E A R LY 1 9 9 0 S on retail sales. It was hit more than average on the way down; taxable sales in California were down nearly 20% year over year in 2009. In contrast to the downturns in 2001 and the early But consumer spending is only one aspect of the 1980s, the downturn in 1990 was structural and there- downturn. Another feature of this downturn is the fore had long-term consequences for the state. In this collapse in international trade as a result of the case, California experienced the collapse of an impor- worldwide credit crisis and the impact that falling tant industry—aerospace and defense. Both industries demand from U.S. consumers and businesses is having went from being large, in the pre-Reagan years, to on the rest of the world. California has the most becoming even larger during President Reagan’s rush manufactured exports of any state according to Wiser to spend the former Soviet Union into defeat. trade data, and these exports were off—based on data available at this writing- by almost 30% since the start With the end of the Cold War and the so-called peace div- of 2009. idend, California saw an important part of its economy wither away substantially and suddenly. It took years Similarly California, as home to information for growth to return, and when it did, the new trend line technology (IT) and a variety of other business was lower. In short, the downturn had an impact that equipment manufacturing, is also over-exposed had a permanent effect on the state’s long-run growth. to declines in business investment, which has A couple of important points need to be made here. proportionally and in absolute terms declined even First, the unemployment rate in the early 1980s more than consumer spending. Indeed the 2001 cycle was higher than in the 1990s—higher, in fact, downturn, so mild as to almost not be a recession than at any point until the current cycle of today. at the national level, hit the Bay Area hard; it was Unemployment alone does not determine the long-run primarily a downturn in business spending. impact of a downturn on a state. Second, in none of these past downturns was California’s normal growth To put things in perspective, consider the downturn in rate affected once recovery had occurred. The claim nominal spending. In 2001, spending on all equipment that long-run growth potential can be stunted by and software fell by 12.4% from peak to trough, with a negative downturn has no basis in historical patterns. spending on IT falling just slightly more. This time, overall spending was down by over 20% at this writing IS THERE A SECOND STRUCTURAL SHIFT? and the downturn may not be over. Information technology spending was down 11%, almost as bad as in 2001. As noted in the national forecast, growth will return to the United States once the major imbalances (too much What kind of downturn is California suffering through consumer spending and overvalued assets) work their today? The state is seeing rough times for a number of way out of the system. The same is true for California. reasons. Take construction and real estate. California But will growth occur from a lower base or will we saw some of the largest increases in home prices and return to the long-run growth line that began after the sales activity, along with a secondary positive impact 1990s downturn? 196 While there is little doubt that the current recession From the peak in 2002, the dollar came down slowly is grim, Beacon Economics does not believe that the for several years. Then the dollar fell sharply in 2007 downturn will have permanent consequences for Cali- and early 2008, in response to the credit problems fornia. Even though the construction market has been that had yet to expand abroad. The dollar was hit hard, the state still has a substantial housing short- briefly back in line with its position at the start of the age. And there is going to be more demand for that bubble. Although the state felt pressure from internal housing since prices in 2009 reached reasonable levels. problems, the dollar decline gave the business sector a big boost. The dollar has since appreciated again, International trade is down. But trade will come but it almost certainly will have to come back down back once things recover—and with more emphasis to close the unsustainable trade gap, giving the state on exports than imports. This recovery is important another boost. because exports create far more jobs than imports (bringing in crates of consumer products for households in the rest of the country). And while the REMAINING ISSUES retail sector is suffering from withdrawal, consumer spending is simply settling to a more sustainable long- The state surely has its problems. Politics in run pace. Sacramento have become more shrill and partisan; serious policy issues are not being addressed. The Some might argue that growth in the state over the state’s revenue and expenditure system is broken, past few years was inflated by the real estate boom not and the regulatory system is a mess. California needs unlike the late 1990s, and that we will settle into significant investments in infrastructure and schools. a lower growth rate at the back end of the downturn. But these are challenges that can be met. Although real estate certainly stimulated local consumer spending and industry profits, it also hurt the In the mean time, the state’s positive attributes still state’s business climate because overly expensive make it one of the most desirable places to be. If homes made the area a costly place to do business. you don’t believe me, ask yourself this important The reverse situation can be expected to balance question—are you planning on moving away? Add it things out. up and things will be tough in the near future. But it is not time to pack up and move east. The California Lastly, the state was dealing with another competitive economy will improve and the state will shine again. issue - this time foreign rather than domestic. Between 1993, when the bubble began, and 2002, when it reached its peak, the real value of the U.S. dollar rose by 32% compared to the rest of the world. This development was largely a cause of the widening trade gap. And this was not good for California. We are an export-heavy state—both from a goods perspective (particularly in information technology) and a services perspective (tourism and intellectual property licensing). A weak dollar helps California in exporting. 197 Published on Dec 17, 2009 The Ralph and Goldy Lewis Center’s California Policy Options offers an unflinching assessment of the measures the State has undertaken to ad...
https://issuu.com/uclapubaffairs/docs/ca_policy_options_2010
CC-MAIN-2018-17
refinedweb
85,797
53.21
Q&A with Elton Stoneman on Migrating Workloads and Running Docker on Windows - | - - - - - - Read later Reading List Key Takeaways - Native Docker on Windows (supported by both Microsoft and Docker, Inc.) is available on Windows Server 2016 and Windows 10 - While Windows containers have a larger footprint than Linux, they are still roughly 10x more efficient than VMs because container processes run directly on the host server - Docker has a positive cultural impact as dev and ops teams start sharing not only artifacts - Dockerfiles and Docker images – but a common language and tools - Feature parity across Windows and Linux containers is expected by the end of 2017 - Microsoft is working on reducing the size of the base images and extending networking capabilities - Any Windows application which you can install and run without a UI should be able to run in Docker – many organizations are migrating applications from old versions of Windows (e.g. from Server 2003) to run on a modern, supported version such as Server 2016 These are still early days for Docker on Windows but the possibilities in terms of workloads keeps growing. InfoQ spoke with Elton Stoneman, author of the book Docker on Windows, and speaker at the recent WinOps conference, to understand how to run containers on Windows and which kind of workloads are a good choice for migration. InfoQ: Could you briefly introduce yourself, what you do and what brought you to the world of containers? Elton Stoneman: Sure. I'm an Azure MVP and a Pluralsight author - and I spent 15 years consulting before I joined Docker. My background is in Windows and .NET programming, typically large server-side applications using ASP.NET, WCF, Web API and SQL Server. I was working on a big Azure project in 2014, providing APIs to support an Android device. It was a cross-platform project, and the Linux team were using Docker to run their dev tools. I got interested, started using Docker a lot, started blogging and speaking about Docker and got invited to join the Docker Captains program (the Docker equivalent of Microsoft MVPs). Then a Developer Advocate role came up at Docker, Inc. and gave me a chance to focus 100% on Docker and the Microsoft ecosystem, and that's what I'm doing now. InfoQ: Could you tell us what's the current status of "native", so to speak, Docker on Windows? Stoneman: In container terms "native" means the application in the container uses the operating system of the host. If you run ten ASP.NET apps in Docker containers, you'll see ten instances of `w3wp.exe` in the task list on the server. The containers are still isolated units, and each app thinks it's on a separate server - with a hostname and an IP address - but it's the container processes which are isolated from each other. That's what makes Docker so efficient, running lots of containers on your server is just like running lots of apps on your laptop. Windows Server 2016 supports native Windows containers, and Docker Enterprise Edition is included in the Windows Server 2016 licence, so you get production support for your containers from Microsoft and Docker, Inc. InfoQ: Does the Docker host for Windows-based Docker containers have to run a specific Windows OS? Stoneman: You can only run Windows containers with process isolation on Windows Server 2016, and that can be on bare metal or VMs, on-prem or in the cloud. On the desktop, you can run Docker Community Edition on Windows 10. That uses a different isolation model (where each container runs in its own Windows Server 2016 kernel), but the way you run and manage containers is the same as on the server. InfoQ: Windows typically has a larger memory and resources footprint than Linux, so isn't there a risk of ending up running "fat containers" that very much resemble a virtual machine? Stoneman: There are differences between Windows and Linux containers, but Windows containers are still much more efficient than VMs. A Linux container could use Alpine Linux as the base (which is a 10MB operating system), and run the application in a single process. A Windows container might use Windows Server Core as the base (which is a 10GB operating system), and the application process will run alongside several background Windows services in the container. But that Windows container is still running the processes directly on the host server, there's no heavyweight VM in between the app and the compute resources. Typically we see customers get between 5X and 10X efficiency - so a server that can run 10 VMs could run 100 containers. Lots of Docker customers are seeing an immediate return on investment when they move to containers, because they can decommission a lot of servers or cloud VMs. There are storage efficiency gains, too. You package your application into a Docker image, which is a complete snapshot of one version of your app, with all its dependencies, configuration and application runtime. Images are split into layers which are shared, so if you have those ten ASP.NET apps packaged in Docker images, they all share the same 10GB Windows Server Core base image - only the delta between images is physically stored. InfoQ: Can you briefly guide us through the biggest hurdles and critical milestones so far for Docker on Windows, both from technical and possibly cultural point of views? Stoneman: The biggest cultural challenge is that this is a new way of running applications, and there is a learning curve for engineers and operations teams. But you can get started with Docker very quickly, and you soon see the benefits from having all your apps built, distributed and managed in the same way. The move to Docker often has a positive cultural impact. Dev and ops teams start working together on a common set of artifacts - Dockerfiles and Docker images - so they start talking the same language and using the same tools, and that can really help in the move to DevOps. Technically, there are still some features of Docker that are Linux-only, but there's a lot of work going into the next update of Windows Server, so by the end of 2017 we should have pretty much parity across Windows and Linux containers. The biggest investment companies need to make is in writing the Dockerfile to package their applications, and integrating Docker into their CI/CD process. Tools like Jenkins, TFS and VSTS all provide Docker support. The outcome is usually a much cleaner, simpler workflow, which makes it easy to deploy updates automatically, but it does take some work to get there. InfoQ: Docker was built upon Linux kernel isolation features such as cgroups and namespaces. How does this translate in the Windows world? Stoneman: Those core Linux features have been around for a very long time, and Docker built on them to make containers easy to use. They've never existed in Windows, but when Microsoft people were working on Windows Server 2016 they wanted to add support for containers on Windows. The engineering teams at Microsoft and Docker worked together to add that support. The implementation is different from Linux, but it exposes a similar API so that Docker can manage containers in the same way. If you want to learn about the internals, there's a great talk from Microsoft at DockerCon 16 which goes into detail. InfoQ: What types of Windows workloads can be safely migrated to Docker today? Do you have real world examples you could share? Stoneman: Any Windows application which you can install and run without a UI should be able to run in Docker. We usually work with clients who are "dockerizing" their own applications - from older ASP.NET WebForms apps, to new Go applications. Docker doesn't impose any restrictions on the style of the application, so you can have a monolithic web app running in a Windows Server Core container, and a microservices app running across multiple Nano Server containers, all running on the same cluster. We have a number of clients who are using Docker to migrate from older versions of Windows (think Server 2003). Then they can move to the cloud or on to modern infrastructure. At Microsoft Ignite we had sessions with customers walking through their Docker journey - MetLife and Fox are real-world examples. You can also package off-the-shelf applications to run in Docker containers, provided you can script the installation. There are some server workloads which you definitely can't run in Windows containers – Microsoft Message Queuing (MSMQ) is one example - because the Windows Server Core image doesn't support it. InfoQ: Who is working on and what is the roadmap for expanding support to more Windows workloads? Stoneman: Microsoft's main focus for Windows containers is reducing the size of the base images, and extending the networking capabilities of Windows Server, so we'll get closer to parity between Docker on Linux and Docker on Windows. Microsoft maintain images on Docker Hub for some of their key workloads: SQL Server, ASP.NET and .NET Core. There are also official images on Docker Hub, which are trusted apps curated by Docker and the product teams. These are mostly Linux right now, but you can run Java apps with the Windows OpenJDK image, and the NATS message queue also has Windows images. Anyone can package a Windows app into a Docker image and publish it on Docker Hub (if the product licence allows for that), so we will see a lot more open-source projects providing a Windows Docker image. Publishing an image on Docker Hub (or Docker Store if it's a commercial app) makes it very easy for users to try your app - all they need is Docker, everything the app needs to run is there in the image. InfoQ: How does Windows licensing work for containers? Stoneman: Windows licensing applies at the host level, so you pay for the number of servers or VMs running Windows. You don't need a licence for a Windows Server container, so if you can run 100 containers on one server, you only pay for one Windows licence. InfoQ: What is your recommended roadmap for adopting Docker on Windows, starting from zero? What kind of considerations are needed in terms of infrastructure/applications as well as process and skills? Stoneman: If you want to learn the basics then my talk from WinOps Docker on Windows: The Beginner's Guide is a good place to start. It covers the key concepts you need to know: Dockerfiles, images, registries, containers and orchestrators. Then if you want to get hands-on, you'll find the content for my Docker on Windows workshop on GitHub, which you can follow along to see how to move existing applications to Docker, and how that puts you in a good position to modernize them. After that you should be ready to run your own proof-of-concept and move one of your existing apps to Docker. Start simple - an ASP.NET web app without too many integrations is a good choice, and you should be up and running in Docker in a day or two. For larger organizations Docker, Inc. can help run the PoC with the “Modernize Traditional Applications” program. And of course you should get a copy of my book, Docker on Windows. InfoQ: In your talk you mentioned a helper tool called "image2docker", can you briefly explain what it does? Are there other tools to help migrate to Docker? Stoneman: Image2Docker is a PowerShell tool that migrates existing applications to Docker. It's targeted for ASP.NET apps right now, and it can connect to a remote machine, or a virtual machine disk, extract the application content from the source and build a Dockerfile to package that app as a Docker image. It's a good starting point for seeing how your app runs in Docker, and we use it for PoCs when we're working with clients who have an existing suite of apps that they want to move to Docker. Image2Docker is the only tool I know of that converts a deployed application to Docker, but a lot of IDEs have Docker support built-in for source code. Visual Studio 2017 has the highest feature set for adding Docker support to an application. It generates the Dockerfile to package the application image, and you can run the app in a container through Visual Studio and debug the app just as though it was running locally. InfoQ: Will a Windows IT person be able to leverage Docker without any Linux knowledge? Stoneman: Absolutely. Docker is cross-platform and it runs in the same way on Linux, Windows, IBM mainframes and the Raspberry Pi. If you only run Windows containers, you don't need to learn any Linux. You'll need to learn the basic Docker commands (like `docker image build` and `docker container run`), and how to package your application in a Dockerfile. The Dockerfile syntax is very simple, and mostly you'll be writing PowerShell or batch commands for the actual deployment in the Dockerfile, so you don't need to learn a lot of new stuff. InfoQ: Do you think Docker on Windows will be a step forward in breaking down OS-level silos (the "Windows IT" vs the "Linux IT") in large organizations? Or will those two parallel skillsets still be needed? Stoneman: All containers look the same to Docker, whether you're running a Go application in a Linux container, or an ASP.NET WebForms application in a Windows container. You can only run Linux containers on Linux servers and Windows containers on Windows servers, but you can join multiple Linux and Windows servers into a single cluster and manage all your workloads in the same way. Docker Enterprise Edition is very attractive to companies with diverse workloads for that very reason - you have a single pane of glass to manage all these apps. You build, deploy, scale, update, secure and administer them all in the same way using the same tool. For IT teams Docker makes it very easy to work with apps from "the other side". Windows developers can add analytics to their apps by running Elasticsearch and Kibana in Linux containers. Linux admins can build a CI/CD pipeline for SQL Server databases running in Windows containers. I think we will get to the point soon where it doesn't really matter what's inside the container, from a user perspective. Maintainers will still need to know the internals to package the most efficient and secure images, but I'm sure the tooling will evolve so that becomes a simple task too. About the Interviewee Elton Stoneman is a Microsoft MVP, Pluralsight author and InfoQ editor, and he works for Docker, Inc. Elton blogs and tweets about Docker, .NET and Azure and is a regular conference speaker. He’s looking forward to the nei xt DockerCon. Rate this Article - Editor Review - Chief Editor Action Hello stranger!You need to Register an InfoQ account or Login or login to post comments. But there's so much more behind being registered. Get the most out of the InfoQ experience. Tell us what you think Docker Windows SQL Server Containers by Digvijay Agarwal
https://www.infoq.com/articles/qa-elton-stoneman-migrate-workload-docker-windows?utm_source=articles_about_dotnet&utm_medium=link&utm_campaign=dotnet
CC-MAIN-2018-51
refinedweb
2,558
59.03
I have tried (and Failed) to install SimpleCV multiple times I am new to Python and SimpleCV, but I'm working from some textbooks, and I keep trying different ways to install and it keeps giving me warnings. Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. from SimpleCV import Shell Shell.main() Warning (from warnings module): File "C:\Python27\lib\site-packages\IPython\config.py", line 13 "You should import from traitlets.config instead.", ShimWarning) ShimWarning: The IPython.config package has been deprecated. You should import from traitlets.config instead. [0;32mSimpleCV:[1;32m1[0;32m> [0m please help! I have tried to work through using a couple other posts on here and this is my last attempt. Thank you in advance.
http://help.simplecv.org/question/177548/i-have-tried-and-failed-to-install-simplecv-multiple-times/
CC-MAIN-2018-51
refinedweb
141
69.89
Thanks Tim, I'm new to the group. Does this mean that most of the development is done on Linux? This might be a Windows (Microsoft) -specific issue. My tools are not that good, though I'll spend some time later today or tomorrow to better understanding what I'm seeing. All I know is that the most basic dump of leaked memory indicates quite a few problems in the Visual Studio environment. I'm guessing this to be the same issue that I'm bumping up against in my program. If there's anyone else who has useful Windows tools, any effort would be most helpful. I've described my changes to the program below. Richard --------------------------------- What I have done is put the following the declarative section of the program (line 41, after #includes): #ifdef _DEBUG #ifndef DEBUG_NEW #include <stdlib.h> #include <crtdbg.h> #define _CRTDBG_MAP_ALLOC #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) #define new DEBUG_NEW #endif #endif And then the following at the bottom of main(): #ifdef _DEBUG _CrtDumpMemoryLeaks(); #endif In reality the first change needs to be installed in all the ActiveMQ-cpp source code, but I haven't reached that point yet. This is a simplistic approach to instruct the memory allocator to track memory usage and then to dump the display leakage. (google for more details.) -- View this message in context: Sent from the ActiveMQ - User mailing list archive at Nabble.com.
http://mail-archives.apache.org/mod_mbox/activemq-users/201205.mbox/%3C1336919532156-4630522.post@n4.nabble.com%3E
CC-MAIN-2016-18
refinedweb
236
63.8
Hello friends, I hope you all are doing great. In today’s tutorial, I am going to give you a detailed introduction to the C++ Programming language. In cross-platform programming languages, C++ is the most popular that can be used to work on low and high-level applications. Bjarne Stroustrup was the founder of C++. He modified C language to develop C++ language. Control over system resources and memory can be attained by using C++. In 2011, 2014, and 2017 it was modified to C++11, C++14, and C++17. C++ is a middle-level language. It is advantageous to both programming languages low-level (drivers, kernels) and higher-level applications (games, GUI, desktop apps etc.). Uses of C++ C++ is one of the world’s most famous programming languages. It is used in today’s OS, embedded systems and GUIs. It provides a clear structure to programs, permits codes to be reused and lowering development costs as its an object-oriented language. Since it is portable and can be used to create applications that can be used on multiple platforms. It is very easy to learn. As it is close to C# and Java, so switching to C++ or vice versa is very simple. It is used in - Operating systems e.g. Linux-based OS - Browsers like UC browser, chrome, opera and firefox. - Games and graphics e.g. Photoshop - Clouds like Dropbox - Database engines like reedit Features of C++ Rich library support: - It is a simple language as programs can be split into logical units and parts. It has rich library support and many data types. Platform Dependent and Machine Independent: - It is machine-independent but platform-dependent. It does not run on windows but is executable on Linux. Middle-level language: - It is a middle-level language as we can do both low-level programmings(drivers, kernels, networking etc.) and build large-scale user applications (Media Players, Photoshop, Game Engines etc.) as a high-level language. 3rd party libraries: - C++ has rich library support as well as 3rd party libraries (e.g. Boost libraries) for easy, smart and rapid development. Fast execution: - For C++ speed of execution is very fast because it is compiled and highly procedural language. - Garbage-collection, dynamic typing etc. slow the execution of the program overall. Since there is no additional processing in C++ so it is fast than others. Provides direct Memory-Access: - It provides pointer support to manipulate storage addresses. This helps in low-level programming ( indirect control over memory addresses). Object-Oriented language: - It is better than C with respect to object orientation that helps it to maintain extensible programs so large-scale applications can be built easily. - Its friends and virtual features violate some important rules rendering it a completely object-oriented language. Amazing facts of C++: Some interesting facts about C++ are listed below - C++ name tells us that C language modified with ++ incremental operator is C++ language - The most famous language C ++ is used in commercial software. - Four primary features of OOP are supported by C++ - Inheritance - Encapsulation - Abstraction, and - Polymorphism - From Simula67 Programming language C++ gained the features of OOP. - For a C++ program to execute(at least main() function) , a function is the least requirement. Basic concepts of C++ : Basic concepts like syntax, variables, loop type etc will be discussed here. Syntax of C++: Here is the C++ basic program #include <iostream.h> using namespace std; int main() { cout << “Hi this is C++”; } - iostream is a header file and provides us with input & output streams. - namesspace std tells the compiler to use standard namespace. It can be used in 2 ways. - the return type of main () is int. - count << is used to print anything on the screen. - // is used to add single comment. For multiple comments /*multiple comments*/ is used Data types in C++: There are built-in as well as user-defined data types in C++. - In C++, classes are user-defined data types. - Built-in data types are int, float, double etc. - Derived data types are Array, function, pointer and reference. C++ Program to get a sum of 3 numbers //Program to receive three integer numbers and display their sum #include <iostream> using namespace std; int main() { int num1, num2, num3, Sum; //variables num1, num2, num3 and sum are declared as integers cout << “\n Enter Number 1: “; cin >> num1; cout << “\n Enter Number 2: “; cin >> num2; cout)<< “\n Enter Number 3: “; cin>>num3; Sum = num1 + num2 + num3; cout << “\n The sum of ” << num1 << num2 “ and ” << num3 << ” is ” << Sum; } Modifiers in C++ In C++, special words(called modifiers) are used to modify built-in data types. There are four main data type modifiers in C++, they are: - Long - Short - Signed and - unsigned These modifiers are with built-in data types to make them more precise and for expanding their range. - long and short modify the maximum and minimum values that a data type can hold. - Signed types include both +ive and _ive numbers as is the default type. - Unsigned, numbers do not have any sign, so they are always positive. Variables in C++ : - Variable is used in C++ to store any value, which can be changed in the program. - Variable is declared in many ways each with different memory location and functioning. - It is the name of the memory location allocated by the compiler to the variable. Variables are divided into two main types, - Global Variables - Local variables Global variables Global variables are those which declared only a single time and used again and again. They are declared outside the main() function. If only declared then assigned different values at different times in program lifetime. But when they are declared and initialized at the same time then they can be assigned any value at any point in the program. For example: Only declared, not initialized include <iostream> using namespace std; int x; // Global variable declared int main() { y=10; // Initialized once cout <<“first value of y = “<< y; y=20; // Initialized again cout <<“Initialized again with value = “<< y; } Local Variables - Local variables exist only between the curly braces, in which they are declared. - Outside the curly braces, they are unavailable and lead to a compile-time error. Example : include <iostream> using namespace std; int main() { int j=10; if(j<20) // if condition scope starts { int m=100; // Local variable declared and initialized } // if condition scope ends cout << m; // Compile time error, m not available here } C++ Program to find the curved surface area of a cylinder (CSA) (CSA = 2 pi r * h) #include <iostream> using namespace std; int main() { float pi = 3.14, Radius, Height, CSA; cout << “\n Curved Surface Area of a cylinder”; cout << “\n Enter radius (in cm): “; cin >> Radius; cout << “\n Enter height (in cm): “; cin >> Height; CSA = (2*pi*Radius)*Height; system(“cls”); cout << “\n radius: ” << Radius <<“cm”; cout << “\n height: ” << Height << “cm”; cout << “\n Curved Surface Area of a Cylinder is ” << CSA <<” sq. cm.”; } Output: - Curved Surface Area of a cylinder - Enter radius (in cm): 7 - Enter height (in cm): 20 - radius: 7cm - height: 20cm - The curved Surface Area of a Cylinder is 879.2 sq. cm. Operators in C++ : - Operators take one or more arguments and generate a new value. - For example : addition (+), subtraction (-), multiplication (*) etc, are all operators. - These are used to perform different operations on variables and constants. Errors in C++: There are three types of errors that occur in C++ programming Syntax Error: - The syntax is a set of grammatical rules to make a program. Every programming language has unique grammatical rules. - when grammatical rules of C++ are violated Syntax Errors occur. - For example: if you type as follows, C++ will throw an error. cout << “Hi welcome to C++” - As per the grammatical rules of C++, there should be a semicolon at the end of the statement. But, this statement does not end with a semicolon so Syntax Error occurs. Logical Error: It may be happened by the wrong use of variable or operator or order of execution etc. This means that the program is grammatically correct, but it contains some logical errors. So, “Logic Error” is also called Semantic error. Run time error: - During the execution of the program when some illegal action takes place, run time error occurs - For example, if a program tries to open a file that does not exist then it will result in a run-time error. Control Statements in C++: - The sequence of flow of instructions is changed by the use of control Statements. Selection statement - Statements can run sequentially, selectively or iteratively in a program. Sequence, selection and iteration processes are handled by every programming language. - If the statements are executed sequentially then the flow is called a sequential flow. In some situations, if the statements alter the flow of execution then this flow is called a control flow. Sequence statement - The sequential statement is executed one after the another only once from top to bottom. - These statements do not alter the flow of execution and are called sequential flow statements. These statements always end with a semicolon (;). Selection statement - When a condition is provided then selection statements are used. - In case when the condition is true then a true block (a set of statements) is executed otherwise a false block is commanded to execute. - This is also called a decision statement because it helps in making decisions for the set of statements to be executed. - Selection statements are if, if-else and nested if statements. if statement - The general syntax of the if statement is: if (expression) true-block; statement-x; - and flow chart for if statement is if-else statement - The syntax of the if-else statement is given below: if ( expression) { True-block; } else { False-block; } - And the flow chart for if-else statement is: C++ program to find either number is Even or Odd #include <iostream> using namespace std; int main() { int Num, rem; cout<< “\n enter a number: “; cin>>Num; rem = Num % 2; if (rem==0) cout<< “\n The given number” <<Num<< ” is Even”; else cout<< “\n The given number “<<Num<< ” is Odd”; return 0; } Output - Enter number: 12 - The given number 12 is Even Nested if It has three forms - If nested inside if part - If nested inside else part - If nested inside both if part and else part Iteration statement - The iteration statement is a set of statements that are executed again and again depends upon conditions. - If a condition evaluates to true, the set of statements (only true) is executed again and again. - As soon as the condition seems to be false, the repetition stops. This is also known as looping statement - The set of statements that are executed repeatedly is called the body of the loop. - The condition on which exits from the loop is called exit-condition or test-condition. - There are 3 kinds of loops in C++ - For loop - While loop - Do while loop for loop - The for loop is the easiest loop which allows code to be executed again and again. - The general syntax is: for (initialization(s); test expression; update expression(s)) { statement 1; statement 2; …………. } C++ program to sum from 1 to 5 using for loop #include <iostream> using namespace std; int main () { int i,Sum=0; for(i=1; i<=5;i++) { sum=sum+i; } cout<<“The sum of 1 to 5 is “<<Sum; return 0; } Output - The sum of 1 to 5 is 15 While loop - It allows the loop statements to be executed as long as the condition is true. - The while loop syntax is: while ( test expression ) { body of the loop; } - Flow chart for while loop is given below C++ program to sum from 1 to 6 using while loop #include <iostream> using namespace std; int main () { int i=1,SUM=0; while(i<=6) { SUM=SUM+i; i++; } cout<<“The sum of 1 to 6 is “<<SUM; return 0; } Output - The sum of 1 to 6 is 21 do-while loop - The do-while loop is used as an exit-controlled loop. In a do-while loop, after executing the body of the loop, the condition is evaluated. - The do-while loop syntax is: do { body of the loop; } while(condition); - The flow chart of the do-while loop is shown below Examples of C++ programs: 1. C++ Program to find the Total marks of three subjects #include <iostream> using namespace std; int main() { Int n1, n2 , n3, Sum; cout << “\n Enter Mark 1: “; cin >> n1; cout << “\n Enter Mark 2: “; cin >> n2; cout << “\n Enter Mark 3: “; cin >> n3; Sum = n1 + n2 + n3; cout << “\n The sum = ” << Sum; } 2. C++ program to find the Area of a Circle #include <iostream> using namespace std; int main() { int Radius; float Area; cout << “\n Enter Radius: “; cin >> Radius; Area = 3.14 * Radius * Radius; cout << “\n The area of circle = ” << Area; } So, that was all for today. In the next tutorial, we are going to discuss the Data Types in C++ in detail. If you have any questions regarding this tutorial, ask in the comments. Thanks for reading !!!
https://www.theengineeringprojects.com/2021/09/introduction-to-c-plus-plus.html
CC-MAIN-2022-21
refinedweb
2,178
60.55
HTTP/2 Client for Python Project Description HTTP is changing under our feet. HTTP/1.1, our old friend, is being supplemented by the brand new HTTP/2 standard. HTTP/2 provides many benefits: improved speed, lower bandwidth usage, better connection management, and more. hyper provides these benefits to your Python code. How? Like this: from hyper import HTTPConnection conn = HTTPConnection('http2bin.org:443') conn.request('GET', '/get') resp = conn.get_response() supports the final draft of the HTTP/2 specification: additionally, it provides support for drafts 14, 15, and 16 of the HTTP/2 specification. It also supports the final draft of the HPACK specification.. Documentation Looking to learn more? Documentation for hyper can be found on Read the Docs. v0.7.0 (2016-09-27) Major Changes - Added a ping method, allowing the user to use the HTTP/2 PING frame to check connection liveness before, instead of, or between issuing requests. Bugfixes - Don’t send WINDOWUPDATE frames on closed streams. - Clean up the outstanding stream reads on stream close. - Ensured that connection state is always unconditionally reset on stream close, regardless of whether the connection has a socket object open or not. 0.6.2 (2016-06-13) Bugfixes - Fixed packaging error made in prior release. 0.6.1 (2016-06-13) Bugfixes - Tolerate errors when attempting to send a RST_STREAM frame. - Ensure that calls to fileno() on the compatibility SSLSocket object actually work correctly. Thanks to @benlast! - Improved some problems with thread-safety in the Stream class. Thanks to @fredthomsen! - Allowed for systems to use hyper without the bundled cert file being present. Thanks to @JasonGowthorpe! 0.6.0 (2016-05-06) Major Changes - The HTTP20Connection object is now thread-safe, so long as stream IDs are used on all method calls. - Replaced the HTTP/2 state machine logic entirely to use hyper-h2. This will dramatically change the behaviour of the library in many situations, mostly for the better. However, this is also likely to introduce new bugs, so please be cautious. API Changes - Allow non-dictionary headers in request. - HTTP20Connection now has a force_proto keyword argument to allow the HTTP20Connection to ignore the NPN/ALPN result. - The --h2 CLI flag now ignores the result of NPN/ALPN negotiation when hitting HTTPS URLs. - Added support for HTTPS client certificates. - Notifications about streams being reset is now delayed to fire when the stream in question is next accessed, rather than immediately. Bugfixes - Overriding HTTP/2 special headers no longer leads to ill-formed header blocks with special headers at the end. - Vastly improved IPv6 support. - Fix converting unicode bodies to bytestrings on Python 2.7. - Allow overriding the HTTP/2 pseudo-headers from the CLI. - Fixed problems with incorrectly generating the HTTP2-Settings header. - Improved handling of socket errors. 0.5.0 (2015-10-11) Feature Enhancement - Pay attention to max frame length changes from remote peers. Thanks to @jdecuyper! Bugfixes - Prevent hyper from emitting oversized frames. Thanks to @jdecuyper! - Prevent hyper from emitting RST_STREAM frames whenever it finishes consuming a stream. - Prevent hyper from emitting lots of RST_STREAM frames. - Hyper CLI tool now correctly uses TLS for any https-schemed URL. - Hyper CLI tool no longer attempts to decode bytes, instead writing them straight to the terminal. - Added new --h2 flag to the Hyper CLI tool, which allows straight HTTP/2 in plaintext, rather than attempting to upgrade from HTTP/1.1. - Allow arguments and keyword arguments in abstract version of get_response. Software Updates - Updated hyperframe to version 2.1.0 0.4.0 (2015-06-21) New Features - HTTP/1.1 and HTTP/2 abstraction layer. Don’t specify what version you want to use, just automatically get the best version the server supports! - Support for upgrading plaintext HTTP/1.1 to plaintext HTTP/2, with thanks to @fredthomsen! (Issue #28) - HTTP11Connection and HTTPConnection objects are now both context managers. - Added support for ALPN negotiation when using PyOpenSSL. (Issue #31) - Added support for user-provided SSLContext objects, with thanks to @jdecuyper! (Issue #8) - Better support for HTTP/2 error codes, with thanks to @jdecuyper! (Issue #119) - More gracefully close connections, with thanks to @jdecuyper! (Issue #15) Structural Changes - The framing and HPACK layers were stripped out into their own libraries. Bugfixes - Properly verify hostnames when using PyOpenSSL. 0.3.1 (2015-04-03) Bugfixes - Fix blocking ImportError. (Issue #114) 0.3.0 (2015-04-03) New Features - HTTP/1.1 support! See the documentation for more. (Issue #75) - Implementation of a HTTPHeaderMap data structure that provides dictionary style lookups while retaining all the semantic information of HTTP headers. Major Changes - Various changes in the HTTP/2 APIs: - The getheader, getheaders, gettrailer, and gettrailers methods on the response object have been removed, replaced instead with simple .headers and .trailers properties that contain HTTPHeaderMap structures. - Headers and trailers are now bytestrings, rather than unicode strings. - An iter_chunked() method was added to response objects that allows iterating over data in units of individual data frames. - Changed the name of getresponse() to get_response(), because getresponse() was a terrible name forced upon me by httplib. 0.2.2 (2015-04-03) Bugfixes - Hyper now correctly handles ‘never indexed’ header fields. (Issue #110) 0.2.1 (2015-03-29) New Features - There is now a hypercommand-line client that supports making HTTP/2 requests directly from the command-line. Major Changes - Support for the final drafts of HTTP/2 and HPACK. Updated to offer the ‘h2’ ALPN token. Minor Changes - We not only remove the Connection header but all headers it refers to. 0.2.0 (2015-02-07) Major Changes - Python 2.7.9 is now fully supported. 0.1.2 (2015-02-07) Minor Changes - We now remove the Connection header if it’s given to us, as that header is not valid in HTTP/2. Bugfixes - Adds workaround for HTTPie to make our responses look more like urllib3 responses. 0.1.1 (2015-02-06) Minor Changes - Support for HTTP/2 draft 15, and 16. No drop of support for draft 14. - Updated bundled certificate file. Bugfixesobjects. Release History Download Files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/hyper/
CC-MAIN-2018-09
refinedweb
1,032
60.41
First Steps With Python Welcome! This tutorial details how to get started with Python. It’s written, edited, and updated by Derrick Kearney (Canadian, Python master, foodie) and Michael Herman (from the Real Python team, of course). - (1) What is Python? - (2) Getting Python – A Prelim - (3) How do I get Python? - (4) Confirming the Python Install - (5) Language Primitives - (6) Coding in Python - (7) Picking a Coding Editor - (8) Python Idioms = Happy Coding - (9) Counting to 10 - (10) Errors and Exceptions - (11) Python’s Power - Packages/Modules - (12) Next Steps - (13) Riding a Bike - (14) Simple Advice for New Coders - (15) Test your knowledge I (Derrick) help administer several Python groups where I field countless questions each day. In this post I’ll answer the question I hear the most, “How do I get started with Python?” (1). Python Properties Python is… - Strongly typed. It enforces data types so you can’t concatenate a string and a integer, for example. - Dynamically, implicitly typed. So, you don’t have to explicitly declare variable data types. Data types are enforced at runtime. - Case sensitive. For example, tokenand TOKENare two different variables. - Object-oriented. Everything is an object. (2) Getting Python – A Prelim Python is free, open-source software that works on Linux, Mac, Windows, and various other platforms (21 in total). It comes preinstalled on Mac and most distributions of Linux; however, you may need to download the latest version (see below). To check your version, open the terminal and run the following command: python -V Choosing a Python Version It can be confusing for both new and seasoned programmers on deciding between Python 2 or 3. Fortunately, there are few syntactical differences between the two and you can run both version on your computer. Currently, there are two main versions of Python - 2.x and 3.x. Only version 3.5.x is in active development, in terms of gaining new features and functionality, while Python 2.7.x as well as 3.2.x to 3.4.x are actively maintained. Which version is right for you? Well, that’s up to you. Honestly, there are few differences between the two that will affect you at this early stage, so either choice will suffice. Plus, once you’ve learned one, it’s not too difficult to learn the other. In general, if you’re just starting to learn Python, go with 3.4.x, since it’s a better version as there are added features along with plenty of bug fixes and refinements. However, 2.7x has much more support from third-party libraries. If you know you’ll need to use a library that has not been ported to version 3.4.x, then it may be best to start with 2.7x. The examples in this series will be shown in version 3.4.2, which is the current version as of writing. That said, most of the examples will work fine with either version since many of the features and updates added to 3.4.x were also added to 2.7.x. We’ll discuss any differences that you should be aware of as they arise. (3) How do I get Python? Regardless of your operating system, you can download Python from the Python Software Foundation (PSF). Grab the version specific to your OS and processor (32 or 64-bit). OS-specific instructions: - Mac: I strongly recommend using Homebrew to install and manage different version of Python. Check out the directions here. You can also download Python from the PSF. - Linux: Again, Python is included on various flavors of Linux. Be sure to upgrade to the latest version using the package manager, if necessary. - Windows: Download Python direct from the PSF. Windows users: Make sure you select the option to add Python to your system path during the installation process: (From the drop-down select the option, “Will be installed on local hard drive”.) (4) Confirming the Python Install Let’s do a quick sanity check to ensure Python installed correctly. Python Shell Open the Python Interactive Shell: - Mac: Open your terminal and run: pythonor python3, depending upon your installation. - Linux: Open your terminal and run: python - Windows: If you have only one version of Python installed simply run python. If you have both Python 2.7 and Python 3 installed, run pythonfor Python 2.7 and/or py -3for Python 3. Windows users: Ensure that your account has administrative privileges: Run the command prompt at an elevated level by right-clicking the command prompt icon, and then selecting ‘Run as Administrator’. The interactive Python Shell should open, and your command prompt or terminal window should look similar to this: Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> While you’re here, you might as well run your first line of code… Python 2: >>> print "Python is fun!" Python 3: >>> print("Python is fun!") If you’re running Python 2.x, the You should see: Python is fun! And that’s it: You’ve just written your first Python program! Each time you entered a line, Python immediately executed the statement, displaying the value between the quotes. Once done, you can use exit() to leave the Python Shell. Or: - Mac and Linux users: Ctrl-D plus Return - Windows users: Ctrl-Z plus Return Keep your terminal or command prompt open. We still have more to do! Let’s continue using the Shell as we run through the Python primitives. (5) Language Primitives In this section we’ll look at the Python primitives - variables, built-in data types, comments, syntax, and semantics. Variables Variables are containers for data. The syntax to declare them is: variable_name = variable_value. While you can name variables anything you’d like (except for a few reserved keywords), you should use a naming scheme that makes intuitive sense. The variable name should provide some indication as to what the values assigned to it are. For example, many new programers, use simple variable names like x and y. Do (err, try) not to do this. Instead, if you have two numbers - say 1 and 52 - use the variable names num1 and num2 instead of x and y. That way when others read your program, they can make an educated guess that num1 and num2 are probably numbers of some sort. Think of others when writing your programs, as well as your future self. Your future self will thank you. Built-in Data Types Python has a number of built-in data types such as numbers (integers, floats, complex numbers), strings, lists, tuples, and dictionaries. Each of these can be manipulated using: - Operators - Functions - Data-type methods Be sure to type each example out along with me. Numbers Numbers can be integers, floating points, Booleans, or complex numbers. The former three are the most important: - Integers are whole numbers - 1, 2, 22, 476, -99999 - Floats have decimal points - 1.0, 2.22, 22.098, 476.1, -99999.9 - Booleans represent either Trueor False(or 1or 0). They represent data that can only be one thing or another. Manipulating numbers Operators You’ve seen operators before. They’re things like addition (or concatenation) and subtraction, just like you learned in Elementary school. >>> 2 + 3 # Addition 5 >>> num1 = 10 >>> num2 = 9.99 >>> num3 = num1 + num2 >>> num3 19.990000000000002 >>> 8 - 5 # Subtraction 3 >>> 2 * 6 # Multiplication 12 >>> 12 / 3 # Division 4.0 >>> 7 % 3 # Modulus (returns the remainder from division) 1 >>> 3 ** 2 # Raise to the power 9 Putting your pre-algebra skills to the test, let’s look at comparisons, which evaluate to boolean values - e.g., either True or False (or 1 or 0). >>> 2 < 5 True >>> 4 > 10 False >>> 3 >= 3 True >>> >>> 5 == 6 False >>> 6 != 9 True Functions Python provides you with a number of built-in functions for manipulating integers. These are always available to you. Please note: These functions can be used on any data type. There are a number of modules available in the Python Standard Library as well, such as math. To use the functions associated with these modules, you’ll first have to import the module. More on this later. For now, let’s look at a few examples of built-in functions. float() - given an integer, this function returns a float. >>> float(9) 9.0 >>> float(-99999) -99999.0 int() - given a float, this function returns and integer. This function does NOT round the input up (ceiling) to the nearest integer – it simply throws out anything after the decimal point (flooring) and returns the number. So the input of 10.6 returns 10, NOT 11. Similarly, 3.25 returns 3. >>> int(10.6) 10 >>> int(3.25) 3 Data-type methods Besides functions, there a number of data-type methods associated with each type of number. float.is_integer() - tests if a float is finite. >>> (10.0).is_integer() True >>> (10.1).is_integer() False Strings Strings are lines of text that are declared with single or double quotes: >>>>> simple_string 'hey!' >>> "hello world!" 'hello world!' >>>>> escaped "can't" >>>>> not_escaped "can't" Manipulating strings Operators Like numbers, you can concatenate strings (string concatenation): >>> "happy" + " " + "birthday" 'happy birthday' >>> "my name is " + "john" 'my name is john' Functions Let’s look at just a few functions that are good to use for string manipulation: len() - given a string, this function returns the length of it. >>> len(name_string) 15 slice() - given a start and stop value, you can access a set of, or single, character(s). >>> print("Hello"[2]) l >>> print("Hello"[3]) l >>> print("Hello"[0]) H >>> print("Hello"[0:2]) He Data-type methods While we’ll only touch on a few data-type methods, be sure to check out the full Python documentation as there are a number of important functions that you should be aware of. string.capitalize() - returns the string with the first letter capitalized. >>>>> lower_case_string.capitalize() 'Michael' >>> ("empire").capitalize() 'Empire' string.format() - you can easily format values into strings. >>>>> greeting = "My name is {}".format(name) >>> greeting 'My name is John Doe' >>> string.strip() - returns the string with the leading and trailing whitespace removed. >>>>> are_you_happy.strip() 'Yes' Lists Lists, which are called Arrays in nearly every other programming language, group various types of data together. create_a_list = [] numbers_list = [1, 2, 3] strings_list = ["spam", "eggs", "cheese"] mixed_list = ["Hello", [1, 2, 3], False] As you can see above, lists may contain any data type (you can mix and match, too), including other lists or nothing at all. You can access parts of lists just like strings with indexes. The syntax is the same: >>> create_a_list = [] >>> create_a_list [] >>> numbers_list = [1, 2, 3, 200] >>> numbers_list [1, 2, 3, 200] >>> strings_list = ["batman", "superman", "iron man"] >>> strings_list ['batman', 'superman', 'iron man'] >>> mixed_list = ["Hello World", [4, 5, 6], False] >>> mixed_list ['Hello World', [4, 5, 6], False] You can access elements from the list from either the beginning or end of the list: >>> numbers_list[0] 1 >>> numbers_list[0:1] [1] >>> numbers_list[0:2] [1, 2] Watch how you can create a new list just by accessing the elements: >>> numbers_list = [1, 2, 3, 200] >>> new_list = numbers_list[0:3] >>> new_list [1, 2, 3] Negative indexes count from the last item backwards: >>> strings_list = ["batman", "superman", "iron man"] >>> strings_list[-1] 'iron man' If you nest a list within another list, you can access the inner list using multiple indexes: >>> mixed_list = ["Hello World", [4, 5, 6], False] >>> mixed_list[1][2] 6 Manipulating lists Operators Lists can be concatenated: >>> fruits = ["apples", "grapes", "oranges"] >>> veggies = ["corn", "kale", "mushrooms"] >>> grocery_list = fruits + veggies >>> grocery_list ['apples', 'grapes', 'oranges', 'corn', 'kale', 'mushrooms'] Functions In general, you can think of lists as strings - only each piece of data is an element. What does that mean in practical terms? Well, the same functions you use on strings can be used for lists. len() - given a list, this function returns the length of it. >>> numbers_list = [1, 2, 3, 200] >>> len(numbers_list) 4 slice() - given a start and stop value, you can access a set of elements. >>> hello = ["H", "e", "l", "l", "o"] >>> hello[2] 'l' >>> hello[3] 'l' >>> hello[0] 'H' >>> hello[0:2] ['H', 'e'] Data-type methods Again, check out the Python documentation to see all available list methods. list.append() - used to add an item to the end of a list >>> fruits = ["apples", "grapes", "oranges"] >>> fruits.append("blueberries") >>> fruits ['apples', 'grapes', 'oranges', 'blueberries'] list.sort() - sort this list >>> fruits.sort() >>> fruits ['apples', 'blueberries', 'grapes', 'oranges'] list.pop() - given an index value, remove an element from the list >>> numbers_list = [1, 2, 3, 200] >>> numbers_list.pop(2) 3 >>> numbers_list [1, 2, 200] Tuples Tuples are similar to lists, but they are immutable - which means they cannot be changed after creation. my_tuple = ("Michael", "Herman", 31, "Software Developer") Just like a list, you can also use indexes to access different elements: >>> my_tuple = ("Michael", "Herman", 31, "Software Developer") >>> my_tuple[1] 'Herman' Often tuples are used for dictionary keys since they should (err, must) be immutable. Manipulating tuples Operators Yes, you can add two tuples: >>> first_tuple = (1, 2) >>> second_tuple = (3, 4) >>> third_tuple = first_tuple + second_tuple >>> third_tuple (1, 2, 3, 4) Functions list() - used to convert a tuple to a list >>> first_tuple = (1, 2) >>> list(first_tuple) [1, 2] What about converting a list to a tuple? Is there a function for that? Where would you go to find out? Data-type methods Because tuples are immutable, many of the list methods don’t work on tuples. >>> first_tuple = (1, 2) >>> first_tuple.append(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'append' >>> first_tuple.pop(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'pop' >>> first_tuple.sort() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'sort' >>> first_tuple.reverse() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'reverse' Dictionaries Dictionaries are a type of associative array (an object) implemented using hash tables containing key/value pairs. They are unordered. my_dict = {"Key 1": "Value 1", "name": "michael herman", "pi": 3.14} You can return a key’s value using the following syntax: >>> my_dict = {"Key 1": "Value 1", "name": "michael herman", "pi": 3.14} >>> my_dict["name"] 'michael herman' >>> my_dict["Key 1"] 'Value 1' Manipulating dictionaries Research this on your own, using the Python documentation. Need help? Comment below. Speaking of comments… Comments are used to describe your code so other developers can quickly understand what’s happening (as well as your future self). # This a comment on it's own line # You create them with the hash symbol var = "Hello" # They can also be on the same line as code Need Help? Like a good friend, Python is always available if you get stuck. Perhaps you want to know how a specific object works, simply open the Python shell and then call help() to get help or dir() to see which methods are available for that particular object. (6) Coding in Python There are three basic approaches to coding in Python. We already used one of them - the interactive Python Shell. The Shell (redux) This is the least powerful of the three. Although you can create functions in the Shell, typically it is reserved for simple, one-line statements to get quick feedback on your code. For example, let’s look at a simple expression. Open the Shell and run: >>> 24 + 10 34 The Python Shell simply evaluated 24 + 10, adding the two numbers, and outputted the sum, 34. Try one more: >>> import this Take a minute to read the output. These are some important concepts in Python, which will help you write idiomatic Python code. Close the Python interactive Shell. Once closed, our code is gone. In other words, the code typed into the Python Shell is not persistent - and cannot be reused. As coders, we want code that we can reuse to save precious keystrokes. Unfortunately, the Python Shell fails in this regard. IDLE Python comes with a program named IDLE (named after Monty Python’s Eric Idle). IDLE is interactive and can be used exactly like the Python Shell. It can also be used for code reuse since we can create and save Python code. That said, IDLE still is not as powerful as the last method, so we will skip it for now. If you are interested in using IDLE check out the excellent guide One Day of IDLE Toying. Code Editor The best approach is to use an actual coding editor. Some people prefer an Integrated Development Environment (IDE), but a far simpler code editor is much better for learning purposes. Why? When you are learning something new you want to peel off as many layers of complexity as possible. Simplify things. By adding a complex IDE into the mix, which you will have to learn how to operate, you are just adding more and more layers, making the task - learning Python - even more difficult. (7) Picking a Coding Editor A Python program, in its basic form, is simply lines of text (code) saved in a file with a .py file extension. Python code can be written in something as basic as Notepad - but there’s no reason to put yourself through such an ordeal since there are much better options available. At it’s core, a code editor should provide a number of features that help a programmer create programs (Python scripts and modules, in our case). In most cases, code editors allow the user to customize the program itself, to suit your needs and style. What should you look for in a code editor? - Ease of use - Syntax highlighting - Auto-indentation - Tabbed views - Line numbering - Ability to customize the look and feel of the editor - Availability of add-ons Take a look at the following example: So, not only is the code easier to read in the editor (Sublime Text) on the top (due to the syntax highlighting and line numbering), but it’s also identifying three simple errors, one of which is a show-stopper. (Can you figure out which one?) Meanwhile, the editor (Notepad) at the bottom does not display the errors and is hard on the eyes since it’s black and while. Which editor should I use? One of the most popular code editors is Sublime Text 3 (shown above). It is powerful, cross-platform, and free to try out. Be sure to support the project by purchasing a license if you continue to use it. If you want something simpler, check out gedit, which is also cross-platform. Notepad++ is also a great editor, but it’s for Windows only. Both of these editors are free and although neither possesses the power of Sublime Text, they are still useful. A third option is Vim, which is free and available for Mac, Linux, and Windows. Vim has a steep learning curve but it has a loyal user base. Steve Francia’s Vim Distribution is the best programming setup for Vim that I have ever seen. I personally prefer Sublime Text 3. Check out the blog post Setting Up Sublime Text 3 for Full Stack Python Development to see how to customize it specifically for writing Python code. Remember: There are many different options when it comes to code editors, both free and commercial. Do your research, and don’t be afraid to experiment! Just remember: an editor should help you adhere to Python coding standards, practices, and idioms… (8) Python Idioms = Happy Coding PEP 8 – Style Guide for Python Code is the style guide for programming Python code. Study this. One idiom that trips up many new Python developers is indentation. Python uses indentation (4 spaces) to logically organize code into sections called [code blocks](. A code block starts with an indent and ends with a dedent (un-indent?). Incorrect indentation will generate an error in Python preventing your code from executing. And this is exactly where having a properly setup code editor pays off, since it will catch indentation errors and highlight them for you. You should also use spaces instead of tabs when indenting. Most editors will allow you to convert tabs to spaces, so that when you tab it is actually applying 4 spaces. Let’s revisit the errors from the above image… - Line 2 - No space around the <operator. As explained in PEP8, Python expects spaces around operators. This is not a critical error but problematic as your code should be clean and readable. - Line 4 - There are two errors here, including the show stopper. As stated above, Python uses indention to define code blocks. count = count + 1, is part of a block of code that starts on line 2, so that it must be indented 4 spaces in order for Python to include it in the code block. (9) Counting to 10 Ready to dive into a basic example?! If you are brand new to programming you may not fully understand the code but it’s the concepts that are important. Python is designed to read very easily and this example demonstrates that principle. We are going to fix the broken code above, and add one more code block to emphasize the concepts of code blocks and indentation. Many programmers get overwhelmed when they initially approach a problem. An effective approach to help solve the problem, regardless of size, is to logically divide the problem into parts. For example, let’s code a basic program that counts from 1 to 10. Each time the count increments we want to display a new number, and to help with the concept of code blocks we are going to show what happens after we reach 10. One approach to help in development of a workflow, is to use pseudocode. Let’s Make a Plan (pseudocode!) I like to keep things organized on my computer, so first create a folder, put it in your “documents” folder or someplace similar. I created a folder called, python_code. Learning to code is hands on, so open up your code editor, and enter the following code. Do not copy and paste no matter how tempting it is. Doing so will hinder learning. Python 2.7: # Python 2.7 count = 1 # Code block 1 while count < 11: print count count = count + 1 # Code block 2 if count == 11: print 'Counting complete.' Python 3: # Python 3 count = 1 # Code block 1 while count < 11: print(count) count = count + 1 # Code block 2 if count == 11: print('Counting complete.') Note that the first line of each example has a # (hash character), followed by a space and then an explanation. This is an inline comment. Such comments have a number of purposes, but for the most part they are used to either explain code or summarize a specific approach a developer took. Do the comments in the above examples make sense to you? If not, change them. Finally, as you will soon come to find out, comments are ignored by Python when the code is executed. Did you notice that the examples use both single =, and double ==? This can be confusing. - n the expression count = 1, the =assigns the value of 1 to the variable named count. - In the conditional if count == 11:, the ==compares the value of countwith 11, returning a boolean Trueor False. Can you tell what the statement evaluates to in the above example after each iteration? Save the file as count_to_ten.py in the folder you created then exit the editor. Open a terminal or command prompt and navigate to the folder you created. Now run the code: python count_ten.py You may need to replace pythonwith python3or py -3, depending on your setup. See Step 4 for more info. And the output should look something like this: Congrats! You just wrote your first program. (10) Errors and Exceptions Errors are something that irritate and frustrate programmers at every level of experience. In Python, there are two types of code-based errors, syntax errors and exceptions. Syntax Errors We have already seen this error already - incorrect indentation. Syntax errors will prevent execution of the program. In this example, the if statement is missing a colon to end the statement. As you can see Python is very helpful to point out the error: >>> if x < 9 File "<stdin>", line 1 if x < 9 ^ SyntaxError: invalid syntax Exceptions Exception errors occur during program execution. Python has a number of built-in exceptions. For example: >>> 12/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero Semantic Errors Semantic errors are errors that happen as a result of one or more problems in logic. These errors can be more complex, because no error is generated. The code runs but generates unexpected and/or incorrect output, or no output. A classic example of this, would be an infinite loop that most new programmers experience at least once. (11) Python’s Power - Packages/Modules One of the great things about Python is the plethora of available modules, both built into the Python core and third party packages/libraries - used to extend the language. These modules can be very helpful. Some of the more utilized built-in Python modules include: - math: mathematical functions from the standard library of the C (you’ve seen this one already) - random: a pseudo-random number generator - datetime: used for manipulating dates and times - re: for working with regular expressions For example, here we import math to use pi, sqrt (square root) and pow (raising to the power): Warning: Do not name your Python files the same as a module - like math.py or random.py. This will cause conflicts, resulting in unexpected behavior in your code. So if you are using the math module, do not name your file math.py. Make sense? Pip The best way to manage Python’s third party packages/modules is with pip. New coders frequently hit a wall when they are following some example code and they see the following error when they try to run the code: ImportError: No module named MODULE_XXXX. These modules need to be manually installed using Pip. In Python 3, pip, called pip3, is included. If you used Homebrew to install Python, pip is included as well. Starting with Python 2.7.9, pip is also included. If you are using a Python version prior to 2.7.9, follow these instructions to install pip: - Download get-pip.py, confirm that the file was saved with a .py extension. - Navigate to the location of the downloaded file in the Terminal or Command Prompt. - Run: python get-pip.py - Read the official pip documentation for more information. (12) Next Steps There are plenty of online tutorials, books, and videos freely available. My first stop was one of the most popular free choices, Learn Python the Hard Way. Zed Shaw’s tutorial is laid out in a progressive and logical exercise format. I found it very useful for learning the syntax, but I needed more. One of the best ways of learning how to code is by building - the project driven learning approach. That’s how I came across Real Python. There are three Real Python that cost a modest fee, which are frequently updated (usually bi-monthly) to keep up with changes (free of charge). Another place that truly helped me was MIT’s course, Introduction to Computer Science and Programming, which covers various computer science concepts along with Python. The course can be found in two locations. - The Harvard and MIT non-profit online initiative (Edx.org) offers the course in two parts. They are challenging and provide an excellent approach to problem solving. Both parts are graded. - The other route is from the MIT open courseware, Introduction to Computer Science and Programming MIT 6.00x. The course is not graded, but it has a very active online community that is quite helpful. There are other online courses of course. Again, this is personal choice, so do your own research. Another source of free learning materials comes from the PSF: Above all, it is important that you do not fall into finding the “best” book or video search and get lost. Do some research. Ask around. But pick something and stick with it! Open your code editor and start coding! Make a commitment to yourself to complete it. (13) Riding a Bike Coding is like riding a bike: You can watch people to see how it is done, and sometimes you can get a push, but in the end it is a solo event. When I get stuck, or need to brush up on a new concept, the first place I go is Google. If I get an error message, typing in the exact error message, into Google, will often bring up a result in the first page that solves my problem. - The official Python Docs - Python 2.7 or Python 3 - Tutorials Point has some very simple and easy to follow examples when I need a quick refresh. - Jeff Knupp’s website (the author of the Idiomatic Python series of tutorials and books) - The Real Python Blog has more specific topics and advanced subjects like Python’s Web Frameworks, Django and Flask. - Bernd Klein’s Python Course contains excellent coverage of Python; his discussion of advanced topics is really helpful. - Stack Overflow, the Q&A for coding, has some great explanations of Python topics. How Python can slice a string, is one truly excellent example. If you get stuck on a problem, try these simple suggestions: - Stop coding! - Get out a piece of paper and map out how to solve the problem using plain words (pseudocode); use a flow chart if necessary. Refer to the example above. - At some point you will be introduced to Python’s exception handling - the try/exceptblock. Do not use use a tryuntil your code is working. The trycan suppress valuable error messages that help identify problems in code. - If you are not getting expected output - i.e., perhaps Python is displaying a word instead of a number (incorrect data type) - add a print statement right after the variable assignment and then right before the expected output. This is an effective, quick and dirty problem solver. - If you are still stumped, a great tool is the Python Visualizer. This tool allows you to ‘step through’ your code as it executes. The Python Visualizer has examples to help you if needed. - One final note - and this is very important - is that a frustrated brain is not going to help. When you start to get annoyed because something is not working, take a break, clear your brain. Go for a run. Do something else. You will be amazed just how effective this can be. Often, you’ll come back with clear eyes and see a simple typo, a misspelled keyword, etc. (14) Simple Advice for New Coders I say this in the nicest kind of way - no one is going to spoon feed you. Coders expect other coders - yes, even beginners - to try and resolve the issue themselves. At some point we all need guidance, though. Once you have tried and truly have hit the wall ask for help, before you smash your keyboard or other inanimate object(s). There are a number of places to get help - code forums, Facebook Groups, the IRC channel #python, to name a few. Take a minute to read any rules or guidelines for any of the groups that you use. Make it easy for others to help you by explaining the problem and what you have tried. If there is an error, include that information as well. Have fun coding! (15) Test your knowledge - What does it mean that Python is a strong, dynamically typed language? - How do you access the Python Shell? - How do you declare’s a dictionary? - Why should you use comments in your code? - Test out the help()function. What did you learn? - Pass in floatto the dir()function. What did you learn? - One primitive that we didn’t go over is None. What does it represent? - You can check the data type of a variable or a value by using the type()function. Test this out using various data types and variables. What did you learn? Open your text editor and create a new file called exercise.py. Copy and paste the following code into the file: ########################################################################## ## Modify the variables so that all of the statements evaluate to True. ## ########################################################################## var1 = var6 = var2 = var3 = var4 = var5 = ############################################ ## Don't edit anything below this comment ## ############################################ # integers print(type(var1) is int) print(type(var6) is float) print(var1 < 35) print(var1 <= var6) # strings print(type(var2) is str) print(var2[5] == 'n' and var2[0] == "p") # lists print(type(var3) is list) print(len(var3) == 5) # tuples print(type(var4) is tuple) print(var4[2] == "Hello, Python!") # dictionaries print(type(var5) is dict) print("happy" in var5) print(7 in var5.values()) print(var5.get("egg") == "salad") print(len(var5) == 3) var5["tuna"] = "fish" print(len(var5) == 3) Following the instructions, update the code. When done, run the code from your terminal to test using the python exercise.py command. Good luck! Now that you know the basics of Python programming, be sure to check out the wide range of Python tutorials here at Real Python to continue building your skills. You can find all of our tutorials by clicking here. 🐍 Python Tricks 💌 Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team. What do you think?
https://realpython.com/learn/python-first-steps/
CC-MAIN-2018-05
refinedweb
5,632
73.58
Explore the tree structure of an XML document with xmllint's shell mode. xmllint is a command-line tool available as part of libxml2 (). It is included in distributions such as Cygwin () and Red Hat Linux (). You can also download xmllib2 individually from. xmllint has an interactive shell mode that lets you traverse an XML document's tree structure as if it were a file structure, allowing you to examine any node in the tree discretely. Provided that you have an Internet connection, this shell mode will work on remote files as well as local ones. This hack will show you how it's done. While in the working directory, we first invoke the shell on an XML document with xmllint: xmllint --shell time.xml / > A prompt appears (>). The location in the tree is shown to the left of the prompt (/), but with the depth of only one node. Enter the dir command to see information about the document or root node, and follow that with the base command to see the base URI of the document being explored: / > dir DOCUMENT version=1.0 encoding=UTF-8 URL=time.xml standalone=true / > base time.xml /> Move to a different node with cd, followed by another dir, then by a cat command: / > cd time/atomic atomic > dir ELEMENT atomic ATTRIBUTE signal TEXT content=true atomic > cat <atomic signal="true"/> atomic > A dir gives you information about the node, and cat gives you the XML representation of the node. Try the validate directive: atomic > validate validity error : no DTD found! atomic > time.xml doesn't have a DTD associated with it, so load valid.xml (which has a document type declaration) and try validate again: atomic > load valid.xml / > validate / > load replaces the current document time.xml with valid.xml, so validate is successful this time (no bad news means success). Use cd to move down the tree to time, enter pwd to see the path to the current node, and then enter du to see the element names in the subtree: / > cd time time > pwd /time time > du time hour minute second meridiem atomic time > Save the document in a new file with the save command, and then exit the shell with bye (exit and quit work, too): time > save timeagain.xml time > bye You can also invoke the shell on a remote file (follow it with base): xmllint --shell / > base / > You will be able to use the same commands on a remote document as you did on the local file. A list of xmllint's shell commands concludes this hack. Following are the shell commands available in xmllint's shell mode: Display the xml:base of the node. Leave the shell (same as exit and quit). Display the path to the node, if one is given, or the path to the current node. Change the current node to the path if given and unique, but change to the document or root node if no argument is given. Dump information about elements, attributes, namespaces, and so forth. Select the current node or node in the path, if given. Show the structure of the subtree under the current node or the path, if given. Leave the shell (same as bye and quit). Show help. Display memory usage. Load a new document with the given name. List contents of the path if given or the current directory. Display the path to the current node. Leave the shell (same as bye or exit). Save the current document to the document name if given or to the original name. Check the document for errors. Write the current node to the given filename.
http://etutorials.org/XML/xml+hacks/Chapter+3.+Transforming+XML+Documents/Hack+35+Explore+a+Document+Tree+with+the+xmllint+Shell/
CC-MAIN-2017-22
refinedweb
607
73.27
This article presents an overview of CRUD operations, using a single stored procedure in ASP.NET MVC of real- time projects CRUD means create update and delete. With ASP.NET in MVC, we can also perform CRUD operations using stored procedure. Description Using a single stored procedure means selecting, updating, inserting and deleting all SQL queries; we can put in one stored procedure and perform this CRUD operation by calling only this single stored procedure. Step 1 Create MVC Application named “SatyaMvc4Crud”. Step 2 Create a model class file called Customer.cs. Code Ref Code description Here, I have created some attributes to check validation of controls, which are based on control values. For textbox name and address validation, I have put [Required(ErrorMessage = "Your Message")]. This code will be executed, if your input is empty in controls. Now, if the user puts something but this does not satisfy the standard validation, then the code will be, as given below. [StringLength(4, ErrorMessage = "Name should be less than or equal to four characters.")] The user can put only four characters to control the input values. Like this, you can check for other attributes, which are based on control validation values. Here, I will declare 6 different entities to access the user and inputs. For every entity, I required an attribute to show the validation message failed for the end users. e.g. [Required(ErrorMessage = "Enter Your Name")] Like this required attribute, I used StringLength, Display, DisplayFormat, RegularExpression attributes. We have used some attributes. For this, we have to add one namespace. using System.ComponentModel.DataAnnotations; In name part, I can enter up to 4 characters. [StringLength(4, ErrorMessage = "Name should be less than or equal to four characters.")] In address part, I can enter up to 10 characters. [StringLength(10, ErrorMessage = "Address should be less than or equal to ten characters.")] In MobileNo. part, I can enter only 10 digit valid phone no. In an E-mail Id part, I can enter only a valid E-mail Id with @ symbol. In Date Time part, I can enter only valid date, which should be less than current date. For Custom validation of the entities, Code Ref is given below. Here, I have used one Custom Validation class to customize your Date time validation. For this, I created one class file in Models folder named “CustomValidationAttributeDemo.cs” . Here, I used one date time variable to access date time . Thus, I put some code to take the user’s birth date. Birth date should always be less than today’s date. Here, I used one class, ValidBirthDate, that is inherited from ValidationAttribute class. Here, System.ComponentModel.DataAnnotations.dll file references for this class files. #region Assembly System.ComponentModel.DataAnnotations.dll, v4.0.0.0 // C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.ComponentModel.DataAnnotations.dll #endregion The ValidationResult override method is used to represent a container for the result of the validation request. The ValidationContext class acts as a parameter inside ValidationResult override method. It is used to describe a context in which validation check is performed. In custom validation class, I used Student.cs for DATE TIME entity. According to this, the user input date should be less than today’s date. Here, CustomValidationAttributeDemo is the name of the Model Class and ValidBirthDate class is the child class of ValidateAttribute base class. Step 3 Create a table to add stored procedure to perform CRUD operation in MVC. Table SQL Ref Table SQL Description Here, six columns are same as entities declared in models class “Customer.cs”. Here “[CustomerID]” is the primary key and auto increment feature is added in these columns. Step 4 Now, create a stored procedure to perform CRUD operation in MVC. Stored procedure Script Ref Stored procedure Script description Here, five @Query parameters with different value for Insert/ Update/ Delete/ Select/Search statement. Here (@Query = 1) means for insertion of the records. Like this, other (@Query = 2 to 5) is assigned for other operation performances. By using single procedure by using this individual query parameter values; we can perform different operations. Step 5 Create a class file called DataAccessLayer.cs inside manually created folder named DataAccess. To add connection string, add name as well as stored procedure name to perform CRUD role. Code Ref Here, I will show how to implement query parameter value, which is 1 to implement in this class file to perform insert operation. In this InsertData() function, I used @Query = 1 value to perform insert operation. Here, I have added stored procedure name. To perform update operation, I have added the code in UpdateData function. To perform delete operation, I have added the code in DeleteData function. To perform select list of data, I have added the code in Selectalldata list function of customer model class. I have added one for loop to perform selection of all the data loop wise by using customer model class. Now, I will filter the records by using customer Id values. I have added the code given below. Thus, I have added customer Id parameter in a function of customer model class. Now, I have closed the connection in every functions in this class by using catch and finally block. Step 6 Create a controller class file called CustomerController.cs. In this controller class file, I have created one controller action method. Here, DataAccessLayer is added as a reference to use all its methods. The code is given below for checking model is valid or not. Here, if the condition satisfies, then model state will be valid, else the data will not save properly. Here, I added the show details view page name as soon as the data is inserted successfully, the page will show you the list of inserted data. In ShowAllCustomerDetails action result method, the Selectalldata of DataAccessLayer class is used. In Details action result method, the SelectDatabyID of DataAccessLayer class is used. The passed parameter value with the related data will be shown in the corresponding view page. The edit action result method has two attributes httpget and httppost. For httpget attribute In “Edit” action result method, the “SelectDatabyID” of DataAccessLayer class is used to step update data by using this particular data. The passed parameter value with the related data will be shown in the corresponding view page. For httppost attribute, the edit controller action method takes customer model class object and UpdateData of DataAccessLayer class is used. In Delete action result method, the DeleteData of DataAccessLayer class is used. The passed parameter value with the related data will show to perform delete operation in the corresponding view page. Step7 Now, create view cshtml file called ShowAllCustomerDetails.cshtml, InsertCustomer.cshtml. ,” Edit.cshtml”,” Details.cshtml”,” Delete.cshtml”. Code ref. of InsertCustomer.cshtml In this view page, I have added customer class reference or namespace. To make validation summary active, use this code. Now, I have added some code to make textbox and label control according to customer model class entities. To add label control, the code is given below. @Html.LabelFor() To add textbox control, the code is given below. @Html.EditorFor() To add validation messages, as defined in customer model class and customized model validation class, the code is given below. @Html.ValidationMessageFor() Here, two types of buttons are used to save the data. Here, two types of buttons are used; where one is to reset the data. After saving data, the details view page will come with all the saved data. Here, ShowAllCustomerDetails is the name of the controller action method as well as view name. Here, I have added one hyperlink to redirect to other page. Code ref. of Edit.cshtml In this view pag,e the editor and label controls will bound existing data to update it. Hence, the data as in insert view page will load in corresponding HTML helper control and the user will update, as per requirement. After update process completes, the view details page will come. Here, I used multiple submit button for different actions. Here, I have added hidden field control associate with customerid to perform an edit operation. Code ref. of Details.cshtml In this view page, the data inserted and updated data will show for reporting purpose. Here, no submit button is required to take action in page event. Afterwards, the page will redirect to view details page. Code ref. of Delete.cshtml Code description In this view page, the delete confirmation text message is added in header. In button event, JavaScript message was added and the user will decide whether it will be deleted or not. The data is loaded and is based on the selection of customer id and data associated with the entities defined in customer model class, which will be deleted. Here, I have added hidden field control associate with customerid to perform delete operation. After this the page will redirect to view details page. Code ref. of ShowAllCustomerDetails.cshtml Code description In this page, all the data will be visible along with EDIT/ DELETE/ DETAILS link to perform Crud operation. The data will be shown, using “@Html.DisplayFor” html helper control in looping. Here, I added the namespace of customer model class. The title of the page will be written here. To go to new customer insertion view page, the code is given below. Here , Link name : "New Customer", The method defined in customer control class file as well as data access layer class file is InsertCustomer, Controller Name: "Customer" Here, I am using tempdata method mechanism to transfer the data from one page to other. To show insertion successful message, the code is given below. To show update successful message, the code is given below. To show delete successful message, the code is given below. To get current data time for better visualization to the client, the code is given below. Step 8 Add connection string in Web.config file. Here, “mycon” is the connection string name to be mentioned in Data Access Layer class file to make connection to the database as well as make CRUD operation. Now, put your correct connection string . Step 9 Set start page when MVC page loads first time. Here, I have mentioned set start page. Here, Controller name is Customer. Now, the view name/ controller action method is ShowAllCustomerDetails. Step 10 You can customize the style of your own view design by using Site.css. Here, you can add color, font size, font style and margin etc. Step 11 Add and check reference Dll/ Assembly files to check version and other information. In the References folder, you can check all DLL file information by right click and going to properties. OUTPUT The set start page URL is given below. Load data details with CRUD functionalities Insert page Update page Details page for report requirement Delete page For delete confirmation, it is, as shown below. Total Operations In One Flow Show all the data on the page is given below. Insert some data Update some data Details of some data Delete of some data Now, the deleted data is not showing that it is empty now. To insert new records, click the New Customer link. Check date and time at footer of the show details view page. Like above mentioned methods, you can implement CRU operation, using MVC in your real time scenario. View All View All
https://www.c-sharpcorner.com/article/crud-operation-using-single-stored-procedure-in-asp-net-mvc-of-real-time-proje/
CC-MAIN-2021-43
refinedweb
1,898
57.57
#include <gromacs/utility/stringutil.h> Stores settings for line wrapping. Methods in this class do not throw. Initializes default wrapper settings. Default settings are: Returns the indentation set with setFirstLineIndent(). If setFirstLineIndent() has not been called or has been called with -1, indent() is returned. Sets a continuation marker for wrapped lines. If set to non-zero character code, this character is added at the end of each line where a line break is added by TextLineWrapper (but not after lines produced by explicit line breaks). The default ( '\0') is to not add continuation markers. Note that currently, the continuation char may cause the output line length to exceed the value set with setLineLength() by at most two characters. Sets the indentation for first output line after a line break. If this method is not called, or called with indent equal to -1, the value set with setIndent() is used. Sets the indentation for output lines. If this method is not called, the wrapper does not add indentation. Sets whether final spaces in input should be kept. This means that wrapping a string that ends in spaces also keeps those spaces in the output. This allows using the wrapper for partial lines where the initial part of the line may end in a space. By default, all trailing whitespace is removed. Note that this option does not affect spaces before an explicit newline: those are always removed. Sets the maximum length for output lines. If this method is not called, or is called with zero length, the wrapper has no maximum length (only wraps at explicit line breaks).
https://manual.gromacs.org/current/doxygen/html-full/classgmx_1_1TextLineWrapperSettings.xhtml
CC-MAIN-2021-39
refinedweb
268
75
Shopify / Liquid specific loop index within loop In Shopify I am trying to cycle through some metafields that contain feature titles. Then I need to cycle through some other metafields and get the feature description based on the current loop index. This code works just fine for me, but it is very inelegant and I'm sure there is a much better way to achieve the same result! {% for field in product.metafields.feature_title %} <h4>{{ field | last }}</h4> {% assign i = forloop.index %} {% if forloop.index == 1 %} <p>{{ product.metafields.feature_description.001 }}</p> {% endif %} {% if forloop.index == 2 %} <p>{{ product.metafields.feature_description.002 }}</p> {% endif %} {% if forloop.index == 3 %} <p>{{ product.metafields.feature_description.003 }}</p> {% endif %} {% if forloop.index == 4 %} <p>{{ product.metafields.feature_description.004 }}</p> {% endif %} {% if forloop.index == 5 %} <p>{{ product.metafields.feature_description.005 }}</p> {% endif %} {% endfor %} Additionally there is a flaw that this is limited to 5, or whoever many if statements creates. Cheers, DB Answer Solution: not tested but something like this should work: {% for field in product.metafields.feature_title %} <h4>{{ field | last }}</h4> {% capture idx %}00{{forloop.index}}{% endcapture %} {% assign key = idx | slice: -3, 3 %} <p>{{ product.metafields.feature_description[key]}}</p> {%.
https://e1commerce.com/items/shopify-liquid-specific-loop-index-within-loop
CC-MAIN-2022-40
refinedweb
195
54.29
Author: bandaram Date: Thu Nov 3 16:39:09 2005 New Revision: 330672 URL: Log: DERBY-675: The "readLine" method in ODBCMetadataGenerator.java was treating single backslashes as "end-of-line" markers and hence was not recognizing escaped sequences like "\n". It turns out that the check for backslashes in that method is unnecessary, so this patch removes it. I ran the metadata.java and odbc_metadata.java tests with this patch and they ran okay, so I think it should be safe. I still want to run some more tests tonight, just to be sure, but I thought I'd post the patch now since it is affecting another developer's current work (Mamta's). Submitted by Army Brown (qozinx@sbcglobal.net) Modified: db/derby/code/trunk/java/build/org/apache/derbyBuild/ODBCMetadataGenerator.java Modified: db/derby/code/trunk/java/build/org/apache/derbyBuild/ODBCMetadataGenerator.java URL: ============================================================================== --- db/derby/code/trunk/java/build/org/apache/derbyBuild/ODBCMetadataGenerator.java (original) +++ db/derby/code/trunk/java/build/org/apache/derbyBuild/ODBCMetadataGenerator.java Thu Nov 3 16:39:09 2005 @@ -23,6 +23,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.LineNumberReader; import java.io.FileWriter; import java.util.Properties; @@ -230,39 +231,51 @@ // JDBC query that we read from metadata.properties. StringBuffer query = new StringBuffer(); - // We assume no single line/query is greater than 1K in - // length, and we'll fail if this isn't the case. The - // limit of 1K was just picked arbitrarily; this can be - // increased if needed at a later time. - char [] line = new char[1024]; - - for (int count = readLine(is, line); - count != -1; count = readLine(is, line)) + // Note: We use ISO-8859-1 because property files are + // defined to be that encoding. + LineNumberReader reader = + new LineNumberReader(new InputStreamReader(is, "ISO-8859-1")); + + String line = null; + for (line = reader.readLine(); line != null; + line = reader.readLine()) { - if (count == 0) + if (line.length() == 0) // blank line; ignore continue; - else if (line[0] == '#') { + else if (line.charAt(0) == '#') { // comment; write it to file. - odbcMetaFile.write(line, 0, count); + odbcMetaFile.write(line); odbcMetaFile.write("\n"); continue; } - // Verify that we haven't passed our limit. - if (count >= line.length) { - throw new IOException( - "Encountered line longer than expected when reading metadata " + - "file; either shorten the line, or increase the limit..."); + // Write the line, then add an end-of-line to maintain + // readability. + query.append(line); + query.append("\n"); + + // Check to see if this is the last line of the query. + boolean done = true; + for (int lastNonWS = line.length() - 1; + lastNonWS >= 0; lastNonWS--) + { + char ch = line.charAt(lastNonWS); + if (!Character.isWhitespace(ch)) { + // this is the last non-whitespace character; if it's + // a backslash, then we continue building the query + // by reading the next line. + if (ch == '\\') { + // then continue building the query. + done = false; + } + break; + } } - // "+1" in next line because we added a "\n" at the end and - // we want to include that, for sake of easier reading. - query.append(line, 0, count+1); - - if (line[count-1] == '\\') - // then continue building the query. + if (!done) + // read next line and append it to current query. continue; // Take the query and see if we need to generate an ODBC- @@ -1055,56 +1068,6 @@ queryText.replace(pos - 1, pos + fragKey.length() + 1, getFragment(fragKey)); } - - } - - /* **** - * readLine - * Reads a line from the received input stream and stores it - * into the received character array. In this method, we - * consider the end of the line to be either 1) "\n" char, or - * 2) a single backslash "\", which is used in metadata - * queries to indicate line continuation. After reading - * a line, we append an EOL to it for formatting purposes, - * but that last EOL is NOT included in the count of - * characters. - * @param is The input stream from which we're reading. - * @param line The char array into which we're reading. - * @return the number of characters read from the - * stream; -1 if we reached end of the stream. - */ - private int readLine(InputStream is, char [] line) - throws IOException - { - - int count = 0; - boolean atLeastOneNonWSChar = false; - - char ch; - int byteRead; - for (byteRead = is.read(); - (byteRead != -1) && (count < line.length); - byteRead = is.read()) - { - ch = (char)byteRead; - line[count++] = ch; - atLeastOneNonWSChar = true; - if ((ch == '\\') || (ch == '\n')) - break; - } - - if ((byteRead == -1) && (count == 0)) - // end of file. - return -1; - - // Take off trailing whitespace. - while ((count > 0) && Character.isWhitespace(line[count-1])) - count--; - - // Add an EOL for ease of reading, but don't include it in - // "count" total. - line[count] = '\n'; - return count; }
http://mail-archives.us.apache.org/mod_mbox/db-derby-commits/200511.mbox/%3C20051104003912.47698.qmail@minotaur.apache.org%3E
CC-MAIN-2019-26
refinedweb
741
60.72
I had a great time yesterday at Roanoke Code Camp! Many thanks to American National University for the venue, the code camp staff and volunteers, the other speakers, and of course the attendees who made my sessions interactive. I learned a lot yesterday and it was a good time all around. I attended sessions on Apache Cassandra by Dr. Dave King (@tildedave), Angular JS by Kevin Israel (@kevadev), and JavaScript for Object-Oriented Programmers by Joel Cochran (@joelcochran). I regret I was unable to attend all the sessions. I also had the opportunity to present. I spoke on Redis and got some people excited about graph databases by talking about Neo4j. You can find my slides and other materials at the following links: If you have any trouble getting any of the materials just respond to this post or tweet me @codesailor and I will make sure you get the information you need. Recently I started working with Neo4j in C#. I am using the Neo4jClient and decided to write a wrapper for it using Generics. In this blog post I'll show how I did it. As always, your feedback is appreciated. The first is the CRUD operations provider. CRUD stands for Create, Retrieve, Update, Delete in case you don't know. The CRUD provider is quite simple. But before we jump into that, we need to make some concessions. We must have a common base type with a common property in order to find the node on successive calls. So I created a base class with a single property, “Id”, as an int. You can choose any property or properties you like but for simplicity I chose a small footprint. Here is my base class: public abstract class Neo4jBase { public int Id { get; set; } } (I don’t know why the “I” is uppercase. I guess I got a little keyboard crazy.) With that in place, we can build our CRUD data provider. Remember, you must be using the Neo4jClient library. Here is my generic provider: using Neo4jClient; public class Neo4jDataProvider<T> where T : Neo4jBase { IGraphClient _client = null; public Neo4jDataProvider (IGraphClient client) { _client = client; } public T Create(T record) if (_client != null) { var inputString = string.Format("({0}:{1}", typeof(T).Name.ToLower(), typeof(T).Name); inputString += " { newRecord })"; _client.Cypher .Create(inputString) .WithParam("newRecord", record) .ExecuteWithoutResults(); } return record; public T Retrieve(int id) T result = null; var inputString = string.Format("({0}:{1})", "record", typeof(T).Name); var query = _client.Cypher .Match(inputString) .Where((T record) => record.Id == id) .Return(record => record.As<T>()); result = query.Results.FirstOrDefault(); return result; public T Update(T entry) _client.Cypher .Match(inputString) .Where((T record) => record.Id == entry.Id) .Set("record = {updatedRecord}") .WithParam("updatedRecord", entry) } return entry; public void Delete(int id) .Where((T record) => record.Id == id) .Delete("record") } } } So what’s going here? First it is a generic class of type T where T is a Neo4jBase object. The reason is the Id property. That property allows us to find and deal with nodes individually in an easy and familiar fashion. Notice that the constructor takes an IGraphClient object. It is expected the IGraphClient is instantiated and connected to a database. The next point to note is the use of the type of T as the label. For those of you new to graph databases, the “label” is the “type” of the node in the database. For example, labels may be “Person”, “Movie”, “Book”, etc. So in each method, the name of the type of T is used as the label. You will also see the word “record” scattered throughout the code. This is used as a variable name. An interesting behavior is that the .WHERE methods seem to break if the variable name in the .MATCH methods is not the same name as the name of the variable in the lambda expression. What about Relationships? Remember that relationships are first-class citizens in graph databases, just like nodes. However, since relationships involve nodes of various types I decided to create a separate class for handling them. The class is still a generic class but instead uses two different types, TLEFT and TRIGHT. A caveat: 1) The relationships data provider only handles unidirectional relationships (always left-to-right); Here is the relationship data provider: public class Neo4jDataProviderRelationships<TLeft, TRight> where TLeft : Neo4jBase where TRight : Neo4jBase { public Neo4jDataProviderRelationships(IGraphClient client) public void Associate(TLeft left, string relationshipName, TRight right) var inputStringLeft = string.Format("({0}:{1})", "tleft", typeof(TLeft).Name); var inputStringRight = string.Format("({0}:{1})", "tright", typeof(TRight).Name); .Match(inputStringLeft, inputStringRight) .Where((TLeft tleft) => tleft.Id == left.Id) .AndWhere((TRight tright) => tright.Id == right.Id) .Create("tleft-[:" + relationshipName + "]->tright") public void Dissociate(TLeft left, string relationshipName, TRight right) .Match(inputStringLeft + "-[:" + relationshipName + "]->" + inputStringRight) .Delete(relationshipName) Notice that like the CRUD data provider, an IGraphClient is expected by the constructor. There are two methods for associating and dissociating nodes. Usage So how are these classes used? Well, suppose you have a class, Person, and a class, Movie as follows (borrowed from the demo database that ships with Neo4j): public class Movie : Neo4jBase { public string title { get; set; } public string released { get; set; } public string tagline { get; set; } } public class Person : Neo4jBase { public string name { get; set; } public string born { get; set; } } Now suppose you want to create a Person and a Movie and relate them. Specifically, let’s create William Shatner, and Airplane II, and relate them. First, create the nodes: Neo4jDataProvider<Person> personDataProvider = new Neo4jDataProvider<Person>(client); Person person = new Person { Id = 1, born = "1966", name = "William Shatner" }; personDataProvider.Create(person); Neo4jDataProvider<Movie> movieDataProvider = new Neo4jDataProvider<Movie>(client); var movie = new Movie { Id = 1, released = "1982", tagline = "The Sequel", title = "Airplane II" }; movieDataProvider.Create(movie); That will create the two nodes. Let’s relate them: Neo4jDataProviderRelationships<Person, Movie> relDataProvider = new Neo4jDataProviderRelationships<Person, Movie>(client); relDataProvider.Associate(person, "ACTED_IN", movie); And that’s it! What’s the catch? There are a number of catches including: I’m sure there are more catches. As an apology, I am just getting started. I hope to extend these classes with more robust operations. Your feedback is appreciated. If someone has already done this (or something similar) I’d love to know about it. Recently. The team spent much of the week working through this issues related to Chrome running on Windows 8 consuming cross-origin resources using Web API. We thought it was resolved on day 2 but it resurfaced the next day. We definitely resolved it today though. I believe I do not fully understand the situation but I am going to explain what I know in an effort to help you avoid and/or resolve a similar issue. My Lotic Factor colleagues Joel Cochran and Chris Atienza suffered with me and Joel wrote an excellent, complementary blog post to this post. We referenced many sources during our trial-and-error troubleshooting. These are the links we reference in order of applicability to the solution: Zoiner Tejada JavaScript and other material from -> WebDAV Where I learned about “Accept” –>? IT Hit Tells about NOT using ‘*’ –> Carlos Figueira Sample back-end code (newer) –> (older version) –> As a measure of protection, Web designers (W3C) and implementers (Google, Microsoft, Mozilla) made it so that a request, especially a JSON request (but really any URL), sent from one domain to another will only work if the requestee “knows” about the requester and allows requests from it. So, for example, if you write a ASP.NET MVC Web API service and try to consume it from multiple apps, the browsers used may (will?) indicate that you are not allowed by showing an “Access-Control-Allow-Origin” error indicating the requester is not allowed to make requests. Internet Explorer (big surprise) is the odd-hair-colored step-child in this mix. It seems that running locally at least IE allows this for development purposes. Chrome and Firefox do not. In fact, Chrome is quite restrictive. Notice the images below. IE shows data (a tabular view with one row for each day of a week) while Chrome does not (trust me, neither does Firefox). Further, the Chrome developer console shows an XmlHttpRequest (XHR) error. Screen captures from IE (left) and Chrome (right). Note that Chrome does not display data and the console shows an XHR error. The Web browser submits these requests and processes the responses and each browser is different. Okay, so, IE is probably the only one that’s truly different. However, Chrome has a specific process of performing a “pre-flight” check to make sure the service can respond to an “Access-Control-Allow-Origin” or Cross-Origin Resource Sharing (CORS) request. So basically, the sequence is, if I understand correctly: 1)Page Loads –> 2)JavaScript Request Processed by Browser –> 3)Browsers Prepares to Submit Request –> 4)[Chrome] Browser Submits Pre-Flight Request –> 5)Server Responds with HTTP 200 –> 6)Browser Submits Request –> 7)Server Responds with Data –> 8)Page Shows Data This situation occurs for both GET and POST methods. Typically, GET methods are called with query string parameters so there is no data posted. Instead, the requesting domain needs to be permitted to request data but generally nothing more is required. POSTs on the other hand send form data. Therefore, more configuration is required (you’ll see the configuration below). AJAX requests are not friendly with this (POSTs) either because they don’t post in a form. The team went through many iterations of self-hair removal and we think we finally have a working solution. The trial-and-error approach eventually worked and we referenced many sources for the information. I indicate those references above. There are basically three (3) tasks needed to make this work. Assumptions: You are using Visual Studio, Web API, JavaScript, and have Cross-Origin Resource Sharing, and several browsers. 1. Configure the client Joel Cochran centralized our “cors-oriented” JavaScript (from here). There are two calls including one for GET and one for POST ); The GET & PUT CORS JavaScript functions (credit to Zoiner Tejada, Joel Cochran) Now you need to call these functions to get and post your data (instead of, say, using $.Ajax). Here is a GET example: corsAjax.get(url, function(data) { if (data !== null && data.length !== undefined) { // do something with data } }); corsAjax.get(url, function(data) { if (data !== null && data.length !== undefined) { // do something with data } }); And here is a POST example: corsAjax.post(url, item); corsAjax.post(url, item); Simple…except…you’re not done yet. 2. Change Web API Controllers to Allow CORS There are actually two steps here. Do you remember above when we mentioned the “pre-flight” check? Chrome actually asks the server if it is allowed to ask it for cross-origin resource sharing access. So you need to let the server know it’s okay. This is a two-part activity. a) Add the appropriate response header Access-Control-Allow-Origin, and b) permit the API functions to respond to various methods including GET, POST, and OPTIONS. OPTIONS is the method that Chrome and other browsers use to ask the server if it can ask about permissions. Here is an example of a Web API controller thus decorated: NOTE: You’ll see a lot of references to using “*” in the header value. For security reasons, Chrome does NOT recognize this is valid. . } } Please note a few specific additions here: * The header attributes at the class level are required. Note all of those methods and headers need to be specified but we find it works this way so we aren’t touching it. * Web API will actually deserialize the posted data into the object parameter of the called method on occasion but so far we don’t know why it does and doesn’t. * [HttpOptions] is, again, required for the pre-flight check. * The “Access-Control-Allow-Origin” response header should NOT NOT NOT contain an ‘*’. 3. Headers and Methods and Such We had most of this code in place but found that Chrome and Firefox still did not render the data. Interestingly enough, Fiddler showed that the GET calls succeeded and the JSON data is returned properly. We learned that among the headers set at the class level, we needed to add “ACCEPT”. Note that I accidentally added it to methods and to headers. Adding it to methods worked but I don’t know why. We added it to headers also for good measure. [HttpHeader("Access-Control-Allow-Methods", "ACCEPT, PROPFIND, PROPPA... [HttpHeader("Access-Control-Allow-Headers", "Accept, Overwrite, Destin... [HttpHeader("Access-Control-Allow-Methods", "ACCEPT, PROPFIND, PROPPA... [HttpHeader("Access-Control-Allow-Headers", "Accept, Overwrite, Destin... That should do it. If it doesn’t let us know. What to do next? * Don’t hardcode the allowed domains. Note that port numbers and other domain name specifics will cause problems and must be specified. If this changes do you really want to deploy updated software? Consider Miguel Figueira’s approach in the following link to writing a custom HttpHeaderAttribute class that allows you to specify the domain names and then you can do it dynamically. There are, of course, other ways to do it dynamically but this is a clean approach. DISCLAIMER:. DISCLAIMER:. Harris (born 1948) is an African American communist politician and member of the National Committee of the Socialist Workers Party. He was the party's candidate for President of the United States in 1996 receiving 8,463 votes and again in 2000 when his ticket received 7,378 votes. Harris also served as an alternate candidate for Róger Calero in 2004 and 2008 in states where Calero could not qualify for the ballot (due to being born in Nicaragua). In 2004 he received 7,102 votes of the parties 10,791 votes. In 2008 he received 2,424 votes. More recently Harris was the SWP candidate in the 2009 Los Angeles mayoral election receiving 2,057 votes for 0.89% of the vote. Harris served for a time as the national organization secretary of the SWP. He was a staff writer for the socialist newsweekly The Militant in New York. He wrote about the internal resistance to South African apartheid and in 1994 traveled to South Africa to attend the Congress of South African Trade Unions convention. The Socialist Workers Party is a far-left political organization in the United States. The group places a priority on "solidarity work" to aid strikes and is strongly supportive of Cuba. The SWP publishes The Militant, a weekly newspaper that dates back to 1928, and maintains Pathfinder Press. Harris has Ballot Access in: CO, IO, LA, MN, NJ, WA (write-in access: NY) Learn more about James Harris and Socialist Workers Party on Wikipedia. DISCLAIMER: Lindsay is an American anti-war activist and presidential nominee of the Party for Socialism and Liberation despite being ineligible to become president due to her age, under Article II, Section 1, Clause 5 of the U.S. Constitution; she would need to be at least 35 in order to take office. Lindsay was born in Virginia and grew up in Philadelphia, Pennsylvania. She became an activist as a middle school student with the Philadelphia Student Union, a non-profit organization of students demanding a high quality education. She was a high school senior in Washington D.C. during the September 11 attacks. Soon thereafter she became active with the ANSWER coalition (Act Now to Stop War and End Racism). On September 24, 2001, Lindsay spoke at ANSWER's first press conference as a high school student. In 2002, she traveled to Cuba with Pastors for Peace. She attended Howard University and continued as a leader with the ANSWER coalition, including as a lead organizer of the January 2003 protest against the upcoming Iraq War. She was recognized by The Washington Post in March 2003 for her anti-war activism in a piece entitled "Student Leader Sees Through Bush Propaganda". In October 2003, Lindsay said of the Iraq War, "The US government has no right to try and recolonize Iraq". The Party for Socialism and Liberation (PSL) is a Marxist-Leninist political party in the United States. It was created as the result of a split within the ranks of Workers World Party (WWP). The San Francisco branch and several other members left WWP in 2004, announcing that "the Workers World Party leadership is no longer capable of fulfilling that mission [of building socialism]". The PSL has since established two national offices in Washington, D.C. and in San Francisco alongside 23 local branches across the country. The PSL sees as its main goal the formation of a revolutionary workers' party, based upon the ideology of Marxism-Leninism. This party would lead a revolution and pave the way towards socialism. Under socialism a new government of working people would be formed. Historically, the PSL is generally positive on the former Soviet Union, describing the October Revolution as "the single biggest event that shaped global politics in the 20th century". The PSL acknowledges that the New Economic Policy of Vladimir Lenin led "to a re-polarization of social classes, especially in the countryside". The PSL blames the reforms initiated by Mikhail Gorbachev for the fall of the Soviet Union The PSL is a member of the steering committee of the Act Now to Stop War and End Racism Coalition (A.N.S.W.E.R.). As one of the most active members of the coalition, PSL has gained notice for successfully forging ties with Arab and Muslim American groups such as the Muslim American Society, Al-Awda and the American-Arab Anti-Discrimination Committee. Learn more about Peta Lindsay and Party for Socialism and Liberation on Wikipedia I believe the media are covering this candidate and party sufficiently that information need not be duplicated here. Learn more about Mitt Romney and Republican Party on Wikipedia..
http://geekswithblogs.net/codesailor/Default.aspx
CC-MAIN-2015-14
refinedweb
2,974
56.96
Python packages - the simple way. Project description Easy Package - for Python Python packages - the simple way. Background Had to code Python so ended up abstracting out these Python package related utilities to be able to deal with Python packages which is in a sad state in comparison to most other language environments. Features Easy package (system) load paths - because package imports and load paths in Python makes adults cry. Easy package tag/release - because package tag/release management should not be done by hand, fallback on conventions. Install Install using pip: pip install easypackage Usage How to to make use of easypackage in various ways: Required Create a package.json in package root folder (e.g. mypackage) - see Node.js specification, in lack of such for Python. Easy package load paths In any package source file: # e.g. `~/dev/projects/mypackage/foo/foo.py` def hello: print('hello!') In any other package source file: # e.g. `~/dev/projects/mypackage/bar/bar.py` from easypackage import syspath as easysyspath # add `~/dev/projects/mypackage` to Python system path unless already added easysyspath.syspath() from mypackage.utils.foo import foo foo.hello() And so on. Easy package tag/release (WIP/TBA) In file release.py in package project root: from easypackage import release as easyrelease easyrelease.release() To tag/release a new version to Git, simply add/update a valid semver version tag in package.json - according to Node.js specification - and then run python release.py. Currently not submitted to any Python package register, but will probably be added soon. License Released under the MIT license. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/easypackage/
CC-MAIN-2019-22
refinedweb
291
61.02
2nd January 2014 11:28 am Django Blog Tutorial - the Next Generation - Part 2 Welcome back! In this lesson, we’ll use Twitter Bootstrap to make our blog look nicer, and we’ll implement individual pages for each post. Now, before we get started, don’t forget to switch into your virtualenv. From within the directory for the project, run the following command: $ source venv/bin/activate If you haven’t used Bootstrap before, you’re in for a treat. With Bootstrap, it’s easy to make a good-looking website quickly that’s responsive and mobile-friendly. We’ll also use HTML5 Boilerplate to get a basic HTML template in place. Now, to install these easily, we’ll use Bower, which requires Node.js. Install Node.js first. On most Linux distros, you’ll also need to set NODE_PATH, which can be done by pasting the following into your .bashrc: NODE_PATH="/usr/local/lib/node_modules" With that done, run the following command to install Bower: $ sudo npm install -g bower Next we need to create a Bower config. First, create the folder blogengine/static. Then create a new file called .bowerrc and paste in the following content: This tells Bower where it should put downloaded libraries. Next, run the following command to gener Bower: $ bower init Answer all the questions it asks you - for those with defaults, these should be fine, and everything else should be easy enough. Next, run the following command to install Bootstrap and HTML5 Boilerplate: $ bower install bootstrap html5-boilerplate --save Note that as jQuery is a dependency of Bootstrap, it will also be installed automatically. Now, we need to keep our Bower-installed files out of version control - the bower.json file keeps track of them for us. So add the following to your .gitignore file: blogengine/static/bower_components/ All done? Let’s commit our changes: Now, let’s make our template nicer. Django’s templating system is very powerful and lets one template inherit from another. We’re going to create a base template, using HTML5 Boilerplate as a starting point, that all of our web-facing pages will use. First, create a directory to hold the base template: $ mkdir templates/blogengine/includes Then copy the index.html file from HTML5 Boilerplate to this directory as base.html: $ cp blogengine/static/bower_components/html5-boilerplate/index.html templates/blogengine/includes/base.html Now amend this file to look like this: Note the following: - We need to use {% load staticfiles %}to be able to load any static files. - We use the {% static %}template tag to load static files such as CSS and HTML - We define blocks called titleand content. Any template that extends this one can override whatever is inside this template. Please note that HTML5 Boilerplate may conceivable change in future, so bear in mind that all you really need to do is load the staticfiles app, use the static tag for any static files that need to be loaded, and define the blocks in the appropriate places. Next, let’s amend our existing template to inherit from this one: Now fire up the server with python manage.py runserver and check everything is working OK. You should see that your new base template is now in use and the CSS and JS files are being loaded correctly. Let’s commit again: Now, let’s use Bootstrap to style our blog a little. First we’ll add a navigation bar at the top of our blog. Edit the base template as follows: Note the footer copyright section. Here we output the current year using now. Also note the addition of the header block. This will let us override the page header if necessary. We’ll also wrap the posts in a div: Let’s commit our changes: Formatting our content As it stands right now, we can’t do much to format our posts. It is possible to include HTML in our posts with Django, but by default it will strip it out. Also, we don’t want users to have to write HTML manually - we want to make our blog user friendly! There are two possible approaches. One is to embed a rich text editor like TinyMCE in the admin and use that for editing the files, but I’ve found things like that to be cumbersome. The alternative is to use some other form of lightweight markup, and that’s the approach we’ll take here. We’re going to use Markdown for editing our posts. Django has actually dropped support for Markdown, but it’s not hard to implement your own version. First, install Markdown and add it to your requirements.txt: Now, we shouldn’t write any production code before writing a test, so let’s amend our existing post test to check to see that Markdown is working as expected: You’ll also need to add the following at the top: import markdown What we do here is we convert our post text to include a link using Markdown. We also need to render that post in markdown within the test so that what we have in the test matches what will be produced - otherwise our test will be broken. We also check that the link is marked up correctly. Save the file and run the tests - they should fail. Now, create the following directory and file: Note that the __init__.py file is meant to be blank. Then create the following file and edit it to look like this: Then just amend the post list template to use it: It’s that easy to use a custom markup system with your blog! Let’s commit the changes: Pagination As at right now, all of our posts are displayed on the index page. We want to fix that by implementing pagination. Fortunately, that’s very easy for us because we’re using Django’s generic views. Go into blogengine/urls.py and amend it as follows: That will automatically paginate our posts by 5 - feel free to change the value of paginate_by if you wish. However, we need to place the links in our template as well: Try adding a few more blog posts, and you’ll see the pagination links. But give them a try, and they won’t work. Why not? Well, as it turns out there was a bug in the project-wide urls.py file (my bad!). Let’s fix that: If you try again, you’ll see that the blogengine app now happily deals with the paginated posts. Let’s commit our changes: Viewing individual posts As our last task for today, we’ll implement individual pages for each post. We want each post to have a nice, friendly URL that is as human-readable as possible, and also includes the date the post was created. First of all, we’ll implement our test for it, however: Add this method to the PostViewTest class, after test_index. It’s very similar to test_index, since it’s testing much the same content. However, not that we fetch the post-specific URL using the method get_absolute_url, and we then fetch that page. Now, if you run the test, it will fail because get_absolute_url isn’t implemented. It’s often a good idea to have a get_absolute_url method for your models, which defines a single URL scheme for that type of object. So let’s create one. However, to implement our URL scheme we need to make some changes. Right now we have the date, but we don’t have a text string we can use, known in Django as a slug. So we’ll add a slug field, which will be prepopulated based on the post title. Edit your model as follows: Here we’ve added a slug field to the model, as well as implementing our get_absolute_url method. Note we’ve limited the date to year and month, but you can include days if you wish. While we’re in here, we’ve also implemented the __unicode__ method. Essentially, this sets how Django describes the object in the admin - in this case, the post title is a logical way of describing that Post object, so it returns the post title. We’ve also added the class Meta, with the ordering field. This tells Django that by default any list of posts should return them ordered by pub_date in reverse - in other words, latest first. To have the slug filled in automatically, we need to customise the admin interface a little as well: Now, I recommend at this stage going into the admin and deleting all of your posts, because otherwise you’ll have problems in migrating them. The issue is that each slug is compulsory and must be unique, and it’s not practical to use South to automatically generate new slugs from the title on the fly, so by deleting them at this stage you’ll avoid problems. Once that’s done, run this command: $ python manage.py schemamigration --auto blogengine You’ll be prompted to specify a one-off default value - enter any string you like, such as “blah”. Then run the migration: $ python manage.py migrate Let’s run our tests now: Whoops! Our tests are broken, because the slug field isn’t being filled in. If you take a look at the page for adding a post, you’ll notice that the slug is filled in using JavaScript, so our test fails because the test client doesn’t interpret JavaScript. So in the tests we have to fill in the slug field manually. Also, for the unit tests, the slug attribute isn’t being created at all, so it can’t be saved. Let’s remedy that. First, edit the test_create_post method of PostTest: Next, let’s amend AdminTest: And PostViewTest: What we’re doing here is that every time we create a Post object programmatically, we add the post.slug atttribute to it. Also, when submitting a post via the admin, we pass the slug parameter via HTTP POST, thus emulating how a form would submit this data. If you run the tests again, you’ll see that test_post_page still fails. This is because we haven’t yet up the URLs, templates and views to do so. Let’s fix that. We’ll use another generic view, called a DetailView, to display the posts. Amend blogengine/urls.py as follows: Running our tests again will still fail, but now because the template post_detail.html has not been found. So let’s create it: If you run your tests again, they should now pass. However, we still need to provide a hyperlink from each post in the index to the post page, so let’s do that: And that’s all for today! We now have individual post pages, we’ve styled our blog a bit, and we’ve implemented Markdown support. All that remains is to commit our changes: As before, I’ve tagged the final commit with ‘lesson-2’, so if you’re following along, you can switch to this point with git checkout lesson-2. Next time we’ll add support for flat pages and multiple authors, as well as adding support for comments via a third-party commenting system.
https://matthewdaly.co.uk/blog/2014/01/02/django-blog-tutorial-the-next-generation-part-2/
CC-MAIN-2019-51
refinedweb
1,881
71.44
See this page as a slide show The word “elision” means “omission”, like how the two-syllable “do not” becomes the one-syllable “don’t”, or Captain Kirk never seems to brush his teeth. It’s not necessary to show everything. The following examples use my class Loud, which displays a message for every method invoked. #include "Loud.h" int main() { Loud alpha; } Loud::Loud() Loud::~Loud() No surprise, here. alpha got created & destroyed. #include "Loud.h" int main() { Loud beta, gamma; } Loud::Loud() Loud::Loud() Loud::~Loud() Loud::~Loud() Sure. #include "Loud.h" int main() { Loud delta; Loud epsilon(delta); delta=epsilon; } Loud::Loud() Loud::Loud(const Loud&) Loud& Loud::operator=(const Loud&) Loud::~Loud() Loud::~Loud() As expected. #include "Loud.h" Loud foo() { Loud zeta; return zeta; } int main() { Loud eta(foo()); } Loud::Loud() Loud::~Loud() zetaand eta, should have been created. #include "Loud.h" int main() { Loud theta = Loud(Loud(Loud(Loud(Loud(Loud(Loud(Loud()))))))); } Loud::Loud() Loud::~Loud() There should be more than that. #include "Loud.h" Loud foo() { Loud iota; return iota; } int main() { Loud kappa(foo()); } Loud::Loud() Loud::~Loud() Loudclass. iota. Instead, the ctor in foo()constructs directly in kappa. No copying; it’s built in the right place. intget passed as an argument? double *? std::string? std::string *? std::string &? const std::string &? int? std::string?
https://www.cs.colostate.edu/~cs253/Spring18/Lecture/CopyElision
CC-MAIN-2018-39
refinedweb
225
57.57
Getting this exact error, Tried removing all my mods but the sapman pack thing, And it just doesn't load minecraft.. I tried removing it and just putting in clay soldiers and it won't load either, So some assistance with this issue would be greatly appreciated.Getting this exact error, Tried removing all my mods but the sapman pack thing, And it just doesn't load minecraft.. I tried removing it and just putting in clay soldiers and it won't load either, So some assistance with this issue would be greatly appreciated.Quote from possumella Okay, so when I start minecraft with the Clay Soldiers mod installed something weird happens. The Minecraft launcher runs all fine and dandy but then I click the big silver "PLAY" button Minecraft doesn't load. I don't even get the Mojang screen or a crash report. It stops before the screen even comes up. Please help me. - - BenniixD - Registered Member - Member for 6 years, 2 months, and 15 days Last active Sat, Oct, 29 2016 19:46:18 - 0 Followers - 1,441 Total Posts - 84 Thanks - Oct 16, 2013BenniixD posted a message on Clay Soldiers Mod v. 3.0.0-alpha.2 (MC 1.10.2) / 2.0.0-beta.2 (MC 1.7.10)Posted in: Minecraft Mods 0BenniixD posted a message on Taking skin requestsIf you could try doing this that'd be amazing, ^.^Posted in: Skins 0BenniixD posted a message on The Betweenlands ~ "A dark, hostile environment..." v2.0.2 [09/03/17] NUMEROUS BUG FIXES AND TWEAKSDem models man, They're just amazing, Along with those textures. Really hope that sporeling is a NPC/Tameable thing.Posted in: Minecraft Mods 0BenniixD posted a message on [16x][1.7.2] Wayukian pack (Magma slime & blaze previews on pg. 144) [800k+ downloads]How.. Have i never seen this amazing texture pack before? Anywho, It looks absolutely amazing, Gonna download it right now.Posted in: Resource Packs 0BenniixD posted a message on Arcticraft - An Icy New Dimension (Maybe we'll release it)Seems like a mod with some great potential, The world gen seems very nice, The blocks nicely textured, The mobs aren't too shabby looking either (Except for that boar, It looks just like a reskinned pig... :/) But overall a seemingly nice mod, Nice work!Posted in: WIP Mods 0BenniixD posted a message on Fossils and Archeology Revival Legacy ThreadPosted in: Minecraft Mods The problem is that you're running build 4 on 1.5.2, You need build 5 prelease, As build 4 is for 1.4.7. 1BenniixD posted a message on (1.5.2) World of Warcraft Wrath of the Lich King mod (still in progress)Nice textures, Gives a little extra to strive for as well, Downloading now.Posted in: Minecraft Mods 0Posted in: WIP Mods I probbably will make a bigger fountain thats round, I've always liked small-ish fountains that are square though.Quote from Thunder9125 You might want to make the fountains round, just suggesting, 0BenniixD posted a message on Fossils and Archeology Revival Legacy ThreadHey, Congrats on 100 Pages, Guys! By the way, The Spinosaurus' model looks nice!Posted in: Minecraft Mods 2Made a bunch of buildings! Let me know what you think of them!Posted in: WIP Mods 0BenniixD posted a message on Sonic the Hedgehog Mod - V1.4.0[SSP/SMP/LAN]-New Update-Checkpoints,new mobs,sound effects,spinning rings and much more!Posted in: Minecraft Mods Same problem, It seems to happen with the forge version, I'm being hoarded by mobs.Quote from BakuMinerGuy Got a question....are the mobs supposed to spawn rapidly in large numbers? 0BenniixD posted a message on Sonic the Hedgehog Mod - V1.4.0[SSP/SMP/LAN]-New Update-Checkpoints,new mobs,sound effects,spinning rings and much more!Sweet, This mod is forge compatible now! Can't wait to try it out with all my other mods =)Posted in: Minecraft Mods 1Posted in: WIP Mods No Problem! I'm currently working on some aesthetic buildings that'll hopefully fit in this mod, Will post them when i'm done. 1@Tyber I went ahead and did it, Hopefully they're not too outrageous, Or too cheap, I tried to keep it with thePosted in: WIP Mods size /tier levels. package tyber.taleofkingdoms.kingdom; public class Balance { //On tick cap of each output public static int trigger = 200; //Honor required to finish the prequel public static float honorRequirement = 17500; //Cost of 1 emerald to gold public static int goldToEmerald = 500; //Number of gold the monsters drop public static int monsterGoldDrop = 20; //Food output of farm public static int farmOutput = 2; //Food cap increase of each granary public static int granaryCap = 50; //Cap increase of each hovel hut public static int hovelHutCap = 2; //Cap increase of each hovel house public static int hovelHouseCap = 3; //Cap increase of each small house public static int smallHouseCap = 5; //Cap increase of each medium house public static int mediumHouseCap = 8; //Cap increase of each large house public static int largeHouseCap = 12; //Stone output of each quarry per person public static int stoneOutput = 2; //Wood output of each lumbermill per person public static int woodOutput = 2; //Food Consume per person working public static int foodConsumption = 1; //Storage cap increase of each storage public static int storageCap = 64; //Windmill multiplier public static float windMillMultiplier = 0.2F; //Potion Duration for apothecary public static int potionDuration = 10000; //Potion Price for apothecary public static int potionPrice = 10000; //Supply Price for apothecary public static int supplyPrice = 18000; //Villager Supply Duration public static int villagerSupplyDuration = 10000; //New Villager add chance (lower value means higher chance) lowest value is 5 public static int newVillagerChance = 15; //Chance Increased when villager birthrate supplied public static int newVillagerChanceDecrease = 5; //How many attacks the ranger need to upgrade public static int rangerUpgrade = 12; //How many attacks the swordsMan need to upgrade public static int swordsManUpgrade = 7; //Cost per claim public static int claimCost = 2; //Cost per fence public static int fenceCost = 2; //Cost per walled fence public static int walledFenceCost = 4; //Cost per stone wall public static int stoneWallCost = 6; //Cost per hired hunter public static int hunterCost = 1000; /* * Building Types: * Apothecary - 1 * Barracks - 2 * Blacksmith - 3 * Chapel - 4 * Farm - 5 * Granary - 6 * HovelHouse - 7 * HovelHut - 8 * Inn - 9 * LargeHouse - 10 * LightHouse - 11 * Lumbermill - 12 * MediumHouse - 13 * Quarry - 14 * Shop1 - 15 * Shop2 - 16 * Shop3 - 17 * SmallHouse - 18 * Stables - 19 * Storage - 20 * Tower - 21 * TownHall - 22 * WatchTower - 23 * Well - 24 * WindMill - 25 * Workshop - 26 * Castle - 27 * StoneGate - 28 * WoodGate - 29 * lost order - 30 * lost order house - 31 * lost order storage - 32 */ //Gold, wood, stone, emerald public static BuildingPrice getPriceOfBuildingType(int type) { BuildingPrice price = new BuildingPrice(7500,600,400,1); if(type == 1) { price = new BuildingPrice(6000,300,500,0); } else if(type == 2) { price = new BuildingPrice(6000,200,600,0); } else if(type == 3) { price = new BuildingPrice(5200,100,350,1); } else if(type == 4) { price = new BuildingPrice(4500,150,50,0); } else if(type == 5) { price = new BuildingPrice(5000,180,70,0); } else if(type == 6) { price = new BuildingPrice(3500,165,80,0); } else if(type == 7) { price = new BuildingPrice(2500,120,60,0); } else if(type == 8) { price = new BuildingPrice(4750,260,185,0); } else if(type == 9) { price = new BuildingPrice(4250,200,150,0); } else if(type == 10) { price = new BuildingPrice(4650,200,185,0); } else if(type == 11) { price = new BuildingPrice(1750,60,60,0); } else if(type == 12) { price = new BuildingPrice(3700,165,115,0); } else if(type == 13) { price = new BuildingPrice(1850,70,70,0); } else if(type == 14) { price = new BuildingPrice(2000,100,75,0); } else if(type == 15) { price = new BuildingPrice(2200,120,95,0); } else if(type == 16) { price = new BuildingPrice(2450,145,110,0); } else if(type == 17) { price = new BuildingPrice(2800,95,80,0); } else if(type == 18) { price = new BuildingPrice(3000,120,80,0); } else if(type == 19) { price = new BuildingPrice(1500,55,55,0); } else if(type == 20) { price = new BuildingPrice(2450,100,120,0); } else if(type == 21) { price = new BuildingPrice(6000,250,200,1); } else if(type == 22) { price = new BuildingPrice(2250,90,120,0); } else if(type == 23) { price = new BuildingPrice(500,10,50,0); } else if(type == 24) { price = new BuildingPrice(2600,100,70,0); } else if(type == 25) { price = new BuildingPrice(2780,120,80,0); else if(type == 26) { price = new BuildingPrice(15800,600,800,4); } else if(type == 27) { price = new BuildingPrice(1000,20,100,0); } else if(type == 28) { price = new BuildingPrice(800,100,15,0); } else if(type == 29) [ 0BenniixD posted a message on FLINT STUFFNo... Just no... So many things wrong with this post.....Posted in: Minecraft Mods I'm 99% sure the mod is most likely a virus as well. - To post a comment, please login or register a new account. - Jun 30, 2012BenniixD posted a message on Community Creations - The Banner ContestI like luus' but i think i'm gonna have to go with Spoonfork99Posted in: News - Jan 25, 2012Posted in: News It doesnt look anything like any snake i've ever seen then!Quote from TikiAndTehBrainz It looks kinda like a bee, actually Actually it kinda does... Except for the face doesnt... - Jan 25, 2012I think... Its a CAT MAN!, The model looks biped! Not tripedPosted in: News - Jan 25, 2012OMG JUNGLE CHICKENS, WOOO.Posted in: News Looks like a baby tiger, Or a jackal..... Or a chimp.... Hard to say, OMG That thing was just to divert out attention, They added bugs!!! SPOILER ALERT - Jan 24, 2012BenniixD posted a message on Minecraft™ LEGO® CUUSOO Project Passes LEGO ReviewAwesome, But probbably going to be way too expensive, :dry.gif:Posted in: News - Nov 18, 2011BenniixD posted a message on More Minecon, More Pics!I think they're watching something different than minecraftPosted in: News - Nov 18, 2011BenniixD posted a message on More Minecon, More Pics!Is that a dude or a chick standing next to jeb? It looks like a girl with 5'o clock shadowPosted in: News - Nov 14, 2011BenniixD posted a message on Minecraft RC2 is Out For Testing"yes. minecraft will never be updated after 1.9 is released. you are correct."Posted in: News Not true, Daaryl, They plan to update it even after its released, They wont stop updating until pretty much they dont continue anymore with the game, But there's going to be lots more released after this.Also, Is anyone having trouble downloading it? I can't seem to download it. When i try to it doesn't download correctly - Oct 5, 2011BenniixD posted a message on 1.9 Updates: Animal Breeding Continues AdvancementThe Baby pigs look kinda ugly. It'd be cool if it was changed so they have cuter eyes.Posted in: News - Sep 10, 2011BenniixD posted a message on Want to play 1.8 Early? Here's How!Posted in: NewsQuote from RedTrummyZero My friend shadowevil1996 found this glitch. Your in CREATIVE mod idiot. - Sep 2, 2011BenniixD posted a message on 1.8 Updates: Changing the ChestsI hope its dual wielding, Bow and sword FTWPosted in: News - To post a comment, please login or register a new account. 0
http://www.minecraftforum.net/members/BenniixD/posts
CC-MAIN-2017-30
refinedweb
1,868
58.72
chemicals used in whitening soaps philippines US $0.01-1 5000 Pieces (Min. Order) import and export company in dubai for interlocking block mak... US $850-100000 1 Set (Min. Order) Alibaba Express Service in China/Spanish/Hong Kong US $99-4999 1 Carton (Min. Order) Best door to door China sea shipping service to Manila ... US $1-150 1 Cubic Meter (Min. Order) Pick Up Cargo From Different Suppliers/Factories China To ... US $1.35-50.37 0.5 Kilograms (Min. Order) Top competitive sea freight from ningbo to philippines US $10-45 1 Cubic Meter (Min. Order) top quality china shipping company,sea freight shipping cost ... US $10-400 1 Kilogram (Min. Order) Cheap ocean shipping service from China to Philippine-- Allen... US $1-90 1 Cubic Meter (Min. Order) Shipping Freight LCL service China to Philippines US $10-50 1 Cubic Meter (Min. Order) top quality china export shipping,sea freight company from Hu... US $10-400 1 Kilogram (Min. Order) Newest Promotional container shipping to cebu philippines US $25-45 1 Cubic Meter (Min. Order) China To Manila Philippines Fast Vessel Shipping --------Achi... US $1.35-50.37 0.5 Kilograms (Min. Order) china forwarding company sea freight rates to Philippines US $5-30 1 Cubic Meter (Min. Order) hot china shipping company,sea freight from Hebei to ... US $10-400 1 Kilogram (Min. Order) Cheap international sea freight philippines US $30-50 1 Cubic Meter (Min. Order) shipping company air freight from China to Philippines-------... US $1-3 45 Kilograms (Min. Order) professional air freight logistics company xianggang to ... US $3-6 45 Kilograms (Min. Order) 40HQ shipping cost to Singapore by Vita freight company US $1-30 1 Cubic Meter (Min. Order) Guangzhou to Philippines air shipping service, China logistic... US $100-200 1 Cubic Meter (Min. Order) Shipping company cheap Air freight rates drop shipping from C... US $1-3.5 1 Kilogram (Min. Order) TOP ocean freight shipping company from guangzhou/shanghai /q... US $10-20 1 Cubic Meter (Min. Order) Logistics Shipping express Service from China To PHILIPPINES US $1-10 0.5 Kilograms (Min. Order) air freight shipping to MANILA PHILIPPINES from China Shangha... US $1.5-5.5 0.5 Kilograms (Min. Order) shipping company in shenzhen to Philippine ----- Elva skype:c... US $10-100 1 Kilogram (Min. Order) DDP sea freight forwarder service from guangzhou to ... US $10-100 1 Cubic Meter (Min. Order) High competitive shipping rate from china to MANILA,... US $1-5 1 Kilogram (Min. Order) great china shipping company,sea freight charges from Hainan ... US $10-400 1 Kilogram (Min. Order) Shipping Company China to Philippines from Guangzhou Port US $1-100 1 Cubic Meter (Min. Order) shipping company to Philippine ----- terry US $6-9 6 Kilograms (Min. Order) Cheap china international air freight cargo forwarder shippi... US $2.5-8.5 45 Kilograms (Min. Order) automatic tape dispenser companies want agents in ... US $350-370 1 Unit (Min. Order) Low price mobile gold washing plant in Philippines US $4500-25000 1 Set (Min. Order) Cheap Sea freight rates dropshipping from China to DAVAO ... US $2.5-20 1 Cubic Meter (Min. Order) Fast Delivery Fusion Italian Glue Top Quality Remy Double Dr... US $0.2-0.9 100 Strands (Min. Order) Native Design Headrest Removable Sofa Set Furniture ... US $400-1000 1 Set (Min. Order) Chandelier Lamp Decor With Different Diwali Lights Wholesale US $600-700 5 Pieces (Min. Order) philippine market plywood plywood US $250-350 45 Cubic Meters (Min. Order) Unprocessed no tangle no shedding hair weft high quality ... US $18.1-60.5 1 Piece (Min. Order) Philippines different sized hand waving flag US $0.0479-4 1000 Pieces (Min. Order) Hottest 10a 250v united trading company limited usa plug adap... US $0.45-0.57
http://www.alibaba.com/showroom/different-companies-in-philippines.html
CC-MAIN-2016-07
refinedweb
636
62.95
A framework for WebProgramming. Masthead - URL - version 0.99.4 (2003-03-27) - licence - GPL - platforms - Apache with mod_python - Python versions - 2.2/2.3 Deployment Platforms Draco plugs into the Apache/mod_python combination. Both Apache 1.3 and Apache 2.0 are supported. For serious use, a relational database must be installed. Currently, the popular MySQL and PostgreSQL database systems are supported. Suitability Development Interfaces No special development environment is available. Draco applications can be made just like a regular Python application using a text editor. Environment Access Most of the standard CGI environment is available as properties or methods of a collection of global Python objects. Session, Identification and Authentication Draco has an integrated and automatic session management mechanism. Both cookie and url tagging methods are supported. Sessions can be logged in, made persistent and optionally made secure by using SSL. Authentication and authorization have to be performed by the application. Persistence Support Draco make use of the namespace concept. A namespace is a place where you can store (almost) arbitrary Python variables using the Python dictionary API (ns['varname'] etc.). There are different namespaces, some of which are persistent. These include the session, user, application and server namespace. Technically, persistence is implemented by a relational database backend. Presentation Support Process Logic versus Markup Logic In Draco program logic is conceptually separated into process and markup logic. The process logic is the logic that processes a request and performs the desired action. The markup logic is the logic that formats the results of the process logic in the html. Handlers and Templates Draco makes use of handlers and templates. The process logic is put in a handler. This handler processes the client's request and performs the requested operations. The result of these operations is put in a special namespace called the interface. The template is template as exist in many web frameworks, namely an html file with embedded code blocks. The only thing this code should do is format the results from the interface namespace into the html. All variables from the interface namespace are directly available to this code as global variables. InTheirOwnWords
https://wiki.python.org/moin/Draco
CC-MAIN-2019-22
refinedweb
357
51.75
How do I induce the Mac graphical login from SSH? Is there a way to make the loginwindow process start a user session by running a command when remotely logged in via SSH as an admin on Mac OS X? loginwindow. Not knowing the password makes things complicated, but maybe the solution is: is it possible to temporarily blank out a user's password? (And afterwards reset it to whatever it was before.) As a start: First, get the login window to display. Just log out the current user, use fast user switching, or use SSH: cd "/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/" sudo ./CGSession -suspend Or, to switch to a specific user right away, which will probably show the login window (this suddenly no longer works on my 10.5 Leopard): sudo ./CGSession -switchToUserID 501 What's shown now depends a bit on the System Preferences, but let's assume it's the users' icons and their names. To activate a name we'd have to type the first letters. Then, after Return, the password prompt shows. Alternatively one can select any name (like by pressing Arrow Down) and then press Option-Return to be prompted for both any username and its password. I don't know how one can tell which screen is shown, but let's save that for later... So, to select the first (random) user name and press Option-Return, type a specific user name, hit Return, and type the password: sudo osascript -e 'tell app "System Events" key code 125 keystroke return using option down keystroke "the username" delay 1.0 keystroke return delay 1.0 keystroke "the password" delay 1.0 keystroke return end tell' The above shows some error, which as far as I can tell does not limit the usage: osascript[285] : 3891612: (connectAndCheck) Untrusted apps are not allowed to connect to or launch Window Server before login. _RegisterApplication(), FAILED TO establish the default connection to the WindowServer, _CGSDefaultConnection() is NULL. Alternatively, use the language specific script from "Script the Login window through Apple Remote Desktop" (maybe one day the comments at that site will show a better solution): tell process "SecurityAgent" set value of text field 1 of group 1 of window 1 to "the username" set value of text field 2 of group 1 of window 1 to "the password" end tell click button "Log In" of window 1 of application process "SecurityAgent" But the main problem is: this still needs the password. However: obviously no password is needed when a user has a blank password. In fact, for blank passwords just clicking a user's icon is all that's needed. So, if sending keystrokes using AppleScript is acceptable, then maybe "all" that's left to figure out: Is it possible to temporarily blank out a user's password, to allow for starting (or resuming) the session without knowing that password...? Can one make the AppleScript error-proof? Like: stat -f%Su /dev/console root (A note for testing: when using Screen Sharing it seems that setting the preference When controlling computers: Encrypt passwords and keystrokes only also retains the connection when the login window is shown, or after a user has successfully logged in. When using Encrypt all network data then my Mac needs to re-establish the Screen Sharing connection each time a login is shown or a user is switched.) sudo osascript -e 'tell app "System Events" to keystroke "password" & return' su I've been investigating this recently. Put this in your app's PAM stack, or test with sshd: session required pam_launchd.so launchd_session_type=Aqua That goes a long way towards getting you a graphical session which is pretty close to a switched-out user session. In particular, it's in the right bootstrap namespace and has the correct bootstrap ports (I think). You can check the source for what pam_launchd does; it's using some reasonable-looking private library (vproc_priv.h functions in libvprop) to call the Mach routines for setting up the ports and namespace. It matches with all the (limited) docs Apple provides for the Mach-derived syscalls. Next, you need to set your audit user-id to the that of the user with the BSM API, or the loginwindow won't talk to you on Lion. The session looks very close to a switched-out session now if you check "launchctl blist", and some processes and services come to life nicely (like the pasteboard, and so on). In fact, everything except Finder and loginwindow is running. Until loginwindow runs though, you can't launch a graphical application, and the per-session loginwindow process is always spawned as a direct child of the global one. How does one poke the loginwindow process to launch a new loginwindow in the fresh session? I can't find a way to get the last piece in place! Any help completing this answer gratefully received. running the command with sudo allows you to set the script to unreadable by standard users. It's not perfect, but if your admin user is already compromised, the game is over anyway! chmod u-r scriptname my script looks like this, it works remotely when one user is already running, to switch to a second user via SSH (tested on Snow Leopard 10.6.3): #!/bin/bash #go to login window /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -switchToUserID 503 osascript -e 'tell app "System Events" keystroke "password" delay 1.0 keystroke return end tell' exit By posting your answer, you agree to the privacy policy and terms of service. asked 6 years ago viewed 4040 times active 2 years ago
http://superuser.com/questions/39322/induce-mac-graphical-login-from-ssh
CC-MAIN-2015-40
refinedweb
948
60.35
- forcing width - Problem: Grid height when loaded from external files into a TabPanel - Lazy script loading ...again - Appear panel animation. Or how can panel be collapsed to the left? - Toolbar-like form - Monitoring global keydown causes Exception in ext-all-debug.js - Want to insert linked images inside a gridpanel. - panel title expand/collapse behaviour - Variable scope question - Testing in multiple versions of IE - Borderl layout - display some region above others - RowExpander? - Datastore with different - Tree Editor w. variable edit field types - I can only delete the first row in my grid when I select multiple rows... - Align Buttons in FormPanel - Ext.example.msg substitute in 2.0 - DD & Resize for SVG Elements - Data not rendering in grid placed in tab - is there an easy way to get a column ID? - Problem with lightbox and extjs - Taking search queries from one page and pass them to another in $_POST - Error with grid fit in viewport - this.root.render is not a function or loader.load is not a function - Sample Panel and scroll problem - Select edited / new record in Grid using ID - Showing errors with a tabbed form - Does Ext.urlDecode should be case sensitive? - ExtJS buliding scripts - how to? - how to 'mark' field in red - strange problem with combobox - Extending HtmlEditor - Edit links and images - About Grid Query? - ie7 compatibility... i m going crazy c00ce56e - Struts+Ext - ManagedIFrame Extends w/ TabPanel Question - Custom mask for grids - [solved] trying to populate a combobox with numbers 0-99 - htmleditor tutorial? - Colorpicker size of frames - How do you update editgrid data to your server's DB? - Looking for standardSubmit example - questions about the columnTree example - Ext.MessageBox.show - ignores width property - Populating FormPanel - [OPEN] How does one build a grid from an XML source with only a value per row? - resizing icon in treenode/treepanel - not getting response from servlet - How to Drag a DragSource object to a iframe's div? - I would send empty value width my combo... - Sub : Ext.namespace - [SOLVED] DateField onChange question - form submission problem - Grid Drag & Drop Handling - TabPanel does not render buttons on first tab - Window problem - X-plain and column layout - Object Required error coming in IE - pls help ..changing items:[] on real-time - Upload form not rendering in 2.0.2 - TreePanel rendering problems [IE6] - Button right under the fields - autoheight not working for tree inside tabpanel - [SOLVED] Grid inside Accordion problem - inserting a div with image as treepanel bbar - PropertyGrid from JSON - How to redirect to a bean from a Ext button - hidden combo values? - How to bind grid with data from database - Refreshing column widths in GridPanel on adding new records - Why this happens (Layout problem) - grid functionality not working - Preventing a TreeNode from displaying the +/- - Dynamically removing components from a Form DOM - Cannot access Ext.Ajax response.responseText - div's in page with id ext-gen135 - How to create a custom skin - Can i do an editable grid without xml? - Accordion inside an Accordion - cross domains element load - Event problem - Ext JS Tree in 'ext-2.0-rc1' is very slow. - Setting Ext.BLANK_IMAGE_URL but Still Getting IE 6.0 "Secure Content Warning" - Full eventName list - Proper ajax cell validation - ComboBox id not posting (not a hiddenName issue)? - Creating 2 Tabs with Grids, only 1 Grid Shown (Initialization Problem) - [Solved] Trouble with Grid Render in IE6 - Server side - TreePanel: connect the TreeSorter inline? - Strange Data Store Error - Button widths in IE6 & IE7 - Positive/Neg numeric Vtype - FAQs - Sticky Me? - How to style the toolbar and buttons? - Ext Not Defines - Comboboxes have visibility set to hidden in modal window in ie6 - Strange null or null is not an object error - Textfield: issues with special chars - Element.load/update with fade-in - Second time form displayed in window shows nothing. - Unordered List NOT rendering inside TabPanel - marking a grid cell in error - Grid problem - new grid added not updated - very slow response to contextmenu click by menuitem click event handler - Disable editing EditorGridPanel? - Vertical scrollbar - 2.01 Firefox Possible Collapse Bug [SOLVED] - region vs. contentEl vs. html? - Viewport with Panels - /n /r and ( - How to change text in a Panel? - IE6 Scrollbars, border layout - Tabbing issues with Firefox 3.0b3 - How to make clicking on a tab go to a new page? - Determine if class is loaded - Can Ext.ux.Multiselect check its content isDirty()? - Change ToolTip content after creation? - [SOLVED] Get Image Selected on DataView - grid problem - Grid cache clearing Problem - FormPanel With TabPanel in it,But the setActiveTab() can't work? - Tutorials for simple DOM manipulation - autoScroll not working with FormPanel - combo select event!! - Problems with Classes etc. in ExtJs - Tooltip not getting displayed - FormPanel - [solved]How to change emptyText of a ComboBox after it has been created? - Panel: how to use full height (100%)? - Bogus Menu Module - I would adding data in jsonstore manualy - [Help]Ext.EventManager.addListener,IE is ok, but Firefox not display! - ComboBox misbehaving - The items of menu is too much? - PANEL AND TABPANEL PROBLEM - [SOLVED] Combobox, allowBlank and forceSelection question - panel and html - what does "p.body" mean in the "grid paging samples"? - [Solved]Qtip on progress bar (displays only on edges!) - Tree View in Ext JS 2.0 version - [2.0??] ColumnTree Keyboard navigation doesn't work - Problem with submit tab form - FORMPANEL and TABPANEL NOT SUBMIT FORM - ComboBox in column layout does not work? - Read-only conversion to entire form - Combobox value in grid column - Performance problems with Ext form / textfield - Problems with .html Property of Panel (only available once? - Simple grid population question - Combobox doesn't create 'name' attribute - Css Dependencies, How?? - Problem with HtmlEditor and links - Ext.MessageBox - How to use json array from serverside file in js file to bind it to the grid - Collapsible panel : save state into php session - Extending DatePicker - How to send data from a java class to extjs - Multiple Checkboxes in grid - How to check if a sevice is available - Change POST Values - Simple Window+accordion doen't work with Internet Explorer 6 - Please Help with Ext.formPanel + PHP + MySQL + JSON. - Dynamically setting the height of a panel - Using a Tree as navigation - best way to prevent/minimize reloading - DWRPRoxy call returning 'this.mainBody' is null or not an object alert box - Will a Grid support ability to include tabs inside the expanded portion - Aligning elements in forms - how do you debug the response of jsonreader - Cursor Style in Custom Renderer in Column - Tree move node confirm - finding an element in DOM subtree - Extending Ext.data.Store - [SOLVED] Tree without json? - [solved!!!]columnmodel Css config ..how to use?? - Newbie question on TextField and FieldSet... - Ext 2.0 - API Documentation Error - How can I render a form to the page? - (portal column) Something I don't understand - How to delete a config option. - find ID inside a div - maskRe - Access to Form's JSON - combobox doesn't load, but then does load - remove all tabs - How can I align the form? - Editable Grid and VTypes - This crap doesn't work in aptana!! - How to use custom css on formpanel - how to obtain rowIndex and ColIndex - Desktop: dynamically adding a new window - Need a bulk selectionchange event for RowSelectionModel - ExtJS vs. JQuery - GridPanel DateTime Formatting - Passing an argument to Ext.onReady() - Access combo box values - Ext.Viewport: width and height ?? - Accordion Layout Events - Horizontally center FormPanel contents - button handler firing at wrong time - Set Cursor Position - igoogle widget - Tree not showing up on IE6 - Ext2.0 how get data in jsonStore after adding data manualy - Reference DOM object?? - Can the Accordian collapse/expand direction be changed? - Animal you're going to love this... - Problem adding components to an already open window - Trouble with IconCombo extension - FX problem in IE6 (specifically fadeIn & fadeOut) - Reconfigure EditorgridPanel with metaData from Server - Ext.onReady Call Failing in IE7 ?? - Simple RowSelectionModel Grid needed - addListener in IE - Placing PagingToolbar in GridPanel - Problems with Simple Basic Functions - Paging Help - How to AddTab w/Url from Accordian to Layout? - [solved] PagingToolBar: how to set page number (determined by server) - why formpanel have not scroll bar? if formpanel layout is absolute - if formpanel is able to add function,That was perfect! - like that complex formpanel. how to implement it by ext2.0,who help me? - Ext.grid.TableGrid example in IE - Using Ext Widgets - How can I add rows to column-table tree - TreePanel - Click & Hold selects node but doesnt fire 'click' - How to pull in raw html from a file into TabPanel? - How to Disable DragDrop on Grid Columns - web desktop - error message "ui is null" -- how to resolve? - How to save a tree structure - bug with icon in menu when using firefox - resizing window to cover the entire browser - Scoping issue, perhaps with grid? - Backgroundcolor on selected row in a grid - 'DOM Node Removed' event? - FormPanel not getting rendered in TabPanel - resizing panel in an tabpanel in a window - Adding tabPanels into a form - [SOLVED] Loading url into dynamic panel - Help : Sub Formpannel in tabpannel - Does Ext.example.msg work in a viewport ? - confirm box: how will i know programmatically what button the user pressed? - adding listener to comobox - Combo box renders wierdly - Grid Binding Example - [HELP] Showing and Hiding Panel ToolBars - multiwindow project ...your comment pls - DateFormat froM JSON DATA date string - Need Event when Mouse over a Tab or Accordion Panel - Problem with IE loadMask centering.
https://www.sencha.com/forum/archive/index.php/f-9-p-38.html?s=ad3eb9478f573973bc836bd8821c6abf
CC-MAIN-2020-10
refinedweb
1,553
56.76
It was easier to implement with the csproj file in the same directory as the source files, as this is the typical VS configuration. One problem that I encountered when I bumped the cproj file up to a higher level than the source files was that newly created files had the incorrect namespace ( src.main.csharp....). Of course, there are other problems. Technically, from VS perspective, the test and main are different projects, if their project file were in the same directory, they would end up each generating properties/files over each other. Shane On Dec 10, 2007 7:41 AM, Franz Allan Valencia See <franz.see@gmail.com> wrote: > Good day > > Why does it placed the csproj files in src/[main|test]/csharp? Since these > are project descriptors, wouldn't it make more sense if they're in the > basedir? > > Thanks, > Franz >
http://mail-archives.apache.org/mod_mbox/incubator-nmaven-dev/200712.mbox/%3Cf7743e090712101032s736ea579i69645a4217e364ff@mail.gmail.com%3E
CC-MAIN-2017-34
refinedweb
143
69.41
Using custom fonts on MenuBar Menu and/or MenuItem921851 Mar 13, 2012 5:26 PM Hi all! I was wondering if there's a way to set a custom font to a Menu and it's children. I can actually do this on the Text object like: I even tried the register font approach, even knowing that javafx.scene.text.Font and java.awt.Font are two different objects and got no success at all. As follows I was wondering if there's a way to set a custom font to a Menu and it's children. I can actually do this on the Text object like: But can't do it on the javafx.scene.control.Menu and javafx.scene.control.MenuItem objects.But can't do it on the javafx.scene.control.Menu and javafx.scene.control.MenuItem objects. ... import javafx.scene.text.Font; import javafx.scene.text.Text; ... @FXML private Text lblAppName, lblLoginFailed; ... Font myFont = Font.loadFont(getClass().getResourceAsStream("/fonts/TRON.TTF"), 40); if(myFont != null) lblAppName.setFont(myFont); I even tried the register font approach, even knowing that javafx.scene.text.Font and java.awt.Font are two different objects and got no success at all. As follows and then tried to use it from my css file:and then tried to use it from my css file: try { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/fonts/Baumans-Regular.ttf"))); } catch (Exception e) { e.printStackTrace(); } But guess what? It didn't (obviously) work. Since Menu and MenuItem don't have a setFont() method I guess I'm stuck with this. Thanks in advanceBut guess what? It didn't (obviously) work. Since Menu and MenuItem don't have a setFont() method I guess I'm stuck with this. Thanks in advance .menu-bar { -fx-background-color: transparent; -fx-font-family: Baumans; -fx-font-size: 14px; -fx-text-fill: #00CCFF; } This content has been marked as final. Show 6 replies 1. Re: Using custom fonts on MenuBar Menu and/or MenuItemjsmith Mar 13, 2012 7:54 PM (in response to 921851)Although I've used custom fonts for JavaFX 1.3, I've never been able to get them to work for JavaFX 2.x.1 person found this helpful Example 9 here talks about how to use custom fonts with JavaFX 2.x, but the example does not work for me (JavaFX 2.1-b16, WinXPsp3, JDK7u4ea) (). Perhaps I am doing something wrong, but not really sure what it is. Also I don't know how to use custom fonts in conjunction with css. So if anybody can get either of these things working, it might be useful to post how it was done. Here is a sample code which demonstrates changing the font for the menu and the menuitem to a monospaced (e.g. Courier) font. CSS used here: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.stage.Stage; public class MenuFont extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { final Menu fileMenu = new Menu("File"); fileMenu.getItems().add(new MenuItem("Open")); MenuBar menuBar = new MenuBar(); menuBar.getMenus().add(fileMenu); Font font = Font.loadFont(MenuFont.class.getResource("TRON.TTF").toExternalForm(), 120); Label label = new Label("TRON"); // label.setFont(font); // if this line is not commented out and the font is set, then no label is actually displayed... VBox layout = new VBox(10); layout.getChildren().addAll(menuBar, label); Scene scene = new Scene(layout, 200, 200, Color.ANTIQUEWHITE); stage.setScene(scene); stage.show(); scene.getStylesheets().add(MenuFont.class.getResource("menufont.css").toExternalForm()); } } TRON font used is this one: .menu-bar .label { -fx-font-family: monospace; -fx-font-size: 20; -fx-text-fill: red; } .menu-item .label { -fx-font-family: monospace; -fx-font-size: 20; -fx-text-fill: green; } 2. Re: Using custom fonts on MenuBar Menu and/or MenuItem921851 Mar 13, 2012 9:06 PM (in response to jsmith)Yours is a easy one. Use Text instead of Label. Check this forum entry: Font.loadFont doesn't work Edited by: 918848 on 13/03/2012 14:05 3. Re: Using custom fonts on MenuBar Menu and/or MenuItemjsmith Mar 13, 2012 10:44 PM (in response to 921851) Yours is a easy one. Use Text instead of Label.Thanks for the info - this was almost correct. Setting the font on the label actually worked, but what happened was that the the custom font I created set the font size to 120, which is huge for the TRON font. This meant that the Scene was sized too small to display the Label and the label implementation converted the text to just ellipses . . ., but even the ellipses could not be seen because they were too large to be displayed on the small Scene I created. If I made the Scene larger, it displayed just fine. It seems that if you just remove the sizing on the Scene it does not work either as the font stuff does not compute the correct layout area for the custom font label and the Scene ends up too small, so you need to manually set it to the right size. Also, as the forum post you linked hints, if you do set any styling in your program for the label which has the custom font displayed (e.g. try to change the font size via label.setStyle("-fx-font-size: 10;"), the font just reverts back to a standard font - so I guess you want to avoid that for now. What I did instead to get multiple size fonts is just make multiple calls to Font.loadFont(fontName, size). Once I worked out how to get a custom font displayed in a label, this meant that I could perform css lookups on the scene at run-time to set the custom font for the menu items. An example which demonstrates this is here: The runtime lookups rely on a deprecated impl_ call to find the popped up menu items, Stage.impl_getWindows(). A css based lookup or setting the custom font from a css stylesheet would be better, but I don't know how to accomplish either. Anyway, hope the above gives you enough information to accomplish what you want. 4. Re: Using custom fonts on MenuBar Menu and/or MenuItem921851 Mar 14, 2012 12:18 PM (in response to jsmith)Man, you won't believe me. But I finally made it and it's pretty simple! In my Application, before call any other window, I make a call to load the font: and then, at the css file: javafx.scene.text.Font baumansFont = javafx.scene.text.Font.loadFont(getClass().getResourceAsStream("/fonts/Baumans-Regular.ttf"), 10); And that's it! By the way, the approach you've shown works too, but I found too much processor intensive (n² complexity) just to use a custom font in a menu. Thanks for all the help. By the way, I won't mark this thread as answered untill you say it works for you too. .menu-bar { -fx-background-color: transparent; -fx-font-family: Baumans; -fx-font-size: 14px; -fx-text-fill: #00CCFF; } .context-menu { -fx-font-family: Baumans; -fx-background-color: transparent; -fx-font-size: 12px; -fx-text-fill: white; } 5. Re: Using custom fonts on MenuBar Menu and/or MenuItemjsmith Mar 14, 2012 7:11 PM (in response to 921851)Very cool. That loaded the custom font and styled it using css :-) I placed the loadFont call inside an overridden Application init method to make sure it was invoked before anything much happened in the application. When I used the styles you provided the colors of the fonts in the menus did not come out right, they just remained their default colors and not the -fx-text-fill color. Font.loadFont(CustomFontTest.class.getResource("TRON.TTF").toExternalForm(), 10); To get the right colors I had to use slightly modified css which explicitly set the -fx-text-fill on the label styleclass. Nice that the CSS sized the fonts fine. .menu-bar { -fx-background-color: transparent; -fx-font-family: TRON; -fx-font-size: 40px; } .menu-bar .label { -fx-text-fill: #00CCFF; } .context-menu { -fx-font-family: TRON; -fx-background-color: transparent; -fx-font-size: 12px; } .menu-item .label { -fx-text-fill: red; } Even when the font was loaded at size 10, the font was resized correctly to what was specified in the CSS fx-font-size specifications. Inline styling of a label via css using a Font loaded during application initialization also worked fine: Label testControl = new Label("TRON"); testControl.setStyle("-fx-font-family: TRON; -fx-font-size: 120;"); 6. Re: Using custom fonts on MenuBar Menu and/or MenuItem921851 Mar 14, 2012 7:33 PM (in response to 921851)Yes! Seems that using Registers the Custom Font and then we can set it using a css file. Also: Font.loadFont() "Place the loadFont call inside an overridden Application init method" Ensures we can access it from css. Marking this as Answered. Thank you JSmith for all the support!
https://community.oracle.com/message/10209688
CC-MAIN-2017-13
refinedweb
1,526
66.94
BINDRESVPORT(3) BSD Programmer's Manual BINDRESVPORT(3) bindresvport, bindresvport_sa - bind a socket to a privileged IP port #include <sys/types.h> #include <netinet/in.h> int bindresvport(int sd, struct sockaddr_in *sin); int bindresvport_sa(int sd, struct sockaddr *sa); The bindresvport() and bindresvport_sa() functions are used to bind a socket descriptor to a privileged IP port, that is, a port number in the range 0-1023.. Other- wise, ad- dress space. [ENOBUFS] Insufficient resources were available in the system to per- form the operation. [EPFNOSUPPORT] The protocol family has not been configured into the sys- tem, no implementation for it exists, or address family did not match between arguments. bind(2), socket(2), rresvport(3), rresvport_af(3) MirOS BSD #10-current August.
http://www.mirbsd.org/htman/i386/man3/bindresvport_sa.htm
CC-MAIN-2014-41
refinedweb
123
55.84
Hey guys, Thanks for the help on the interface stuff. Got it working. Running into another problem now. I have a small Java based execution harness that will load in some Jython code and execute it. The Jython makes a call out to some other Jython code I have that does some XML parsing using minidom. I keep getting the following error whenever it goes to run: Exception in thread "main" Traceback (innermost last): File "<string>", line 8, in ? File "c:\project files\JBI\Fuselets\.\jbiWrappers.py", line 25, in ? File "c:\project files\JBI\Fuselets\XmlSerializer.py", line 23, in ? ImportError: no module named xml Line 23 is: import xml.dom I've got Jython.jar in my java classpath, and the code runs just fine if I execute it directly in Jython. Any ideas what I'm missing or doing wrong? Thanks! --Mike
http://sourceforge.net/p/jython/mailman/attachment/002e01c388f9$4ea75810$8b01010a@isxwin2k.com/1/
CC-MAIN-2015-40
refinedweb
145
70.39
In C#, namespaces are used to logically arrange classes, structs, interfaces, enums and delegates. The namespaces in C# can be nested. That means one namespace can contain other namespaces also. In C#, namespaces are used to logically arrange classes, structs, interfaces, enums and delegates. The namespaces in C# can be nested. That means one namespace can contain other namespaces also. The .NET framework already contains number of standard namespaces like System, System.Net, System.IO etc. In addition to these standard namespaces the user can define their own namespaces. Declaring a Namespace The C# language provide a keyword namespace to create a user defined name space. The general form of declaring a namespace is as follows. namespace For example:using System;namespace Rajesh.Csharp.Codes{class MyClass{public MyClass(){Console.WriteLine("My Class");}} class MyClient{public static void Main(){MyClass mc = new MyClass();// Displays 'My Class'}}} It is not possible to use any access specifiers like private, public etc with a namespace declarations. The namespaces in C# are implicitly have public access and this is not modifiable. The namespace elements can't be explicitly declared as private or protected. The namespace allows only public and internal elements as it members. The default is internal. The following code doesn't compile in C#, since the class inside the namespace is declared as private. namespace Rajesh.Csharp.Codes{private class MyClass{}} Accessing Namespace Members The namespace members can be accessed by using a fully qualified name, which including the namespace name and member name separated by dot(.) from outside the namespace. For example using System;namespace Rajesh.Csharp.Codes{class MyClass{public MyClass(){Console.WriteLine("My Class");}}} class MyClient{public static void Main(){//Using the fully qualified name to access the namespace member.Rajesh.Csharp.Codes.MyClass mc = new Rajesh.Csharp.Codes.MyClass();}} But in order to save developer from typing fully qualified name every time, the C# provides another keyword using to define some aliases to namespaces. Then while writing our code, we just refer the classes with their class name only. During compile time, the compiler will map all the class names with aliases to reach at the fully qualified name of the class. Once the fully qualified name has been found, it is used to convert the code to IL code. Remember that in IL code all classes, interfaces, enums and delegates are referenced with their fully qualified name. An example of using is shown below. using Rajesh.Csharp.Codes;MyClass mc = new MyClass(); Remember that inside C# namespaces, it is possible to use the keyword using. The same namespace can be span over multiple lines as follows. using In C#, namespaces can be nested with each other as showing below. These are some of impoetant namespaces of .NET framework. Remember that the above list is a not complete one.
http://www.c-sharpcorner.com/UploadFile/rajeshvs/WorkingWithNamespacesInCS11112005044200AM/WorkingWithNamespacesInCS.aspx
crawl-002
refinedweb
471
50.43
PyCharm Professional 2020.2 Windows 10 Professional 19041.685 Background: I downloaded the folder from: Put it in D:\Dropbox\Code\course-nlp-master I right clicked the course-nlp-master from Windows Explorer, Open Folder as Pycharm Project Settings-> Build, Execution, Deployment -> Console -> Python Console Working Directory: set it from Blank to D:\Dropbox\code\course-nlp-master Problem 1: import os os.getcwd() Got: D:\\Dropbox\\code when I wanted D:\\Dropbox\\code\course-nlp-master Problem 2: in 2-svd-nmf-topic-modeling.ipynb, there is an image img src="images/document_term.png" which does not display in the right panel I changed the working directory to D:\\Dropbox\\code\\course-nlp-master using os.chdir() and changed the code above to img src="\images\document_term.png" However, it still fail to display. My question is, what is the best setting to use in PyCharm so that I can display all the images in all Jupyter notebook with the least amount of changes to the ipynb files? note: I opened the same notebook in Jupyter Notebook (Anaconda) and the images display correctly. Thanks! Hi, There's a known issue about images in Jupyter: Please follow the issue for updates, feel free to vote and comment, and let us know if you need any help. If you're not familiar with YouTrack, please see
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360010236459-Working-Directory-in-Windows-10-running-Jpyter?sort_by=created_at
CC-MAIN-2022-27
refinedweb
226
55.84
Created on 2018-05-02 10:35 by filips123, last changed 2019-08-03 00:53 by steve.dower. Unix socket (AF_UNIX) is now avalible in Windows 10 (April 2018 Update). Please add Python support for it. More details about it on I've been asked by my team to investigate what is required to enable AF_UNIX in Python. Is anyone else actively investigating this? I did a prelinary investigation and the impact on test in test_sockets was pretty simple. However there were 26 test failures in test_asyncio tests, with only the naive changes to all AF_UNIX to work with the socket class on Windows. The first failure I looked at was caused by ProactorEventLoop in windows_events.py not providing a windows-specific version of create_unix_server. This results in the code falling back to AbstractServer.create_unix_server which raises NotImplementedError. Have you upgraded the building SDK that supports AF_UNIX? And should remove AF_UNIX flag at runtime on systems older than Windows 10 1804, see issue32394. It would be nice to investigate the habit of using AF_UNIX in Python code on GitHub: If adding this flag will break a lot of code, due to lacking supports to datagram, maybe we should not add AF_UNIX at once, and waiting for full support to AF_UNIX. I don't know if datagram support is coming to AF_UNIX on Windows. The changes will only add the flag on Windows, and will enable stream sockets to use AF_UNIX on Windows. In mind this isn't breaking datagram support. It is true that it's a subset of what appears to be supported on Linux/Unix. The current AF_UNIX address family of Windows10 doesn't support datagram, adding this flag may break some cross-platform code: ... So I'm -1 on adding AF_UNIX personally. I thought a compromise proposal: - if (building SDK >= 1804 and run-time Windows >= 1804), add a undocumented flag _WIN_AF_UNIX, its value is equal to AF_UNIX. - only use _WIN_AF_UNIX in stdlib, this is a black-box optimization. - if someone really need high performance, he/she can uses this undocumented flag privately. If one day Windows support full AF_UNIX, we can remove _WIN_AF_UNIX and add standard AF_UNIX. Most of those examples would break today if run on Windows, though (AttributeError). So they'd just continue to break, probably with a different error (I'm not clear what happens if we specify SOCK_DGRAM with this change). Having an undocumented field doesn't really help much - what we want is a documented field with a different name, perhaps WIN_AF_UNIX? (I think we need to keep the "AF_" prefix for real values and not mess up the namespace ourselves.) That way we can document that it matches AF_UNIX when defined on Windows, but will not trigger existing code that checks for the presence of AF_UNIX. Then we'll have to update the standard library to use either/both values where supported. If you try to create a datagram socket with the current AF_UNIX changes on Windows the error is: OSError: [WinError 10047] An address incompatible with the requested protocol was used All of the examples given will fail to load with AttributeError on Windows because socket.AF_UNIX is not a valid attribute on Windows. I think it's possible that there is code that detects whether AF_UNIX is an attribute on socket or not and does something different on Windows, but I haven't seen an example of it so far. I can make the changes to WIN_AF_UNIX when I continue working on this, just in case there is portable code out there somewhere. > I think it's possible that there is code that detects whether AF_UNIX is an attribute on socket or not and does something different on Windows, but I haven't seen an example of it so far. One of the test suites linked above had a skipUnless(hasattr(socket, 'AF_UNIX')) on the whole class, and at least one test assumed that it could use datagram support, so there's the example.
https://bugs.python.org/issue33408
CC-MAIN-2021-21
refinedweb
666
62.07
In some ways SharePoint 2007 was a brand new incarnation of the SharePoint product. For the very first time, ASP.NET 2.0 was applied properly to the product. Things such as master pages, membership providers, sitemap providers etc. were used heavily in SharePoint. As a result, SharePoint 2007 got a whole new developer story to it. But in some ways it was a first version of a big product, so the development story left us wanting for more. Wanting for more because in some ways the API wasn’t ideal, and most certainly the development tools were somewhere between non-existent to bad. Diagnosing SharePoint errors was another frustrating story many have endured. What has changed in SharePoint 2010? Let’s find out. Much better development tools Developing for SharePoint 2007 meant either handcrafting your own project structures, or having community products such as WSPBuilder greatly help you out, or use tools released by Microsoft such as VSeWSS. It is fair to mention that VSeWSS was released very late in the product cycle. The whole world was already using WSPBuilder. But one very good reason for picking VSeWSS over WSPBuilder was the possibility being able to the current version of tools built into Visual Studio 2010. I am very happy to say that the Visual Studio 2010 built for SharePoint 2010, actually work! They are actually good. You no longer need any community tools, or visits deep into hackistan to get simple things done. Of course it is important to remember that the Visual Studio 2010 tools are built for SharePoint 2010 only, you can’t use them for SharePoint 2007 platforms. Now, you still need your own SharePoint development machine, but now that machine can be Windows 7 or Windows Vista. Client operating systems are supported for development reasons only. Also, as much as these tools try and wean you away from the 14 hive, now known as SharePoint root, directory structure, believe me, you still need to know it. Not only that, there is still no replacement for basic SharePoint fundamentals, such as what happens when you deploy a WebPart. For instance, writing a WebPart in the new Visual Studio 2010 tools is a perfect example. Earlier, using WSPBuilder, you had to craft up a directory structure that would literally represent the feature structure in the 12 hive. Then you had to meticulously hand craft the XML inside feature.xml, another set of XML inside your elements.xml, in which you had to remember that you had to deploy a .webpart file using a module into the _catalogs/wp, with a list ID of 113. Then inside of the .webpart file you had to remember to have a certain XML structure so your WebPart would be properly available in the right group, with the right icon and the right name. And then if anything was misspelled, there were usually no errors. Oh and you had to remember the feature had to be scoped to a site collection, which is really referred to as “Site” in the XML. What a mess! In comparison, Visual Studio 2010 tools let you write an equivalent WebPart using the following steps: - Create an Empty SharePoint project - Right click, add a new WebPart. Or, if you prefer, just create a Visual WebPart Project, though that requires you to write your WebPart as a farm solution in the current toolset. Now, you still have to know the basics – you have to know that a safecontrols entry will be created for you, you have to know that a .webpart file is deployed that you are responsible for the cleanup of, and you have to know the fundamentals of Sandbox solutions vs. Farm Solutions which is a new, and very important concept in SharePoint 2010. Reworked Architecture – Sandbox Solutions When you create a SharePoint Project in Visual Studio 2010, you are presented with the following dialogbox: There are two questions being asked here. The first is, which local site do you want to use for debugging? This is the same machine that you are running SharePoint on. Some may wonder why Visual Studio has to ask such a silly question, because after all this is always your local machine. The reality is, sometimes you may have alternate URLs setup even for your local site, and that may be important in certain development tasks. Secondly, the site collection you intend to debug your code on may not be a root level site collection. Finally, if you have multiple web applications, this tells Visual Studio which w3wp.exe process to attach to for debugging. Providing the URL tells Visual Studio what w3wp.exe to attach to, in order to debug your code. So you see it's not such a silly question after all. That was my marketing side talking. Although in simplistic scenarios F5 debugging will work, in many situations you will still find yourself attaching to processes. For example, sometimes your code may not run inside w3wp.exe. It may run under a separate EXE called SPUserCodeService.exe. That would be a sandboxed solution which I will cover in more detail later in this chapter, but for now, that is the second question Visual Studio wishes you to answer. Therefore, the second question is whether you intend to create a sandboxed solution or a farm solution? A farm solution is what used to be a solution in SharePoint 2007. It had unfettered rights to your SharePoint farm, so it could do anything. Sounds like a good proposition, but this created an immense headache for the two poor farm administrators in your organization who were then expected to somehow review every line of code being deployed to the server. A task they intend to get around to doing right after they solve world peace and hunger. Frankly, it is unreasonable to expect two overtaxed IT Pro people to review every single developer's code. Plus since some developers can be really crafty with custom code, while being necessary, is the number one reason for support issues on SharePoint in general. In response, Microsoft came out with the concept of sandboxed solutions, sometimes also referred to as user solutions or user code. Put simply, a sandboxed solution is what runs inside a secure sandbox. It runs inside a separate process from W3WP.exe, and it is protected by a CAS policy, so you no longer have to craft custom CAS policies. Also, in addition to being more secure, it is also more easily monitored. Being more restricted, secure, and being more easily monitored, sandboxed solutions can now be deployed with more confidence. Thus, they are now deployable and can be activated right through the site collection. The Farm Administrator doesn't even need to be bothered, because he is monitoring the solution anyway. You cannot break his farm by deploying a sandbox solution, so everyone can be at peace, no more IT-Developer wars. If there are two things you carry from this article about Sandbox Solutions, they are: - Secure by default, you should create sandboxed solutions when you can. Creating a farm solution unnecessarily is bad practice. Perhaps a better way of saying this is, create farm solutions only when you cannot create a sandboxed solution. - You can choose to change your mind later, i.e., change a sandboxed solution to a farm solution or vice versa if you need to. Oh and did you hear about the cloud? Microsoft is all about the cloud these days, and so is everyone else. I really doubt you’ll be able to deploy farm solutions on SharePoint online. Client Side APIs What are good development tools without a decent API? We live in a changed world, 5 years ago, with no facebook, no google maps, no foursquare, it was actually possible to get lost and avoid people you didn’t like! Now you have all these crazy applications that feel like desktop applications, but they run right through the browser. So, finally, for the very first time in the history of computing, you have the power of desktop apps, with no installation hassle, and complete security! How did we do it? We did it using client side technologies, specifically JavaScript, Flash, and Silverlight. It is no surprise therefore that SharePoint 2010 includes amazing support for both JavaScript and Silverlight. The biggest proof in the pudding of course is Microsoft’s own commitment to these products. Core features of SharePoint 2010 use JavaScript heavily. And they do so in an “upgrade to Silverlight” mentality. For instance, if you use the word or powerpoint office web apps, everything will work if you don’t have silverlight. But soon as you install silverlight, the user experience becomes so much better. Fonts start to use cleartype rendering, pages load faster, etc. Visio services does that too, it renders everything as .PNG if you don’t have silverlight. But prefers to render everything as .XAML. So the question is, is any of this power available to you? Certainly! It is available to you in 3 forms on the server side. - The Client Object Model, which gives you a whole new namespace at Microsoft.SharePoint.Client, which looks and feels like a subset of the server side API with two big differences. - It runs in the client, which can be .NET CLR application not running on the server, or JavaScript, or Silverlight - It allows you, the developer to control when you round trip to the server, and what is done during those round trips. Concepts such as concurrency management, object identity are built into its API. - The REST API, which exposes every SharePoint list over a RESTFUL interface. Which means you can use simple HTTP Verbs such as GET, PUT, MERGE, DELETE, and POST to query and update data on the server, or even generate proxies and use higher constructs such as LINQ to work with server side data. - Custom WCF services, because both the client object model, and the REST API are built using WCF – you can write your own services if you wanted to. And on the client side, you can choose to use .NET CLR, Silverlight, Flash, jQuery, iOS, Java, basically whatever you want! This will truly usher in a new era of apps. Better Diagnosis Tools An “unexpected error has occurred”. Well I guess, I wasn’t expecting an error in the first place, was I? Diagnosing SharePoint errors can be a black art, there are many places to look at when an error happens. This is because the product is inherently big and complex with a lot of moving parts. So I was really excited to see some improvements on the error logging and tracing side. SharePoint’s central logging capability is referred to as ULS, or the Unified Logging Service. The ULS, is a bunch of text files, that wrap around a certain character length, but suffice to say, each file is wide enough that it doesn’t fit properly on a 30” monitor in 8pt font even. Looking for your error inside the ULS can be almost like looking for a needle in a haystack. Well, not anymore! In SharePoint 2010, you get an error message that looks like this, Note there is a Correlation ID there? Now using that correlation ID, you can easily trace down your error needle in the ULS haystack. And there are tools available to help you do that. One such tool is the ULS Viewer which you can download for free from code.msdn.microsoft.com/ulsviewer. And guess what, that tool will work with SharePoint 2007 as well. And in general, there are many other such enhancements in the logging framework, and diagnosis of issues in your SharePoint installation. Summary SharePoint 2010 is quite different from SharePoint 2007. One article is merely touching the tip of the top molecule of the iceberg. Come join us for more such information at the DevWeek SharePoint 2010 post conference on Friday, March 18th, 2011 with Sahil Malik. You can find more details about the post conference workshops here.
http://www.developerfusion.com/article/92338/sharepoint-2010-for-developers-whats-new/
CC-MAIN-2017-22
refinedweb
2,014
64.1
In this discussion I will be tackling the whys and wherefores of creating COM servers in Python. In the first section the focus will be on COM servers. In the second section and third sections, I will detail the necessary steps for creating a COM server in Python. The fourth section will provide a real world example of developing a COM server and calling it from Visual Basic. That’s the outline for this discussion. More About COM In the world of COM there is a clear line of separation between accessing COM components and implementing COM objects. While accessing COM objects, method calls are made on them, provided externally using the interfaces exposed by the COM object. When implementing COM objects, which are also known as COM servers, the object has to publish or expose its interfaces so that external clients can use them. This difference is evident from the way the interfaces and methods implemented are utilized either to access a COM component or expose the functionalities of a COM component. The interface under consideration is IDispatch. Programs that use an IDispatch object must call the GetIDsOfNames() and Invoke() methods to perform method calls or property reference, whereas the objects that wish expose their functionalities via IDispatch must implement the GetIDsOfNames() and Invoke() methods, providing the logic for translating between names and IDs, and so on. In the world of PythonCOM, the former is called client-side COM and the latter is server-side COM. The next topic I will cover is the types of server-side COM objects. There are three types of server-side COM objects: - In-Proc Server - Local Server - Remote Server The difference in the types is based on where the COM server is executing. The COM server could be executing in the process space of the client, in its own separate process space, or on a different system. Here are the details. In-Proc Server When the COM server is loaded into the process space of the client, it is known as an In-Proc server. In other words, "A Component Object Model (COM) object that is executing in the same process space as the user of that object is called an In Process object (InProc for short)." An In-Proc server is implemented as a DLL in other languages. Local Server When the COM server is loaded and executed in its own process space, it is called a Local Server. By definition, "When the user code is executing in the process space of Application A, and the COM object is executing in the process space of Application B, interface method invocations by A on interfaces implemented on B clearly must cross process boundaries, then the COM objects in Application B are cross-process objects, or Local Servers." A Local Server is implemented in the form of an EXE. Remote Server When the COM server is implemented as an EXE but executed on a remote machine, it is known as a Remote Server. Remote Servers come under the heading of Distributed COM or DCOM. The important aspect of these differences is that they are mutually inclusive. That means a COM component can be registered as a combination of any of the above three types. Now that the types of COM servers have been introduced, let’s see how to develop COM servers in Python step-by-step. {mospagebreak title=Developing COM Servers Step by Step} Developing a COM server in Python is easier than in any other language. If the process is broken down into steps there are primarily two steps, which are developing the class and annotating the class with attributes. Furthermore, in the first step you must decide on which model the class must be based. Developing the class The philosophy of COM is that a fixed interface must be built and the class must be modeled around it. In essence, once the interface has been defined, it must not be changed. To work with this philosophy there are three design patterns that can be used. They are: - COM base class, pure Python subclass - Pure Python base class, COM subclass - COM interface, Python delegate The COM interface, Python delegate pattern is the most commonly used. The reason for this is the ability to develop the class first. In the pattern of a COM base class, pure Python subclass, a base class has to be defined and exposed as a COM server. The methods in the base class perform no tasks. The base class works as a COM interface. Then a sub class, which implements the base class, has to be developed; this class provides the actual services. In other words a class that implements the base class performs the tasks. This pattern is most appropriate when designing a class whose main function is to be used from COM and not from Python. Now let’s look at a pure Python base class, COM subclass pattern. It is in a way the opposite of the previous pattern. Here, the existing COM class is inherited from a Python base class. The COM class can be differentiated by the the attributes used to annotate the class, which will be discussed shortly. Finally, let’s examine the COM interface, Python delegate pattern. In this case, the COM interface is defined. The class that defines the COM interface has variables internal to it that point to the pure Python counterpart. The Python counterpart is known as the delegate. The methods of class that represent the COM interface translate their arguments, return values as needed, and forward them to the delegate. Let’s take the third pattern as an example. For the sake of the example, suppose there is a BookSet class that implements the methods of the COM interface. Now if the third pattern is applied to define a COM interface, it would look like this: __BookSet variable points to the pure Python class BookSet. This is how it delegates the task to the pure Python class. You will observe that there are certain attributes such as _reg_clsid_. The explanation of these attributes is coming up next. {mospagebreak title=Annotating the Class with Attributes} Every Python class representing a COM interface must expose itself as a COM object. To achieve this, the PythonCOM framework requires certain attributes to be associated with the Python class that needs to be exposed as a COM object. There are three main attributes, which are: - _public_methods_ - _reg_progid_ - _reg_clsid_ All of the above attributes are required in exposing a Python class as a COM object – from simplest to the most complex COM objects. The _public_methods_ attribute takes a list of all those methods that need to be exposed via the COM. The _reg_progid_ attribute is used to assign the ProgID for the new object, that is, the name that the users of this object must use to create the object. It is the human readable name of the object. Finally, the _reg_clsid_ attribute sets the unique CLSID for the object. These IDs must not be copied. Instead new ones should be created using pythoncom.CreateGuid(). Let’s take a look at the same example of the COM server: _reg_clsid_ contains a 32 bit class id for the object. The _reg_progid_ contains the human readable name using which the object can be called. Here the _public_methods_ contains the list of all the methods exposed via COM. Here there is only one — double. That completes this section. In the next section, I will be creating a real world example and call it from Visual Basic. {mospagebreak title=Creating COM Servers in the Real World} In the previous sections I introduced the basic requirements for creating a COM server in Python. Now let’s put the concepts into practice. The example will provide a simple functionality — splitting a given string. There are two parts of the application: - PyCOMServer.py – The COM server implemented in Python - SampleClent.vb – The client implemented in VB Let’s start with the server. First let’s define the Python class contained in PyCOMServer.py – PythonUtilities class PythonUtilities: def SplitString(self, val, item=None): import string if item != None: item = str(item) return string.split(str(val), item) This class defines a single method, SplitString, that takes two arguments: item, which is the string to be split; and the value contained in val on the basis of which string has to be split. The next step is to embed the attributes so that the class can expose its functionalities through the COM: class PythonUtilities: _public_methods_ = [ ‘SplitString’ ] _reg_progid_ = "PythonServer) Since there is only one method that needs to be exposed, the list for _public_methods_ contains only the SplitString method. Next, the name by which it can be called is given via _reg_progid_ which is PythonServer.Utilities. Finally the class id generated using pythoncom.CreateGuid(). Next is the main code that is required to register and run the COM server. class PythonUtilities: _public_methods_ = [ ‘SplitString’ ] _reg_progid_ = "PythonDemos) # Add code so that when this script is run by # Python.exe, it self-registers. if __name__==’__main__’: print "Registering COM server…" import win32com.server.register win32com.server.register.UseCommandLine(PythonUtilities) Next comes the client. For developing the client start the Macro editor either in MS Word or MS Excel. Enter the name for the macro. The implementation of the macro is as follows: Set PythonUtils = CreateObject("PythonDemos.Utilities") response = PythonUtils.SplitString("Hello from VB") for each Item in response MsgBox Item That brings us to the end of this discussion. The application developed doesn’t apply the design patterns, as certain advanced aspects of COM programming have to be covered yet. That’s the agenda for the next part: advanced aspects of COM servers. Till then…
http://www.devshed.com/c/a/python/windows-programming-in-python-creating-com-servers/
CC-MAIN-2018-09
refinedweb
1,620
63.29
Install Precompiled OpenCV 4.5 on Raspberry Pi OpenCV is an open-source library for image processing, computer vision, and machine learning. OpenCV is widely used for object detection, gesture recognition, motion tracking, face detection and recognition, image segmentation, medical image analysis, license plate recognition, and so on. This tutorial shows how to install precompiled OpenCV 4.5 on Raspberry Pi. Debian package We have created Debian package ( .deb) that contains precompiled OpenCV 4.5.3 binaries for Raspberry Pi 3 Model A+/B+ and Raspberry Pi 4 Model B. Binaries are compatible with Raspberry Pi OS Buster (32-bit). We have created a release on GitHub repository and uploaded opencv.deb package. OpenCV was built with the following features: - NEON optimization - VFPv3 optimization - TBB library - FFmpeg library - GStreamer library - Python 2 and Python 3 bindings You can found detailed build information on GitHub repository. We tested on Raspberry Pi 4 Model B (8 GB). Install OpenCV Connect to Raspberry Pi via SSH. Download the .deb package from releases page of the repository: wget Execute the following command to install OpenCV: sudo apt install -y ./opencv.deb We can run opencv_version command to check version of OpenCV: opencv_version The .deb package is no longer needed, you can remove it: rm -rf opencv.deb Testing OpenCV (C++) Before starting, make sure you have installed GNU C++ compiler: sudo apt install -y g++ Create a main.cpp file: nano main.cpp When a file is opened, add the following code: #include <opencv2/opencv.hpp> int main() { std::cout << cv::getBuildInformation() << std::endl; return 0; } Execute the following command to compile code: g++ main.cpp -o test -lopencv_core The core functionality of OpenCV has been used. So we need to link libopencv_core.so shared library. Run a program: ./test Testing OpenCV (Python) Create a main.py file: nano main.py Add the following code: import cv2 print(cv2.getBuildInformation()) Run a script using Python 3: python3 main.py Python 2 can be used as well: python main.py Uninstall OpenCV If you wish to completely remove OpenCV and related dependencies, execute the following command: sudo apt purge --autoremove -y opencv
https://lindevs.com/install-precompiled-opencv-on-raspberry-pi/
CC-MAIN-2021-31
refinedweb
357
60.21
Book. The author has over 16 years experience in IT and enterprise web application development. He has deployed Ext-based applications in large corporations such as Marriott International, Lockheed Martin, JPMorgan Chase, and the Financial Industry Regulatory Authority. In his spare time, Jay enjoys assisting the Ext JS community forums, where he is one of the top posters not employed by Ext JS LLC (over 13,000 posts). The book includes information on: - Building dynamic UIs using core components like panels with layouts - Creating live forms that submit data without a page refresh - Effective UI using trees, menus, and toolbars - Creating custom composite widgets - Full coverage of Ext JS 3.0 The reader will be guided through the Ext component model and layouts, learn how core components, such as the Container class, serve as building blocks for building complex user interfaces. The book covers Ext utility classes, AJAX, Observable (the Ext events model), DOM helpers and Function Helpers and illustrates how use of JavaScript Object Notation (JSON). It also examines the proper ways to customize or extend Ext widgets. The book’s publisher, Manning, made an expert available to InfoQ which includes the contents of the 3rd chapter, “The Component model and lifecycle”. InfoQ readers can take advantage from a 40% discount on Ext JS in Action using the promo code “infoq40”, courtesy of the publisher. InfoQ had a Q&A with the author about his new book: InfoQ: Hi Jesus, would you like to tell us a little bit about yourself and how you came about writing a book about Ext JS? Jesus: I began with Ext JS back in early 2006, when it was a set of extensions for the YUI library. Back then, it was known as “YUI-ext” and was developed as a side project by a little known guy named Jack Solcum. Like many newcomers to the framework, I was first attracted to the data grid. What sold me to the library was the documentation, which is probably the best Ajax framework API to date. Soon after my introduction to the framework, I decided to become a specialist and focus my career, becoming an independent consultant. After this decision, I started becoming active in the early community, spending a lot of my own time in the help forums, answering people’s questions or working through their problems with them. By doing this, I was able to learn much more about the framework than I would by just doing application development. To this day, this still gives me a means to learn a lot while contributing to the community by helping others. Being on the Ext JS forums has earned me a bit of a reputation, and is how I got onto the radar of Michael Stephens from Manning. He contacted me, along with other active community members, to request a review of a book proposal. After reading the first few lines of the proposed table of contents, it was clear to me that this book was not an “Ext JS in Action”. After submitting my thoughts and recommendations on the proposed TOC, Michael held a post-review meeting and that’s where he asked if I would be willing to submit a TOC of my own, and I did. Fast forward two years, and here we are. InfoQ: What is Ext JS and what is the problem that it tries to solve? Jesus: Ext JS is a UI library for the web. It is light years ahead of any UI library on the market because it abstracts developers from having to write a single ounce of HTML if they don’t want to, yet has the flexibility to allow any developer to Extend the widget libraries or create real plugins via a simple, yet powerful plugin architecture. Ext JS solves the problem of managing HTML and CSS to provide a UI look and feel that rivals desktop applications. It empowers developers to inject widgets into existing HTML web pages or develop extremely rich Enterprise class RIAs, some of which are used in mission critical applications, such as real time monitoring and managing of network infrastructures. The framework also has quite a lot of utilities, such as the data Store, templates and xTypes that further empower application development capabilities. InfoQ: In your book you mention that the Component and Container models that Ext JS follows is what makes it stands out from the rest of the Ajax libraries. Would you like to elaborate on that? Jesus: The Component and Container models (among other things) make Ext JS quite unique among competing Ajax libraries because they bring structure to the UI portion of the library. Without it, Ext JS would be not much different from other Ajax Libraries. The Component model introduces the “Component Lifecycle” to the framework and brings a set of well-defined and dependable behaviors to the widgets. It is broken up into three phases, Initialization, Render and Destruction. Initialization occurs whenever you instantiate a new instance of a component. The Render phase occurs when the Component is rendered or painted on screen. Lastly, the Destruction phase allows the Component to perform cleanup tasks, such as the removal of any injected HTML nodes and purge any event listeners. The Container model allows Components to manage other components in a parent-child relationship model. With the Container model, developers can easily create dynamic UIs by leveraging its add() or remove() methods to add or remove one or more child items. To manage the visual organization of child items, Containers use a Layout. InfoQ: Would you like to tell us a little bit about how you use Ext JS in your work? How do you see other people using it. Are there types of RIA applications where it is not a suitable solution? Is Ext JS suitable for mobile web applications? Jesus: I typically use Ext JS to develop applications for a wide variety of customers. My latest task was to develop a screen to manage member information for one of my customers. Because Ext JS is so versatile, I’ve been able to leverage it to develop a wide variety of applications from a custom UI merging data from IBM’s Tivoli Enterprise Console and HP Universal CMDB to a front-end for EMC’s Documentum product. I’ve even developed applications to help organizations develop content for exams. Developers can leverage Ext JS pretty much to develop whatever they need in a RIA. Throughout its lifespan, I’ve seen such a wide range of applications, most of which were business-centric. Ext JS, itself is not geared towards mobile web development, but its sibling Sencha Touch is. I have seen and toyed with Ext JS applications running on an iPad with limited functionality. It does not contain support for touch gestures that make mobile applications useful and its UI theme is certainly not mobile-centric. InfoQ: How good do you see Ext JS perform on the various browser platforms? What do you have to say to people that might be reluctant to use it because of current compatibility issues, or fear to lose compatibility because of future upgrades? Jesus: Boy that’s a loaded question (smile). I would have to say that Ext JS performs the best given the best environment to run in. Generally, it has been my experience that Ext JS runs best in Webkit-based browsers, and absolutely the worst in IE. Naturally, the browser has a lot to do with this perception, but there were some issues in the early release of the Ext JS 3.0 code base that contributed to the slow performance in IE. It’s a known fact that general performance for the initial release of Ext JS 3.0 was much less than 2.x, but it certainly has gotten better with subsequent releases. The Ext JS team has been pretty sensitive to the feedback that various customers and community members have been giving them and have been making necessary changes to try to squeeze as much performance as possible without limiting functionality. I also have to throw in that performance of the framework also as a lot to do with how developers implement it. Newer developers tend to make simple mistakes, such as what is known as “overnesting”. This is when someone unnecessarily wraps a widget with a parent widget, adding an unnecessary layer of effort for the UI. Another common mistake is loading thousands of records into a view (GridPanel, DataView, ListView or ComboBox), which can lead to the “JavaScript is running too long” message on your screen. Upgrading from the 2.x branch to the 3.x version is pretty easy. This also holds true with upgrading within the 3.x family. From my experience, most of the problems people have with upgrading is that they have code that are depends on, uses or overrides private members, which are subject change. They are marked private for a reason. Obviously, this practice is not recommended by the team or even by veteran developers and is something you should work to avoid to allow for easier upgrades. InfoQ: What is your preferred process for developing an Ext JS application? What tools do you use and how good do you think the current JavaScript/HTML tool stack is? Jesus: I typically develop applications locally on my laptop to make the feedback loop as rapid as possible. I use a pattern to developing applications following the framework’s patterns, with somewhat of a twist. For instance, I like to lay out the files in the file system (and project) according to the namespace of the class. This allows for quick access to files. This same pattern is applied to any plugins, user extensions (ux) or overrides that are applied to the framework. There are quite a few good tools to develop your JavaScript code, but I prefer to develop my applications with Jetbrains’ Intellij IDEA. While it’s not the fastest tool, it is the one that I have fallen in love with. It allows me to do things like have dynamic code auto completion and refactoring on class members. It also includes its own debugger for JavaScript, though I typically don’t use it. I’ve heard great reports from developers using tools such as NetBeans or even Aptana, which is a wrapper for Eclipse. InfoQ: Does using a substantial JavaScript client-side framework like Ext JS pose difficulties in debugging? When things go wrong how do you debug? Jesus: It can pose serious difficulties for a lot of reasons. The first typically is that developers will use ext-all.js (concatenated and minified version of the framework) instead of ext-all-debug.js (concatenated with white space preserved and comments removed) when developing. If an exception is thrown by the JS interpreter, the message will typically be extremely cryptic due to the nature of JS minification. If the error is viewed in IE, it generally will make no sense what so ever and add to your frustration. Generally, to remedy this, you would want to develop your apps using the uncompressed ext-all-debug.js file, which will make the error message a tad less cryptic and you can at least get an accurate line indication for which the exception occurred. Whenever an exception is generated by ext-all-debug.js, I typically will try to view the area where the exception occurred. From there, I scroll up to find the method that the exception was generated in, then scroll up again to find the class that the method belongs to. Nine times out of ten, for me at least, the problem is usually between the keyboard and the chair. I have to say that because I use Webkit, viewing hundreds of thousands of lines of JS in the ext-all-debug.js file is a breeze. Sadly, the current state of Firefox prevents Firebug from reaching the same level of performance, which is why I moved to Webkit from Firefox a few months ago. I’ve tried the same in IE8 and ended up pulling a lot of my hair out. InfoQ: Are you using any functional testing methods in your work? How do you go about this issue? Jesus: Unfortunately no. I have thought about injecting unit testing into the application development cycles for my customers, however time always seems to be an issue. The amount of time spent writing tests can save you tons of time in bug fixes in the future, but making that initial investment is difficult for my customers. InfoQ: In your book you describe several components that you get out of the box, when using Ext JS. Is it easy to extend those? How easy is it to create new components? Jesus: I find it easy to extend the framework, but then again, I’ve been using it since 2006. Ext JS is developed to be extended and have plugins written for it and demonstrates some of the best JavaScript development patterns that I’ve seen in any competing framework. The level of difficulty for extending components is relative to the developer’s experience with Object Oriented JavaScript patterns and the framework. You absolutely need to be experienced with OOJS (prototypal inheritance) to be able to extend the components. afterall, if you don’t understand prototypal inheritance, the concept of extending inside of JavaScript will seem foreign to you. You also need to be able to understand concepts like execution context and how the ‘this’ keyword is used. Likewise, you should be familiar with the Component, Container and layout models to extend widgets properly and prevent common mistakes like overnesting. Good knowledge other areas of the framework helps as well. I bring all of this up because I’ve seen so many new developers come to the framework with grand dreams of building complex and elaborate applications. Yet they find themselves stumbling on simple tasks, all because they do not have the foundation necessary to fully understand or utilize the framework. For people who want to get up to speed on JavaScript, I suggest “Pro JavaScript Techniques” by Dustin Diaz (Apress). This will explain a lot about modern JavaScript programming, allowing you to get a clearer picture of what some of the advanced code you see in the wild. InfoQ: How do you see Ext JS evolving with the emergence of HTML5? Jesus: The one thing that has been great about the Sencha team is that they are always looking ahead. They have been working hard to bring Ext JS HTML5 and CSS3 compliant for version 4.0, which is due out some time next year. Ext JS 4.0 shares the same base code as Sencha Touch, which already has great support for these technologies. InfoQ: What do you think would be the most valuable take away from your book for people that have just found about Ext JS and what for seasoned users of this frameworks that want to take it to the next level? Jesus: For the newbies to the framework, I think getting a deep understanding of the Component, Container and Layout models is a great take away. I tried my best to explain them in plain English as possible and have gotten pretty good feedback from readers. For the veterans, I’d have to say that the most valuable take away from the book has to be the last three chapters (15-17). Chapter 15 gives readers the basics of creating extensions with Ext JS and developing plugins using real-world examples. The last two chapters are dedicated to constructing a fictional application and walk readers through core decision making processes, such as laying out a namespace and developing abstract classes to reduce duplicate code. Developers from many experience levels have given me positive feedback from after reading these chapters and have said that some the concepts have helped them in various ways when developing applications. You can find more information on JavaScript and Rich Internet Applications right here on InfoQ. gxt by tom corcor
http://www.infoq.com/articles/extjs-in-action
CC-MAIN-2015-18
refinedweb
2,683
61.06
On 2020-11-16 16:21, Brian Inglis wrote: >. Attaching UG build doc outputs as results easier to see and review and change more obvious, rather than specialnames.xml and Makefile.in patches for now, as git does not appear to like non-patch attachments. One of the issues with the xml input is that formatting wide screen displays as if at .in 0 appears to be impossible, or at least not in evidence in any of the other inputs or outputs, which don't include such heavily indented lists of lists, and ending and restarting heavy indenting context appears ugly. -- Take care. Thanks, Brian Inglis, Calgary, Alberta, Canada This email may be disturbing to some readers as it contains too much technical detail. Reader discretion is advised. [Data in binary units and prefixes, physical quantities in SI.] -------------- next part -------------- A non-text attachment was scrubbed... Name: cygwin-ug-net.info Type: application/octet-stream Size: 10765 bytes Desc: not available URL: <> -------------- next part -------------- A non-text attachment was scrubbed... Name: cygwin-ug-net.info-1 Type: application/octet-stream Size: 300804 bytes Desc: not available URL: <> -------------- next part -------------- A non-text attachment was scrubbed... Name: cygwin-ug-net.info-2 Type: application/octet-stream Size: 164834 bytes Desc: not available URL: <> -------------- next part -------------- '\" t .\" Title: proc .\" Author: [FIXME: author] [see] .\" Generator: DocBook XSL Stylesheets v1.77.1 <> .\" Date: 2020-11-11 .\" Manual: Cygwin User\*(Aqs Manual .\" Source: Cygwin .\" Language: English .\" .TH "PROC" "5" "2020\-11\-11" "Cygwin" "Cygwin User\*(Aqs Manual" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" .\" .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" proc \- process information pseudo\-filesystem .SH "DESCRIPTION" .PP The proc filesystem is a pseudo\-filesystem which provides an interface to Cygwin data structures\&. It is commonly mounted at /proc\&. Typically, it is mounted automatically by the system\&. .SS "Overview" .PP Underneath /proc, there are the following general groups of files and subdirectories: .PP /proc/[pid] subdirectories .RS 4 Each one of these subdirectories contains files and subdirectories exposing information about the process with the corresponding process id\&. .sp The /proc/[pid] subdirectories are visible when iterating through /proc with \fBreaddir\fR(2) (and thus are visible when one uses \fBls\fR(1) to view the contents of /proc)\&. .RE .PP /proc/self .RS 4 When a process accesses this magic symbolic link, it resolves to the process\*(Aqs own /proc/[pid] directory\&. .RE .PP /proc/[a\-z]* .RS 4 Various other files and subdirectories under /proc expose system\-wide information\&. .RE .PP All of the above are described in more detail below\&. .SS "Files and directories" .PP The following list provides details of many of the files and directories under the /proc hierarchy\&. .PP /proc/[pid] .RS 4 There is a numerical subdirectory for each running process; the subdirectory is named by the process id\&. Each /proc/[pid] subdirectory contains the pseudo\-files and directories described below\&. .sp The files inside each /proc/[pid] directory are normally owned by the effective user and effective group id of the process\&. .RE .PP /proc/[pid]/cmdline .RS 4 followed by null bytes (\*(Aq\e0\*(Aq)\&. .RE .PP /proc/[pid]/ctty .RS 4 This read\-only file holds the name of the console or control terminal device for the process, unless the process is detached from any terminal\&. In the latter case, there is only a newline in this file\&. .RE .PP /proc/[pid]/cwd .RS 4 This is a symbolic link to the current working directory of the process\&. To find out the current working directory of process 20, for instance, you can do this: .sp .if n \{\ .RS 4 .\} .nf $ \fBcd /proc/20/cwd; /bin/pwd\fR .fi .if n \{\ .RE .\} .sp Note that the \fIpwd\fR command is often a shell built\-in, and might not work properly\&. In \fBbash\fR(1), you may use \fBpwd\ \&\-P\fR\&. .RE .PP /proc/[pid]/environ .RS 4 This read\-only file contains the current environment that may have been changed by the currently executing program\&. The entries are separated by null bytes (\*(Aq\e0\*(Aq), and there may be a null byte at the end\&. Thus, to print out the environment of process 1, you would do: .sp .if n \{\ .RS 4 .\} .nf $ \fBcat \-A /proc/1/environ\fR .fi .if n \{\ .RE .\} .sp If, after an \fBexecve\fR(2), the process modifies its environment (e\&.g\&., by calling functions such as \fBputenv\fR(3) or modifying the \fBenviron\fR(7) variable directly), this file will reflect those changes\&. That may not be the case on other systems such as Linux\&. .RE .PP /proc/[pid]/exe .RS 4 This file is a symbolic link containing the actual pathname of the executed command\&. This symbolic link can be dereferenced normally; attempting to open it will open the executable\&. You can even type /proc/[pid]/exe to run another copy of the same executable that is being run by process [pid]\&. /proc/[pid]/exe is a pointer to the binary which was executed, and appears as a symbolic link\&. .RE .PP /proc/[pid]/exename .RS 4 This read\-only file contains the actual pathname of the executed command\&. .RE .PP /proc/[pid]/fd/ .RS 4 This is a subdirectory containing one entry for each file which the process has open, named by its file descriptor, and which is a symbolic link to the actual file\&. Thus, 0 is standard input, 1 standard output, 2 standard error, and so on\&. .sp For file descriptors for pipes and sockets, the entries will be symbolic links whose content is the file type with the inode\&. A \fBreadlink\fR(2) call on this file returns a string in the format: type:[inode] .sp For example, socket:[2248868] will be a socket and its inode is 2248868\&. .sp Programs that take a filename as a command\-line argument, but don\*(Aqt take input from standard input if no argument is supplied, and programs that write to a file named as a command\-line argument, but don\*(Aqt send their output to standard output if no argument is supplied, can nevertheless be made to use standard input or standard output by using /proc/[pid]/fd files as command\-line arguments\&. For example, assuming that \fB\-i\fR is the flag designating an input file and \fB\-o\fR is the flag designating an output file: .sp .if n \{\ .RS 4 .\} .nf $ \fBfoobar \-i /proc/self/fd/0 \-o /proc/self/fd/1 \&.\&.\&.\fR .fi .if n \{\ .RE .\} .sp and you have a working filter\&. .sp /proc/self/fd/N is approximately the same as /dev/fd/N in some Unix and Unix\-like systems\&. Most Linux \fBmakedev\fR scripts symbolically link /dev/fd to /proc/self/fd, in fact\&. .sp Most systems provide symbolic links /dev/stdin, /dev/stdout, and /dev/stderr, which respectively link to the files 0, 1, and 2 in /proc/self/fd\&. Thus the example command above could be written as: .sp .if n \{\ .RS 4 .\} .nf $ \fBfoobar \-i /dev/stdin \-o /dev/stdout \&.\&.\&.\fR .fi .if n \{\ .RE .\} .sp: .sp .if n \{\ .RS 4 .\} .nf $ \fBecho test | sudo \-u nobody cat\fR test $ \fBecho test | sudo \-u nobody cat /proc/self/fd/0\fR cat: /proc/self/fd/0: Permission denied .fi .if n \{\ .RE .\} .sp File descriptor 0 refers to the pipe created by the shell and owned by that shell\*(Aqs user, which is not nobody, so \fBcat\fR does not have permission to create a new file descriptor to read from that inode, even though it can still read from its existing file descriptor 0\&. .RE .PP /proc/[pid]/gid .RS 4 This read\-only file contains the primary group id for the process\&. .RE .PP /proc/[pid]/maps .RS 4 A file containing the currently mapped memory regions and their access permissions\&. See \fBmmap\fR(2) for some further information about memory mappings\&. .sp The format of the file is: .sp .if n \{\ .RS 4 .\} .nf \fIaddress perms offset dev inode pathname\fR 00010000\-00020000 rw\-s 00000000 0000:0000 0 [win heap 1 default shared] \&.\&.\&. 00080000\-00082000 rw\-p 00000000 0000:0000 0 [win heap 0 default grow] 00082000\-0009A000 ===p 00002000 0000:0000 0 [win heap 0 default grow] 000A0000\-000A1000 rw\-p 00000000 0000:0000 0 [win heap 2 grow] 000A1000\-000BA000 ===p 00001000 0000:0000 0 [win heap 2 grow] 000C0000\-000D9000 rw\-p 00000000 0000:0000 0 [win heap 0 default grow] 000D9000\-001C0000 ===p 00019000 0000:0000 0 [win heap 0 default grow] 00200000\-00377000 ===p 00000000 0000:0000 0 00377000\-00378000 rw\-p 00177000 0000:0000 0 [peb] 00378000\-0037A000 rw\-p 00178000 0000:0000 0 [teb (tid 8844)] \&.\&.\&. 00400000\-005F9000 ===p 00000000 0000:0000 0 [stack (tid 8884)] 005F9000\-005FC000 rw\-g 001F9000 0000:0000 0 [stack (tid 8884)] 005FC000\-00600000 rw\-p 001FC000 0000:0000 0 [stack (tid 8884)] 00600000\-006C7000 r\-\-s 00000000 EE45:4341 281474976741117 /proc/cygdrive/c/Windows/System32/locale\&.nls \&.\&.\&. 100400000\-100401000 r\-\-p 00000000 EE45:4341 281474978095037 /usr/bin/sh\&.exe 100401000\-100413000 r\-xp 00001000 EE45:4341 281474978095037 /usr/bin/sh\&.exe 100413000\-100414000 rw\-p 00013000 EE45:4341 281474978095037 /usr/bin/sh\&.exe \&.\&.\&. 180010000\-180020000 rw\-s 00000000 0000:0000 0 [procinfo] 180020000\-180029000 rw\-s 00000000 0000:0000 0 [cygwin\-user\-shared] 180030000\-18003C000 rw\-s 00000000 0000:0000 0 [cygwin\-shared] 180040000\-180041000 r\-\-p 00000000 EE45:4341 2251799814294868 /usr/bin/cygwin1\&.dll 180041000\-18022D000 r\-xp 00001000 EE45:4341 2251799814294868 /usr/bin/cygwin1\&.dll 18022D000\-180231000 rwxp 001ED000 EE45:4341 2251799814294868 /usr/bin/cygwin1\&.dll 180231000\-18026A000 rw\-p 001F1000 EE45:4341 2251799814294868 /usr/bin/cygwin1\&.dll \&.\&.\&. 800000000\-800090000 rw\-p 00000000 0000:0000 0 [heap] 800090000\-820000000 ===p 00090000 0000:0000 0 [heap] 7FF4FDEB0000\-7FF4FDEB5000 r\-\-s 00000000 0000:0000 0 7FF4FDEB5000\-7FF4FDFB0000 ===s 00005000 0000:0000 0 7FF4FDFB0000\-7FF5FDFD0000 ===p 00000000 0000:0000 0 \&.\&.\&. 7FFBEEAC0000\-7FFBEEAC1000 r\-\-p 00000000 EE45:4341 844424934724994 /proc/cygdrive/c/Windows/System32/kernel32\&.dll 7FFBEEAC1000\-7FFBEEB36000 r\-xp 00001000 EE45:4341 844424934724994 /proc/cygdrive/c/Windows/System32/kernel32\&.dll 7FFBEEB36000\-7FFBEEB68000 r\-\-p 00076000 EE45:4341 844424934724994 /proc/cygdrive/c/Windows/System32/kernel32\&.dll 7FFBEEB68000\-7FFBEEB6A000 rw\-p 000A8000 EE45:4341 844424934724994 /proc/cygdrive/c/Windows/System32/kernel32\&.dll 7FFBEEB6A000\-7FFBEEB72000 r\-\-p 000AA000 EE45:4341 844424934724994 /proc/cygdrive/c/Windows/System32/kernel32\&.dll \&.\&.\&. .fi .if n \{\ .RE .\} .sp The address field is the address space in the process that the mapping occupies\&. The perms field is a set of permissions: .PP r .RS 4 read .RE .PP w .RS 4 write .RE .PP x .RS 4 execute .RE .PP === .RS 4 reserved .RE .PP s .RS 4 shared .RE .PP g .RS 4 guard .RE .PP p .RS 4 private .RE .sp The offset field is the offset into the file/whatever; dev is the device (major:minor); inode is the inode on that device\&. 0 indicates that no inode is associated with the memory region, as would be the case with BSS (uninitialized data)\&. .sp The pathname field will usually be the file that is backing the mapping\&. .sp There are additional helpful pseudo\-paths: .PP [cygwin\-shared] .RS 4 Global shared Cygwin process information\&. .RE .PP [cygwin\-user\-shared] .RS 4 Global shared Cygwin user information\&. .RE .PP [peb] .RS 4 Windows Process Environment Block\&. .RE .PP [procinfo] .RS 4 Cygwin process information\&. .RE .PP [shared\-user\-data] .RS 4 Shared user information\&. .RE .PP [heap] .RS 4 The process\*(Aqs heap\&. .RE .PP [stack] .RS 4 The initial process\*(Aqs (also known as the main thread\*(Aqs) stack\&. .RE .PP [stack (tid <tid>)] .RS 4 A thread\*(Aqs stack (where the <tid> is a thread id)\&. .RE .PP [teb (tid <tid>)] .RS 4 Windows Thread Environment Block (where <tid> is a thread id)\&. .RE .PP [win heap <n> default shared exec grow noserial debug] .RS 4 Windows extended heap (where <n> is a heap id) and the rest of the words are heap flags: .PP default .RS 4 default heap flags .RE .PP shared .RS 4 shareable and mapped heap flags .RE .PP exec .RS 4 executable heap flag .RE .PP grow .RS 4 growable heap flag .RE .PP noserial .RS 4 do not serialize heap flag .RE .PP debug .RS 4 debugged heap flag .RE .sp .RE .sp If the pathname field is blank, this is an anonymous mapping as obtained via \fBmmap\fR(2)\&. There is no easy way to coordinate this back to a process\*(Aqs source, short of running it through \fBgdb\fR(1), \fBstrace\fR(1), or similar\&. .sp pathname is shown unescaped except for newline characters, which are replaced with an octal escape sequence\&. As a result, it is not possible to determine whether the original pathname contained a newline character or the literal \ee012 character sequence\&. .sp If the mapping is file\-backed and the file has been deleted, the string "(deleted)" is appended to the pathname\&. Note that this is ambiguous too\&. .RE .PP /proc/[pid]/mountinfo .RS 4 This file contains information about mount points in the process\*(Aqs mount namespace (see \fBmount_namespaces\fR)\&. .sp The file contains lines of the form: .sp .if n \{\ .RS 4 .\} .nf 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 \- ext3 /dev/root rw,errors=continue (1)(2)(3) (4) (5) (6) (?) (7) (8) (9) (10) .fi .if n \{\ .RE .\} .sp The numbers in parentheses are labels for the descriptions below: .PP (1) .RS 4 mount id: a unique id for the mount (may be reused after \fBumount\fR(2))\&. .RE .PP (2) .RS 4 parent id: the id of the parent mount (or of self for the root of this mount namespace\*(Aqs mount tree)\&. .RE .PP (3) .RS 4 \fBmajor\fR:\fBminor\fR: the value of st_dev for files on this filesystem (see \fBstat\fR(2))\&. .RE .PP (4) .RS 4 root: the pathname of the directory in the filesystem which forms the root of this mount\&. .RE .PP (5) .RS 4 mount point: the pathname of the mount point relative to the process\*(Aqs root directory\&. .RE .PP (6) .RS 4 mount options: per\-mount options (see \fBmount\fR(2))\&. .RE .PP (?) .RS 4 optional fields: zero or more fields of the form "\fItag\fR[:\fIvalue\fR]"; see below\&. .RE .PP (7) .RS 4 separator: the end of the optional fields is marked by a single hyphen\&. .RE .PP (8) .RS 4 filesystem type: the filesystem type in the form "\fItype\fR[\&.\fIsubtype\fR]"\&. .RE .PP (9) .RS 4 mount source: filesystem\-specific information or "none"\&. .RE .PP (10) .RS 4 super options: per\-superblock options (see \fBmount\fR(2))\&. .RE .sp .RE .PP /proc/[pid]/mounts .RS 4 This file lists all the filesystems currently mounted in the process\*(Aqs mount namespace (see \fBmount_namespaces\fR(7))\&. The format of this file is documented in \fBfstab\fR(5)\&. .RE .PP /proc/[pid]/pgid .RS 4 This read\-only file contains the process group id for the process\&. .RE .PP /proc/[pid]/ppid .RS 4 This read\-only file contains the parent process id for the process\&. .RE .PP /proc/[pid]/root .RS 4 UNIX and Linux support the idea of a per\-process root of the filesystem, set by the \fBchroot\fR(2) system call\&. This file is a symbolic link that points to the process\*(Aqs root directory, and behaves in the same way as exe, and fd/*\&. .RE .PP /proc/[pid]/sid .RS 4 This read\-only file contains the session id for the process\&. .RE .PP /proc/[pid]/stat .RS 4 Status information about the process\&. This is used by some implementations of \fBps\fR(1)\&. .sp The fields, in order, with their proper \fBscanf\fR(3) format specifiers, are listed below\&. .PP (1) \fIpid\fR %d .RS 4 The process id\&. .RE .PP (2) \fIcomm\fR %s .RS 4 The filename of the executable, in parentheses\&. This is visible whether or not the executable is swapped out\&. .RE .PP (3) \fIstate\fR %c .RS 4 One of the following characters, indicating process state: .PP R .RS 4 Runnable .RE .PP O .RS 4 Running .RE .PP S .RS 4 Sleeping in an interruptible wait .RE .PP D .RS 4 Waiting in uninterruptible disk sleep .RE .PP Z .RS 4 Zombie .RE .PP T .RS 4 Stopped (on a signal) or trace stopped .RE .RE .PP (4) \fIppid\fR %d .RS 4 The PID of the parent of this process\&. .RE .PP (5) \fIpgrp\fR %d .RS 4 The process group id of the process\&. .RE .PP (6) \fIsession\fR %d .RS 4 The session id of the process\&. .RE .PP (7) \fItty_nr\fR %d .RS 4 The controlling terminal of the process\&. (The minor device number is contained in the combination of bits 31 to 20 and 7 to 0; the major device number is in bits 15 to 8\&.) .RE .PP (8) \fItpgid\fR %d .RS 4 The id of the foreground process group of the controlling terminal of the process\&. .RE .PP (9) \fIflags\fR %u .RS 4 The kernel flags word of the process\&. .RE .PP (10) \fIminflt\fR %lu .RS 4 The number of minor faults the process has made which have not required loading a memory page from disk\&. .RE .PP (11) \fIcminflt\fR %lu .RS 4 The number of minor faults that the process\*(Aqs waited\-for children have made\&. .RE .PP (12) \fImajflt\fR %lu .RS 4 The number of major faults the process has made which have required loading a memory page from disk\&. .RE .PP (13) \fIcmajflt\fR %lu .RS 4 The number of major faults that the process\*(Aqs waited\-for children have made\&. .RE .PP (14) \fIutime\fR %lu .RS 4 Amount of time that this process has been scheduled in user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK))\&. .RE .PP (15) \fIstime\fR %lu .RS 4 Amount of time that this process has been scheduled in kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK))\&. .RE .PP (16) \fIcutime\fR %ld .RS 4 Amount of time that this process\*(Aqs waited\-for children have been scheduled in user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK))\&. (See also \fBtimes\fR(2))\&. .RE .PP (17) \fIcstime\fR %ld .RS 4 Amount of time that this process\*(Aqs waited\-for children have been scheduled in kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK))\&. .RE .PP (18) \fIpriority\fR %ld .RS 4 For processes running a real\-time scheduling policy (\fIpolicy\fR below; see \fBsched_setscheduler\fR(2)), this is the negated scheduling priority, minus one; that is, a number in the range \-2 to \-100, corresponding to real\-time priorities 1 to 99\&. For processes running under a non\-real\-time scheduling policy, this is the raw nice value (\fBsetpriority\fR(2)) as represented in the kernel\&. The kernel stores nice values as numbers in the range 0 (high) to 39 (low), corresponding to the user\-visible nice range of \-20 to 19\&. .RE .PP (19) \fInice\fR %ld .RS 4 The nice value (see \fBsetpriority\fR(2)), a value in the range 19 (low priority) to \-20 (high priority)\&. .RE .PP (20) \fInum_threads\fR %ld .RS 4 Number of threads in this process\&. Currently shown as 0\&. .RE .PP (21) \fIitrealvalue\fR %ld .RS 4 The time in jiffies before the next SIGALRM is sent to the process due to an interval timer\&. This field is no longer maintained, and is hard coded as 0\&. .RE .PP (22) \fIstarttime\fR %llu .RS 4 The time the process started after system boot\&. The value is expressed in clock ticks (divide by sysconf(_SC_CLK_TCK))\&. .RE .PP (23) \fIvsize\fR %lu .RS 4 Virtual memory size in bytes\&. .RE .PP (24) \fIrss\fR %ld .RS 4 Resident Set Size: number of pages the process has in real memory\&. This is just the pages which count toward text, data, or stack space\&. This does not include pages which have not been demand\-loaded in, or which are swapped out\&. .RE .PP (25) \fIrsslim\fR %lu .RS 4 Current soft limit in bytes on the rss of the process; see the description of RLIMIT_RSS in \fBgetrlimit\fR(2)\&. .RE .RE .PP /proc/[pid]/statm .RS 4 Provides information about memory usage, measured in pages\&. The columns are: .PP (1) size .RS 4 total program size (same as VmSize in /proc/[pid]/status) .RE .PP (2) resident .RS 4 resident set size (same as VmRSS in /proc/[pid]/status) .RE .PP (3) shared .RS 4 number of resident shared pages (i\&.e\&., backed by a file) (same as RssFile+RssShmem in /proc/[pid]/status) .RE .PP (4) text .RS 4 text (code) .RE .PP (5) lib .RS 4 library .RE .PP (6) data .RS 4 data + stack .RE .PP (7) dt .RS 4 dirty pages (always 0) .RE .sp .RE .PP /proc/[pid]/status .RS 4 Provides much of the information in /proc/[pid]/stat and /proc/[pid]/statm in a format that\*(Aqs easier for humans to parse\&. Here\*(Aqs an example: .sp .if n \{\ .RS 4 .\} .nf $ \fBcat /proc/$$/status\fR Name: bash Umask: 0022 State: S (sleeping) Tgid: 17248 Pid: 17248 PPid: 17200 Uid: 1000 1000 1000 1000 Gid: 100 100 100 100 VmSize: 131168 kB VmLck: 0 kB VmRSS: 13484 kB VmData: 10332 kB VmStk: 136 kB VmExe: 992 kB VmLib: 2104 kB SigPnd: 0000000000000000 SigBlk: 0000000000010000 SigIgn: 0000000000384004 .fi .if n \{\ .RE .\} .sp The fields are as follows: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIName\fR: Command run by this process\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIUmask\fR: Process umask, expressed in octal with a leading zero; see \fBumask\fR(2)\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIState\fR: Current state of the process\&. One of: .PP R .RS 4 runnable .RE .PP O .RS 4 running .RE .PP S .RS 4 sleeping .RE .PP D .RS 4 disk sleep .RE .PP T .RS 4 stopped or tracing stop .RE .PP Z .RS 4 zombie .RE .sp .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fITgid\fR: Thread group id (i\&.e\&., Process id)\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIPid\fR: Thread id (see \fBgettid\fR(2))\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIPPid\fR: PID of parent process\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIUid\fR, \fIGid\fR: Real, effective, saved set, and filesystem UIDs (GIDs)\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIVmSize\fR: Virtual memory size\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIVmLck\fR: Locked memory size (see \fBmlock\fR(2))\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIVmRSS\fR: Resident set size\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIVmData\fR, \fIVmStk\fR, \fIVmExe\fR: Size of data, stack, and text segments\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fIVmLib\fR: Shared library code size\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fISigPnd\fR: Number of signals pending for process as a whole (see \fBpthreads\fR(7) and \fBsignal\fR(7))\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fISigBlk\fR, \fISigIgn\fR: Masks indicating signals being blocked and ignored (see \fBsignal\fR(7))\&. .RE .sp .RE .PP /proc/[pid]/uid .RS 4 This read\-only file contains the user id for the process\&. .RE .PP /proc/[pid]/winexename .RS 4 This read\-only file contains the Windows pathname of the executed command\&. .RE .PP /proc/[pid]/winpid .RS 4 This read\-only file contains the Windows process id for the process\&. .RE .PP /proc/cpuinfo .RS 4 This is a collection of CPU and system architecture dependent items, for each supported architecture a different list\&. Two common entries are \fIprocessor\fR which gives CPU number and \fIbogomips\fR, a system constant that is calculated during kernel initialization\&. SMP machines have information for each CPU\&. The \fBlscpu\fR(1) command gathers its information from this file\&. .RE .PP /proc/cygdrive .RS 4 This file is a symbolic link that points to the user\*(Aqs Windows mapped drive mount point, similar to \fIroot\fR\&. .RE .PP /proc/devices .RS 4 Text listing of major numbers and device groups\&. This can be used by \fBmakedev\fR scripts for consistency with the system\&. .RE .PP /proc/filesystems .RS 4 A text listing of the filesystems which are supported by Cygwin\&. (See also \fBfilesystems\fR(5)\&.) If a filesystem is marked with "nodev", this means that it does not require a block device to be mounted (e\&.g\&., virtual filesystem, network filesystem)\&. .RE .PP /proc/loadavg .RS 4 The first three fields in this file are load average figures giving the number of jobs in the run queue (state R) or waiting for disk I/O (state D) averaged over 1, 5, and 15 minutes\&. They are the same as the load average numbers given by \fBuptime\fR(1) and other programs\&. The fourth field consists of two numbers separated by a slash (/)\&. The first of these is the number of currently runnable scheduling entities (processes, threads)\&. The value after the slash is the number of scheduling entities that currently exist on the system\&. .RE .PP /proc/meminfo .RS 4 This file reports statistics about memory usage on the system\&. It is used by \fBfree\fR(1) to report the amount of free and used memory \&. Some fields are displayed only if the system was configured with various options; those dependencies are noted in the list\&. .PP \fIMemTotal\fR %lu .RS 4 Total usable RAM (i\&.e\&., physical RAM minus a few reserved bits and the kernel binary code)\&. .RE .PP \fIMemFree\fR %lu .RS 4 The sum of \fILowFree\fR + \fIHighFree\fR\&. .RE .PP \fIHighTotal\fR %lu .RS 4 Total amount of highmem\&. .RE .PP \fIHighFree\fR %lu .RS 4 Amount of free highmem\&. .RE .PP \fILowTotal\fR %lu .RS 4 Total amount of lowmem\&. Lowmem is memory which can be used for everything that highmem can be used for, but it is also available for the system\*(Aqs use for its own data structures\&. Bad things happen when you\*(Aqre out of lowmem\&. .RE .PP \fILowFree\fR %lu .RS 4 Amount of free lowmem\&. .RE .PP \fISwapTotal\fR %lu .RS 4 Total amount of swap space available\&. .RE .PP \fISwapFree\fR %lu .RS 4 Amount of swap space that is currently unused\&. .RE .RE .PP /proc/misc .RS 4 Text listing of minor device numbers and names of devices with major device number of the misc device group\&. This can be used by \fBmakedev\fR scripts for consistency with the system\&. .RE .PP /proc/mounts .RS 4 With the introduction of per\-process mount namespaces, this file became a link to /proc/self/mounts, which lists the mount points of the process\*(Aqs own mount namespace\&. The format of this file is documented in \fBfstab\fR(5)\&. .RE .PP /proc/net .RS 4 This directory contains various files and subdirectories containing information about the networking layer\&. The files contain ASCII structures and are, therefore, readable with \fBcat\fR(1)\&. However, the standard \fBnetstat\fR(8) suite provides much cleaner access to these files\&. .RE .PP /proc/net/if_inet6 .RS 4 This file contains information about IP V6 interface adapters, if used\&. Each line represents an IP V6 interface adapter\&. .sp .if n \{\ .RS 4 .\} .nf fe800000000000002c393d3da6108636 12 40 20 80 {C6B5FBE5\-A3AC\-4DB0\-A308\-8EE94E1406A4} fe8000000000000039da016f76bd92bc 13 40 20 20 {E06B8972\-0918\-41FC\-851B\-090C446C7D1C} fe8000000000000050ba9cedf1fe1628 0b 40 20 20 {680ED6FD\-DFAC\-4398\-AA85\-FB33E17E38EA} fe8000000000000030c5c6a0b30f109d 11 40 20 20 {B9E39F53\-1659\-4065\-BDA5\-F41162250E03} 20021840ac2c12343427e3b9ec6fa585 08 40 00 80 {4083A7F8\-99CF\-4220\-8715\-6FDF268B002F} 20021840ac2c12342403e3b2c7a5a32f 08 80 00 20 {4083A7F8\-99CF\-4220\-8715\-6FDF268B002F} 20021840ac2c1234284e8d0ecb4160cb 08 80 00 20 {4083A7F8\-99CF\-4220\-8715\-6FDF268B002F} 20021840ac2c123468cb06ea72f1d678 08 80 00 80 {4083A7F8\-99CF\-4220\-8715\-6FDF268B002F} 20021840ac2c12346cb59aca97c36e3b 08 80 00 20 {4083A7F8\-99CF\-4220\-8715\-6FDF268B002F} 20021840ac2c123498af9881de1fb828 08 80 00 20 {4083A7F8\-99CF\-4220\-8715\-6FDF268B002F} 20021840ac2c1234cd62a3d73a498611 08 80 00 20 {4083A7F8\-99CF\-4220\-8715\-6FDF268B002F} 20021840ac2c1234e410c873be09df93 08 80 00 20 {4083A7F8\-99CF\-4220\-8715\-6FDF268B002F} fe800000000000003427e3b9ec6fa585 08 40 20 80 {4083A7F8\-99CF\-4220\-8715\-6FDF268B002F} 00000000000000000000000000000001 01 80 10 80 {2B5345AC\-7502\-11EA\-AC73\-806E6F6E6963} (1) (2)(3)(4)(5) (6) .fi .if n \{\ .RE .\} .sp The fields in each line are: .PP (1) .RS 4 The IP V6 address of the interface adapter\&. .RE .PP (2) .RS 4 The IP V6 interface adapter index\&. .RE .PP (3) .RS 4 The prefix length of the IP V6 interface address\&. .RE .PP (4) .RS 4 The scope of the IP V6 interface address\&. .RE .PP (5) .RS 4 The state of the IP V6 interface address\&. .RE .PP (6) .RS 4 The DUID/GUID/UUID of the IP V6 interface adapter\&. .RE .sp The last number exists only for compatibility reasons and is always 1\&. .RE .PP /proc/partitions .RS 4 Contains the major and minor numbers of each partition as well as the number of 1024\-byte blocks and the partition name\&. .RE .PP /proc/registry .RS 4 Under Windows, this directory contains subdirectories for registry paths, keys, and subkeys, and files named for registry values which contain registry data, for the current process\&. .RE .PP /proc/registry32 .RS 4 Under 64 bit Windows, this directory contains subdirectories for registry paths, keys, and subkeys, and files named for registry values which contain registry data, for 32 bit processes\&. .RE .PP /proc/registry64 .RS 4 Under 64 bit Windows, this directory contains subdirectories for registry paths, keys, and subkeys, and files named for registry values which contain registry data, for 64 bit processes\&. .RE .PP /proc/self .RS 4 This directory refers to the process accessing the /proc filesystem, and is identical to the /proc directory named by the process id of the same process\&. .RE .PP /proc/stat .RS 4 kernel/system statistics\&. Varies with architecture\&. Common entries include: .PP \fIcpu 10132153 0 3084719 46828483\fR .RS 4 .RE .PP \fIcpu0 1393280 0 572056 13343292\fR .RS 4 The amount of time, measured in units of USER_HZ (1/100ths of a second on most architectures, use sysconf(_SC_CLK_TCK) to obtain the right value), that the system ("cpu" line) or the specific CPU ("cpu \fIN\fR" line) spent in various states: .PP (1) \fIuser\fR .RS 4 Time spent in user mode\&. .RE .PP (2) \fInice\fR .RS 4 Time spent in user mode with low priority (nice)\&. .RE .PP (3) \fIsystem\fR .RS 4 Time spent in system mode\&. .RE .PP (4) \fIidle\fR .RS 4 Time spent in the idle task\&. .RE .sp .RE .PP \fIpage 5741 1808\fR .RS 4 The number of pages the system paged in and the number that were paged out (from disk)\&. .RE .PP \fIswap 1 0\fR .RS 4 The number of swap pages that have been brought in and out\&. .RE .PP \fIintr 1462898\fR .RS 4 The number of interrupts serviced\&. .RE .PP \fIctxt 115315\fR .RS 4 The number of context switches that the system underwent\&. .RE .PP \fIbtime 769041601\fR .RS 4 boot time, in seconds since the Epoch, 1970\-01\-01 00:00:00 +0000 (UTC)\&. .RE .sp .RE .PP /proc/swaps .RS 4 Swap areas in use\&. See also \fBswapon\fR(8)\&. .RE .PP /proc/sys .RS 4 This directory contains a number of files and subdirectories linking to Windows objects, which can be read using these entries\&. .sp String values may be terminated by either \*(Aq\e0\*(Aq or \*(Aq\en\*(Aq\&. .sp Integer and long values may be either in decimal or in hexadecimal notation (e\&.g\&. 0x3FFF)\&. Multiple integer or long values may be separated by any of the following whitespace characters: \*(Aq\ \&\*(Aq, \*(Aq\et\*(Aq, or \*(Aq\en\*(Aq\&. .RE .PP /proc/sysvipc .RS 4 Subdirectory containing the pseudo\-files msg, semand shm\&. These files list the System V Interprocess Communication (IPC) objects (respectively: message queues, semaphores, and shared memory) that currently exist on the system, providing similar information to that available via \fBipcs\fR(1)\&. These files are only available if the cygserver Cygwin service is running\&. These files have headers and are formatted (one IPC object per line) for easy understanding\&. \fBsvipc\fR(7) provides further background on the information shown by these files\&. .RE .PP /proc/uptime .RS 4 This file contains two numbers (values in seconds): the uptime of the system (including time spent in suspend) and the amount of time spent in the idle process\&. .RE .PP /proc/version .RS 4 This string identifies the kernel version that is currently running\&. For example: .sp .if n \{\ .RS 4 .\} .nf CYGWIN_NT\-10\&.0\-18363 version 3\&.1\&.7\-340\&.x86_64 (corinna@calimero) (gcc version 9\&.3\&.0 20200312 (Fedora Cygwin 9\&.3\&.0\-1) (GCC) ) 2020\-08\-22 17:48 UTC .fi .if n \{\ .RE .\} .sp .RE .PP Many files contain strings (e\&.g\&., the environment and command line) that are in the internal format, with subfields terminated by null bytes (\*(Aq\e0\*(Aq)\&. When inspecting such files, you may find that the results are more readable if you use a command of the following form to display them: .sp .if n \{\ .RS 4 .\} .nf $ \fBcat \-A \fR\fB\fIfile\fR\fR .fi .if n \{\ .RE .\} .PP This manual page is incomplete, possibly inaccurate, and is the kind of thing that needs to be updated very often\&. .SH "SEE ALSO" .PP \fBcat\fR(1), \fBfind\fR(1), \fBfree\fR(1), \fBps\fR(1), \fBpstree\fR(1), \fBtr\fR(1), \fBuptime\fR(1), \fBchroot\fR(2), \fBmmap\fR(2), \fBreadlink\fR(2), \fBsyslog\fR(2), \fBhier\fR(7), \fBarp\fR(8), \fBmount\fR(8), \fBnetstat\fR(8), \fBroute\fR(8)\&. .SH "COLOPHON" .PP This page is part of the \fICygwin\fR project\&. A description of the project, information about reporting bugs, and the latest documentation, can be found on \m[blue]\fBthe Cygwin project web pages\fR\m[]\&\s-2\u[1]\d\s+2\&. .SH "COPYRIGHT" .br .SH "NOTES" .IP " 1." 4 the Cygwin project web pages .RS 4 \% .RE
https://cygwin.com/pipermail/cygwin-patches/2020q4/010809.html
CC-MAIN-2022-40
refinedweb
5,864
75.81
[RPG TEMPLATE] Texture Cache Just a small peice of the RPG template.. if the community would like i can post updates along the way. for thosenwho dont know what im talking about. RPG Templateis just a easy import providing the core mechanics andlogic for rpg development. currently provides character attribute system, experience and leveling system. texture handling is about 1/2 way there and im currently building the item and inventory system. doing this to try n help other that just want a fast poject to play with. if you have never constructed a rpg core structure before i can tell ou its no fast project.. lol if people would like regular updates just mention it in comments snd if there is any lol ill post. good day 🤓😉 Thought i would share this small class to cache game Textures. has came in handy for myself and my fellow developers. Hopfully it will help others in thiers. Its pretty simply.. just creat a file named assetsthen once an instance is created it will walk through all files and folders within nd get any files ending with .pngor .PNGit will then take the file name and split it at %. first section will be used as the name used to call on the cached texture. example: `iron-ore%mining-stone.png` ⇢ cached[file.split('%')[0]] = scene.Texture("iron-ore%mining-stone.png") then to use the cached texture `ASSETS('iron-ore')` gives cached `_scene2.Texture object` Hope this helps out anyone 🙃🤓😉 from os import (walk, getcwd, path) from scene import Texture class Assets: def __init__(self): self.cached = dict({}) self.CacheAssets() def __call__(self, name): return self.cached[name] def PrintCache(self): for k, v in self.cached.items(): print(f'{k}\n\t{v}\n{"*"*42}') def CacheAssets(self): id: int = 0 for r, d, f in walk(getcwd()+'/assets/'): for file in f: if file.endswith(".png") or file.endswith(".PNG"): id += 1 if '%' in file: name: str = file.split('%')[0] self.cached[name] = Texture(path.join(r, file)) else: self.cached[f'{id}'] = Texture(path.join(r, file)) ASSETS = Assets() ASSETS.PrintCache()
https://forum.omz-software.com/topic/6307/rpg-template-texture-cache
CC-MAIN-2021-31
refinedweb
352
68.26
The problem is that colon is not a valid character in the qname in an xml element. The SVN DAV exposes the custom property as having a namespace of "" and a qname of the property name. What if the namespace for a custom property was taken from the property instead? Why not use the namespace the property is suggesting. For example, "cvs2svn:cvs-rev" would be broken out as having a namespace of "cvs2svn" and a qname of "cvs-rev"? Colons are permissible values inside the namespace, so if the property were foo:bar:property it should be broken out as "foo:bar" and "property" for the namespace and qname respectively. /colin --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@subversion.tigris.org For additional commands, e-mail: dev-help@subversion.tigris.org Received on Tue Jan 18 20:54:24 2005 This is an archived mail posted to the Subversion Dev mailing list.
http://svn.haxx.se/dev/archive-2005-01/0772.shtml
CC-MAIN-2014-35
refinedweb
152
56.35
Developing user interfaces with React tends to require effort and often it's done at the level of code. What if we could create user interfaces in the browser itself? It's this question that we'll explore in this interview of Yang Zhang. I'm a software engineer currently working full-time on Plasmic, which is a dream job for me - getting to build novel visual tools for users like myself. It's funny that I'm now deep in the front-end space because I came from a very backend-focused past life. I used to study distributed database systems in my Ph.D. days, and I worked in applied machine learning at my last startup (Infer). I also used to work at big companies like Google and Microsoft, and now I'm all about tiny startups. In any case, I did a lot of product engineering over the years, and so building surfaces that directly touch and empower end-users became my drug! It's a tool for visually building components and full pages for any web app codebase! You can use it merely as a no-code full-page builder that plugs into your codebase or use it to design low-level, complex, stateful components like autocompletes and date/time pickers. One use case we're especially interested in is freeing up developers from requests from marketing, design, content teams, etc. These collaborators can instead directly create the things they want to see without being blocked by developers. Developers can, in turn, work on higher leverage things than pixel-pushing. Plasmic is starting as a pretty technical tool since we've been focused on letting developers build low-level components. Still, we're actively making the service accessible to anyone. That way, it's as approachable as a Squarespace or Wix (but for your codebase). We're focused on making it scale well up and down this spectrum. What you build in Plasmic can be consumed flexibly. You can generate actual React code into your codebase, or you can consume it like CMS content over an API - and more. The central point of Plasmic is about integrating into your arbitrary real-world codebase. It's a browser-based tool, so it's easy to jump in and start creating things on any platform. What you're manipulating is the "real thing," the existing web platform (DOM/CSS/etc.), and not (say) vectors in WebGL or another medium, so what you see is what you ship. You create your visual designs in Plasmic, and then: All the logic/behavior (state bindings, event handlers, etc.) are all done from your code, the usual way. So Plasmic isn't trying to reinvent programming, make your code via a GUI, impose any particular routing/state management, etc. In the case of codegen, what Plasmic spits out for you is a library of presentational components. They take care of rendering what you designed in the visual tool. If relevant, they provide a flexible interface that lets you wire up any props you want to any element within the component. For instance, if you're making a simple "new post" form in Plasmic with an input and a button, you'll be provided the PlasmicNewPost component that handles all the styling/layout/tags for you, and you can wire up your real state and event handlers like so: function NewPost({ onAdd, ...rest }: NewPostProps) { const [content, setContent] = useState(""); const history = useHistory(); return ( <PlasmicNewPost {...rest} postContent={{ autoFocus: true, value: content, onChange: (e) => { setContent(e.target.value); }, }} postButton={{ onClick: () => { onAdd( createPost({ content, createdAt: new Date() }) ); history.push("/"); }, }} /> ); } It's a simple example. As things go much deeper, with components supporting different variations across different states, the composition of components, responsive design, and more. There's also a new feature within Plasmic called Plume, which generates the behavior of components for certain well-known component types. So you can create an arbitrary design for (say) a Slider component and then have that fully working and accessible without writing any code – undifferentiated work that is time-consuming and tricky to do yourself. You can trivially create a bespoke design system this way. Everything is powered by the excellent react-aria and react-stately libraries from Adobe. They go very deep on accessibility and take it further than most libraries I've seen. I'll compare Plasmic with a few categories in terms of trade-offs. These are drawing programs, great for exploratory mockups. Plasmic is for building the real thing. The trade-off is that Plasmic is more complicated since it lets you express all of the nuance and complexity that comes with production - maintainable abstractions, element semantics and accessibility, combinations of states, more complex layouts, and so on. These are focused on static websites and are closed platforms. Plasmic focuses on flexible integration into arbitrary codebases and complex environments. The trade-off is that having full control of a closed platform is a faster way to build a simple end-to-end solution. Plasmic is a better fit for complex projects with development teams or (for instance) JAMstack projects that unbundle into best-of-breed CMS, framework, hosting, CI, etc. Plasmic certainly isn't getting into the CI business, for example. You can use Plasmic-as-a-CMS - invoke the client in your site's codebase, and from then on; your content teams can start using Plasmic immediately. We don't try to replace any existing CMSes, and we're looking to build integrations with CMSes and other data sources so that you can directly design with the real data in the tool. (And then you can still consume the output via an API, so it's a bit like layering CMSes.) These are one-shot code generators that let you copy/paste into your codebase - as soon as you add your logic, you diverge from the original generated code. Plasmic lets you iterate on the design and consume that continuously from your codebase. The trade-off is that one-shot generated code can look more familiar since you can generate what looks like clean, hand-written code. While Plasmic can also run in this mode and produce such code to generates, it's then consumed as a library of components. Two reasons: Plasmic is a very young project, so we have a ton of work to do. But we are already starting to see production usage and fascinating use cases that we never anticipated, which is super exciting. The usage is across small and large companies. Our immediate focus is on fully supporting our budding community of developers and also designers. I also mentioned above that we want to make the editor more streamlined and approachable to non-technical creators. Another big project is code components - the ability to bring in your own existing React components into the editor. But we want to cater our roadmap to the use cases that we see from our early adopters. So try out Plasmic and tell us what you would like to see! We would love to start a dialogue. For Plasmic itself, building interfaces like this is just the start. We want to take this further and empower folks to create things that are more dynamic and more end-to-end. Our north star is about dramatically simplifying and accelerating many more facets of building digital products. Focus on the users, experience, and product goals you are ultimately serving. It's is one of the extraordinary things about front-end development generally, and its proximity to the user. (This proximity is what drew me to focus on the front-end in my career!) I mentioned above that Plasmic's Plume component system leverages react-aria and react-stately. I would encourage you to chat with Devon Govett. He is the madman behind these projects and the Parcel bundler! We welcome you to check out Plasmic; we'd love to hear your thoughts! Thanks for the interview, Yang! I feel there's a lot of potential in tools that bridge design with development and it looks like you are headed to an amazing direction. To learn more about Plasmic, see the React Finland session below: You can also find Plasmic online and follow Plasmic on Twitter.
https://survivejs.com/blog/plasmic-interview/
CC-MAIN-2022-40
refinedweb
1,378
54.83
Publishing Schema as Web Service in BizTalk 2004 Introduction Buying and selling is the basic thing a company would do to run its business. A company buys raw material from its suppliers, refines it, and sells it to the customers. If a company buys some material from its supplier, it places a purchase order and the supplier supplies the material based on the requirement in the purchase order. Almost all the companies prefer to use anelectronic PO these days because it saves effort, tracking, and money. Scenario The scenario is as follows: - Supplier creates/gets a BizTalk schema for PO from buyer. - Supplier publishes the schema as a Web service because Web services are loosely coupled and available on the Internet. - Buyer consumes this Web service in his Application and creates a PO. - Web service sends the PO to supplier's BizTalk via SOAP. - BizTalk routes the PO to the appropriate application. We will implement this scenario in five steps. - Create and Deploy PO Schema - Publish Schema as a Web service - Create a subscriber for the PO in BizTalk - Create a buyer application - Test the scenario Create and Deploy a PO Schema Create a BizTalk project (WS_Schema in my solution) and add a new schema (PO.xsd) to it. I have promoted PONum node as a property to facilitate content-based routing. When we create a subscriber, we will use value of PONum to consume the PO. Figure 1 Build and deploy the schema. After successful deployment, you should be able to see WS_Schema.dll in the BizTalk Explorer -> Assemblies section. See Figure 2. Figure 2 Publish the Schema as a Web Service Go to tools-> BizTalk Web Services Publishing Wizard and click Next. See Figure 3. Figure 3 Select Publish schemas as Web services and click Next. See Figure 4. Figure 4 Rename the Web service name as WS_Schema. Create a one way Web method and name it SubmitPO. Rename the message to PO. The Web service description should look like Figure 5. Figure 5 Right click and select Select Schema Type. Select WS_Schema.dll from the bin directory of the WS_Schema project. Click Ok and Next. See Figure 6. Figure 6 Specify target namespace, SOAP header, and so forth if required. In our scenario, we won't select anything to keep it simple. Click Next. See Figure 7. Figure 7 Specify the project location as WS_Schema. Check anonymous access to allow IIS to execute this Eeb service without any authentication. Check create BizTalk receive location to create a BizTalk receive location when we publish this Web service. Otherwise, you can create receive locations manually. Click Next. See Figure 8. Figure 8 Click Create and finish to publish the Schema as a Web service. See Figure 9. Figure 9 Click on Biztalk explorer -> Receive Ports to check whether the receive location is created or not. A receive location named WebService_WS_Schema/WS_Schema should be created. See Figure 10. Figure 10 Edit this receive location. Change the receive pipeline to Microsoft.BizTalk.DefaultPipelines.XMLReceive. Select the Transport Type as SOAP and Address (URI) to /WS_Schema/WS_Schema.asmx (this is the schema we created as a Web service). See Figure 11. Figure 11 Create a Subscriber for the PO in BizTalk I will create a file send port as the subscriber of our PO. Create a new File Send Port and enter all the configurations. Because I am using content-based routing here, I will specify a filter, WS_Schema.PONum=PO101, to fetch our PO and send it to a file location. See Figure 12. Figure 12 Create a Buyer Application We will create a VB.NET client application in our scenario; it will consume this Web service and send the PO to the supplier's BizTalk. Create a Windows application. See Figure 13. Figure 13 For simplicity, I will create a form and a button. Once the button is clicked, it will send the PO to the supplier. Add a Web reference in the buyer project. Select the WS_Schema Web service and click add reference. See Figure 14. Figure 14 It will add a WS_Schema Web reference to the buyer application. Add the following code to the Button Click event. Private Sub txtSendPO_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles txtSendPO.Click Dim objPO As New localhost.PO Dim objPOBilling As New localhost.POBillingAddress Dim objPOShipping As New localhost.POShippingAddress Dim objPOItems As New localhost.POItems Dim objPOItem As New localhost.POItemsItem Dim objPOSubmit As New localhost.WS_Schema objPO.PONum = "PO101" objPO.Date = "15-Jul-2004 objPOBilling.Street = "Corwell Lane" objPOBilling.City = "Uxbridge" objPOBilling.ZipCode = "UB8 3DE" objPO.BillingAddress = objPOBilling objPOShipping.Street = "Corwell Lane" objPOShipping.City = "Uxbridge" objPOShipping.ZipCode = "UB8 3DE" objPO.ShippingAddress = objPOShipping objPOItem.Code = "I101" objPOItem.Description = "Sony DVD Writer" objPOItem.Quantity = "20" objPOItem.Rate = "150" objPOItems.Item = objPOItem objPO.Items = objPOItems objPO.Total = "3000" objPOSubmit.SubmitPO(objPO) MsgBox("PO Sent to the Supplier") End Sub Test the Scenario Run the buyer application and click the SubmitPO button. It will create a PO with the values defined in our function and send it to the Supplier's BizTalk receive location. The receive location will pass the message to MessageBox and our subscriber will fetch the PO from MessageBox and send the XML to a file location. Figure 15 shows the screen snapshot of Health and activity tracking before our subscriber consumed the PO. Figure 15 Open the PO, delivered to a file location, and it will look like the following. <?xml version="1.0" encoding="utf-8"?> <PO xmlns: <PONum xmlns="">PO101</PONum> <Date xmlns="">15-Jul-2004</Date> <ShippingAddress xmlns=""> <Street>Corwell Lane</Street> <City>Uxbridge</City> <ZipCode>UB8 3DE</ZipCode> </ShippingAddress> <BillingAddress xmlns=""> <Street>Corwell Lane</Street> <City>Uxbridge</City> <ZipCode>UB8 3DE</ZipCode> </BillingAddress> <Items xmlns=""> <Item> <Code>I101</Code> <Description>Sony DVD Writer</Description> <Rate>150</Rate> <Quantity>20</Quantity> </Item> </Items> <Total xmlns="">3000</Total> </PO> Summary We have seen a simple scenario to create and consume a Schema as a Web Service with minimum effort. It hardly takes a few minutes to create the entire scenario. Once I publish and consume the Web service in my buyer application, I need not use any XML DOM. All I need is to create an object of consumed Web Service and use it. The method automatically creates and submits the XML for you. programmerPosted by suresh on 08/19/2014 12:35am excellent article..ThanksReply
http://www.codeguru.com/cpp/i-n/internet/webservices/article.php/c7785/Publishing-Schema-as-Web-Service-in-BizTalk-2004.htm
CC-MAIN-2016-30
refinedweb
1,075
61.53
This tutorial is a sequel of our tutorial called “Capture image from the webcam”. Here we’ll add a new functionnality that let the user save the captured photo to his desktop. This example requires Flash Player 10. 1. Read and follow the steps of our previous tutorial “Capture image from the webcam” . We’ll begin this tutorial from the finished capatureWebcam.fla file of this previous tut. 2. Open the previous file. Create a new button on the stage, convert it to a movie clip and give it an instance name of save_mc. 3. In order to encode the captured image as a JPG, we’ll use the Adobe JPG Encoder that is available in the as3corelib. Visit to download the library. Unzip the file and inside the src folder grab the com folder. We’ll use what’s in the com/abode/images folder. In order to save the image, we’ll use the Flash Player 10 FileReference API. 4. With the ‘actions’ layer selected open the actions panel. Add the following import statements : import com.adobe.images.JPGEncoder; import flash.net.FileReference; 5. Next add a click event listener to the save button that will be handled by the saveImage function. save_mc.buttonMode = true; save_mc.addEventListener(MouseEvent.CLICK,saveImage); 6. Inside the saveImage function declare a JGPEncoder and create a ByteArray of the bitmapData encoded as JPG. Use the FileReference.save() method and pass in the ByteArray and the file name.++; } 7. Here’s the final code with the added code highlighted, test the movie to see it in action. import flash.display.Bitmap; import flash.display.BitmapData; import com.adobe.images.JPGEncoder; import flash.net.FileReference;); save_mc.buttonMode = true; save_mc.addEventListener(MouseEvent.CLICK,saveImage); function captureImage(e:MouseEvent):void { bitmapData.draw(video); }++; } Pingback: Coding the Capture | Final Project Diary Pingback: Codes used REFERENCED | Final Project Diary how do I save image from webcam without using save dialogue box. I want it like once i click save it should save image to specified location on disc shoild not pop up dialogue box for saving image. how can we do this? Hi can any one help me how to use the above sample to capture video instead of image….? how do I import the jpgencoder into this thing? Good.Thank you very much. How would I go about automating the capture and adding a delay? I would like a movie clip to play a 3…2…1 countdown animation then take the capture automatically can you help?! thanks Hi, I tried your code..its working good..still i need a help..I want store the captured image in mysql database using asp.net..can anyone tell me how to do this Hi, Here you are saving an image in desktop rite..Instead of that i need to store it in database Thank you very much. I struggled with the instructions in the Adobe site, and in other places, but your instructions are so clear, I’ve been able to use them to make a little web cam to run from inside our LMS so the students don’t have to access Web Toy etc.
http://www.riacodes.com/flash/captures-images-from-the-webcam-and-save-them-to-the-desktop/
CC-MAIN-2016-07
refinedweb
526
68.47
Ever been on the features page and wondered what the Id of a Feature is? The features page in the SharePoint UI is obviously a quick and easy way to activate and deactivate features. However, at first glance all you see is the title and description of the feature. You have no idea of knowing what the folder is let alone its Id. You’re out of luck on determining the feature folder name here, but you can get the Id pretty easily by viewing the source HTML of the page. I want to know the Id of the My Web Part feature, so I view the source and type in the name of the web part. Looking at the source, we can quickly find what we need. Take a look at the snippet of HTML above. This is where it displays the information for the title and description of my web part. Following that, you will see a non XHTML compliant div tag (really hope the HTML is better in the next version) with an id set to a GUID. As you might guess, that GUID is the Id of the Feature. It’s that simple. Just a quick tip today. Hope you find it useful. I’ve been chasing this particular error for a little while and thought I would take the time to share my experience and how to resolve it. The scenario I had is I have a custom content type with several custom site columns. I generated the CAML for my content type and site columns using SPSource. When I clicked on the Create a new custom template button, I received the following error (or one similar). propertySchema0.xsd#/schema/element[1][@name = 'properties']/complexType[1]/sequence[1]/element[1][@name = 'documentManagement']/complexType[1]/all[1]/element[1] Reference to undeclared namespace prefix: 'ns1'. As with all InfoPath errors, this is completely useless. After many attempts at trying to figure out this issue, I noticed that I could create a new Lookup Column and a new Content Type using the SharePoint UI and not receive this error. I then busted out the Imtech Fields Explorer and as far as I could tell all of the properties were just about the same. However, I noticed one difference in the SchemaXML property. My Field element did not have a SourceId but the column created through the UI did. It’s value was set to the Id of the web hosting the site column. I knew I couldn’t set it to that and so I remembered in the past I had always set the SourceId of the field element as seen below. SourceID=”” This got me closer, the content types and site columns deployed correctly and the SchemaXML had a SourceID in it. However, when I tried to create a Document Information Panel this time, I got this new lovely error. InfoPath has encountered an error. The operation failed. Catastrophic failure Once again, thanks InfoPath team for such useful error information. After further investigation, I discovered I needed to set the StaticName attribute as well. I simply set this to match the Name attribute I had and everything works now. It’s strange how the content type can work completely everywhere else, but in InfoPath it’s very picky. Here is what a complete working Field element might look like for you. <Field Type="Text" DisplayName="MyField" Required="FALSE" MaxLength="255" Group="My Field Group" ID="{2E6858a5-6ae2-409f-8492-fa15c39821c8}" Name="MyField" SourceID="" StaticName="MyField" /> I mentioned above the issue I had was with a Lookup column but I quickly discovered that this was happening with all of my columns and had nothing to do with the lookup. SPSource has saved me a ton of time, but this is just another minor thing to look out with the tool. I logged an issue on CodePlex to see if we can get these two attributes added to the Site Column export. If you aren’t customizing Document Information Panels, then there is nothing to worry about with the exported CAML, but if you are be sure and add these two attributes. According to Google Analytics, my introduction to SharePoint topics are by far the most popular topics on the site. I wanted to continue the trend on topics for new SharePoint developers, so I thought i would discuss debugging today. I’ve already discussed remote debugging in the past, but I thought it would be worth spending time on simple local debugging and provide some pictures. There may be several posts on this already, but I wanted something that I could refer to new developers I am working with. In the ASP.NET world, you are used to working with everything on your own machine, setting a breakpoint, hitting F5 and you start debugging. We can do it the same way with SharePoint development right? No, of course not. Before we start, lets assume you built a web part and want to debug it. If you aren’t familiar with how to build and deploy a web part, be sure and take a look at my post. In the scenario we are talking about, you are most likely developing inside a virtual machine and it is hosted on your other computer or somewhere else. This virtual machine has Visual Studio installed. The way you debug varies slightly by whether or not you are deploying your binary to the GAC or to the bin folder. If you are deploying to the GAC, you do not need to worry about the .PDB file as Visual Studio will magically find it on its own when you start debugging. However, if you are deploying to the bin folder, you must copy the .PDB file from your bin\debug folder and copy it to the bin folder in inetpub for you web application. At this point you are ready to start debugging. First, I’ll start by marking a breakpoint in my code. As I mentioned earlier though, you can’t just hit F5 and call it good. Instead, you have to attach to the process running the web application your web part is on. This is the same process used when remote debugging. The difference is you don’t have to run the remote debugger and tell Visual Studio to connect to a remote server. to do this, go to the Debug menu and choose Attach to Process. You will then get a screen that looks like the one below. The first thing you need to do is check the Show processes from all users and Show processes in all sessions checkbox. Don’t worry about the Transport, Qualifier, or Attach to options. The default options should work for you. If you happened to change them in the past, use the above screenshot, to get you back to where you need to be. What we want to do is attach to the w3wp process that is running our web application. We know this is a w3wp.exe process, but if you look at the screenshot, you can see that we have three w3wp.exe processes in the list. How do you know which one to use? Well you have a number of options. You can use brute force and try each one and hit your web page and see if the breakpoint hits. That’s not really an ideal solution. If you’re smart when you set up your environment, you might have created separate accounts for each application pool. Notice above, how we have accounts named MOSS_AP_SSP, MOSS_AP_Portal, and MOSS_AP_CentralAdmin. Obviously, I am not debugging the SSP or Central Admin, so the MOSS_AP_Portal is the account to use in my case. I get it though. That is an ideal situation and you may not be lucky enough to have everything running on separate accounts, so we need an alternative solution. Luckily, IIS has a script you can run which will tell you which worker process is running on which port. My web application is running on port 80, so if we identify a worker process for that port, we are in luck. In Windows Server 2003, you run cscript iisapp.vbs. In Windows Server 2008, you run appcmd list wps. Here is what it looks like in Windows Server 2008. Now, I can confirm the process I want to attach to is 5980. I’ll click on this process in the list and we can start the debugging process. If all goes well, your breakpoint should look good in Visual Studio and it won’t have an explanation point. If it still has an explanation point, you may just need to hit a page on the site first to get Visual Studio to load the assemblies for debugging. Try hitting the page that has your web part and if everything works correctly, your break point should be hit and look like this. As an ASP.NET developer, this may be different than what you are used to, but the steps involved really aren’t that bad. The code that I debugged in this example is the same code used in the How to Build and Deploy a Web Part post. If your breakpoint doesn’t get hit, I recommend recompiling and trying again. Verify that you have the right worker process and copy the .PDB file out if you are deploying to the bin folder. A few months ago, I discussed how to use LINQ to XML to parse your elements.xml file to delete any files that you may have deployed on feature activation. Today I have decided to reuse this concept to delete any lists that I have created when I deactivate a feature? Now you may ask, “why would I want to delete a list when a feature is deactivated? I’ll lose all of my data in that list!” My answer is: Yes, of course you will, but sometimes when building a feature to deploy a list(s), you want to delete the list each time before you deploy a new version of it. During development this is a huge time saver. Right now, I am working on a feature that deploys four document libraries. This means I have to manually delete each one. That is a huge waste of time, but what is nice is that we can reuse the concept above with LINQ to XML and delete lists instead. The code is quite similar. Have a look. We first, write some code to get the path to the elements.xml file. This code snippet assumes, it is always named Elements.xml. Maybe in the future, I will have it look in the feature.xml file, get all of the ElementManifest definitions and then delete whatever it finds in each file. For now though, we assume, you can change the path as needed. public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { using (SPWeb currentSite = (SPWeb)properties.Feature.Parent) { string elementsPath = string.Format(@"{0}\FEATURES\{1}\Elements.xml", SPUtility.GetGenericSetupPath("Template"), properties.Definition.DisplayName); DeleteLists(currentSite, elementsPath); } } From here, it passes a reference to the current SPWeb and the path to the XML document. The path to the elements.xml file is used to populate an XDocument which we can then query with LINQ to XML. private void DeleteLists(SPWeb currentSite, string elementsPath) try XDocument elementsXml = XDocument.Load(elementsPath); XNamespace sharePointNamespace = ""; // get each URL to each list var listInstances = from module in elementsXml.Root.Elements(sharePointNamespace + "ListInstance") select new { ListUrl = (module.Attributes("Url").Any()) ? module.Attribute("Url").Value : null, }; // iterate through each list and delete it foreach (var listInstance in listInstances) { try { SPList currentList = currentSite.GetList(string.Format("{0}/{1}", currentSite.Url, listInstance.ListUrl)); currentList.Delete(); } catch (System.IO.FileNotFoundException e) // this exception is thrown if the list does not exist } // update the site currentSite.Update(); catch This code is quite similar to that used in my other post, however instead of looking for Module elements we are looking for ListInstance elements. It creates a list of those Urls to each list and iterates through them. For each list it finds, it deletes the list. I’ve written code in the past to manually delete lists, I create by name. That works fine, but the name of each list has to be maintained. Now, I just attach this to any feature I am working on and it deletes any list (or lists) that I throw at it. More than likely this isn’t something you want once you go to production, but it will save you a ton of time during development.). It’s a known fact that MOSS 2007 Service Pack 2 hates me. Today, I was excited when I upgraded a server to SP2 and the configuration wizard didn’t fail. I was even more excited to see that my SSP and Central Administration still worked after the upgrade as well. Unfortunately, when I hit my main web application, I got a yellow screen with the following error. COMException (0x80004005): Cannot complete this action. Please try again.] Microsoft.SharePoint.Library.SPRequestInternalClass) +0 Microsoft.SharePoint.Library.SPRequest) +215 That’s just great I figured. I checked the logs folder in the 12 hive and all I could find was an entry with the same text “Cannot complete this action”. Quite useless. After doing some searching, I encountered the following KB article. This articles applies to WSS2, but I noticed a lot of things mentioning the word impersonation, so I decided to have a look in my web.config. Sure enough, this server had impersonation turned off for some reason (no telling why). I set it back to true and the error went away. I can’t continue to reiterate how much time SPSource can save you when it comes to exporting existing lists into usable features, but I found one minor thing to look out for when you are exporting lists. Usually, you can take just about whatever SPSource gives you and redeploy it without having to change a thing, however in the cases of lists you need to look out for the TemplateType attribute otherwise it can cause you problems. Take a look at the XML below from the elements file. <Elements xmlns=""> <ListTemplate AllowDeletion="True" AllowEveryoneViewItems="False" BaseType="1" DisplayName="Concepts" Description="" EnableModeration="False" Hidden="False" OnQuickLaunch="True" Name="List1" Type="100" SecurityBits="11" Sequence="110" DocumentTemplate="101" VersioningEnabled="True" /> <ListInstance FeatureId="cac9f905-9380-4252-8307-d2cffb6f0c1f" Id="c5dd284f-fb59-44b9-bcfd-b4f779d9fd8d" TemplateType="100" Title="List1" Url="Lists/Lists1" /> <ListTemplate AllowDeletion="True" AllowEveryoneViewItems="False" BaseType="1" DisplayName="Regionals" Description="" EnableModeration="False" Hidden="False" OnQuickLaunch="True" Name="Regionals" Type="101" SecurityBits="11" Sequence="110" DocumentTemplate="101" VersioningEnabled="True" /> <ListInstance FeatureId="cac9f905-9380-4252-8307-d2cffb6f0c1f" Id="631657f0-b687-4b61-ad28-13ea1140cd21" TemplateType="101" Title="List2" Url="Lists/List2" /> As you can see I have a ListTemplate and ListElement element for two different lists (list1 and list2). If you look further you notice that the Type attribute on the ListTemplate elements is 100 and 101 respectively. The issue is that 100 is already reserved for a generic list and 101 is a document library so deploying this file can cause general weirdness in SharePoint. Here is the list of stock list template IDs in case you were curious. As you may guess this is pretty easy to resolve. Just pick a new number that is not reserved for your Type. I believe the best practice recommends starting at 10000. After you change the Type attribute, be sure and change the TemplateType attribute of the ListInstance element to match it. That is all there is to it. If you haven’t checked out SPSource yet be sure to, the next time you need to export sites, lists, content types or site columns. It can save you a ton of time. This week, I needed to deploy lookup columns to some of my lists and as usual I wanted to avoid writing code at all costs. As some of you may know, Kyle Kelin and I debate this topic often as he prefers a code approach. I figured it had to be possible with CAML, but many claimed it was not even possible. A few approaches showed up out there involving using code to modify the elements.xml file with your GUID, but that just wasn’t going to cut it for me. One popular post on the topic by Josh Gaffey, started me in the right direction, but there were a few hurdles I ran into as I was trying to implement it. It would create the list, show the content type, and site columns, but when I tried to create a new item, the lookup column was not there. The basic technique is that you specify the path to the list in the form of (Lists/MyListName) in the List attribute of the Field element in both your schema.xml file of your document library template as well as the definition of the site column. The first thing I learned here is that you cannot simply omit declaring site columns and a content type out and go with list level columns. It simply will not work (no idea why). <Elements xmlns=""> <ContentType Name="Test" /> </Elements> In my example, my content type was called Test. Create a separate feature folder for your list template and instance. Create another feature.xml and an .spsource file for the list which looks something like this. My list is also named Test in this case. <ListTemplate Name="Test" /> SPSource does a good job when it exports my list definition and properly specifies the list using a path instead of a guid in my lookup column as shown below (from schema.xml). <Field Type="Lookup" DisplayName="DocumentCategory" Required="FALSE" List="Lists/Categories" ShowField="Title" UnlimitedLengthInDocumentLibrary="FALSE" Group="My Group" ID="{9266e0fa-ae49-438c-acdc-73063684ac8f}" SourceID="{50b253e5-e90e-4781-8fce-cece417b185e}" StaticName="DocumentCategory" Name="DocumentCategory" Customization="" ColName="int1" RowOrdinal="0" /> We don’t actually have to change a thing in this file. What I did have to change is the List attribute of the file it generated for my site columns. As Josh’s post above stated, we have to change the List attribute from a GUID to the path of the list. His post also mentioned you might want to set the PrependId attribute but I have since learned that this is only used when you are using the LookupMulti type (although I can’t remember the source I got this from). <Field Type="Lookup" DisplayName="DocumentCategory" Required="TRUE" List="Lists/Categories" ShowField="Title" UnlimitedLengthInDocumentLibrary="FALSE" Group="My Group" ID="{9266e0fa-ae49-438c-acdc-73063684ac8f}" Name="DocumentCategory" /> At this point you can deploy your site columns, content type, and then custom list (in that order) and if all goes well you will be able to create a new item of that content type with the lookup column functioning. One thing to note, if you get this wrong, your list will behave oddly. One thing I noticed is that it won’t turn on content types for the list when that happens. If this is happening go back and check your work. Another thing people mentioned is that the source list for the lookup column has to exist before you create the lookup column. This in fact is not true. It will work and it will display a drop down list for the lookup column, but it will be empty of course since the list does not exist. Along the way I figured out a few other things. When I was trying to figure this out, I was trying to just create the content type and then manually add it to the list via the UI. Doesn’t work. If you try to add a content type with a lookup column defined in this way to an existing list, you will get the following error.) The only way to get the content type associated with the list is via CAML when it is created. Another odd thing is that the lookup column never shows it is bound to the other list correctly. Here is what the source lookup column looked like. Notice where it says Get information from, the name of the list is present. Here is what my copy of the list looks like. Notice that the list name is not present. Strangely enough though, everything works fine in the copy. This one through me for a loop for a while because it didn’t seem like things weren’t working and as I mentioned above I couldn’t add the content type to a list (nor could I add the column to a content type). As you can see there are few oddities about deploying lookup columns in this manner, but it does work. @SPKyle informed me he could have written code to do this hours ago, but I am quite happy that I can deploy things in this manner now. Twitter: @coreyroth
http://dotnetmafia.com/blogs/dotnettipoftheday/archive/2009/09.aspx
CC-MAIN-2018-13
refinedweb
3,503
71.85
Beginning C#: Basic I/O and Variables WEBINAR: On-demand webcast How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER > Last month, we saw that you already had everything you needed on your computer that you needed to start writing C# programs. In this post, we're going to take a look at getting input from the user, and doing something with that input. If you already have Visual Studio of some kind installed, feel free to use that. All of the programs you write will be "Console Mode" programs with nothing special. I'll go over installing Visual Studio in a couple of posts' time; for now, however, I will assume the use of the command line tools introduced last month, and a simple text editor such as Notepad or Notepad++ being used. Outputting Text When we left the last post, you'd created a simple program that used Console.WriteLine("Hello World"); to write some text to the console. C#, unlike many C-like programming languages, does not have a simple function or keyword for outputting text. Instead, we need to use a .NET library to output our text. It comes as no surprise that this library is called the 'Console' library, and, as can be seen above, it contains a method called 'WriteLine' that is used to output text. The console library has a number of methods for dealing with simple console operations, 'WriteLine' outputs the text supplied, followed by a newline. Its counterpart 'Write' also outputs the supplied text, but unlike its predecessor, does not output a newline afterwards. 'Write' is used when you want to output multiple items of text on the same line. As you did last post, create a simple text file called 'Hello2.cs' and make sure it contains the following code: using System; namespace BlogConsole { class Program { static void Main(string[] args) { Console.Write("Hello "); Console.WriteLine("World"); } } } When you compile and run this using CSC you should see the exact same output as in the previous version. Figure 1: The same output is produced by using write and writeline If you want to receive input, the console class also includes 'Read' and 'ReadLine' methods. Read reads the next available character from the console input stream whereas readline reads an entire line followed by a carriage return. You'll also find that the console class has a method called 'ReadKey'. Readkey differs from read in that it captures a specific keypress. Readkey is used if you're looking for a single specific key, something like a function key, and it returns its data in a special type of data object called a 'KeyInfo' object. Read, like readline, waits for you to press Return to let it know you've entered the key you want to enter; but, unlike readline, it returns the pressed key by using its special numeric code. Performing a Google search online for "ASCII code chart" will give you a full list of these codes. To get you started, capital A has a code of 65, B has 66, and so on. I'll describe the difference in more detail in a future post. For now, however, know that there is a difference. If you were producing an onscreen menu, for example, ReadKey would be the appropriate method to use. If, however, you were trying to read a person's initial as part of an input form, read would be your weapon of choice. Let's try another example. Create a new file called 'input1.cs' and, using your text editor, make sure it has the following code in it: using System; namespace BlogConsole { class Program { static void Main(string[] args) { Console.WriteLine("Hello please enter your name"); string name = Console.ReadLine(); Console.WriteLine("pleased to meet you {0}", name); } } } Compile it using 'csc input1.cs' and then run it. You should see the following: Figure 2: Our program can now ask for our name You'll notice that there's one new thing in the previous code: string name = Console.ReadLine(); Data and Variables Any program, large or small, needs to store data. Data is stored in something called a variable. You'll also find variables described as 'fields', 'properties', and 'objects' too, which is used depending on how you design your app. We'll get into this more in later posts once we start to cover object-orientated programming. For now, however, we'll use 'variables' to describe our data holders. So what's in a variable? Well, in the line above we're telling the C# compiler that we're expecting a string and we want to refer to that variable as 'name'. A string is a sequence of characters that usually spells out a word or a sentence of text. Strings of text that you add manually are surrounded by quote marks so that the compiler knows where the start and end are, something like the following: string myText = "This is a string variable"; Variables can also hold numbers. If you wanted to store whole numbers only, you would use an 'int' variable type: int myNumber = 10; There are different types of number variables; if you wanted a standard decimal, you'd use the 'decimal' type; if you wanted floating point. you'd use 'float'. We'll cover the differences in number types in more detail later on; for now, we'll use 'int'. The last simple variable type that I'll introduce you to is the 'boolean'. Booleans (or 'bools') are a very simple variable type that represents only true or false. Booleans are typically used as flags to indicate a yes or a no for something, and are declared as follows: bool myChoice = false; Variables are used to store the data you want to work with in your application. Let's now put this into practice. Create a new file. Let's call this input2.cs, and make sure it has the following code in it. using System; namespace BlogConsole { class Program { static void Main(string[] args) { Console.WriteLine("Hello please enter your name <Remember to press return afterwards>"); string name = Console.ReadLine(); Console.WriteLine("Hello please enter your age {0} <Remember to press return afterwards>", name); int age = int.Parse(Console.ReadLine()); Console.WriteLine("It must be nice to be {0} years old {1}", age, name); Console.WriteLine("Here's a menu for you, please choose wisely then press return."); Console.Write("a) "); // Code for lowercase a is 97 Console.WriteLine(" Choice A"); Console.Write("b) "); // Code for lowercase b is 98 Console.WriteLine(" Choice B"); Console.Write("c) "); // Code for lowercase c is 99 Console.WriteLine(" Choice C"); Console.Write("d) "); // Code for lowercase d is 100 Console.WriteLine(" Choice D"); int menuChoice = Console.Read(); if(menuChoice == 97) { Console.WriteLine("a is a mighty fine choice"); } if (menuChoice == 98) { Console.WriteLine("b is a superb choice"); } if (menuChoice == 99) { Console.WriteLine("c is the best choice"); } if (menuChoice == 100) { Console.WriteLine("d is the last choice"); } } } } There are a couple of things in there that may be new to you, but don't worry about them at the moment. We'll get to them in future posts once we start to build up our knowledge of C#. For now, however, if everything compiles okay using CSC, you should see something like the following: Figure 3: The output is more robust now Before I leave you alone to play with the code, I'll show you one more trick that the console class has. You can make your programs look a little bit nicer by using a variable, called 'ForegroundColor', inside the console library. By setting this to one of the variables available inside 'ConsoleColor', you can use different colors for different parts of your text. Create a new file called coloredtext.cs and add the following code. using System; namespace BlogConsole { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("This is green text"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("This is red text"); Console.ForegroundColor = ConsoleColor.White; } } } Compile it using CSC and then run it. You should see something similar to the content of Figure 4. Figure 4: The output text is coloured according to the code's specifications By using colour statements in appropriate places, you can even have different parts of the same line appear in different colours. Next month, we'll take a closer look at using variables, and I'll explain how and why you should convert them using methods such as parse to ensure that you get good data. Until then, happy experimenting. There are no comments yet. Be the first to comment!
https://www.codeguru.com/columns/dotnet/beginning-c-basic-io-and-variables.html
CC-MAIN-2017-47
refinedweb
1,451
64.51
On Wed, 11 Mar 1998, Garst R. Reese wrote:> What do I do with /sbin/kerneld.> At present, my rc.S script tests for its presence, and does things if it> is present.My solution wasif test `uname -r` == "2.0.33"; then /sbin/kerneldfiThis assumes, of course, that you'll never boot into a pre-2.1.90 kernelother than 2.0.33.> Also, where in the start up scripts should the echos in kmod.txt go?You usually won't need them, kmod defaults to reasonable values.If you do need to change something, I'd recommendif test `uname -r` == "2.0.33"; then /sbin/kerneldelse put.the.echos.herefiLLaPbero-- bero@bero-online.ml.org - ICQ/UIN 6545964 - --
https://lkml.org/lkml/1998/3/11/140
CC-MAIN-2017-51
refinedweb
120
80.58
I'm making a specific number guessing game called "Bagels". I have most of the work done. But once I get to the actual game, I can only input one number for it to say if it is right or not. I need the program to keep allowing numbers to be inputted until it satisfies the do/while statement. The input statements for the guessing are in the second do/while statement towards the bottom. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; public class Bagels { public static void main(String[] args) { BufferedReader input = new BufferedReader (new InputStreamReader (System.in)); System.out.println("Welcome to Bagels the Guessing Game!"); System.out.println("Press [Enter] to continue"); String start = new String (); try {start = input.readLine();} catch (IOException e) {}; String user1 = new String (); String rulesornot = new String (); System.out.println("To learn the rules, enter(1)"); System.out.println(" "); System.out.println("To skip to the game, enter(2)"); try {rulesornot = input.readLine();} catch (IOException e) {} int rules; rules = Integer.parseInt(rulesornot); int userin1; int userin2; int userin3; if (rules == 1) { System.out.println("Rules: You are to guess a 3-digit number and you may not repeat a digit within an answer."); System.out.println("If you guess correct on one number and it is in the correct spot that is \"Fermi\"."); System.out.println("If you guess correct on one number but it is not in the correct spot that is \"Pico\"."); System.out.println("If you don't guess any numbers correctly, than you will receive \"BAGELS\"."); System.out.println("Press [Enter] to continue"); String start2 = new String();// User has to press enter to continue to the game try {start2 = input.readLine();} catch (IOException e) {}; System.out.println("Begin guessing..."); } else if((rules == 2) || (rules == 3)) System.out.println("Begin guessing..."); Random r = new Random(); int num; int d1; int d2; int d3; do{//generates a unique random 3 digit number num = r.nextInt(900) + 100; d3 = num % 10; d2 = ((num - d3) / 10) % 10; d1 = (num - d3 -(d2 * 10)) / 100; }while (d1 == d2|| d1 == d3 || d2 == d3); userin3 = num % 10; userin2 = (num % 100) % 10; userin1 = (num - d3 -(d2 * 10)) / 100; int guessNumber; do{ try {user1 = input.readLine();}//Input for guessing catch (IOException e) {}; guessNumber = Integer.parseInt(user1); if (d1 == userin1){ System.out.print("Fermi ");} if (d2 == userin2){ System.out.print("Fermi ");} if (d3 == userin3){ System.out.print("Fermi ");} if (d1 == userin2) { System.out.print("Pico ");} if (d1 == userin3) { System.out.print("Pico ");} if (d2 == userin1){ System.out.print("Pico ");} if (d2 == userin3){ System.out.print("Pico ");} if (d3 == userin1){ System.out.print("Pico ");} if (d3 == userin2){ System.out.print("Pico ");} if ((d1 != userin1) && (d1 != userin2) && (d1 != userin3) && (d2 != userin1) && (d2 != userin2) && (d2 != userin3) && (d3 != userin1) && (d3 != userin2) && (d3 != userin3)){ System.out.println("BAGELS!");} }while (num == guessNumber); if (num == guessNumber){ System.out.println("You won!");} } } Your while loop continues whilst the guess is equal to the hidden number, shouldn't this be whilst it isn't equal to the hidden number. You may want to think of adding a way to allow the user to exit from the game without having to guess the correct number. Also you input the guess number but then don't do anything with it (other than in the while statement), shouldn't you be breaking into 3 separate digits to compare with the hidden number. Posting code? Use code tags like this: [code]...Your code here...[/code] I fixed the while loop but how do I make sure the game says the right stuff to the right inputted numbers? how do I make sure the game says the right stuff to the right inputted numbers? Is it printing the "wrong" stuff now? Try debugging your program by printing out the values of all your variables so you can see how they are set and changed by the program. For example: System.out.println("d1=" + d1 + ", d2=" .... for the rest of the variables Please copy the screen contents when you run the program and paste it here and add comments to it to explain what is wrong. Norm but how do I make sure the game says the right stuff to the right inputted numbers? Read the last line of my previous reply. If you have fixed this and still have a problem post your latest code. I solved it on my own. Thanks. All I did wrong was mix the random digits and the user inputed digits together in my formulas. Forum Rules
http://forums.codeguru.com/showthread.php?502609-another-array-to-use-in-another-class&goto=nextoldest
CC-MAIN-2013-48
refinedweb
757
67.76
ifaddrs Structure that describes an Internet host Synopsis: #include <ifaddrs.h> struct ifaddrs { struct ifaddrs * ifa_next; char * ifa_name; u_int ifa_flags; struct sockaddr * ifa_addr; struct sockaddr * ifa_netmask; struct sockaddr * ifa_dstaddr; void * ifa_data; }; Since: BlackBerry 10.0.0 Description: The ifaddrs structure contains the following entries: - ifa_next - A pointer to the next structure in the list. This field is NULL in the last structure in the list. - ifa_name - The interface name. - ifa_flags - The interface flags, as set by the ifconfig utility. - ifa_addr - Either the address of the interface or the link-level address of the interface, if one exists; otherwise it's NULL. See the sa_family member of the sockaddr structure pointed to by ifa_addr to determine the format of the address. - ifa_netmask - The netmask associated with ifa_addr, if one is set; otherwise it's NULL. - ifa_dstaddr - The destination address on a P2P interface, if one exists; otherwise it's NULL. If the interface isn't a P2P interface, ifa_dstaddr contains the broadcast address associated with ifa_addr, if one exists; otherwise it's NULL (see <ifaddr.h>). - ifa_data - Currently, this is set to NULL. Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/i/ifaddrs.html
CC-MAIN-2015-11
refinedweb
203
50.12
I've been going through a relatively painless process of converting Tapestry from Maven to Gradle, and am thrilled with the results. My biggest stumbling point so far was Tapestry's use of Antlr3 for its property expression language. The built-in support for Antlr only went as far as Antlr2. The Maven plugin I had been using understood Antlr3. After a bit of research and hacking, this is what I came up with as a solution for Tapestry: description="Central module for Tapestry, containing all core services and components" antlrSource = "src/main/antlr" antlrOutput = "$buildDir/generated-sources/antlr" configurations { antlr3 } sourceSets.main.java.srcDir antlrOutput dependencies { compile project(':tapestry-ioc') compile project(':tapestry-json') provided project(":tapestry-test") provided "javax.servlet:servlet-api:$servletAPIVersion" compile "commons-codec:commons-codec:1.3" // Transitive will bring in the unwanted string template library as well compile "org.antlr:antlr-runtime:3.3", { transitive = false } // Antlr3 tool path used with the antlr3 task antlr3 "org.antlr:antlr:3.3" } // This may spin out as a plugin once we've got the details down pat task generateGrammarSource { description = "Generates Java sources from Antlr3 grammars." inputs.dir file(antlrSource) outputs.dir file(antlrOutput) } << { mkdir(antlrOutput) // Might have a problem here if the current directory has a space in its name def grammars = fileTree(antlrSource).include("**/*.g") ant.java(classname: 'org.antlr.Tool', fork: true, classpath: "${configurations.antlr3.asPath}") { arg(line: "-o ${antlrOutput}/org/apache/tapestry5/internal/antlr") arg(line: grammars.files.join(" ")) } } compileJava.dependsOn generateGrammarSource The essence here is to create a configuration (a kind of class path) just for running the Antlr Tool class. The new task finds the grammar files and feeds them to the tool. We also thread the output of the tool as a search path for the main Java compilation task. Finally, we define the inputs and outputs for the task, so that Gradle can decide whether it is necessary to even run the task. Part of the fun of Gradle is that it is still a Groovy script, so there's a familiar and uniform syntax to defining variables and doing other non-declarative things, such as building up the list of grammar files for the Tool. As you might guess from some of the comments, this is something of a first pass; the Maven plugin was a bit better at assembling the list of input file names in such a way that the Antlr3 Tool class knew where to write the output Java source files properly; if Tapestry used a number of grammars in a number of different locations, the solution above would be insufficient. It also seems roundabout to use Ant to launch a Java application ... I didn't see an easier way (though I have no doubt its hidden inside the Gradle documentation). My experience getting this working was mostly positive; there's a very large amount of documentation for Gradle that helped, though it can be a bit daunting, as the information you need is often scattered across a mix of the Gradle DSL reference, the User Guide, the Javadoc and the GroovyDoc. Too often, it feels like a solution is only understandable once finished, working backwards from some internal details of Gradle (such as which exact classes it chooses to instantiate in a given situation) back through the various interfaces, Java classes, and Groovy MetaObject extensions to those classes. In fact, key parts of what I did ultimately accomplish were discovered through web searches, not in the documentation. But, that also means that the system works. Of course, this is the pot calling the kettle black ... one criticism of Tapestry can be paraphrased as we can customize it to do anything, and in just a few lines of code, but it can take three days to figure out where those lines of code go. At the end of the day, I'm much happier with Gradle; the build process is faster, the build scripts are tiny and much, much easier to maintain, and the feedback from the tool is excellent. There's still many more issues to work out ... mostly in terms of Apache and Maven infrastructure: - Ensuring the Maven artifacts are created properly, with the right dependencies in the generated pom.xml - Generating a Maven archetype using Gradle - Generating JavaDoc and Tapestry component documentation with Gradle, along with a minimal amount of pages to link it together (akin to the Maven site plugin) - Generating source and binary artifacts and getting everything uploaded to the Apache Nexus properly Regardless, I think all of these things will come together in good time. I'm not going back, and dearly hope to never use Maven again! From Shoaib Almas replied on Sat, 2012/08/25 - 6:02am * I think you may be able to get away without converting configurations.antlr3.asPath to a String. * You can use the JavaExec task to eliminate the doLast block of your task (although you might still need a doFirst for the mkdir still). * To address spaces in the path you should be able to change grammars.files.join(" ")) to grammars.files..collect { '"'+it+'"' }.join(" ")) * You could create a separate sourceSet for the generated code. i.e. sourceSets.generated.java.srcDir Java Forum
http://java.dzone.com/articles/combining-gradle-antlr3
CC-MAIN-2014-41
refinedweb
872
51.38
Hi, i've just made a Fortune teller using java, my task now is to write the pseudo code for the code. i'm a bit confused about how you do it, do i just write out the program but only with the statements in code? I'm not asking for someone to do my work for me obviously, could i be shown an example of pseudo code taken from my code? here is my code: import java.util.Scanner; public class NewClass { public static void main(String[] args) { String[] Outcome = new String[11]; Outcome[0] = "Idiot"; Outcome[1] = "You will find love today"; Outcome[2] = "You will be killed in a horrific way today"; Outcome[3] = "Someone will be watching you today"; Outcome[4] = "You will lose everything you own today"; Outcome[5] = "You will find something of value today"; Outcome[6] = "You will be attacked by a dog today"; Outcome[7] = "You will have luck on your side today"; Outcome[8] = "Unlucky day today"; Outcome[9] = "You will be promoted today"; Outcome[10] = "You will get fired today"; Scanner fortune = new Scanner(System.in); System.out.println("Enter a number from 1-10"); int number = Integer.parseInt(fortune.nextLine()); int sum = number; while (sum >= Outcome.length) { sum = Outcome.length; } System.out.println("Your fortune: " + Outcome[sum]); } } Thanks, Emiel
http://www.javaprogrammingforums.com/member-introductions/6473-help-pseudo-code.html
CC-MAIN-2014-52
refinedweb
220
58.82
In this user guide, we will learn about pointers and multidimensional arrays. In our previous tutorial, we looked upon the general relationship of arrays with pointers and how to work with them. Follow the link given below to access that article: We have already looked at pointers in the context of one-dimensional arrays. Now let move ahead and see how we can work with two-dimensional or even three-dimensional arrays using pointers. Pointers with 1-D Arrays To understand this concept better let us first briefly look at how to handle one dimensional array with pointers. First, we will declare a one dimensional array for e.g. an integer array num[] of size 5: int num[5]; This means we are creating five different integer variables that are named num[0], num[1], num[2], num[3] and num[4] as one contiguous block of memory. This can be seen below as a section of the system’s memory. The starting address of ‘num’ is ‘100.’ As we know byte in the system’s memory has an address and if we assume that an integer is stored in 4 bytes in a typical compiler then the block of four bytes at starting address 100 will be num[0]. Block of 4 bytes at starting address 104 will be num[1]. Next block of 4 bytes at starting address 108 will be num[2] and so on. Lets store some values in this array for e.g: int num[]={10,11,12,13,14}; Now let us look at the following statement: int *ptr = num; If we just use the variable name ‘num’ then the name of the array in an expression basically returns a pointer to the first element of the array. As ‘num’ is an array of integers so each element will also be an integer. Hence, ‘num’ returns a pointer to integer. After writing the above statement, we can now use pointer arithmetic and dereferencing to access all the elements in the array. If we print the address stored in ‘ptr’ then the output will be 100. printf("\n%d",ptr); Dereferencing ‘ptr’ will give us the output ’10’. printf("\n%d",*ptr); If we print *(ptr+2), then the output will be 12. This is because we have an integer pointer adding 2. This will take us to the address of the next to next integer which will be 8 bytes ahead. printf("\n%d",*(ptr+2)); Language gives us this flexibility that we can use the name of the array just like a pointer for all the dereferencing. So instead printing ‘ptr’ we can also do all of this with ‘num’. The output will still be the same. printf("\n%d",num); printf("\n%d",*num); printf("\n%d",*(num+2)); In fact *(num+i) is same as num[i]. These are alternate syntax. Similarly, *(num+i) is same as &A(i). Both will give us the address of the i-th element in the array. Thing to note: Even though we can use the name of the array just like pointer for all this dereferencing and arithmetic, it does not seem like a pointer variable. We can write the statement ptr= num; However, we can not write num =ptr; This will give us compilation errors. Pointers with 2-D Arrays Now let us look at how to handle pointers with two dimensional arrays. For example purposes, we will declare the following two dimensional array of integers named ‘num’. int num[2][3] We have created an array of array. ‘2’ is the number of rows and ‘3’ is the number of columns. In fact, we have created two one dimensional arrays consisting of three elements each. This time num[0] and num[1] are both one dimensional arrays of three integers each. A one dimensional array of three integers would be 12 bytes if each integer is 4 bytes in size. So, showing it in the system’s memory the first block of 12 bytes starting address 200 will be num[0] and the next block of 12 bytes starting address 212 will be num[1]. Point to Note: In the 2-D array, the address of a block is the address of the first byte in the block. As we know that the name of the array returns a pointer to the first element in the array. This time each element is not an integer but instead each element is a one-dimensional array of three integers. So if we will write a statement like this: int *ptr=num; This will give us a compilation error. This is because ‘num’ will return a pointer to one dimensional array of three integers and not just a pointer to integer. The type of a pointer matters not when you have to read the address. It matters when you dereference or when you perform pointer arithmetic. It is very important to understand this. We can define a pointer to a one-dimensional array of three integers in the following way. int (*ptr)[3]; Equate ‘ptr’ with num: int (*ptr)[3]=num; Now we will print just ‘num’ which is the same as printing the address of num[0] through &num[0]. Thus, the output will be 200. However, if we will print *num which will be same as num[0] then num[0] is the variable name for the one dimensional array of three integers. So just using the name num[0] will return a pointer to the first integer in num[0]. This will be accessed as &num[0][0]. We will store values in our 2-D array as shown in the following statement. int num[2][3]={{4,5,6},{14,24,34}}; You can view the individual integers in the memory blocks below. Here you can see num[0] consists of three integer elements num[0][0] that is 4, num[0][1] that is 5 and num[0]num[2] that is 6. Likewise, num[1] also consists of three elements num[1][0] that is 12,num[1][1] that is 24 and num[1][2] that is 34. Pointer Arithmetic and dereferencing with 2-D arrays - Now if we print (num+1), the output will be 212. This is because num returns a pointer to one dimensional array of three integers. So if we will perform pointer arithmetic of adding plus 1 we are moving to the next 1-D array of three integers. Hence, we will be moving to address 200+size of 1-D array of 3 integers in bytes so that is why the output will be (200+12)=212. This is true because num+1 is equivalent to &num[1]. - Let us print *(num+1). Notice that we put an asterisk sign to dereference. Here the type of pointer holds significance. ‘num’ is a pointer to a 1-D array of three integers. Hence, (num+1) is also a pointer to 1-D array of 3 integers. When we will dereference this we will obtain the whole 1-D array of three integers with starting address 212. *(num+1) is the same as num[1]. This 1-D array num[1] which should return us the pointer to the first integer in num[1]. Thus, *(num+1) is basically the pointer to the integer at address 212. In other words, &num[1][0]. Hence the output will be again 212. Notice that all these expressions including *(num+1) or num[1] or &num[1][0] are returning an integer pointer and are equivalent statements. - Now let us look at a bit harder one. What will be the output if we print *(num+1)+2? As we saw above, *(num+1) returned us the integer pointer to the first integer in num[1] to the integer at address 212. Adding plus 2 here is performing pointer arithmetic because *(num+1) is a pointer to integer stored at address 212. Adding 2 means we are moving ahead to the next to next address of the integer thus skipping 8 bytes. We will end up at address (212+8)=220. *(num+1) in this expression can be written as num[1] as they are equivalent statements. Thus *(num+1)+2 is the same as num[1]+2 or &num[1][2]. All of these expressions are returning pointer to integer. In fact they are returning the the pointer corresponding to the element num[1][2]. - Lastly, let us find out the output if we print *(*num+1) Whenever we encounter an expression with pointer arithmetic and dereferencing make sure to solve it in a series of steps to make it easier to obtain the output. - Here ‘num’ is returning us the pointer to the 1-D array of size three. Then we are dereferencing this 1-D array of three integers. This will give us the 1-D array of integers so *num will give us num[0]. - Now num[0] is named for a 1-D array returns us the pointer to the first integer in the 1-D array so num[0] returns a pointer to integer. We will get a pointer to integer at address 200. - Adding 1 to an integer pointer will take us 4 bytes ahead to the next integer. Thus, it will return us the pointer to the next integer. We will obtain a pointer to this integer at address 204. So we can say that *(num+1) is basically &num[0][1]. - With the final dereferencing *(&num[0][1]), we can get rid of the & operator so the overall expression now becomes num[0][1]. This is equal to ‘5’ in our case. Note: For a 2-D array, num[i][j] where num is the name of our 2-D array i and j are indices, can be written as: num[i][j] = *(num[i]+j) = *(*(num+i)+j) where num[i] can be re-written as *(num+i) Hence these three expressions are equivalent. Pointers with 3-D Arrays Now let us look at how to handle pointers with three dimensional arrays. For example purposes, we will declare the following three dimensional array of integers named ‘num’. int num[3][2][2] We have an array of 3x2x2. A three dimensional array is an array or collection of 2-D arrays. Here the first parameter ‘3’ is the block size or the number of 2-D arrays, the next parameter ‘2’ is the number of rows of the 2-D arrays and last parameter ‘2’ is the number of columns of the 2-D arrays. The following figure depicts ‘num’ in the system’s memory. Here we have assumed that the starting address of ‘num’ is 400. The first sixteen bytes at starting address 400 is the first 2-D array which is num[0]. We are assuming that each integer will take 4 bytes so the first block is part of the first 2-D array. The next block of sixteen bytes with starting address 416 is num[1]. Likewise ,the next block of sixteen bytes with starting address 432 is num[2]. We will store values in our 3-D array as shown in the following statement. int num[3][2][2]= { {{4,14},{20,31}}, //elements of block 1 {{30,6},{36,32}}, //elements of block 2 {{9,0},{19,67}} //elements of block 3 }; You can view the individual integers in the memory blocks below. We can further break down the 2-D arrays into 1-D arrays. The first two integers in num[0] are part of the first 1-D array num[0][0]. The next two integers 20 and 31 in our case are part of num[0][1] and as follows as shown in the figure below: The first integer in num[0][0] can be accessed as num[0][0][0]. We can access each integer in the following manner as shown below: This time just using the array name ‘num’ will give us a pointer to a 2-D array of integers of size 2×2. Pointer Arithmetic and dereferencing with 3-D arrays The following statement declares a pointer to 2-D array of integers of size 2×2: int (*ptr)[2][2]= num; - The name of the pointer is ‘ptr’. Printing ‘prt’ or ‘num’ gives the output 400. - Now if we will perform dereferencing and try to print *num then this will be the same as printing num[0]. As num[0] is a 2-D array so we will get a pointer the first element in num[0] which is accessed through &num[0][0]. All of these expressions return pointer to one dimensional array of integers of size 2. The address printed will be 800. Remember ‘num’ is a type pointer to 2-D array of 2×2 and dereferencing once gives us pointer to 1-D array of 2 integers. ‘num’ is returning us pointer to 2-D array of integers. For ‘num’, num[i][j][k], where i, j and k are some indices, can be written as *(num[i][j]+k). We can write num[i][j] as *(num[i]+j) and num[i] as *(num+i) so the overall expression becomes: num[i][j][k] = *(num[i][j]+k) = *(*(num[i]+j)+k) = *(*(*(num+i)+j)+k) - Let us print *(num[0][1]+1) and see what the output will be. num[0][1] means we are going to the 1-D array that has two elements ’20’ and ’31’ in our case. Using the name num[0][1] means that we are obtaining the pointer to the first integer in this 1-D array. Now pointer to this integer ’20’ plus 1 means that we are moving ahead one integer that is ’31.’ Dereferencing this gives the output as ’31.’ Have a look at the section of the system’s memory to have a better understanding of the scenario: Now let us find the output if we print *(num[1]+1). Here num[1] will return us a pointer to the 1-D array. The 1-D array in num[1] is the block containing the integers ’30’ and ‘6’ basically num[1][0]. Adding 1 to this is performing pointer arithmetic and thus moving ahead to the next 1-D array. This is the 1-D array which contains the integers ’36’ and ’32’ basically num[1][1]. Then we will dereference it to get the 1-D array from the pointer. As we used the name of the 1-D array we will get the pointer to the first element in the 1-D array. So we will get the pointer to the integer ’36’. Hence the output will be 424. Have a look at the section of the system’s memory to have a better understanding of the scenario: Example Code Now let’s look at sample example codes for all the different concepts we have learned so far. #include <stdio.h> int main() { int num[3][2][2]= { {{4,14},{20,31}}, {{30,6},{36,32}}, {{9,0},{19,67}} }; printf("%d %d %d %d",num,*num,num[0],&num[0][0]) ; } Now let’s see the code output. After the compilation of the above code, you will get the following output. As you may notice that all four expressions gave us the same output as was expected. All of these expressions return a pointer to a one-dimensional array of integers of size 2. They are equivalent statements. Now let’s print the following statement: printf("%d",*(num[0][0]+1)) ; After the compilation, you will get the following output. As this expression is equivalent to num[0][0][1] hence we will obtain the output ’14’. You may also like to read other tutorials on pointers: - Pointer Arithmetic, Pointer Size, and Pointer Type in C and C++ - C Program to change Endianness of data and bytes swapping example using Pointers - Function Pointers in C/C++ and Function Callbacks - Pointers as Function Arguments or call by reference in C - Double Pointers or Pointers to Pointers in C/C++ - How to find the Size of structure without sizeof() Operator? - Dynamic Memory Allocation through Double Pointer and Function without returning address
https://csgeekshub.com/c-programming/pointers-multidimensional-arrays/
CC-MAIN-2021-49
refinedweb
2,725
71.75
Recommended Answers … for( int i = 0; i < 32; ++i ) That's not very portable. Use something in <climits> or the C++ equivalent. > //A quicker method is to simply use the value as an Except your other two methods never risk an out of bounds memory access. > 1. unsigned int arithmatic is faster than signed int. Where's your evidence? > 2. registers are registers ! They're simply faster than … > 1. In VS 6.0 (on Intel H/W) (are unsigned better?) So, you pick one specific processor / compiler combination out of the many 10's of processors (or maybe hundreds of variants, or thousands of compilers + flag variations) and decide that proves it? Interesting it may be, but it's … All 47 Replies This is a short list of recommendations on how to use C++. My experiences are from using gcc 2.8.0 and Visual C++ 6.0. I had to have things compatible between these two compilers, and between Unix and Windows. (Note: The recommendations in this post may not be consistent with modern and correct C++ and were not peer reviewed before being posted to this thread. Use them with caution. -Narue) Contents IO of binary files When are destructors called for local variables Use {} to keep things local Scope of variables declared in for() When to use virtual members IO of binary files To make sure that there is no CR/LF translation on non-Unix computers, you have to use the following lines to open streams to files with binary data. [left]ofstream os("output.flt", ios::out | ios::binary); [/left]). When are destructors called for local variables Non-static (or 'automatic' ) variables are 'destructed' automatically when they go out of scope. Scope is a farily complicated thing, and I'm not going to repeat the definition here. Roughly speaking the scope ends when you encounter the } around the declaration of the variable. See also the use of {} and how scope is defined in the for() statement. Variables are destructed (by the compiler) by calling the appropriate destructor of their class. If the objects allocate memory (and hence the destructor should free that memory), this means that you recover the memory allocated. class array { private: float *ptr; public: // constructor array(int n) { ptr = new float[n]; } // destructor ~array() { delete [] ptr; } } main() { // ... { array a(5); // allocates memory // do something } // here the array is destructed, and so the memory is freed //.... } Use {} to keep things local Use of the grouping construct {} enables you to declare variables local to that group. When leaving the group, all local variables are destructed. This has the advantage that the reader of the code knows (s)he shouldn't worry about these variables to understand the rest of the code. In a way this can be understood as if every use of {} is like a function call (with local variables declared in the function). Of course, you don't have the overhead of stack manipulations and jumps involved in a proper function call. // recommended usage void f(int a) { if(a==1) { myclassA Aobject; // here I do something with 'Aobject', and maybe 'b' } // Aobject does not exist here anymore This tip is just an extension of the 'avoid global variables' credo. As always, this can be disabused as in the following piece of code, where the outer variable 'a' is hidden by a local 'a', resulting in not very readable code. [left]// not very readable code { int a=1; { // local variable hides outer 'a' int a; a = 2; assert (a==2); } // a is again the previous variable assert (a==1); } Scope of variables declared in for() The new ANSI C++ standard specifies that variables declared as in for(int i=1; ...) have a scope local to the for statement. Unfortunately, older compilers (for instance Visual C++ 5.0) use the older concept that the scope is the enclosing group. Below I list 2 possible problems, and their recommended solutions: - you want to use the variable after the for() statement [/left] - you have to declare the variable outside of the for() statement. [left]int i; for(i=1; i<5; i++) { /* do something */ } if (i==5) ... - you want to have multiple for() loops with the same variables. [/left] Put the for statement in its own group. You could also declare the variable outside of the 'for', but it makes it slightly trickier for an optimising compiler (and a human) to know what you intend. [left]{ for(i=1; i<5; i++) { /* do something */ } } [/left] When to use virtual members Make a member 'virtual' if a derived class extends the functionality of a member of the base class, and this extended functionality has to be accessible: - inside other member functions of the base class - when using pointers that can point to either an object of the base class, or an object of the derived class. Example: multi-dimensional arrays which are defined recursively in terms of a 1D array. We wanted to have a 'grow' member that enlarged the outer dimension of the multidimensional array. At first sight, this is simply calling a general grow of the base class. However, 'grow' has to know the size of the new elements (which are again multidimensional arrays). So, we had to define in the derived class a new 'grow', which calls the base class 'grow' first, and then does more stuff. At many points in the base class, 'grow' is called to adjust sizes. By making 'grow' virtual we avoid to having to rewrite these members for the derived class. Caveat: For members of the base class which use temporary objects of its own type, the base class 'grow' will be called. For instance: [left]class array { ... virtual void grow(int new_size); array& operator +=( const array& a) { /* some definition using 'grow' */ } array operator +(const array& a1, const array& a2) { array a=a1; a += a2; // Warning, this will call array::grow, even if a1 is really from a derived type } }; [/left] Thus, you should provide a member of the derived class for every member of the base class which uses temporary objects. [indent]class multiarray : public array { ... virtual void grow(int new_size); multiarray operator +(const multiarray& a1, const multiarray& a2) { multiarray a=a1; a += a2; } }; [/indent] - No Need to change existing code for incrementing functionalities in terms of inheritance - Better than type field solution. - and many more.. All above from bjarne Stroustrup. The C++ programming languages..inventor of C++ Happy going virtual!!!!!!!!!!! Introduction These tips are based mainly on ideas from the book Efficient C++ by Dov Bulka and David Mayhew. For a more thorough treatment of performance programming with C++, I highly recommend this book. This document, while presenting many of the same ideas in the book, does not go into as much detail as to why certain techniques are better than others. The book also provides code examples to illustrate many of the points presented here. Constructors and Destructors - The performance of constructors and destructors is often poor due to the fact that an object's constructor (destructor) may call the constructors (destructors) of member objects and parent objects. This can result in constructors (destructors) that take a long time to execute, especially with objects in complex hierarchies or objects that contain several member objects. As long as all of the computations are necessary, then there isn't really a way around this. As a programmer, you should at least be aware of this "silent execution". If all of the computations mentioned above are not necessary, then they should be avoided. This seems like an obvious statement, but you should be sure that the computations performed by the constructor that you are using is doing only what you need. - Objects should be only created when they are used. A good technique is to put off object creation to the scope in which it is used. This prevents unnecessary constructors and destructors from being called. - Using the initializer list functionality that C++ offers is very important for efficiency. All member objects that are not in the initializer list are by default created by the compiler using their respective default constructors. By calling an object's constructor in the initializer list, you avoid having to call an object's default constructor and the overhead from an assignment operator inside the constructor. Also, using the initializer list may reduce the number of temporaries needed to construct the object. See the Temporaries section for more information on this. Virtual Functions - Virtual functions negatively affect performance in 3 main ways: - The constructor of an object containing virtual functions must initialize the vptr table, which is the table of pointers to its member functions. - Virtual functions are called using pointer indirection, which results in a few extra instructions per method invocation as compared to a non-virtual method invocation. - Virtual functions whose resolution is only known at run-time cannot be inlined. (For more on inlining, see the Inlining section. - Templates can be used to avoid the overhead of virtual functions by using a templated class in place of inheritance. A templated class does not use the vptr table because the type of class is known at compile-time instead of having to be determined at run-time. Also, the non-virtual methods in a templated class can be inlined. - The cost of using virtual functions is usually not a factor in calling methods that take a long time to execute since the call overhead is dominated by the method itself. In smaller methods, for example accessor methods, the cost of virtual functions is more important. Return Value Methods that must return an object usually have to create an object to return. Since constructing this object takes time, we want to avoid it if possible. There are several ways to accomplish this. - Instead of returning an object, add another parameter to the method which allows the programmer to pass in the object in which the programmer wants the result stored. This way the method won't have to create an extra object. It will simply use the parameter passed to the method. This technique is called Return Value Optimization (RVO). - Whether or not RVO will result in an actual optimization is up to the compiler. Different compilers handle this differently. One way to help the compiler is to use a computational constructor. A computational constructor can be used in place of a method that returns an object. The computational constructor takes the same parameters as the method to be optimized, but instead of returning an object based on the parameters, it initializes itself based on the values of the parameters. Temporaries Temporaries are objects that are "by-products" of a computation. They are not explicitly declared, and as their name implies, they are temporary. Still, you should know when the compiler is creating a temporary object because it is often possible to prevent this from happening. - The most common place for temporaries to occur is in passing an object to a method by value. The formal argument is created on the stack. This can be prevented by using pass by address or pass by reference. - Compilers may create a temporary object in assignment of an object. For example, a constructor that takes an int as an argument may be assigned an int. The compiler will create a temporary object using the int as the parameter and then call the assignment operator on the object. You can prevent the compiler from doing this behind your back by using the explicit keyword in the declaration of the constructor. - When objects are returned by value, temporaries are often used. See the Return Value section for more on this. - Temporaries can be avoided by using <op>= operators. For example, the code a = b + c; could be written as a=b; a+=c;. Inlining Inlining is one of the easiest optimizations to use in C++ and it can result in the most dramatic improvements in execution speed. The main thing to know when using inlining is when you should inline a method and when you shouldn't inline. - There is always a trade-off between code size and execution speed when inlining. In general, small methods (for example, accessors) should be inlined and large methods should not be inlined. - If you are not sure of whether or not a given method should be inlined, the best way to decide is to profile the code. That is, run test samples of the code, timing inlining and non-inlining versions. - Excessive inlining can drastically increase code size, which can result in increased execution times because of a resulting lower cache hit rate. - Watch out for inlined methods that make calls to other inlined methods. This can make the code size unexpectedly larger. - Singleton methods, methods that are only called from one place in a program, are ideal for inlining. The code size does not get any bigger and execution speed only gets better. - Using literal arguments with an inlined method allows the compiler to make significant optimizations. (This is, however, compiler dependent.) - The compiler preprocessor can be used to implement conditional inlining. This is useful so that during testing the code is easier to debug. But for compiling production code, there are no changes to be made to the source code. This is implemented by using a preprocessor macro called INLINE. Inlined code is defined within #ifdef INLINE ... #endif code blocks. Similarly, non-inlined code is defined within #ifndef INLINE ... #endif code blocks. Then to compile using inlined code, you tell the compiler to treat INLINE as defined. (-DINLINE with g++) - Sometimes it makes sense to inline a given method in some places, but to not inline in other places within the same program. This can be accomplished using a technique called selective inlining. The implementation of this technique is not very convenient. For each method that you want to selectively inline you have two methods, where on one has "inline_" prepended to the method name and is of course inlined. The method without the "inline_" prepended to its name simply calls the inlined version of the method. - Recursive calls cannot be inlined, but there are two techniques to try to improve performance in the case of recursive methods: - If the recursion is tail recursion, then the algorithm can be rewritten as an iterative algorithm, eliminating the overhead of method invocations. - Recursive call unrolling basically allows the programmer to inline the first steps of recursion in a recursive algorithm. For example, for a recursive method print() we might do the following: print_unrolled() calls print1() which calls print2() which calls print3() which calls print(). All methods except print() are inlined. The number of recursive steps can be made as high as desired, depending on the application. How about precalculated values. It saves a lot of time in slower machines during long iterations, does it not? For eg: x=23.45; xinv=1/x; and use xinv where its needed. Also one can use precalculated trigonometrical functional values such as float x=sin(x); and so avoiding virtual functions while still allowing inheritance (does not work well all the time since only a limited amount of the behaviour is simulated though)... well anyway if you are intrested take a look (it involves specifying the extending class as a template argument to the base class so the implemented class is known at compile time)... Two guidelines from Thinking in C++ by Bruce Eckel: - Avoid the preprocessor. Always use const for value substitution and inlines for macros. - Avoid global variables. Always strive to put data inside classes. Global functions are more likely to occur naturally than global variables, although you may later discover that a global function may fit better as a static member of a class. This book has 73 guidelines. See book: An easy way to swap 2 variables without using another variable: a=a+b; b=a-b; a=a-b; An easy way to swap 2 variables without using another variable: a=a+b; b=a-b; a=a-b; Not this again. This is not 1970! Don't do this today or in the future. Use a temp variable. An easy way to swap 2 variables without using another variable: a=a+b; b=a-b; a=a-b; it can't be used if operator+ and operator- arn't defined!!! and you don't have to use another variable, in C++ standard, there is the STL. It is the strength of C++ because there are lots and lots of algorithms in it. For example, there is a sort that sorts your elements always in O(n log n) time, which is the fastest it can get (if you don't count counting sort). Therefore I use the it any time I can. There is also a templated function swap, that swaps any two elements that are of same type. So i think it is be easier and cleverer to type swap(a, b); than to use your idea. the best way to do this is to use the bits. The code would be: inline string to_binary( const int &x ) { int t; string ret; if( x > 0 ) t = x; else t = -1 * x; for( int i = 0; i < 32; ++i ) if( t & ( 1 << i ) ) ret.push_back( '1' ); else ret.push_back( '0' ); reverse( ret.begin(), ret.end() ); ret.erase( 0, ret.find( '1' ) ); if( ret.size() == 0 ) return "0"; if( x < 0 ) return '-' + ret; return ret; } An easy way to swap 2 variables without using another variable: a=a+b; b=a-b; a=a-b; Easy way? I don't know, but sure it is inefficient (except if the optimizer is really good). There *are* temporary variables if from an ISO standard point-of-view. And, this algorithm can only be useful if (assuming an optimizer as good as Turbo C++ 1.0 optimizer or better, knowing that it is a very old compiler, with an obsolete optimizer): - Both a and b are in a register (otherwise, I don't know any architecture where the temporary would be avoided) - AND There is no builtin XCHG instruction at the assembly level (false for x86 and PowerPC) - AND The CPU lacks register (in that case, it is very probable that the CPU has a XCHG instruction). And, in that case, you may, ocasionally (rarely) gain little performance... In all other cases, you just can pray that the optimizer will understand your bad code, and implement it in a correct way. Most compilers I know produce bad code for that. If you use a 25 years old compiler, with a very very bad optimizer, it might also be possible that this compiler lacks register variables... In that case, the following code: a-=b; b-=a; a-=b; Will produce something like (on x86-16, yep I can't imagine any such bad optimizer on x86-32): mov ax, [bp-8] ; timings on a k6-2 CPU (1) sub ax, [bp-4] ; 3 mov [bp-8],ax ; 4 CPU cycles mov ax,[bp-4] sub ax,[bp-8] mob [bp-4],ax mov ax, [bp-8] sub ax, [bp-4] mov [bp-8],ax ;11.5 CPU cycle (i.e. the last one might be paired with the next instruction) Note : If the optimizer is even more bad than what I described, the generated code might even be worst. And, your code (which has temporaries), on the same compiler might be twice as slow... The classical int c; c=b; b=a; a=c; Will produce something like: mov ax,[bp-4] mov [bp-12],ax mov ax,[bp-8] mov [bp-4],ax mov ax,[bp-12] mov [bp-8],ax ; 5.5 CPU cycles (on a K6-2 CPU) Note : I don't think that the compiler can generate worst code, even if there is no optimizer. So, my point is that your code is *always* a bad idea. This algorithm might only be used in some very special contexts, only on weird architectures (I don't know any such architecture, but it probably exists or existed), and at assembly level only! Please, read my posts (SuperKoko) on these two threads (of another forum): Also, remember that std::swap can be assumed as being optimal on your architecture : The compiler is allowed to do specific optimizations on it. When you want to pass a constant variable, pass it by reference to save memory. Example: int example (const int value); // Uses more memory than int example (const int &value); // this one That's the opposite! Using const references is a good idea for large objects (say, 16 bytes and more). For very small objects (smaller than a pointer), if you're lucky, you'll not loose performance. But it is quite probable that the compiler will generate more code, slower code, and use more stack memory (if the argument is not a lvalue). And, moreover, it is very hard for the compiler to optimize the const-reference thing when the function is used across translation units boundaries (at least, for most compilers), because it must respect a calling convention, and can't know whether the function, internally, gets the address of the const reference. In that case, the compiler can't replace such const-reference by a simple value. Please read my posts on these two threads: Valid, albeit ancient, advice -- much like the XOR swap. It's one of those things that language implementers knew about ages ago, and should be done by the compiler automagically (or it may take some optimization option). Bottom line: don't do this unless your compiler sucks. Write code to multiply by 4 like this num*=4 . Obfuscating it as num<<=2 will make your code look strangeto newbies, and it will look like a newbish hack to old timers (both making what you write a little suspect). And don't forget that right-shifting signed values is implementation defined! A few more I find useful... 1. Replace switch-case/if-else with array-indexing: switch ( queue ) { case 0 : letter = 'W'; break; case 1 : letter = 'S'; break; case 2 : letter = 'U'; break; } //or maybe if ( queue == 0 ) letter = 'W'; else if ( queue == 1 ) letter = 'S'; else letter = 'U'; //A quicker method is to simply use the value as an //index into a character array, eg. static char *classes="WSU"; letter = classes[queue]; 2. I'm sure most ppl know this but writing as it's not already mentioned in this topic so far. Use unsigned int stored in registers for loop variables. Reasons 1. unsigned int arithmatic is faster than signed int. 2. registers are registers ! They're simply faster than memory access. for( register unsigned int loop_variable = 0; loop_variable <=100000; i++ ) { /*do your stuff*/ }*/} 4, Optimizing very small loops using switch-case. When you know that the range of loop variable's value is pretty small avoid the loop altogether. //unoptimized code for( int i = some_small_positive_int; i--; ) {/*do your stuff with i*/} //optimized based on the assumption that some_small_positive_int can only be from 1 to 7. switch( i ) { case 7 : /*do your stuff with i*/ i++; case 6 : /*do your stuff with i*/ i++; case 5 : /*do your stuff with i*/ i++; case 4 : /*do your stuff with i*/ i++; case 3 : /*do your stuff with i*/ i++; case 2 : /*do your stuff with i*/ i++; case 1 : /*do your stuff with i*/ }*/} Except if your description is true, you'd be better off using i = 30; while (i--) { /*do your stuff*/ } 5. Another way of optimizing loops is to unroll it: //unoptimized loop int loop_count = 50000; /* could be anything */ for( int j = 0; j < loop_count; j++ ) printf("process(%d)\n", j); //optimized one static int BLOCKSIZE = 8 ; /* The loop_count may not be divisible by BLOCKSIZE, * go as near as we can first, then tidy up. */ int i = 0; int blocklimit = (loop_count /; } //we already know how to optimize small loops. switch( loop_count -); } > //A quicker method is to simply use the value as an Except your other two methods never risk an out of bounds memory access. > 1. unsigned int arithmatic is faster than signed int. Where's your evidence? > 2. registers are registers ! They're simply faster than memory access. True, but any decent compiler nowadays is far more capable of deciding which variables would be best placed in registers. >. @WaltP Except if your description is true, you'd be better off using i = 30; while (i--) {/*do your stuff*/} >> Sorry but I fail to see the different between for and while loop.. Do you mean it's faster to use while instead of for? @Salem > //A quicker method is to simply use the value as an Except your other two methods never risk an out of bounds memory access. KashAI>> TRUE. So I hope that anyone able enough to understand this won't blindly copy my code. > 1. unsigned int arithmatic is faster than signed int. Where's your evidence? KashAI>> I was afraid someone will ask. :). Anyway, simple answer is I don't know. But here is what I know: 1. In VS 6.0 (on Intel H/W) a simple for loop with loop variable being unsigned is about 2 seconds faster than when loop variable is signed int. (looped some 100K and 500K times to print the value of loop variable) 2. In most cases one can see that there are seperate assemply instructions for signed and unsigned arithmetic. Which at least indicates a difference in performance. 3. Number of flags applicable (CF=carry-over-flag, SG=sign-flag, OF=overflow-flag) to signed and unsigned instructions' execution are different. 4. I'm vaguely remember an instruction called SBB (substract using borrow) which, if i'm not wrong, is only applicable to signed arithmetic. And use of it is in case where the requested substraction of 2 signed numbers can not be completed with a single instruction due to register size. > 2. registers are registers ! They're simply faster than memory access. True, but any decent compiler nowadays is far more capable of deciding which variables would be best placed in registers. KashAI>> So if I understand it right what I've written is correct, but not neccesarry. >. KashAI>> So in short, should one NOT optimize it this way? May be you could add some practical numbers for the benefit of readers which will help them in deciding whether to use this optimization or not? E.g. "in 80% of cases cache is optimised in favour of incremental access" OR "Now-a-days most machines support ". KashAI>> Now that is useful info. Just checked and found that VS 6.0 and Sun Workshop 6.0 also support lopp unrolling. Sorry forgot one more thing regarding "1. unsigned int arithmatic is faster than signed int. Where's your evidence?" See. 2. I'm sure most ppl know this but writing as it's not already mentioned in this topic so far. Use unsigned int stored in registers for loop variables. Reasons 2. registers are registers ! They're simply faster than memory access. Most compilers ignore the "register" keyword, because their optimzations are far more advanced than back in the time, where a variable had only one storage in its life... But, the register keyword can reduce performances on some compilers, because they interpret it as a strong request, from the programmer, to use a register for storage of the variable, which condemns one register. Even on very old compilers where the register keyword was a useful hint, it would have been utterly stupid to use the register keyword everywhere, as it would be as slow, or slower, than using no keyword at all, because the compiler would not be better than using its default "guessing" algorithm. The register keyword should be used only at places, where you want to give a hint to the compiler, that THIS variable needs to be accessed faster than other ones, even if it reduces performances of other variables. 1. unsigned int arithmatic is faster than signed int. Ridiculous. On two's complement machines, additions, substractions and multiplications have identical performances as signed or unsigned, since this is exactly the same operation. For comparisons, the performances are identical on x86 architectures, since the same operation is used for all comparisons (cmp). On all other architectures, there is absolutely nothing that would add a performance penalty on signed comparisons, because integer comparisons require only very very few transitors... The comparison itself, cannot require more than one CPU cycle. For integer division, signed integer division was a bit slower than unsigned integer division on old CPU. But, integer divisions are very rarely time critical, because division is not a very much used operation. 3. Optimizing the breaking conditions in for loops. If you know that the loop variable's range is from 0 to some +ve number AND it doesn't matter which way you traverse while looping, you can optimize the loop like this: Assuming that the compiler doesn't optimize it for you. GCC 3.4.5 (-O2) for i386, is clever enough to optimize the first loop with a decrementation operation. This is because, forward loops are very common, and GCC has specific optimizations for this type of code. On the other hand, GCC 3.4.5 is not clever enough to produce good code for your "manually optimized" loop. for( int i = 0; i <= 30; i++ ); Produces this assembly code (MinGW 3.4.5 for Win32 -O2): 0x401300 : dec eax 0x401301 : jns 0x401300 But: for( int i = 30; i--; ); Produces: 0x401300 : dec eax 0x401301 : cmp eax,0xffffffff 0x401304 : jne 0x401300 Why this pessimization? First, the following code: 0x401300 : dec eax 0x401301 : js 0x401300 Would immediately stop if eax is negative... But, the conditional expression is about the inequality with zero! The compiler could have seen that all the values of i will be in range [0,30), but GCC is not clever enough to understand that, because you wrote a weird loop. A good code, benefiting from the fact that "dec eax" sets the zf and sf flags, would require that you stop when i reaches zero, not -1. Your code confuses the compiler, and is a pessimization. So, don't do that! Note: for( int i = 31; --i; ); Generates the right code: 0x401300 : dec eax 0x401301 : jns 0x401300 With MinGW 3.4.5. I don't claim that it's ok. It may be a pessimization with another compiler. 4, Optimizing very small loops using switch-case. When you know that the range of loop variable's value is pretty small avoid the loop altogether. Or... activate the -funroll-loops option (or your compiler equivalent), which is less error prone. Also, you should notice that, this should only be used on the most critical code, as it greatly increases the code size, which can have a serious performance penalty. 5. Another way of optimizing loops is to unroll it: Knowing that printf is so slow that the loop code itself is negligible... I benchmarked the two programs, using NUL as the standard output. There is no sensible speed difference. Both require 3900 milliseconds to execute on my computer. A revelant piece of code of the two things: ; without manual loop unrolling ; Assume a K6-2 CPU 0x401323 <main+67>: inc ebx 0x401324 <main+68>: push 0x403000 ;1 0x401329 <main+73>: call 0x4018a0 <printf> 0x40132e <main+78>: add esp,0x10 0x401331 <main+81>: cmp ebx,0xc350 ;1 0x401337 <main+87>: jl 0x401320 <main+64> ; 3 ; -> 3 CPU cycles + approximatively 39600 CPU cycles for the printf call (if the output stream is the NUL device). ; with manual loop unrolling 0x40134d <main+109>: pop eax 0x40134e <main+110>: lea eax,[ebx+1] ;1 0x401351 <main+113>: pop edx ;2 0x401352 <main+114>: push eax ;3 0x401353 <main+115>: push 0x403000 ;4 0x401358 <main+120>: call 0x4019c0 <printf> ; -> 4 CPU cycles + approximatively 39600 CPU cycles for the printf call. So, your "optimization", approximatively reduce performances by 0.0025%. Which is negligible.. You should not do that before checking whether printf is slower or faster than cout. This is very highly compiler dependent. For example, Borland C++ 5.0 is faster for cout than for printf. Check my answer on this thread: And, don't forget that micro-optimizations are the ennemy of real optimizations. A performance tip that has served me well with C++, C#, Java, VB, and scripting languages is counting backwards. When using a comparison in a loop (presumably for termination purposes), if possible, count down to zero instead of up to a non-zero value. Since every machine language in existence has "compare to zero" operators, smart compilers can utilize this efficiency. Normally, the compiler saves the comparison value in memory and then accesses it indirectly for each loop. However, many compilers will recognize the comparison to zero and optimize it with a single machine language command, bne, bge, etc.. In complex, nested loops, the optimization can be amazing. The main down fall I've observed is compiler consistency. I have not observed .NET's IL doing this and it doesn't always do this when going native. We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.
https://www.daniweb.com/programming/software-development/threads/21515/c-performance-tips
CC-MAIN-2021-10
refinedweb
5,548
62.88
Crystal Space Guest . Please or . March 07, 2014, 10:53:19 am 1 Hour 1 Day 1 Week 1 Month Forever Login with username, password and session length Search: Advanced search 8991 Posts in 2037 Topics by 7168 Latest Member: Katherinebaker Show Posts Pages: [ 1 ] 1 Crystal Space Projects / Finished Projects / cAudio 2.0.0 Release! on: February 22, 2010, 12:16:36 am The next version of cAudio has been released. cAudio is an advanced C++ wrapper around OpenAL that makes it easier to put 3D audio into your games and other applications. This version includes some major API rework, many new features, and a brand new plugin system. It also includes much better API documentation to make it easier to incorporate into your projects. Also included is a large number of bug fixes. New Features: All OpenAL "Effects Extension" audio effects and filters are now supported by the engine. This means you can easily drop in effects like EAX Reverberation, Distortion, Flanger into your application and attach them to any number of audio sources in your world. Use them to create the illusion of large caverns, or tiny hallways, or virtually any other environment. Audio Capture is now supported. Stream audio from a microphone, line in, or virtually any other capture device into your application using a simple interface. cAudio now uses multiple threads internally to handle loading and playback of sounds (as well as background capture of audio). cAudio is also now thread safe. Ability for users to override where cAudio gets its file data for playing sources. Instead of only being able to get files from the hard drive or from a memory location in your program, you can now supply an interface for cAudio to use. Thus you can stream data into cAudio from virtually any location, whether that is a zip archive, TCP/IP stream, or Ogre/Irrlicht resource system. New logging system with user definable log receivers, allowing the developer to have full control of where the log messages go. cAudio also provides default console and html file log receivers. New Event system. cAudio can now automatically call functions in your code when certain events happen in the engine. For example, you can get an event when a source stops playback. New Plugin System. This system supports both dynamically linked libraries and static plugin definitions. Plugins have full control of the engine and can be used to add new audio decoders, log receivers, data sources, and act upon events in the engine. New MP3 Decoder plugin. Many of our users have been asking for mp3 playback capability and now it is offered as an official plugin. New EAX Legacy Preset plugin. Offers all of the classic EAX Legacy presets for EAX Reverberation effects. This makes it easy to drop in an reverberation effect that sounds close to the environment you are modeling and then tweak it later. Several new examples to show off the new features of the engine. Advanced Memory Manager Major changes: The Audio Playback Manager is no longer a singleton. It must be created using the createAudioManager() API function. This is to support the possibility of multiple playback managers someday in the future, though this feature is not currently supported. A 3D vector class is now provided by the engine and is required by several API functions. This means no more entering 3 floats into a function constantly. Several components of the library are now reference counted. This is to ease issues when the user may want to retain an object even after they remove it from the engine, as well as make deletion of unused objects easier internally. A cross platform sleep function is included for example usage. The Audio source class has been renamed from cAudio to cAudioSource. Added a global include file "cAudio.h" that will automatically include all the major headers in the engine. We also have a new web site, SourceForge project, and forums. Official Web Site: Official Forums: SourceForge Project: API Documentation: SVN Trunk: Windows (MSVC 2008 and Codeblocks) and Linux (Make and Codeblocks) SDK downloads are available. Get them here: Thank you for your time and we hope that cAudio is useful to you. Remember, you can always drop us a line at our forums to ask questions, report bugs, or discuss with other developers. 2 Crystal Space Development / General Crystal Space Discussion / cAudio 1.7.1 c++ Audio Engine on: May 20, 2009, 09:34:09 pm cAudio was created to be a good alternative to fmod,bass, and irrklang. Example code cAudio: Code: //Basic 2d audio #include <iostream> #include "../../include/IAudioManager.h" #include "../../include/IAudio.h" using namespace std; int main(int argc, char* argv[]) { cout <<"cAudio 1.7.1 Tutorial 1: 2DSound\n"; cAudio::IAudioManager* manager = cAudio::getAudioManager(); manager->init(argc,argv); cAudio::IAudio* mysound = manager->createFromFile("bling","../../bin/bling.ogg",true); mysound->play2d(true); while(mysound->playing()){ manager->update(); } manager->release(); manager->shutDown(); return 0; } The cAudio Engine is a c++ wrapper around openal to allow you to get sound and music into your games easily. current version 1.7.1 The main reason behind making cAudio was there wasn't a hole lot of choices for getting sound into your game. Basically there was audiere, fmod, bass, irrKlang,and SDL mixer. Also there was openal which cAudio is built on. The only problem with using openal is its. Special Thanks to Dark_Kilauea,KittyCat, Sudi, Rooly, and BloodInch Supports: ogg,wav Download at: Direct at: Features: * 2d Audio * 3d Audio * Pitch control * Directional control * Velocity control * Listener orientation control * Doppler control * Looping * Multiple streams * Load file into memory and play * Stream file * Play,pause,and stop controls * Easy to use Audio manager * Self contained *no longer need runtime installed* * Easy to extend License: zlib Fill free to ask any questions. There are currently binary builds for win32-gcc win32-visual and linux-x86 Pages: [ 1 ] | SMF © 2006-2007, Simple Machines LLC Page created in 7.411 seconds with 18 queries.
http://www.crystalspace3d.org/forum/index.php?action=profile;u=1162;sa=showPosts
CC-MAIN-2014-10
refinedweb
1,001
55.44
Why didn't anyone use this obvious variant? proc lambda {p b} { set name [list lambda $p $b] if {[info procs $name] eq ""} { proc $name $p $b } return $name } General lambda use cases work well: % [lambda {s1 s2} {puts "s1=$s1 s2=$s2"}] asd cvb s1=asd s2=cvb % set aaa [lambda {s1 s2} {puts "s1=$s1 s2=$s2"}] lambda {s1 s2} {puts "s1=$s1 s2=$s2"} % $aaa q w s1=q s2=w Something wrong? Personally I think the [apply] method that we now have in 8.5 is the way to go. Lambdas are after all merely values. So there is no reason to treat a lambda as anything other than a string until you want to use it as a function. So: # In tcl a lambda is simply a string: set aaa {{s1 s2} {puts "s1=$s1 s2=$s2"}} # Only when you want to use it does it need special treatment: apply $aaa q w..... ;-) > > See "If we had no proc" > > OTOH since variables are locally scoped writing tcl code in pure > lambdas is going to be annoying: > > set something {{} { > global do_something print ;# must "import" all lambdas before > using :-( > $do_something here > $print Done! No.. just say $::do_something, $::print. Or if you use [interp alias] like in the Wiki page mentioned, you have global names back :^) We WILL have ;) there's still no release. At least, I could use this lambda for backward compatibility. Tcl 8.4 is actual standard now. >..... ;-) Procs are compiled only once. And what about apply-lambda? No ;) There are arrays AFAIK they get their bytecodes cached in the internal rep, so they only get compiled once like procs. Michael Correct. Donal. There's no reason why you couldn't implement [apply] in 8.4. It's not a syntax extension, it's just a special kind of [eval]. Here's one possible implementation: proc apply {lambda args} { # Sanity check: if {[llength $lambda] != 2} { error "malformed lambda" } foreach {vars script} $lambda break # Process the args: if {[lindex $vars end] == "args"} { set vars [lrange $vars 0 end-1] set vals [lrange $args 0 [expr {[llength $vars]-1}]] set args [lrange $args [llength $vars] end] if {[llength $args] < [llength $vars]} { error "wrong # of args" } } else { set vals [lrange $args 0 [expr {[llength $vars]-1}]] if {[llength $args] != [llength $vars]} { error "wrong # of args" } } # Done preprocessing arguments, # now do the eval: eval [string map [list \ %VARS% $vars \ %VALS% $vals \ %ARGS% $args \ %SCRIPT% $script \ ] { if {[llength {%VARS%}]} { foreach {%VARS%} {%VALS%} break } %SCRIPT% }] } In fact, I don't see anything from the code above that requires Tcl version > 7.3. So in theory we could have had lambdas way back in Tcl 7. The problem is not that Tcl didn't (or doesn't) support lambdas. The problem is lack of imagination of how to implement lambdas in a tclish way. I don't know who's idea is it to implement [apply] but the paradigm shift of having a command to create lambdas to having a command that treats strings as lambdas is genius -- very tclish. Actually, the word "apply" is not needed. It is like using the word "CALL" for procedure invocation. In Tcl, the first word IS the proc name to be called. So why "apply"? Being the first word in line, lambda must be automatically called. Because the lambda is an anonymous proc - it has no name. As you said, the first word IS the proc name - so it can't be the lambda. One could do without - e.g. with some [unknown] trickery as shown above. But that's not very efficient.). You don't have to store lambdas in variables, you can also [interp alias] them: interp alias {} do_something {} apply {{..} {...}} Although, of course, if you are doing this then it is best to just use a regular named procedure. The most likely use of a lambda is when it is passed either to or from a procedure as an argument/return value, so no importing would be needed. -- Neil I would say, that tricks are very inefficient :) - hope they are not going to be common. Transparent lambda calls should have been built-in, not emulated. >). Well.. it is not just so simple. There are already several separate tables to search for command name: built-in commands, global procs, package procs, namespaces, aliases.. The interpreter just need to recognize the special form of lambda as a "command name". This will make happy everyone :) Moreover.. I hope, lambdas are not being compiled every time before execution. There must be some kind of cache. So, just one more table to lookup.. As for apply, it should accept ordinary proc names then. No. All of those things are commands. They are all found in a command table. -- | Don Porter Mathematical and Computational Sciences Division | | donald...@nist.gov Information Technology Laboratory | | NIST | |______________________________________________________________________| Indeed, best to avoid such tricks in production code. > Transparent lambda calls should have been built-in, not emulated. Why? Does it seriously pain you having to write [apply $fun a b] rather than just [$fun a b]? That seems to me like a fairly small matter of syntax for very little gain over what [apply] already provides. Especially when you consider that lambdas are typically used as callbacks, and callbacks are usually evaluated with either [eval] or [uplevel] which neatly allows you to avoid any problems. For example, did you realise that [apply] works nicely with pretty much every command in the Tcl and Tk libraries that takes a callback? # I always recommend using a constructor for lambdas: proc lambda {params body} { list apply [list $params $body] } lsort -command [lambda {a b} { ... }] $xs http::geturl $url -command [lambda tok { ... }] after 1000 [lambda {} { puts "Hello!" }] socket -server [lambda {sock addr port} { ... }] 8080 trace add variable foo write [lambda {v1 v2 op} { ... }] etc etc These all work fine, as do the great majority of callbacks in tcllib and other packages. Indeed, I can't think of a counter-example of the top of my head. So, what exactly isn't transparent about lambdas using [apply]? ... > The interpreter just need to recognize the special form of lambda as a > "command name". This will make happy everyone :) Such an idea was proposed and rejected at the time. [apply] works fine without any new special forms being introduced and is syntactically convenient for 95%+ of all use cases I can think of. > > Moreover.. I hope, lambdas are not being compiled every time before > execution. There must be some kind of cache. That is correct, the byte-code is cached. > So, just one more table to lookup.. The byte-code is cached directly in the lambda internal representation, so there is no table lookup (that I know of). If you feel there are performance problems with [apply] then supply some figures. -- Neil The worst thing is that lambda implementation proposed in 8.5 doesn't make lambdas look like ordinary procs. In every language that support lambdas, it doesn't matter whether a function has name or not. Reference to lambda is equal to named function reference in any use case. But what do we have in Tcl? If I store an ordinary proc "reference", it is called this way: % set XX puts % $XX 123 But if I store lambda, I have to KNOW that! % set XX {{x} {puts $x}} % $XX 123 ;# This will NOT work! % apply $XX 123 What's next? Suppose, "apply" will accept proc names. But I don't want to write dummy "apply" for every call. It's not Fortran! :) Sweet.. so the variable itself is marked as a lambda then? (this means that lambda is just a "type" of object.. like integers, strings, arrays and lists?) If so does [eval] do the same? Also, does it mean that the following doesn't get bytecompiled? : # lambda not stored in a variable: apply {{x y} {set x [expr {$y*$x}];puts $x}} 20 20 Okay, I have really overlooked this. This is handy. > The byte-code is cached directly in the lambda internal representation, > so there is no table lookup (that I know of). If you feel there are > performance problems with [apply] then supply some figures. This means that variable containing "{{a b} {return a+b}}" will be compiled (at first use? at assignment? - it doesn't matter) and cached.}} ;) And one more advantage. With apply, deep lambda call stack would have incomprehensible look - bunch of "apply"'s. On the contrary, if one had lambdas as commands, they would be visible on the stack. [info level] would remain usable as well. You are not "thinking in Tcl". The string "{{a b} {return a+b}}" is just a string. When [apply] encounters it, it interprets it as an anonymous proc and runs it. If you send it to eg [llength], it will be interpreted as a list. Values are just strings, commands may interpret them in different manners. An interesting exercise is to type at the prompt set set set and then ask: is "set" now a command? a variable? a variable's value? The only answer reasonable answer in Tcl is "yes" ... The fact that anonymous procs are bytecompiled (and the bytecodes are saved/cached) is just a performance hack. A variable cannot be compiled - its value can. Note that when you do set L0 {{a b} {return a+b}} set L1 $L0 {*}$L0 1 2 the value of L0 is now bytecompiled ... as is the value of L1, they are the same! >}} ;) Considered, rejected. If lambdas are command names you lose the automatic lifetime management ("garbage collection"), which is very important. Commands are long-lived, they exist and occupy memory as long as you do not delete them. These anonymous procs do not. You may find it interesting to read the tips in this area: and. > And one more advantage. With apply, deep lambda call stack would have > incomprehensible look - bunch of "apply"'s. On the contrary, if one > had lambdas as commands, they would be visible on the stack. [info > level] would remain usable as well. Would? Have you actually tried it? % proc showCaller {} {puts **[info level -1]; moo} % apply {args showCaller} can I see this? **apply {args showCaller} can I see this? invalid command name "moo" % set errorInfo invalid command name "moo" while executing "moo" (procedure "showCaller" line 1) invoked from within "showCaller" (lambda term "args showCaller" line 1) invoked from within "apply {args showCaller} can I see this?" If you have concrete suggestions as to how to make the call stack clearer or more useful, please file a bug or RFE. > But you propose to store "lambda {{a b} {return a+b}}" everywhere > which is NOT a lambda-expression. Therefore, it may not be compiled > and cached. > This wat, the lambda expression itself gets generated, assigned and > compiled upon each call! No - it's not stored, but "executed immediately". Take > > trace add variable foo write [lambda {v1 v2 op} { ... }] This is sugar-coated for > > trace add variable foo write [list {v1 v2 op} { ... }] and what gets stored is the two-element {argl body} list. This, when first [apply]ed, gets compiled, and on later calls just the bytecode is executed. Aargh!!! Serves me right for posting before breakfast ... Either of set L0 {{a b} {return a+b}} set L1 $L0 apply $L0 1 2 or set L0 [list apply {{a b} {return a+b}}] set L1 $L0 {*}$L0 1 2 An by the way: I am using your proposed body ... it returns the string "a+b" for any input. I do imagine you wanted {{a b} {expr $a+$b}}] which returns the sum. I wonder, if the bytecode is attached to the whole thing, or just to the body. If it's attached to the whole "{params} {body}" thing, then a simple [llength $function] would replace the bytecode-rep with the list-rep, and next time it's got to be recompiled. (otoh, why should someone treat the lambda as list? perhaps to check for a namespace? or use lindex as pendant to [info args/body]? not too likely to happen repeatedly enough to be an issue) If it's "compiled" to a list, only whose second item has the actual bytecode attached, then it could perhaps be recombined with a different parameter list, and result in unexpected behaviour ... Or is it done even differently (e.g. such that both list-information and lambda-information is maintained together? also the string-rep?) PS: I know, as a scripter I shouldn't care about these internals, but I'm just curious... Heh: the correct answer is RTFS, but you are so nice and polite about it ... what the hell. The whole [list $params $body ?$ns?] is converted to lambdaType. If you for instance request the llength, the type shimmers and the bytecompiled code is lost - it will be regenerated at the next usage. No, that will get byte-compiled. The bytecode is stored in the internal rep of the Tcl_Obj, not any particular variable. In other words, the Tcl_Obj used to represent {{x y} {set x ...}} gets a compiled proc stashed in its internal rep. This bytecode is generated the first time that value is passed to [apply] and then sticks around until someone messes with the internal rep. Note that originally, apply was going to take the arguments separately: [apply params body args...]. Miguel pointed out that the bytecode depends on both the script body *and* the parameter list, which is why they are now combined into a single argument, to give a handy place to stash the bytecode. -- Neil This isn't an artefact of lambdas, but rather that Tcl has a distinction between command and variable namespaces, and that it expects a command *name* not a command itself. Common Lisp is an example of another language which makes this distinction and also has this same problem: (defun adder (n) (lambda (x) (+ x n))) ((adder 1) 2) --> ERROR: illegal function call (funcall (adder 1) 2) --> 3 (apply (adder 1) '(2)) --> 3 Tcl's [apply] is roughly equivalent to CL's (funcall) or (apply). To get to something like Scheme or Haskell in Tcl, you could drop variables and use commands for everything: proc def {name = args} { interp alias {} $name {} {*}$args } def XX = puts XX "Hello, World!" def XX = apply {{x} {puts $x}} XX "Hello, World!" Although, of course you lose local variables! I also prefer the Scheme situation, but that's a bigger change to Tcl than just lambdas. -- Neil On the other hand, if you're combining with actual parameters then you are using the form: [list apply [list $params $body ?$ns?] $arg1 $arg2 ...] and in that case adding extra arguments to the outer list won't hurt. (It's the inner former-list that holds the bytecode inside it.) Donal. Not in Common Lisp or in any of the earlier Lisp dialects. 2-Lisps use (FUNCALL) to call procedure values. > But what do we have in Tcl? If Tcl is like Lisp at all, it's like a 2-Lisp. [apply] is Tcl's rough equivalent of Lisp's (FUNCALL). See also: You might prefer 1-Lisps (so do I), but Tcl just ain't like that, and it don't work that way. --Joe English
https://groups.google.com/g/comp.lang.tcl/c/NKxsvPrLx8I
CC-MAIN-2021-49
refinedweb
2,537
74.08
Train Networks Using Deep Network Designer The Deep Network Designer app lets you build and train deep neural networks. Deep Network Designer supports trainNetwork training using image data or datastore objects. You can also export your untrained network for training at the command line, for example, to train your network using custom training loops. To train a network, follow these steps: Create network Import data Select training options Train network Export network You can build a network interactively using Deep Network Designer, or import a network from the workspace. You can also select a pretrained network from the Deep Network Designer start page for transfer learning. For more information, see Build Networks with Deep Network Designer. To train a deep learning model, you must have a suitable network and training data. To import image data from a folder containing a subfolder of images for each class, or from an imageDatastore object, on the Data tab, click Import Data > Import Image Data. To import any datastore, on the Data tab, click Import Data > Import Datastore. After import, Deep Network Designer displays a preview of the imported data so that you can check that the data is as expected prior to training. For more information, see Import Data into Deep Network Designer. Select Training Options Once you have your network and data, the next step is to select the training options. On the Training tab, click Training Options. If you do not know which training options to use, try training with the default settings and then adjusting them to suit your network and data. For example, try adjusting the initial learning rate, or train for longer by increasing the number of epochs. For information about techniques for improving the accuracy of deep learning networks, see Deep Learning Tips and Tricks. For more information about the training options, see trainingOptions. Train Network After you select your training options, train the network by clicking Train. The Deep Network Designer app displays an animated plot of the training progress. The plot shows mini-batch loss and accuracy and additional information on the training progress. If you specified validation data, the plot also shows the validation loss and accuracy. The plot has a stop button in the top-right corner. Click the button to stop training and return the current state of the network. For more information on the training progress plot, see Monitor Deep Learning Training Progress. You can train a variety of networks using Deep Network Designer. For example, image classification or regression networks, sequence networks, numeric data networks, semantic segmentation networks, and image-to-image regression networks. In Deep Network Designer, you can train a network using the trainNetwork function on any data that you can express as a datastore object. The following examples show how to build and train a network using Deep Network Designer. Once training is complete, on the Training tab, click Export to export your trained network and results to the workspace. To save the training progress plot as an image, click Export Training Plot. You can learn how to build and train your network using command line functions by clicking Export > Generate Code for Training and examining the generated live script. Deep Network Designer does not support training using custom training loops.. Next Steps Once training is complete, click Export > Create Experiment to create a deep learning experiment in Experiment Manager. You can use Experiment Manager to sweep through a range of hyperparameter values or use Bayesian optimization to find optimal training options. For an example showing how to use Experiment Manager to tune the hyperparameters of a network trained in Deep Network Designer, see Generate Experiment Using Deep Network Designer. See Also Deep Network Designer | Experiment Manager
https://nl.mathworks.com/help/deeplearning/ug/train-networks-using-deep-network-designer.html
CC-MAIN-2022-21
refinedweb
620
54.12
Download presentation Presentation is loading. Please wait. Published byMontana Scriven Modified over 2 years ago 1 From risk to opportunity Lecture 11 John Hey and Carmen Pasca 2 Lecture 11 Implications of EUT Finding your (EU) utility function… … two different ways. Defining risk aversion and risk loving. Defining two indices of risk aversion. Some special utility functions with nice properties. Examples of its use in economics: 1.The theory of the competitive firm facing price uncertainty. 2.The life-cycle savings problem under income risk. 3 Lecture 11 Implications of EUT: Finding your (EU) utility function 1 Finding your utility function over [x, X]. Here we are using x to denote the lower bound and X the upper bound of the interval over which we are going to find your (EU) utility function. There are lots of ways to find it. Here is just one. Put u(x)=0 and u(X)=1. To find the utility value for some intermediate amount x i answer the question: “what probability u i in the gamble [X,u i ;x,(1-u i )] makes you indifferent between that gamble and x i ?”. It immediately follows that u(x i ) = u i. Repeat for lots of different values of x i. Example, put x= €0 and X= €100. Suppose you are risk-averse and you are indifferent between €50 and the gamble [€100,0.75; €0,0.25] then for you u(€50) = (Note EX=€75>€50.) 4 Lecture 11 Implications of EUT: Finding your (EU) utility function 2 Here is another way: interpolation. Suppose that you have already found x a and x b such that, for you, u(x a )=a and u(x b )=b. To find your utility value half-way in-between answer the question: “what amount of money x (a+b)/2 makes you indifferent between that amount and the gamble between x a and x b ; that is the gamble [x a,½;x b,½]?”. It immediately follows that u(x (a+b)/2 ) = (a+b)/2. Example, suppose a=0.5, x a =25; b=0.7, x b =49 and you are indifferent between €36 and a gamble between €25 and €49 then for you u(36) = 0.6. Note this latter gamble has expected value €37 – you are risk-averse (and your function is concave between €25 and €49). 5 Lecture 11 Implications of EUT: Certainty Equivalent For a given individual we define his or her certainty equivalent, CE, of some lottery/gamble as the amount of money, which, if received with certainty, the individual regards as the same as the lottery. So u(CE) = Eu(X) where X is the amount received in the lottery, CE denotes the Certainty Equivalent and where u(.) is the individual’s utility function. Example: lottery is 50:50 chance of €16 or €4. (Note that EX = 10.) Suppose u(x) = x 0.5. Then Eu(X) = 0.5u(16) + 0.5u(4) = 0.5(4)+0.5(2) = 3. And hence the CE is given by u(CE)=3. Hence CE = 9. 6 Lecture 11 Implications of EUT: Risk Premium For a given individual we define his or her risk premium, RP, for some lottery/gamble as the amount of money he or she would pay to convert the lottery into its expected value. So RP = EX – CE, where CE is the individual’s certainty equivalent for the gamble. Example: lottery is 50:50 chance of €16 or €4. (Note that EX = €10.) Suppose u(x) = x 0.5. Then Eu(X) = 0.5u(16) + 0.5u(4) = 0.5(4)+0.5(2) = 3. And hence the CE is given by u(CE)=3. That is CE = €9. And so the RP = 10 – 9 = 1; the individual would pay up to €1 to exchange the lottery for the certainty of €10. 7 Lecture 11 Implications of EUT: Risk aversion We define a risk-averse person as one who (always) prefers a certainty to a risk with the same expected value. So his or her certainty equivalent for some lottery is (always) less than the Expected Value of the lottery; the risk premium is always positive. This implies that his or her utility function is (everywhere) concave. Let us continue with the example where u(x) = √x = x 0.5 (concave) and where the lottery is a 50:50 chance of 16 or 4. What is the expected value of this lottery? 0.5(16) + 0.5(4) = 10. And the CE? 9. See the next slide. 8 Lecture 11 Implications of EUT: Concave utility Gamble pays €4 with probability ½ and €16 with probability ½. Expected Value is €10 Certainty equivalent is €9 because u(9) = 3 = ½ u(4) + ½ u(16) = EU(X) Risk Premium = €1 = €10 - €9 = EX- CE 9 Lecture 11 Implications of EUT: risk attitudes An individual is everywhere risk-averse (-neutral, -loving)… …if his or utility function is always concave (linear, convex) … if his or her certainty equivalent for some risk is always less than (equal to, more than) the expected value of the risk. … if he or she is always willing to pay a positive (a zero, a negative) amount to turn a risk into a certainty with the same expected value. The degree of concavity (convexity) indicates the degree of risk-aversion (loving). 10 Lecture 11 Implications of EUT: measuring risk attitude The degree of concavity indicates the degree of risk aversion. Concavity of a function is to do with its second derivative. But as the function is unique only up to a linear transformation, it has to be divided by the first derivative. Absolute risk aversion index = -u”(x)/u’(x) Relative risk aversion index = -xu”(x)/u’(x) 11 Lecture 11 Implications of EUT: CARA and CRRA For one who has Constant Absolute Risk Aversion: If we add some constant to all the outcomes of a gamble, the CE of that gamble rises by the same constant and hence the Risk Premium stays the same. From -u”(x)/u’(x) = r we get u(x) is proportional to –e -rx [unless r=0 in which case is proportional to x] If X is N(μ,σ 2 ) then Eu(X) proportional to –exp(-rμ+r 2 σ 2 /2). For one who has Constant Relative Risk Aversion: If we multiply by some constant to all the outcomes of a gamble, the CE of that gamble is multiplied by the same constant and hence the Risk Premium is multiplied by the same constant. From -xu”(x)/u’(x) = r we get u(x) is proportional to x 1-r [unless r=1 in which case is proportional to ln(x)] Note that the proportionality results from the fact that the utility function is unique only up to a linear transformation. 12 Lecture 11 Implications of EUT: the perfectly competitive firm Consider the perfectly competitive firm under output price uncertainty. p, the price, is risky with known density function. The cost function c(.) is known. The firm wants to maximise the Expected Utility of profits = π = px – c(x) by its choice of x, the output. Choose x to maximise Eu(π)=Eu[px – c(x)]. FOC is that E{u’(π)[p-c’(x)]} = 0. From this we can show c’(x) < Ep Firm produces less under risk. See Hey JD Uncertainty in Economics, Martin Robertson 1979 (now way out of print). 13 Lecture 11 Implications of EUT: life-cycle savings Life-cycle consumption/savings problem under income risk. Objective to maximise u(C 1 ) + ρu(C 2 ) + ρ 2 u(C 3 ) + … subject to W t+1 = R(Y t – C t + W t ) for all t. C, Y and W are consumption, income and wealth; ρ and R are the discount rate and the rate of return (1 plus the rate of interest). In general it can be shown that the optimal strategy is C* = a + b W, and that b=(R-1)/R So the marginal propensity to consume (out of wealth) depends only on the rate of interest/return. When the utility function is CARA, with r the index of absolute risk aversion and the distribution of income is N(μ,σ 2 ) it can also be shown (assuming r > 0) that a = μ – ½r(R-1)σ 2 –ln(Rρ)/[r(R-1] So the intercept of the consumption function depends positively on the mean of the income distribution and negatively on the variance; also if Rρ < 1 then increases in r and in R both lead to decreases in the intercept. Hey J D, “Optimal Consumption under Income Uncertainty”, Economic Letters, 5, 1980, 14 Lecture 11 Implications of EUT: Conclusions The great joy of EUT is its elegance and tractability. It is easy to find your (EU) utility function. It is concave (linear, convex) where you are risk- averse (-neutral, -loving). The degree of risk-aversion can be measured by the degree of concavity of the utility function (using either an absolute or a relative measure). CARA and CRRA are to useful special cases… … which lead to insightful results. 15 Lecture 11 Goodbye! 16 Lecture 11 Implications of EUT Similar presentations © 2017 SlidePlayer.com Inc.
http://slideplayer.com/slide/1372699/
CC-MAIN-2017-04
refinedweb
1,546
62.98
Artem Bityutskiy wrote: > On Sat, 2010-06-19 at 07:08 +0200, Lars-Peter Clausen wrote: >> diff --git a/include/linux/mtd/jz4740_nand.h >> b/include/linux/mtd/jz4740_nand.h >> new file mode 100644 >> index 0000000..379f9b6 >> --- /dev/null >> +++ b/include/linux/mtd/jz4740_nand.h >> @@ -0,0 +1,34 @@ >> +/* >> + * JZ4740 SoC NAND controller driver >> + * >> + * __JZ_NAND_H__ >> +#define __JZ_NAND_H__ >> + >> +#include <linux/mtd/nand.h> >> +#include <linux/mtd/partitions.h> >> + >> +struct jz_nand_platform_data { >> + int num_partitions; >> + struct mtd_partition *partitions; >> + >> + struct nand_ecclayout *ecc_layout; >> + >> + unsigned int busy_gpio; >> + >> + void (*ident_callback)(struct platform_device *, struct nand_chip *, >> + struct mtd_partition **, int *num_partitions); >> +}; >> + >> +#endif > > Do you really have to add your platform data strucutre to > "inlculde/mtd" ? That is quite global namespace, and ideally only things > like user-space interface and "public" interface of the MTD subsystem > should live there. > > Can you keep this somewhere in mips architecture directory? Hi Hm, ok, I see. I'll move it to arch/mips/include/asm/mach-jz4740/ then. But I guess I should move the headers for all the other jz4740 driver to the same directory as well. On the other hand I'm wondering where on would put headers for non platform specific drivers? - Lars
http://www.linux-mips.org/archives/linux-mips/2010-07/msg00058.html
CC-MAIN-2013-48
refinedweb
191
50.12
Arch IFC Description The Arch and BIM Workbenches feature an Industry Foundation Classes (IFC) importer and exporter. The IFC format is a continuously growing format to interchange data among BIM applications, used in architecture and engineering. Both the importer and exporter depend on the IfcOpenShell library, which is bundled in some distributions of FreeCAD. An easy way to check if IfcOpenShell is available is to enter the following in the Python console: import ifcopenshell If no error message appears, IfcOpenShell is installed, and you may proceed with importing IFC files. Otherwise, you will need to install IfcOpenShell yourself; read the IfcOpenShell page to learn more about this process. Note: the BIM Setup tool will look for IfcOpenShell too, and issue a notification if it is not installed. Note 2: in the past (2013) the Arch Workbench used to feature a simpler IFC importer that didn't depend on IfcOpenShell. This legacy module is still included in the source code but as of v0.19 it is not recommended at all; it will only be able to import a very small subset of IFC objects, and should be considered completely obsolete.. -
https://wiki.freecadweb.org/Arch_IFC/sv
CC-MAIN-2021-10
refinedweb
190
58.72
1570523569 With the problem of form context solved with Formik, developers are free to focus on the behaviour they are aiming to achieve from their forms. In this post, we’ll look at how we can build better React forms with Formik. Formik is a small library that helps you with the three major React form issues: By fixing all of the above, Formik keeps things organized, thereby making testing, refactoring and reasoning about your forms a breeze. We’ll look at how Formik helps developers build better React forms while handling those three issues. You can install Formik with NPM, Yarn or a good ol’ <script> via unpkg.com. $ npm install formik --save, Formik also has a global (“UMD”) build hosted on the unpkg.com CDN. Simply add the following script tag to the bottom of your HTML file: <script src=""></script> Let’s look at how Formik handles one of the major React form issues of passing values around in React forms. Consider an example where we have two input fields for email and password. We want to log the values of these fields to the console when the form is submitted. With the usual React form, we can create this form like so: import React, { Component } from 'react'; class App extends Component { constructor(){ super() this.state = { email: '', password: '' } this.handleEmailInput = this.handleEmailInput.bind(this) this.handlePasswordInput = this.handlePasswordInput.bind(this) this.logValues = this.logValues.bind(this) } logValues (){ console.log(this.state.email); console.log(this.state.password); }; handleEmailInput (e) { this.setState({ email: e.target.value }); }; handlePasswordInput (e) { this.setState({ password: e.target.value }); }; render() { return ( <form onSubmit={this.logValues} > <input type="email" onChange={this.handleEmailInput} value={this.state.email} <input type="password" onChange={this.handlePasswordInput} value={this.state.password} <button onClick={this.logValues}> Log Values </button> </form> ); } } export default App; Here, you’ll notice that we have a state object that manages the state of the form. We’ve also defined handlers to manage the state of the input fields, the values, the changes and so on. This is the conventional way of creating forms in React, so let’s skip all the explanations and get to the Formik part. With Formik, this could be better, even neater and, oh, done with less code. Now let’s try recreating this exact functionality with Formik: import React from 'react' import { withFormik, Form, Field } from 'formik' const App = ({ values, handleSubmit, }) => ( <Form> <Field type="email" name="email" placeholder="Email"/> <Field type="password" name="password" placeholder="Password"/> <button>Submit</button> </Form> ) const FormikApp = withFormik({ mapPropsToValues({ email, password}) { return { email: email || '', password: password || '', } }, handleSubmit(values){ console.log(values) } })(App) export default FormikApp; Did you notice how clean and simple it was to recreate the form with Formik? Yeah, you did. Now, let’s walk you through it. Here, we used withFormik() to create the FormikApp component. WithFormik takes in an option, which, according to Formik docs, is a list of objects that we can pass into the withFormik() method to define its behavior. In this case, we have passed in the mapPropsToValues({ }) option as a function which itself takes in the values of the input fields and passes them as props to our App component. In the App component we can access the values of all the input fields simply by destructuring it and passing in the Formik props called values, which is just an object with a bunch of key/value pairs. With Formik, we don’t have to define an onChange handler or even an onSubmit on the form, it all comes built-in. All we have to do is import the Form prop from Formik and destructure it in the App component. With that done, we can use it to create our form fields. Finally, with Formik, we don’t have to define a value in the input field. We simply import the Field prop provided by Formik and it saves us the stress of all those boilerplate codes. In React, there is no simple way to handle validation in forms as at this time. Don’t get me wrong, there are good ways — just not as simple as Formik makes it. If you have created a sign-up form before in React, you’ll understand that you had to write your own validation logic to make sure users comply to your standards. You probably had to write a lot of code to validate the email input field, password, number, date and even your own error messages. With Formik, we can use Yup to handle all that. It is so simple that you can implement standard validation in your input fields in less than 10 lines of code. That’s not all. It also allows you to define your custom error messages for every field condition you check. Continuing from our last Formik form example, let’s validate the email and password fields with Yup: import React from "react"; import { withFormik, Form, Field } from "formik"; import Yup from "yup"; const App = ({ values, handleSubmit, errors, touched }) => ( <Form> <div> {touched.email && errors.email && <p>{errors.email}</p>} <Field type="email" name="email" placeholder="Email" /> </div> <div> {touched.password && errors.password && <p>{errors.password}</p>} <Field type="password" name="password" placeholder="Password" /> </div> <button>Submit</button> </Form> ); const FormikApp = withFormik({ mapPropsToValues({ email, password }) { return { email: email || "", password: password || "" }; }, validationSchema: Yup.object().shape({ email: Yup.string().email().required(), password: Yup.string().min(6).required() }), handleSubmit(values) { console.log(values); } })(App); export default FormikApp; Here we have implemented validation and error reporting for both the email and password fields with the addition of about seven lines of code. How is this possible, you might ask? Well, let’s tell you how. In the FormikApp component, we passed in another option, validationSchema to withFormik({ }), which automatically handles all the validations for us. With the errors prop we just destructured in the App component props, we now have access to the validationSchema errors. As a result, we can define a text field above the input fields to show the validation error messages to the users. Finally, to be certain that the error messages appear only during submission (not when the user is typing), we used the touched prop. That way, we can conditionally check if a certain field has been touched. If it has, check if there are any errors; if there are, show the text when the field is submitted. So far, if you run this App and try submitting false values, this is the output you’ll get: That is all well and good, but what if we wanted to provide a custom error message for the individual validation checks? With Formik, we can do this by specifying the messages inside the validationSchema methods like this: validationSchema: Yup.object().shape({ email: Yup.string() .email("Invalid Email !!") .required("Email is required"), password: Yup.string() .min(6, "Password must be above 6 characters") .required("Password is required") }), At this point, the error messages will update appropriately with the contents that we have defined: Formik gives us the functionality to make asynchronous requests even on submission of the form. Sometimes we’ll want to check if the submitted email address already exists in the database, and if it does we report it to the user. Also, while the asynchronous request is running, we may want to dynamically disable the submit button until the execution completes. Formik provides us all this functionality and more. To further demonstrate this, let’s simulate a scene where, if an email address already exists, we’ll report an error to the user after the asynchronous request, which we have replaced with a timeout of two seconds. Then if the supplied email address doesn’t exist yet, we reset the form. To do this, we’ll pass in the necessary Formik props as the second argument to the handleSubmit handler in our FormikApp component like this: handleSubmit(values, {resetForm, setErrors, setSubmitting}) { setTimeout(() => { if (values.email === "john@doe.com") { setErrors({ email: 'Email already exists'}) } else { resetForm() } },2000) } Wonderful, now we can perform dynamic asynchronous operations while submitting forms. You may have noticed that we still have an unused argument setSubmitting, and you’re probably wondering why we have it there if we are not going to use it. Well, we are. We’ll use it to conditionally disable our submit button when a submission operation is running. All we need to do is access a prop that is passed to our App component called isSubmitting. As the name suggests, it is a Boolean. If we are submitting, the value is true so we can do something, and if we are not, it’s false, and we can do something else. const App = ({ values, handleSubmit, errors, touched, isSubmitting }) => ( <Form> <div> {touched.email && errors.email && <p>{errors.email}</p>} <Field type="email" name="email" placeholder="Email" /> </div> <div> {touched.password && errors.password && <p>{errors.password}</p>} <Field type="password" name="password" placeholder="Password" /> </div> <button disabled={isSubmitting}>Submit</button> </Form> ); Then in the handleSubmit handler, we just set setSubmitting to false: handleSubmit(values, {resetForm, setErrors, setSubmitting}) { setTimeout(() =>{ if (values.email === "john@doe.com") { setErrors({ email: 'Email already exists'}) } else { resetForm() } setSubmitting(false) },2000) } Now whenever a submit operation is running, the submit button is conditionally disabled until the asynchronous operation is done executing. This is Formik at the barest minimum. There are a ton of things you can do with Formik that we didn’t touch in this post. You can go ahead and find out more yourself in the documentation and see how you can optimize the React forms in your existing application or how to implement these amazing features in your subsequent React apps. Compared to the conventional way of creating forms in React, Formik is a must have. #reactjs #javascript 1570862424 Great article Shubham, Even the React official documentation site mentions Formic as one solution for creating forms in Creat. However I would highly recommend developers understand the concept of controlled components and uncontrolled components. I have taken a stab at it in one of my blog posts. 1571450697 Thanks 1598954760 A while ago I wrote an article about creating a contact form using React and PHP. Many people found it interesting. So, here I am writing an updated version of that article. Check out the article about creating a contact form with React and PHP: Hooks are a new addition in React and we are going to re-create the contact form using React Hooks. Same as the previous project. This tutorial is beginners friendly. You don’t have to be an expert in Javascript, React, or PHP but I won’t go into basic details like installing React and setting up the project. I assume you already have an up and running React project. We will focus on creating the component. If you have a component folder in your project please go ahead and create a ‘Form’ folder inside it. It is up to you to decide where the component should live. Once you created the folder let’s create the ‘index.js’ file. #react #reactphp #react-php-contac-form #contact-form #react-hook
https://morioh.com/p/5164782dfe67
CC-MAIN-2022-40
refinedweb
1,853
54.83
Activating Perl 6 syntax highlighting in Vim Modern versions of the Vim text editor ship with Perl 6 syntax highlighting, but automatically activating it is tricky because Perl 6 files can have ambiguous file extensions. It can get tiresome to correct the file type every time you open a Perl 6 file, so I’m going to show you a few tricks that I use to make Vim detect Perl 6 files automatically. Showing and setting the filetype in Vim First of all I want to make sure that syntax highlighting is turned on by default, so I add this option to my .vimrc: syntax on To edit your .vimrc just start Vim and enter this command :e $MYVIMRC. Save your changes with :w, and then reload your .vimrc with :so %. Now that I have syntax highlighting turned on, I need to know how set Vim’s file type to Perl 6 when I’m working with Perl 6 files. I can see the current file type by typing this command :set filetype?. To set the file type to Perl 6, I use this command :set filetype=perl6. The filetype keyword can be shortened to ft. In which case the last command becomes :set ft=perl6. Detecting Perl 6 files Now the challenge becomes correctly detecting when I’m working with Perl 6 files in Vim. Perl 6 scripts shouldn’t be a problem: Vim (not Vi) automatically parses the shebang line to determine the file type. However this fails when the script has an extension like .pl. Use the .pm6 file extension Vim will automatically use Perl 6 syntax highlighting if the file extension is .pm6. So when working with Perl 6 module files, it’s better to use this extension. This doesn’t help when I’m working on other people’s Perl 6 projects however. It also doesn’t help for test files, which do not have an equivalent Perl 6 file extension ( .t6 test files are ignored when installing Perl 6 modules). Use a modeline A modeline is a line of code in the text of the file which Vim reads and executes. So to activate Perl 6 syntax highlighting I just need to add this modeline to every Perl 6 file I work with: # vim: filetype=perl6 Take a look at the source code of JSON5::Tiny for a real-World example. To Perl 6 this code looks just like an ordinary comment, but Vim will use it to turn on Perl 6 syntax highlighting. The modeline can appear anywhere in the code, but it’s better to place it at the start or end of the file. Older versions of Vim (pre 7.3) and when Vim is run under root privileges, disable modelines as a security risk. Don’t run Vim as root! But if you have an older Vim, you can turn on modelines with :set modeline. As with filetype, modeline can be abbreviated to ml, so set ml works too. To activate modelines automatically, add this line to your .vimrc: set ml The downside of using modelines? First there is aforementioned security risk for older Vims. Also it feels impure to add editor directives to the code I’m working with, as not everyone uses Vim. These seem like minor issues though. Use a local vimrc Often different Open Source projects will have different coding conventions that I need to follow, so it can be helpful to use a local vimrc file to store these project-specific settings. This works for syntax highlighting too. In order to use local vimrc files, I add the following code to my .vimrc: if filereadable(".vimrc.local") so .vimrc.local endif This will check the current working directory for .vimrc.local file, and automatically execute it if it finds it. Warning this is a security risk - Vim will execute ANY instruction in a local vimrc, so I am very careful when working with projects that are not my own. Next I create a .vimrc.local file in the root project directory and add this auto command to it: au Bufnewfile,bufRead *.pm,*.t,*.pl set filetype=perl6 Now when I open or create any file with a Perl extension, Vim will set the syntax highlighting to Perl 6. I like this technique because it’s not intrusive: it doesn’t require any changes to the Perl 6 files themselves, so it works well on shared projects (I never check-in my local vimrc to the Git repo). Use code detection I can also have Vim try to detect Perl 6 code automatically. Two directives which would indicate we’re working with Perl 6 instead of Perl 5 code: the shebang line and the use v6; directive. To check for these, I’ll add a function to my .vimrc:() This function uses getline() to check the first line of the file to see if it looks like a Perl 6 shebang. This should work well for .pl scripts, but Perl 6 module files will not have a shebang, so the next part of the script checks the first 5 lines of the file for the use v6; directive. The last line of code is an auto command which will call the function anytime we open file with a Perl file extension. The main drawback of this technique is that not all Perl 6 code uses the use v6; directive, and so when working with module files, the code detection can fail. However the code detection could be improved to use more rules for detecting Perl 6 code such as class declarations. The vim-perl plugin has more sophisticated Perl 6 code detection rules. Complete .vimrc This .vimrc contains all the code shown above: syntax on "Recognize modeline # vim: filetype=perl6 set ml "check for a local vimrc if filereadable(".vimrc.local") so .vimrc.local endif "check for Perl 6 code() Conclusion So that’s it, four useful-but-imperfect techniques for detecting file types in Vim. I tend to use a combination of all four. This would be a nice problem not to have. I’d like the Perl 6 community to agree and encourage unambiguous file extensions like .pm6, .t6 and .pl6. Larry Wall called this “free advertising”. It’s also a simple way to make Perl 6 programmers more productive. Not every text editor is as customizable as Vim. This article was originally posted on PerlTricks.com.
https://www.perl.com/article/194/2015/9/22/Activating-Perl-6-syntax-highlighting-in-Vim/
CC-MAIN-2019-26
refinedweb
1,073
72.05
Despite monastic rules that forbid it, monk Keo Heng has smoked two packs a day for the last 10 years. "When we are stressed or bored, a cigarette is like a good friend that makes our brain clear," said Heng, 30, who lives at Wat Entagnean in Sihanoukville. But like a growing number of smokers, Heng realized that cigarettes gave him nothing and took quite a lot. They were eating away his money and his health - so he decided to quit. While tobacco use in Cambodia is still widespread, the number of quitters is on the rise, according to several surveys published recently. One of them, produced by the Adventist Development and Relief Agency, researched monasteries in Phnom Penh and four other provinces and found that 23 percent of the sangha had smoked cigarettes during the previous year, a sharp drop from the 36 percent they found in the same provinces in 2001. The survey results were presented during the second National Workshop on Buddhism and Tobacco Control, held in Phnom Penh May 10 and 11. Other statistics cited at the conference also showed progress for the anti-tobacco lobby. The percentage of male smokers aged 20 years or over fell from 59 percent in 1999 to 54 percent last year, according to a 2004 nationwide survey conducted by the National Institute of Statistics. The research found that the number of adult women who used tobacco products had also dropped 1 percent since 1999 to 6 percent in 2004. The results are encouraging, but health experts know there is still along way to go in reducing the negative effects of smoking in the Kingdom. About 80 percent of children under 13 years old are exposed to secondhand smoke from at least one regular smoker in the family, said Yel Daravuth, national program coordinator of the Tobacco Free Initiative at the World Health Organization (WHO). Daravuth said many people in rural areas believe that smoking homegrown tobacco will not damage their health as much as commercially produced cigarettes. "It is a big confusion," Daravuth said. As well as a gnawing away at smokers' health, cigarettes also take a bite from their pocketbook. The average monthly expenditure on tobacco products per household is 14,000 riel, or $69 million nationwide in 1999, according to one report from the WHO. That's enough to buy 274,304 tons of high quality rice, or build nearly 28,000 big wodden homes. Lim Thaipheang, director of the National Center for Health Promotion estimates that at least 20 cigarette companies operate in Cambodia and advertise in the media. "I am not in favor of the advertising, but we do not have the law to ban them," Thaipheang said. The law on tobacco control was drafted in 2001 and is now under consideration at the Council of Ministers, said Ung Phyrun, secretary of state at the Ministry of Health. He said when the law on tobacco control is approved, tobacco advertising will be banned, its sales near schools and health facilities prohibited, and the tax on its import increased. The World No Tobacco day will be held on May 31 with the theme 'Health Professionals and Tobacco Control'.
https://www.phnompenhpost.com/national/your-money-or-your-life-smokers-give-both
CC-MAIN-2018-34
refinedweb
531
55.68
This article focuses on setting up a continuous integration pipeline for a Django project, but the information here can be extended to other Python projects, too. Django is a Python framework that is described as the “web framework for perfectionists with deadlines.” It is considered a great tool for creating Minimal Viable Products (MVPs) because it is easy to set up an application with a database and to run tests. It delivers high quality code and has excellent documentation. These features also benefit your users because it promises the fast shipping of new features. Here are the steps we will take: - Create a Django app - Create tests for the app - Dockerize the app - Configure CircleCI - Run locally - Push to GitHub - Add a badge - Explore optimization with caching Prerequisites In order to go through this tutorial, you will need to have the following installed: Create a Django app Django Girls offers a great tutorial on the Django framework. We’ll start off with a blog application that is the result of completing the Django Girls tutorial and setup CircleCI for it. For the database, we’ll use a flat file: .sqlite. To get the blog app, clone this repo by typing this line into your terminal: git clone Then, enter the directory by running: cd django_girls_complete After I completed the tutorial from Django Girls, I made additional changes to the application’s codebase. Since these changes are not directly related to setting up CI for the project, I will just add links to the file changes in GitHub. The changes include: - Updating the templates in the blog/templates/blogdirectory and settings.py. - Adding a .gitignorefile. - Adding a .editorconfigfile. - Adding files to Dockerize the app. More on this later. To see the original, run: git checkout original To get the codebase after my changes, run: git checkout 1.1.0 From now on I will take us step by step through setting up our continuous integration pipeline. The folder structure of our app looks like this (I simply run tree from my terminal to get this): . ├── Dockerfile ├── LICENSE ├── README.md ├── blog │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── static │ │ └── css │ │ └── blog.css │ ├── templates │ │ └── blog │ │ ├── base.html │ │ ├── post_detail.html │ │ ├── post_edit.html │ │ └── post_list.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── docker-compose.yml ├── init.sh ├── manage.py ├── mysite │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── requirements.txt 7 directories, 26 files Creating tests for the app Our CI pipeline needs to have tests so that we can ensure that our automated build is A-Okay before any new commit is merged. Writing tests with Django is extensively documented here. First, replace the code in blog/tests.py with: from django.contrib.auth.models import User from django.test import TestCase from django.utils import timezone from .models import Post from .forms import PostForm class PostTestCase(TestCase): def setUp(self): self.user1 = User.objects.create_user(username="admin") Post.objects.create(author=self.user1, title="Test", text="We are testing this", created_date=timezone.now(), published_date=timezone.now()) def test_post_is_posted(self): """Posts are created""" post1 = Post.objects.get(title="Test") self.assertEqual(post1.text, "We are testing this") def test_valid_form_data(self): form = PostForm({ 'title': "Just testing", 'text': "Repeated tests make the app foul-proof", }) self.assertTrue(form.is_valid()) post1 = form.save(commit=False) post1.author = self.user1 post1.save() self.assertEqual(post1.title, "Just testing") self.assertEqual(post1.text, "Repeated tests make the app foul-proof") def test_blank_form_data(self): form = PostForm({}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { 'title': ['This field is required.'], 'text': ['This field is required.'], }) What we’ve added is a PostTestCase class extending from django.test.TestCase with four methods: - In the setUpmethod, defined as def setUp(self), we create one user, self.user, and a post by that user. - The test_post_is_postedmethod confirms that the text of the post titled Test is We are testing this. - The test_valid_form_datamethod confirms that the form saves correctly: a title and text is filled on the form to create a post, the post is saved, and its title and text confirmed to be correct. - The test_blank_form_datamethod confirms that the form will throw an error when neither title nor text is filled. Second, run the following command: python manage.py test Note: This command builds a test suite out of all of the test cases, extending TestCase in any file whose name begins with test and then runs that test suite. The tests are passing! A breath of fresh air. To start with the codebase after the tests have been added, run: git checkout tests Dockerize the app Next up is Dockerizing the app. What does that even mean? To Dockerize an app means to develop, deploy, and run an application in a container using Docker. This involves three key files: .dockerignorefile: A .dockerignorefile is to Docker what a .gitignorefile is to Git. The files and/or folders listed therein will be ignored in the Docker context and will not be found within a Docker image. See our .dockerignorefile here. Dockerfilefile: Defines the steps to create a Docker image. See our Dockerfilehere. docker-compose.ymlfile: Whether you are running one service or multiple services, Docker compose removes the need to type out a long docker runcommand and allows you to run one line, docker-compose up, to spin up containers in the context of the file. See our docker-compose.ymlfile here. I also added an initialization script to be used when running the Dockerfile. See our init.sh file here. CircleCI configuration For us to integrate CircelCI into our project, we need to add a configuration file for a Python app. Create a .circleci folder in the project’s root and add a config.yml file. Copy these lines into it: version: 2 jobs: build: docker: - image: circleci/python:3.6 steps: - checkout - restore_cache: key: deps1-{{ .Branch }}-{{ checksum "requirements.txt" }} - run: command: | python3 -m venv venv . venv/bin/activate pip install -r requirements.txt - save_cache: key: deps1-{{ .Branch }}-{{ checksum "requirements.txt" }} paths: - "venv" - run: name: Running tests command: | . venv/bin/activate python3 manage.py test - store_artifacts: path: test-reports/ destination: python_app If this is your very first time doing this, you’ll notice four steps that may not be apparent: checkout: This command fetches your source code over SSH to the configured path (the working directory, by default). restore_cache: This command restores a previously saved cache. save_cache: This command generates and saves a cache of a file, multiple files, or folders. In our case, we save a cache of the installed Python packages obtained after running pip install …. store_artifacts: This command stores logs, binaries, etc. so that they are accessible by the app in later runs. Running the CircleCI build locally I advocate that one installs the CircleCI CLI tool to run the build locally before pushing it to GitHub and running it on CircleCI. Running the build locally keeps you from having to commit code to your online repository to confirm that the build is passing. It quickens the development cycle. You can install the CLI using Homebrew by running: brew install circleci Then, start by running the circleci switch command: You then run circleci config validate to validate that your config file is written correctly and circleci build to build the app: The output from the commands concludes with Success! The local build ran successfully. With this check, we can now push the code to GitHub. To start with the codebase after the tests have been added, run: git checkout circleci Pushing to GitHub All we need now is to connect CircleCI to our code on GitHub and we will have the CI pipeline working like a charm: push code change, run test, merge if passing. Open GitHub in your browser and create a new repository. If you don’t have a GitHub account, you can create one here. After creating your repo, type these lines into your terminal: git remote set-url origin git push -u origin master Then, log into CircleCI to view the dashboard. If you don’t have an account, you can sign up for a free one here. On your dashboard page, click Add Projects and then click on the project name you are using. In my case, the name is django_girls_complete. Notice the defaults that CircleCI sets for you: - Linux OS - Python Language Since we already have a config file, click on Start Building to run the job: A successful run will look like this: There you have it! That’s how to set up CI for Django projects. Type this into your terminal to run the application: docker compose up The app will be live at <0.0.0.0:8000>. Adding a badge You can have a number of integrations within your codebase. Having badges in your README is a best-practice that allows you to show others how the state of these integration services stand. It help others by letting them know how the state of these services stand. To get your badge, navigate to:<Username>/<Project>/edit#badges. In my case it is:. Click the cog icon next to the name of the project: Then, in the side menu, click Status Badges: Copy the embedded code: And, finally, paste it into your README, preferably close to the top, after the brief introduction of the repository. From the README, you’ll be able to see the build status of the most recent job in the default branch. Exploring caching In the screenshot showing the local CircleCI CLI run, you may have noticed the text in red: Error: Skipping cache - error checking storage: not supported. Cache is not supported when running the CircleCI build locally. For a CircleI job (a single run of the commands in a config file) to be faster, caching is implemented. More on this here. In our setup, we included steps for caching. For our learning, I ran the CircleCI job with and without caching to show us the advantage. Observe: Starting from the lowest build, the extreme right tells us the time it took to run the job: 00:11 (11 seconds), 7 seconds, and so forth. Caching is beneficial for us in overlooking the pip install -r requirements.txt command if the requirements.txt file is not modified. Of course, the first job just sets up the cache. It is no wonder that it took 11 seconds. We can assume that consecutive commits to GitHub without changing the requirements.txt file will run in the range of 7 seconds. In the third job, I removed caching, and the time got returned to the range of the first: 11 seconds. On the fourth run, I restored caching resulting in a 20 second run. Finally, a rerun of that same job lasted 7 seconds, taking advantage of the cache again. The seconds here might seem few and insignificant but with scale, the lost seconds can turn to minutes, even hours. Conclusion If you have followed the above instructions, you are well on your way of mastering continuous integration for your Django project(s). We started by creating a Django app and writing tests for it. Then we Dockerized the app so that we could build it in an isolated container. Doing this is beneficial because it results in only one dependency needed to run the app on any machine: Docker. The other dependencies for the app are all installed in the Docker container. We then went ahead and covered some best-practices in using CircleCI: - Running the CI build locally with the CircleCI CLI - Adding a badge and - Utilizing caching for even faster builds. About Stanley: From a young age, Stanley tinkered with electronics and building things with tech. Now, he’s an engineer at Andela and his work involves data, ML, and IoT. Stemming from his lifelong love of DIY, he’s on a personal journey of invoking the builder within and teaching others along the way. He cares about how technology affects society and seeks collaborations with others who are working to create positive impact.
https://circleci.com/blog/continuous-integration-for-django-projects/
CC-MAIN-2020-05
refinedweb
2,014
65.42
Please help us make the Marketplace better! Take the survey This is a console app-based project template to help you demonstrate how the standard query operators of the Language Integrated Query, LInQ work during your classes, courses or demos. When creating the project template I had three goals in mind: In order to realize these goals, basic console-app template is extended with a simple data model, a data repository and some extension methods. After you install the extension, you'll find a new project template in Visual Studio: The data model is based on the late-and-great Northwind database, or at least parts of it. You can find the elements of the data model inside the Model folder of the project. The Product class represents a product that you can buy at a store. The Category class represents a product category; basically a product group (e.g. "Books", "Drinks"). Note that everything is wired together by reference and there is exactly one of each object in the data source, no matter whether you access it directly from the data source, from the Category property of a Product or from the Products property of a Category. This is an important piece of information when discussing operators that do equality comparison, like the set operators, joins or GroupBy(). Note that both classes have their ToString() method overridden to return the value of their Name property. Note that the namespace of the model classes, Model is already referenced in Program.cs. If you add other files, you have to add the reference to the namespace yourself. Instances of the model classes are available through the static DataRepository class in the DataSource folder. The class has two static properties: The properties are instantiated and populated in the static constructor of the class. The data for the properties come from the two XML files in the DataSource folder, which were exported from the Northwind database using the DataContractSerializer. Please make sure to make your students aware that the static class and static properties are only used here for the sake of simplicity and this is by no means a best practice to implement data sources. Note that the properties are actually of type List at runtime. Note that the namespace of the DataRepository class, DataSource is already referenced in Program.cs. If you add other files, you have to add the reference to the namespace yourself. In order to visualize the results of queries, an extension method called Dump() was implemented to the IEnumerable type. The Dump() method has the following capabilities: Note that the namespace of the class of the extension method, Extensions is already referenced in Program.cs. If you add other files, you have to add the reference to the namespace yourself. Please make sure to discuss with your students how LInQ query evaluation works and the inner implementation of Dump() triggers query evaluation. ##Licensing and terms, contribution and other materials You are welcome to use this extension during your presentations, classes or courses with the limitations of the MIT license (which is not that much :) ). But use it at your own risk :) and always test your demos beforehand (especially in the case of Dump() which was not tested extensively). If you have ideas, requests or comments, visit the Github page of the extension. For other teaching aids and materials, check out my blog.
https://marketplace.visualstudio.com/items?itemName=CONWID.LinqStandardQueryOperatorsTemplateExtension
CC-MAIN-2021-49
refinedweb
565
50.57
User handling is a fundamental part of a ton of web projects. This post will walk through how to customize Friends of Symfony (FOS) User attributes and forms in a Symfony 3 project. By default FOS Users only have username, email, and password attributes. If you want to add more information like an address or phone number to your users there are several steps you’ll need to take which are described here. The FOS User bundle also comes with some handy forms for user registration, login, and profile editing. These forms do not contain any styling information, and will not automatically incorporate any custom attributes you add to the User entity. How to overcome these obstacles is also detailed here. Assumptions This post will assume you have already set up some things: - LEMP or equivalent development environment with - global install of Composer - Symfony 3 Project with FOS user bundle installed and setup Expanding the User Entity Open up src/AppBundle/Entity/User.php. The @ORM annotations tell Symfony’s default ORM, Doctrine, how to update the schema the database is built from. Define a new class attribute, phoneNumber, including @ORM annotations to inform the database schema. Add Validator/Constraints to the use statements to define form validation using annotations as well. Symfony validation groups allow different subsets of attributes in a class to be validated by passing the name of a group as an option to the form validator. Only attributes in the group passed to the validator will have their validation assertions checked. The FOS User we’re extending has placed attributes into the validation groups: Registration, Profile, ResetPassword, and ChangePassword. Only the password fields need to be validated when resetting or changing the password, so phoneNumber is only assigned to the Registration and Profile validation groups. Create Getters and Setters Later when creating and updating Users, you will need to be able to access the phoneNumber attribute and any others we create in future. The User class will need public methods called “getters and setters”. These methods are easy enough to type out, but it can become tedious and many IDEs will have a built in way to generate them. For example, in PHPStorm you would place your cursor in your User class after the __construct method, then from the Code menu select Generate, and then choose “Getters and Setters” from the menu that appears. This is what your getter and setter will look like for the phoneNumber attribute: Update the Schema: Using the mysql shell, SequelPro, PHPMyAdmin, or another database interface of your choice, you can visually confirm that the fos_user table in your project database now contains a phone_number column. Update User Forms The User class has been expanded, but the registration form, edit profile form, and the view profile page will not include our new phoneNumber attribute without some additional work. Create New Form Types In the src/AppBundle directory, create a new folder named Form. Create two new php files in your new directory: RegistrationType.php and ProfileType.php containing a RegistrationType class and ProfileType class respectively. Both of these new classes will be in the AppBundle namespace, extend AbstractType, and implement the methods: buildForm(), getParent(), and getBlockPrefix(). Here’s what your RegistrationType will look like when complete: Notice how it adds phoneNumber to the FormBuilderInterface instance in buildForm(). ProfileType will be almost the same, except the class name will change, getParent() will return FOSUserBundleFormTypeProfileFormType, and getBlockPrefix() will return app_user_profile. Update Config To make use of the new form types you will need to add information on them to your configuration files. Add the following under “services:” in app/config/services.yml: In app/config/config.yml you’ll need to add registration and profile config to the end of your existing fos_user config. Once added, the whole fos_user config should look like this: Override Templates You’ve added the new phoneNumber attribute to the registration and edit profile forms, but it still will not appear when viewing a user’s profile. Additionally, all the FOS User bundle forms are completely unstyled and thus are not ready to mesh with the rest of the project. These issues are fixable using Symfony’s handy bundle template overriding and Twig template inheritance. Create a base template. Open up app/Resources/views/base.html.twig – the default base template for your project. The blocks defined in this template can be overridden by other twig files which extend this one, so this is a great place to put things like styles and javascript that you want to be universal to all pages in your project. Add some content to the stylesheets block: This brings in some basic style options from bootstrap and adds one small custom class style for use later. Add some content to the javascripts block. This brings in some bootstrap javascript that works with bootstrap styles: Now these styling options will be available in any twig template which starts with: To add styles to forms automatically, open app/config/config.yml and add the form_themes option to the existing twig config: Create overriding templates directory structure. Incorporating third party bundles into a Symfony project is a great way to add functionality without reinventing the wheel. Visually, it’s still important for a project to present as a cohesive set of pages, and not a hodge podge of stitched together components. This can be accomplished by leveraging Symfony’s option to override bundle templates. To override any or all of a bundle’s templates in Symfony, create a directory inside your project’s app/Resources directory with the same name as the bundle’s main classname. If any files and folders inside the new directory match those in the bundle’s Resources directory, the new files will be used instead of the bundle’s version. So that you can modify the existing FOS User bundle template content rather than starting from scratch, create the following directories and copy the FOS User bundle templates ( vendor/friendsofsymfony/user-bundle/Resources/views) we want to modify into them: create app/Resources/FOSUserBundle/views - place a copy of layout.html.twig into the new directory create app/Resources/FOSUserBundle/views/Profile - place a copy of Profile/edit.html.twig into the new directory - place a copy of Profile/show.html.twig into the new directory - place a copy of Profile/show_content.html.twig into the new directory create app/Resources/FOSUserBundle/views/Registration - place a copy of Registration/register.html.twig into the new directory create app/Resources/FOSUserBundle/views/Security - place a copy of Security/login.html.twig into the new directory Once the targeted vendor files have been copied into the new folders, your directory structure will look like this: Merge the base and layout templates. From app/Resources open up the base project template, views/base.html.twig, and the base FOS User template, FOSUserBundle/views/layout.html.twig. There are several pieces of layout.html.twig that we might want to have throughout our site. Moving them into base.html.twig accomplishes this. FOS User bundle’s layout includes conditional authentication text and links at the top of each FOS User bundle page. To make that content part of every project page, just inside base.html.twig’s body block, create a navbar component that contains the conditional login / logout options and greeting: Then remove that content from layout.html.twig After the new navbar, create a div with the “jumbotron” class you customized earlier. Inside the new div, add new “name” and “content” Twig blocks. Between those tags, copy in the messaging content from layout.html.twig Delete that messaging content from layout.html.twig Now that the dynamic content from layout.html.twig has been moved into the project’s base template, all it needs to do is extend that base template and state where to place the fos_user_content block. After all the other content has been removed, your template will look like this: Update the Profile Symfony’s Twig templates allow for multi level inheritance. Use this to create a profile.html.twig which fills in the name block we created earlier: Open up Profile/edit.html.twig and Profile/show.html.twig and update them, replacing the current extends tags with: {% extends "@FOSUser/Profile/profile.html.twig" %} Open up Profile/show_content.html.twig and add a line to display the new phoneNumber: Registration and Security Open up Registration/register.html.twig and Security/login.html.twig Add and fill in the name block for each. Add a link under their included content so that a user can easily switch between the register and login forms. The final register.html.twig will look something like: The final login.html.twig will look something like: Success! Congratulations, you now have a functional, if content-free, Symfony 3 application! Check out the registration process and navbar access to login, logout, and edit profile: Now you have custom Users! Above we expanded FOS User bundle User and forms, created a simple universal style for the project, then overrode FOS User templates to modify their content and look to match. Using the same techniques you practiced here, you will be able to add attributes to FOS User bundle Users to suit your project’s needs, and incorporate FOS User forms and pages into any Twig templated project. Are you building something awesome for users with Symfony? Have suggestions for Symfony howtos you’d like to see? I want to hear about it! - Twitter: @dead_lugosi - Github: mstaples
https://www.twilio.com/blog/2017/09/symfony-3-and-fos-user-bundle-customizing-users.html
CC-MAIN-2018-05
refinedweb
1,590
55.13
<stdio.h> int main (){ for (int i = 1; i <= 5; i++){ printf("%i\n", i); } return 0; } 1 2 3 4 5 Multiple initializations, condition checks and loop counter updates can be performed in a single for loop. Please see the below example. #include <stdio.h> int main (){ for (int i = 1, j = 100; i <= 5 || j <= 800; i++, j = j + 100){ printf("i=%i, j=%i\n",i,j); } return 0; } i=1, j=100 i=2, j=200 i=3, j=300 i=4, j=400 i=5, j=500 i=6, j=600 i=7, j=700 i=8, j=800
https://www.alphacodingskills.com/c/c-for-loop.php
CC-MAIN-2019-51
refinedweb
104
78.93
Allows you to interface Python and zepto crudely Project description pyzepto A crude way of interfacing zepto and Python. Installation pip install pyzepto Usage I really advise against using it. It’s amazingly crude. But if you really want to do this, it’s relatively straight-forward. The main function that is exposed by this package is zepto. It takes a string of zepto code and evaluates it, returning the return value as a string. from pyzepto import zepto zepto("(+ 1 2 3)") # => "6" zepto("(make-byte-vector 10 0)") # => "b{0 0 0 0 0 0 0 0 0 0}" I also implemented a custom module loader for your convenience, so you can import zepto files into Python using regular import statements. What could possibly go wrong?
https://pypi.org/project/pyzepto/
CC-MAIN-2020-10
refinedweb
128
56.15
Hey issue in my project in displaying time in the correct format on the required time zone. Handling date/time when dealing with time-zones is a tedious task. As a developer, getting date from server then converting, comparing and displaying date and time might get tricky on front-end side. So the best solution for this is use of a library called – Moment.js Moment.js is a Javascript library for parsing, validating, manipulating, formatting and displaying dates and times. It’s easy documentation also makes it the first choice for the developers. Integrate moment.js with Angular INSTALL npm install moment –save # npm yarn add moment # Yarn Install-Package Moment.js # NuGet spm install moment –save # spm meteor add momentjs:moment # meteor IMPORT (in the component app.component.ts and in the component to be used) import * as moment from ‘moment’; Now you can now use Moment.js in your entire Angular app, as long as you import it into the component in which you plan to use it Here I will show how to get local time if you have a utc date time string. Lets say you have a UTC date-time string as 2014-02-19 05:24:32 AM and you want to convert utc time to local time then use following : utcDateTime: any; this.utcDateTime =“19 June 2011 13:23 “; let local_date = moment.utc(this.utcDateTime).local().format(‘YYYY-MM-DD HH:mm:ss a’); Output: 2011-06-19 18:53:00 pm let local_date = moment.utc(this.utcDateTime).local().format(‘MMMM DD, LT’); Output: June 19, 6:53 PM There are multiple manipulation’s and formats under moment.js which can be referred to it’s documentation at this link . we will discuss it’s detailed features further … 4 thoughts on “Manipulating Server returned dates at client Side in Angular” Hi Kritika, if you are using moment.js just only for converting UTC time to client-side timezone, then it is really not required you can convert between them without using this (moment.js), it will even make your application heavy Hi @sourabh , Thanks for your time , and FYI we are not just using it for conversion but for various human friendly formats and few manipulations too, it is just to demonstrate on this post we are showing the integration and conversion part of moment.js as it supports i18n (internationalization) and l10n (localization) so is best for conversion, also i’ll surely discuss it’s bundle of available options in futher posts. @kritika that’s fine, we can have a 1to1 discussion for this Reblogged this on sangeetagulia.
https://blog.knoldus.com/manipulating-server-returned-dates-at-client-side-in-angular/
CC-MAIN-2018-34
refinedweb
437
51.89
Contents Up until now, our entire Flask application mainly resides in a single file main2.py. That’s fine for small applications, but as the project grows it becomes difficult to manage. When we break a monolithic file into multiple files, the code in it becomes more maintainable and predictable. Flask doesn’t impose any restrictions on how you should structure the application. However, it does provides some guidelines to make the application modular. In this course, we will use the following application structure. Here is the rundown of what each file and folder does: In the rest of the lesson, we will convert our project to conform to this directory structure. We will start by creating config.py. Class-Based Configurations A software project usually runs in three different environments: - Development. - Testing. - Production. As the project evolves you will encounter a need to specify different configuration options for different environment. You will also notice that no matter which environment you are in some configurations always remains the same. We can implement such a configuration system using classes. Start off by defining default configurations in the base class and then create environment-specific classes which inherit from the base class. The environment-specific classes can override or add environment-specific configurations. Create a new file named config.py inside flask_app directory and add the following code in it: flask_app/config.py Note that for the first time we are reading values of some configurations from the environment variables. We are also providing default values in case environment variables are not set. This method is particularly useful when you have some sensitive data that you don’t want to hardcode in the application itself. To read configurations from a class use from_object() method as follows: Creating Application Package Create a new directory app directory inside the flask_app directory and move all files and directories to this directory ( except env and migrations directories and our newly created config.py file ). Inside the app directory create __init__.py file with the following code: flask_app/app/__init__.py The __init__.py creates the application instance and initializes extensions. If FLASK_ENV environment variable is not set the Flask application will run in the debug mode ( i.e app.debug = True ). To put the application in production mode set the FLASK_ENV environment variable to config.ProductionConfig. After initializing extensions, the import statement in line 21, imports all the views. This is necessary to connect the application instance to the view functions, otherwise, Flask will not be aware of your view functions. Rename main2.py file to views.py and update it so that it only contains routes and view functions. Here is the complete code of updated views.py file. flask_app/app/views.py The views.py file now only contains view functions. We have moved the code for models, form classes and utility functions to their respective files, as follows: flask_app/app/models.py flask_app/app/forms.py flask_app/app/utils.py Finally, to launch the application add the following code to runner.py file: flask_app/runner.py The runner.py is the entry point of our project. The file starts by creating an instance of Manager() object. It then defines make_shell_context() function. The objects returned by make_shell_context() function will be available inside the shell without explicit import statements. At last, the run() method on the Manager instance is called to start the server. Import Flow We have created quite a few files in this lesson and it is very easy to lose track of which file does what and the order in which files are executed. To make things clear this section explains shows how everything works together. Things start with the execution of runner.py file. The second line of runner.py file imports app and db from the app package. When Python interpreter encounters this line, program control transfers to __init__.py to start its execution. In line 7, __init__.py imports the config module which transfers the program control to config.py. When the execution of config.py completes the program control again comes back to __init__.py. In line 21, __init__.py file imports views module which transfers the program control to views.py. The first line of views.py again imports application instance app from the app package. The application instance app is already in the memory so it will not be imported again. In line 4, 5 and 6, views.py imports models, forms and send_mail function respectively which transfers the program control temporarily to their respective files in turn. When the execution of views.py finishes the program control comes back to __init__.py. This completes the execution of __init__.py. The program control comes back to runner.py and starts the execution of the statement in line 3. The third line of runner.py imports the classes defined in the models.py module. Since models are already available from views.py, the models.py file will not be executed again. Since we are running runner.py as the main module, the condition in line 17 evaluates to True and manager.run() starts the application. Running Project We are now ready to run our project. In the terminal enter the following command to start the server. If FLASK_ENV environment variable is not set, the preceding command will start the application in the debug mode. Navigate to and you should see the home page which currently looks like this: Browse the remaining pages of the application to make sure everything is working as expected. Our application is now very flexible. It can pick up a completely different set of configurations just by reading an environment variable. For example, let’s say we want to put our site in production mode. To do so, simply create an environment variable FLASK_ENV with the value config.ProductionConfig. In the terminal, enter the following command to create FLASK_ENV environment variable: This command creates an environment variable in Linux and Mac OS. Window user can use the following command: Run the application again. Now our application is running in production mode. At this point, if Python code raises an exception you will see a 500 Internal Server Error instead of a stack trace. Because we are still in development, we have to delete FLASK_ENV environment variable. The FLASK_ENV will be deleted automatically as soon as you close the terminal. To manually delete it enter the following command: Window users can use this command: Our project is in much better shape. Now things are organized in a much more predictable way than it was possible before. The technique devised here is useful for small to medium-sized projects. However, Flask has some more tricks under its sleeve which can help you to become more productive. Blueprints Blueprints are yet another way to organize the application. Blueprints provide separation of concerns at the level of views. Just like a Flask application, a Blueprint can have its own views, static files, and templates. We can also map blueprints with their own URIs. For example, let’s say we are working on a blog and its admin panel. A blueprint for a blog would contain view function, templates and static assets specific to the blog only. Whereas the blueprint for admin panel would contain views, static files, and templates specific to the admin panel. Blueprints can be implemented either by using a module or a package. It’s time to add a blueprint to our project. Creating Blueprint Create an directory named main inside the flask_app/app directory and move views.py and forms.py to this directory. Inside the main directory create __init__.py file with the following code: flask_app/app/main/__init__.py We are creating blueprint object using the Blueprint class. The Blueprint() constructor takes two arguments, the blueprint name and the name of the package where blueprint is located; for most applications passing __name__ to it will suffice. By default, views functions in the blueprint will look for templates and static assets in the application’s templates and static directories respectively. We can change that by specifying the location of templates and static assets while creating Blueprint object as follows: In this case, Flask will look for templates and static assets in the templates_dir and static_dir directories inside the blueprint package. The template path added by a blueprint has lower priority than the application’s templates directory. That means if you have two templates of the same name in templates_dir and templates directories, Flask will use the template from the templates directory. The following are some noteworthy points to remember about the blueprints: 1. When using blueprints the routes are defined using the route decorator of the blueprint object rather than the application instance ( app ). 2. To create URLs when using blueprints you have to prefix the endpoint with the name of the blueprint and a dot ( .). This is true whether you are creating URLs in the Python code or in templates. For example: This will return the URL of the index route of the main blueprint. The name of the blueprint can be omitted, in case you are in the same blueprint that you want to create URL for. For example: This will return the URL of the index route of the main blueprint assuming you are in the view function or template of the main blueprint. To accommodate the changes we have to we have to update import statements, url_for() calls and routes in views.py file. Here is the updated version of views.py file. flask_app/app/main/views.py Notice that throughout the views.py file, we are creating URLs without specifying the blueprint name because we are inside the same blueprint for which we are creating URL for. Also update the url_for() call in admin.html as follows: flask_app/app/templates/admin.html The view functions in views.py are now associated with the main blueprint. Next, we have to register the blueprint on the Flask application. Open app/__init__.py and modify it as follows: (changes are highlighted): flask_app/app/__init__.py The register_blueprint() method of the application instance is used to register blueprint. We can register multiple blueprints by calling register_blueprint() for each blueprint. Notice that in line 11, we are assigning main.login to the login_manager.login_view. In this case, it is necessary to specify the blueprint name otherwise Flask wouldn’t be able to tell which blueprint you are referring to. At this point, the application structure should look like this: The Application Factory We are already using packages and blueprints in our application. We can further improve our app by delegating the task of instantiating application instance to the Application Factory. Application Factory is simply a function which creates an object. So what do we get by doing this: - It makes testing easier because we can create application instance with different settings. - We can run multiple instances of the same application in the same process. This is handy when you have load balancers distributing traffic across different servers. Let’s update app/__init__.py to implement an application factory as follows (changes are highlighted): flask_app/app/__init__.py We have delegated the task of creating application instance to the create_app() function. The create_app() function takes a single argument named config and returns an application instance. Application factory separates the instantiation of the extensions from their configurations. The instantiation occurs before create_app() is called and configuration occurs inside the create_app() function using the init_app() method. Next, update runner.py to use applicaton factory as follows: flask_app/runner.py It is important to note that when using application factories, we no longer have access to the application instance in the blueprint at the import time. To access application inside a blueprint use current_app proxy from the flask package. Let’s update our project to use current_app variable as follows: flask_app/app/main/views.py flask_app/app/utils.py Now you should have a have a solid understanding of Flask, its different components and how everything fits together. Believe it or not, we have explored quite a lot. In the next part of this course, we will use what we have learned to create a Delicious clone named Flask-Marks. Delicious is a social bookmarking site launched in 2003. In 2017, it was acquired by Pinboard and since then it is running in read-only mode. Flip the page and let’s get started. 3 thoughts on “Application Structure and Blueprint in Flask” Hi, Thanks for sharing this. can you please explain line 2 in file flask_app/app/main/views.py. How the import works here? And how can I test it tat this line works? Please let me know In line 2 . represent current directory. Please help. I’m having trouble with Blueprints static folder on a site that has one main domain with two sub-domains. The sub-domain static_folder defaults to the main. How would I setup the sub-domains to use their own static folder?
https://overiq.com/flask-101/application-structure-and-blueprint-in-flask/
CC-MAIN-2019-35
refinedweb
2,173
58.89
A Simple Machine Learning Implementation to Predict Linear Algebra in Python This article was published as a part of the Data Science Blogathon. Machine learning is used to solve the problem in which the rules to get the desired output are too hard (almost impossible) to mapped manually by a human. So, instead of giving the rules to a computer, we feed the desired output and let the computer learn (guess) the pattern to figure out the rules by itself. In this article, we will create a simple machine learning implementation in Python using the TensorFlow library. The real-world problems are more complex than this and require advanced-level algorithms to derive better and crisp insights from data. Check out our Certified AI & ML BlackBelt Accelerate program. The model we will build expected to be able to find this formula: y = 2x + 4 We will not write that formula into the program. Instead, we will give several input samples (x), and outputs from the given input. Creating the model architecture This is the model architecture we want to build. It’s a very simple model. and this is how it looks in the code: import tensorflow as tf model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(units=1, input_shape=[1])) model.compile(optimizer='sgd', loss='mean_squared_error') The input_shape argument defines the number of input neurons and the units argument defines the number of output neurons. The loss argument is to define the loss function. The loss function is a function to measure how bad our current output compared to the target output. We also define the optimizer for our model. The optimizer is the algorithm that helps us find the best weight. Here we are using Stochastic gradient descent (SGD). The best weight is the weight that gives us a minimum loss. We can print our model to the console to check the parameters of the model compiled using this line of code. model.summary() There are two trainable parameters listed. Because we only have one neuron in the input layer and one neuron in the output layer, therefore, we only have one weight to be trained. Another parameter is a bias neuron. Provide the dataset The input data will be stored on the x variable and the output data on the y variable. Here we only have ten data for each. In machine learning, the output of training data is called a label. import numpy as np x = np.array([0, 4, 8, 6, 3, 2, 9, 5, 7, 1]) y = np.array([4, 12, 20, 16, 10, 8, 22, 14, 18, 6]) Train the model Now we are ready to train our model. The epoch is 1000, which means that the algorithm will train on the data 1000 times. Thousand seems too big for epochs, but don’t worry, because our model is simple, it only takes a second to finish. model.fit(x, y, epochs=1000, verbose=0) Predict the unseen data The main goal of our model is to be able to predict the unseen data. This is what distinguishes machine learning from other computer programs. It has the ability to adapt to unseen input data. prediction = model.predict([12]) print(prediction) The output is: [[28.010925]] The model never sees input 12 in the training phase, and the model also never told that the formula to calculate the output is y = 2x + 4. However, the machine learning model successfully predicts the output from the given input. The problem used in this article can also be solved without machine learning. It is even easier without machine learning. However, the main goal of this article is for us to successfully build a simple machine learning model and to understand how it actually works. What’s next - Train the model with a different dataset - Build a more complex model - Play with an MNIST dataset Short Author Bio: My name is Muhammad Arnaldo, a machine learning enthusiast. Currently a master’s student of computer science. The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion. Leave a Reply Your email address will not be published. Required fields are marked *
https://www.analyticsvidhya.com/blog/2021/02/a-simple-machine-learning-implementation-to-predict-linear-algebra-in-python/
CC-MAIN-2022-40
refinedweb
703
64.81
. I. After done mapping for my entities I wanted to test the basic CRUD operations. I stuck with a problem of inserting a data to tables in many to many relation, so I wanted to look at the generated sql by the NHibernate to find out, what is really generated to investigate the problem in my mappings. The NHibernate have a property called show-sql to show the generated statements. I enabled it in the config: var configure = new Configuration(); configure.SessionFactoryName("BuildIt"); configure.DataBaseIntegration(db => { //... db.LogFormattedSql = true; db.LogSqlInConsole = true; db.AutoCommentSql = true; }); To set the output to the build-in console in Visual Studio I used a Maciej Aniserowicz solution. His post is all in polish language, so a little clarification. Every line of text send to System.Diagnostics.Debug.WriteLine(..) is going to the VS console. So Maciej added a simple wrapper for it: public class CustomDebugWriter : TextWriter { public override void WriteLine(string value) { Debug.WriteLine(value); base.WriteLine(value); } public override void Write(string value) { Debug.Write(value); base.Write(value); } public override Encoding Encoding { get { return Encoding.UTF8; } } } At the beginning of the application there must be placed a #if DEBUG Console.SetOut(new CustomDebugWriter()); #endif to set the new class responsible for operating on the output set to the console. Running that code results ALMOST in that way I wanted to. Generating sql is placed in the VS console, but only for sql SELECT statements and I didn't know why (really I still don't ;). So I decided to use the log4net logging library to get the result in the file at least. After adding a reference to this library and set the framework target there must be done two things. One is placed in app.config/web.config the configuration for the library. I found somewhere a little config which work ok: <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> </configSections> <log4net> <appender name="NHibernateFileLog" type="log4net.Appender.FileAppender"> <file value="logs/nhibernate.txt"/> <appendToFile value="false"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n"/> </layout> </appender> <logger name="NHibernate.SQL" additivity="false"> <level value="DEBUG"/> <appender-ref </logger> </log4net> And second is to add at the beginning of the application a single line log4net.Config.XmlConfigurator.Configure(); In this moment we have all, including INSERT and UPDATE statements in the logs/nhibernate.txt file. But this is not all. When we now check the VS console, we can see that we have there all the logs sended to the file, that means the INSERT/SELECT/UPDATE statements, so using this log file is useless :) Don't know, why after added and configured the log4net library is started to work as I expected, but I'm glat it did :) I? I'm diving in the NHibernate 3.2 mapping by code recently. I throught that, mapping a string with specific max length to the appropriate database table will be easy, but it wasn't. I lost some time to figure it out. At the beginning I mapped a string field in that way Property<string>(x => x.Title, x => x.Length(Int32.MaxValue)); After generating the tables in database with my schema, unfortunatelly this field was generated as a nvarchar(255) and I didn't know why. Property<string>(x => x.Title, x => x.Length(Int32.MaxValue)); After generating the tables in database with my schema, We can deal with it in few ways. 1. We can manually set the length to the value greater than 4001 (link) Property<string>(x => x.Title, x => x.Length(4002)); 2. We can set the type in this way: Property<string>(x => x.Title, x => x.Length(4002)); Property(x => x.Title, x => x.Type(NHibernateUtil.StringClob)) 3. Or we can set manually the sql type: Property<string>(x => x.Title, x => x.Column(z => z.SqlType("nvarchar(max)")));));
http://geekswithblogs.net/lszk/archive/2011/07.aspx
crawl-003
refinedweb
655
51.44
On 5/20/21 10:46 AM, Jan Beulich wrote: > On 20.05.2021 16:44, Jan Beulich wrote: >> On 20.05.2021 16:38, Boris Ostrovsky wrote: >>> On 5/20/21 3:43 AM, Jan Beulich wrote: >>>> On 20.05.2021 02:36, Boris Ostrovsky wrote: >>>>> On 5/18/21 12:13 PM, Jan Beulich wrote: >>>>>> >>>>>> @@ -95,22 +95,25 @@ static int __xen_pcibk_add_pci_dev(struc >>>>>> >>>>>> /* >>>>>> * Keep multi-function devices together on the virtual PCI bus, >>>>>> except >>>>>> - * virtual functions. >>>>>> + * that we want to keep virtual functions at func 0 on their >>>>>> own. They >>>>>> + * aren't multi-function devices and hence their presence at >>>>>> func 0 >>>>>> + * may cause guests to not scan the other functions. >>>>> So your reading of the original commit is that whatever the issue it was, >>>>> only function zero was causing the problem? In other words, you are not >>>>> concerned that pci_scan_slot() may now look at function 1 and skip all >>>>> higher-numbered function (assuming the problem is still there)? >>>> I'm not sure I understand the question: Whether to look at higher numbered >>>> slots is a function of slot 0's multi-function bit alone, aiui. IOW if >>>> slot 1 is being looked at in the first place, slots 2-7 should also be >>>> looked at. >>> >>> Wasn't the original patch describing a problem strictly as one for >>> single-function devices, so the multi-function bit is not set? I.e. if all >>> VFs (which are single-function devices) are placed in the same slot then >>> pci_scan_slot() would only look at function 0 and ignore anything >>> higher-numbered. >>> >>> >>> My question is whether it would "only look at function 0 and ignore >>> anything higher-numbered" or "only look at the lowest-numbered function and >>> ignore anything higher-numbered". >> The common scanning logic is to look at slot 0 first. If that's populated, >> other slots get looked at only if slot 0 has the multi-function bit set. >> If slot 0 is not populated, nothing is known about the other slots, and >> hence they need to be scanned. > In particular Linux'es next_fn() ends with > > /* dev may be NULL for non-contiguous multifunction devices */ > if (!dev || dev->multifunction) > return (fn + 1) % 8; > > return 0; Ah yes..
https://lists.xenproject.org/archives/html/xen-devel/2021-05/msg01138.html
CC-MAIN-2022-33
refinedweb
367
61.67
Lets face it, there are over 6,000 modules there, and I for one would love to search on "foo" and sort by "reputation" (to borrow a PM phrase). There is/was something in the works. CPANTS (Comprehensive Perl Archive Network Testing Service) has been talked about for some time and work appears to have begun on it. If you want to help, there's a developer list you can subscribe to here. As part of this there is meant to be a karma rating for authors and modules. At YAPC::Eu::2001 I signed up for a working group to implement a karma. OeufMayo and BooK were also involved. I think that we all felt that the PerlMonks system could be used in some way. However, I haven't written any code and judging by the mailing list no-one else has either. Nevertheless, it is a good idea and it should be followed through. Does anyone have any opinions about the suitablity of the Slash, PerlMonks or Everything engines for this task? -- John. The other downside is that as soon as you see a message like: If you like this module, visit vote.cpan.org and vote for it. [download] And then CPAN will turn into a great big vote-whoring exercise and before you know it, someone will write Natalie::Portman and Hot::Grits. counting downloads wouldn't work, though, because of all those pesky mirrors This is true if FTP downloads are counted. However CPAN.pm and PPM could be modified to notify a central server every time a user installs or updates a module. Of course, not everyone uses CPAN.pm or PPM. Also, this may be considered undesirable from a privacy standpoint. I don't think counting downloads alone in any fashion is going to provide the kind of info to be really helpful. However, it would be good to have it along side a 'vote' based system, so that you could tell what percentage of the people that downloaded it rated it well. /\/\averick perl -l -e "eval pack('h*','072796e6470272f2c5f2c5166756279636b672');" If that's any help once upon a time I designed a Module Review Report. It might be a starting point to design an application that would let people give their opinion on modules. A general index listing categorized modules (that's easy, the namespace provides a convenient category) and the summary could link to the detailed report (which could be sorted on the various fields). BTW I think it is important that comment authors be listed, as it prevents "ballot stuffing" and gives readers a way to evaluate the credibility of the rating. At the moment the review section is... just an idea, there is no code whatsoever to support it. I would think that in order to work it would have to be part of PerlMonks, just so users can be authenticated by the site. I (or anybody with half a clue and more time on their hands!) can write a quick proto, just to demonstrate the concept and get the UI right, but then the maintainers would have to integrate it in the site. Authentication-wise, we can can always have our own list of users, although admittedly a Perl Monks tie-in would be great. Where's the "Summon a Perl Monks Maintainer" button when you
http://www.perlmonks.org/index.pl?node_id=137276
CC-MAIN-2014-49
refinedweb
558
71.44
If for some reason, you end up with a shapefile that is missing the shx file then most software is going to complain and refuse to deal with it. The shapefile spec requires, at a minimum, that you have an shp, shx, and dbf file to have a complete file. However this requirement is not a technical requirement and a lot of people seem to be confused about that. The shx file is a trivial index file that provides fixed-length records pointing to the byte offsets of records in the shp file only. It does not connect the shp file and dbf file in any way nor does it contain any sort of record number. There are no record numbers stored in any of the three standard files which is often a point of confusion. The software reading a shapefile has to count the number of records read to determine the record id (geometry and attributes). If you wrote a program to randomly select a record from a shapefile there is no way to tell what the record number is by the record contents. The purpose of the shx file is to provide faster access to a particular record in a shapefile without storing the entire record set of the shp and dbf files in memory. The header of the shx file is 100 bytes long. Each record is 8 bytes long. So if I want to access record 3, I know that 2*8 = 16 and I can jump to byte 100+16=116 in the shx file, read the 8-byte record to get the offset and record length within the shp file, and then jump straight to that location in the shp file. While the shx file is convienient it isn't necessary. Most software balks if it is not there though. However pyshp handles it gracefully. If the shx index is there it is used for record access, if not then pyshp reads through the shp records into memory and handles the records as a python list. Sometimes shx files become corrputed or go missing. You can build a new shx index using pyshp. It's kind of a hack but still very simple. In the following example we build an index file for a point shapefile named "myshape" that has two files: "myshape.shp" and "myshape.dbf" # Build a new shx index file import shapefile # Explicitly name the shp and dbf file objects # so pyshp ignores the missing/corrupt shx myshp = open("myshape.shp", "rb") mydbf = open("myshape("myshape") If the shx file is missing it will be created. If it's corrupt it will be overwritten. So the moral of the story is because shapefiles consist of multiple files, it is actually a robust format. The data in the individual files can usually be accessed in isolation from the other files despite what the standard requires - assuming the software you're using is willing to cooperate. had an issue with auto cad where i would use map export to create my shape file, then when i import the file into another drawing to check that it did it correctly i would get an error about the dbf and shp files not matching, your software corrected it, thanks very much! oops, not the shp file, the error said the dbf is corrupt or does not have same number of objects as the shx file, run your program and it works, pretty simple, I wonder why its not working properly though, any ideas? This is just what I needed! I modified it slightly into a standalone module/program so I could fix several shapefiles which were missing their SHX. (Sorry, indentations don't show up.... makes it harder to use this sample code!) def RebuildShx(path): '''This code based on''' print(path) # Build a new shx index file import shapefile # Explicitly name the shp and dbf file objects # so pyshp ignores the missing/corrupt shx myshp = open(path+".shp", "rb") mydbf = open(path+"(path+"_fixed") # I got this idea from the python help: 6 Modules 6.1.1 Executing modules as scripts # Basically it means you can just run this module as a command with the item after the module name as input. if __name__ == "__main__": import sys if len(sys.argv)>1: RebuildShx(sys.argv[1]) Hello, Novice Python user here. I pasted code into Pyscripter, supplied pathname to my shapefile. I get "Import Error: No module named shapefile." How to avoid this error? Thank you.
http://geospatialpython.com/2011/11/generating-shapefile-shx-files.html
CC-MAIN-2018-51
refinedweb
752
78.59
I have data in a CSV file that I would like to plot in a Swarmplot like the 4th example here - i.e. with colours denoting groups. In the CSV file the data is arranged in rows like this: Group,1,1,2,2 Value1,0.5,0.3,0.2,0.1 Value2,1.7,1.3,1.1,1.0 ... import pandas as pns import seaborn as sns data_in = pns.read_cvs('file.csv',header=None,index_col=0) data_t = data_in.transpose() 0 Group Value1 Value2 ... 1 1 0.5 1.7 2 1 0.3 1.3 3 2 0.2 1.1 4 2 0.1 1.0 k = data_t.keys()[[2,3]] sns.swarmplot(data_t[k]) 0 Group Name Value 1 1 Value1 0.5 2 2 Value1 0.3 3 1 Value2 0.2 4 2 Value2 0.1 In order to transform the table, you can use melt pd.melt(df,id_vars='Group',value_vars=['Value1','Value2']) Group variable value 0 1 Value1 0.5 1 1 Value1 0.3 2 2 Value1 0.2 3 2 Value1 0.1 4 1 Value2 1.7 5 1 Value2 1.3 6 2 Value2 1.1 7 2 Value2 1.0
https://codedump.io/share/6Bg0BeEsESk/1/getting-pandas-dataframe-in-correct-format-for-seaborn-swarmplot
CC-MAIN-2017-09
refinedweb
204
82.41
The Apache Project has released Ant 1.6, the popular open source build tool. "Ant 1.6 adds a lot of new features, most prominently support for XML namespaces as well as a new concept of Ant libraries that makes use of namespaces to avoid name clashes of custom tasks." New tasks in this release include scp, symlink, chown, chgrp, attrib, p4integrate, p4resolve, p4labelsync, sshexec, image, sync, import, macrodef, and presetdef. Java 1.2 or later is required. Java 1.1 is no longer supported. Michael Clark has posted JMemProf 0.6, an open source (LGPL), live Java memory profiler suitable for deployment in Web containers such as JBoss and Tomcat. JMemProf can retrieve memory profile information from a running application. This release fixes various bugs..
http://www.cafeaulait.org/oldnews/news2003December19.html
CC-MAIN-2017-51
refinedweb
126
67.65
JetBrains News DataGrip 2017.3 is Here! DataGrip, our IDE for SQL and databases, has reached a new version. New features and improvements:Database tree view — Ability to group data sources — More convenient managing schemas — Users and roles are now displayed in PostgreSQL and AWS Redshift — Foreign data wrappers are now displayed in PostgreSQL — Drag-and-drop multiple objects to the editor SQL coding — SQL generator — Better JOIN statement completion — PostgreSQL 10 grammar support Executing queries — Ability to choose a schema when running an SQL file — The list of data sources/consoles is available when attaching the console to a file — Three independent Execute actions — Foreign data wrappers are now displayed in PostgreSQL — Set Current Schema action Connectivity — OpenSSH config files are supported (~/.ssh/config и /etc/ssh/ssh_config) — Dialog added for One Time Password — Ability to use SSH-agent and Pageant for authentication — Exasol support Data editor — Paste data in a DSV format (i.e. from Excel) — Numerical data are now right-aligned by default — Tabs are restored after re-opening DataGrip — Cells can be compared Navigation — Navigate references to DDL editor options — Jump to Console in the context menu of the data source — Replace the selected occurrences in the Replace In Path dialog — Scratches and Consoles are now placed in Files Your DataGrip Team CLion 2017.3 released with C++ support improvements, Valgrind Memcheck, Boost.Test and much - And more it installed on your machine, enable the Registry option clion.enable.msvc__ macr - Generate Definitions (Ctrl+Shift+D on Linux/Windows, Shift-Command-D on macOS) for function templates - New intention action to invert the condition in an if clause and flip its if-else blocks and dst pointers in memcpy and related functions - Incorrect size value passed to the memory allocation functions - Memory leaks Learn how to configure and use ValgrindMem) / Control-Option-R (macOS) for Run and with Shift+Alt+F9 (Linux/Windows) / Control-Option-D . Your CLion Team IntelliJ IDEA 2017.3: Coding Assistance, Debugger, Run Dashboard, Frameworks and More Exciting news: A new massive update for IntelliJ IDEA is here! Please welcome IntelliJ IDEA 2017.3! It includes loads of new features and dozens of important bugfixes. Try it now and see for yourself. Read this summary about the highlights of this release. - Java - Smart code completion is now aware of type casts. - Many new and improved inspections: inspection for Redundant throws declarations, quick-fix for deprecated code, inspection for possible nullability in Stream API call chains, and more. - Improved JUnit5 support. Learn more - Configurable command line shortener: a new handy way to specify a method used to shorten the command line for each configuration. Learn more - Run Dashboard: Add different run configurations types - JVM debugger - A new feature called On-demand Data Renderers helps reduce overhead. To enable it for any renderer, choose Mute Renderers from the context menu. - Async Stacktraces now causes very low overhead and works out of the box. - The Java Stream Debugger plugin is now bundled. - Java EE 8 - For Asynchronous CDI Events, you can now navigate between where an event was fired and where it was received. - Navigate between Injection point and Injected Beans using gutter icons for dynamic beans (CDI extensions). - Navigate from disposer methods to their producers. Learn more - Spring and Spring Boot - The Spring Beans Dependencies diagram has a new Neighborhood Mode. For better readability, you can switch to Borderless View. - There’s now an auto-detection facet for Spring Boot MVC web applications and Spring. Learn more - Brand new editor-based REST client - Kotlin: a bundled Kotlin plugin has been updated to v1.2, and support for the experimental Kotlin multiplatform projects is now available. - IntelliJ IDEA 2017.3 provides better synchronization of your settings across different installations. Learn more - Local variable type inference is supported. Learn more For more detailed information about the shiny new features, check out the What’s New page. You can download the new IntelliJ IDEA 2017.3 right now! Your feedback, as always, is very much appreciated in our issue tracker. RubyMine2017.3 RubyMine 2017.3 Released! RubyMine 2017.3, the biggest and final release of this year, is now available! What's new in RubyMine 2017.3: - IDE: improved performance, support for apps with nested projects, and better code resolution and code insight. More - Linux subsystem for Windows (WSL) support. More - Refactoring: Extract methods directly to privateand protectedsections. More - RuboCop: autocorrect by offense class or cop department. More - Code style: the ability to indent privateand protectedmethods, and choose which operators should be wrapped with space. More - Puppet: Embedded Puppet (EPP) templates support. More - Debugger: the new Trace to_s evaluation option detects costly operations and throws a timeout message. More - JavaScript: better code completion, documentation, CSS, and Vue.js. More - VCS: the Interactively Rebase from Here action, workspaces for branches. More - Database tools: managing schema, SQL generator, grouping data sources. More Other improvements include support for Ruby 2.5, Gems.rb, Docker Compose v3, Cucumber Expressions, and more. Check out the What's new page, and update to RubyMine 2017.3! PyCharm 2017.3 Out Now We're happy to announce that PyCharm 2017.3 is now available! PyCharm 2017.3 is faster, more usable, and better for data science. Upgrade Now - It's Faster. Indexing got faster for both Python and JavaScript code. Faster variable loading during debugging. Debugging is now fast by default on Windows and macOS. - Scientific Mode. The scientific mode puts all the tools you need for analyzing data at your fingertips. - Easier Setup For Virtualenvs. With PyCharm 2017.3 it is easy to set up virtualenvs when creating a project, and when configuring existing projects. - New REST Client. If you develop an API, you often need to construct a request to test your software. PyCharm 2017.3 has an all-new REST client. PhpStorm 2017.3 Out Now Today we are proud to announce the release of PhpStorm 2017.3, the last major update for PhpStorm in 2017. - Brand new editor-based REST client. With the new REST client, all the powers of the PhpStorm code editor are now available for your REST requests. - Significant performance improvements. Typing latency in very complex PHP files has decreased significantly. We've examined typing latency in the mPDF main file, which is a 38k-line-long mix of PHP, JS, and HTML, and it is down by 75% in PhpStorm 2017.3! - New inspections for exception handling. Three new inspection Unhandled exception, Redundant @throws and Redundant catch clause with corresponding Quick Fixes will help you take exceptions under your control! - Test generation improvements. Now you can create Codespec and PhpSpec classes and create test methods! - Improved Twig support. We've implemented language injections for Twig custom tags and named blocks as well as improved Twig formatting that can now handle complex structures. Announcing WebStorm 2017.3 Today we’re announcing WebStorm 2017.3! This big update brings improvements to all parts of the IDE, from support for JavaScript, TypeScript, and the frameworks to debugging and testing. Explore the new features and download WebStorm 2017.3 on our website. YouTrack 2017.4 Please welcome YouTrack 2017.4 featuring Japanese localization, estimation report type, date and time custom fields, and other improvements. The latest release also brings: - Sort by Relevance in Search Results - Date and Time Custom Fields - npm Package Support for Workflows in JavaScript Other enhancements: - Text Indexing for Issue Fields - Extended Text Index Support - Import from Jira Option for New Projects - Redefined Project Teams - Shared Mailbox Support for Microsoft Exchange - Markdown Support as an experimental feature For more details visit the What's new page. Get YouTrack 2017.4 today and enjoy its wide range of issue tracking and project management capabilities. The latest version is available for download or cloud registration.! This update brings a better user experience to both learners and educators, making the product’s use as simple as possible, whether it is used for learning, or for teaching. First of all, we’ve changed the welcoming UI. Now you begin by choosing your role, Learner or Educator. Depending on your choice, you get access to the courses you can join as a learner and can practice with the help of simple and effective “fill in the missing code” exercises. Or, you can create your own code practice tasks and integrated tests as an educator.VCF7 skips the frames without sources. We hope this makes the feature easier to use and more intuitive., shift cmd A line numbers, - Debugger: filtering arrays, collections, and maps - Spring Boot run dashboard and actuator endpoints - Managing multiple applications is now easier, thanks to the new Run Dashboard tool window - Both the Run and Run Dashboard tool windows now provide temporarily.!. This means that only constexpr is actually missing from C++14. As for C++17, we've started with the most upvoted feature, nested namespaces. ,. Check more details. testing.. - CLion supports Microsoft Visual C++ compiler that ships with VS 2013, 2015 and 2017. - There's no support for msbuild. CLion works through CMake and the NMake.
http://www.jetbrains.com/allnews.jsp?year=2012
CC-MAIN-2017-51
refinedweb
1,509
57.77
Hi, I'm trying to display a PDF saved in local on my iOS App. Here's my code, it works with a Web URL (example :) but not with a local url (example : ). Here's my C# code : public class WebViewDoc : ContentPage { public WebViewDoc (String filename) { String documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); String fullPath = Path.Combine (documentsPath, filename); // Result : var browser = new WebView (); browser.Source = @fullPath; // Works if replacing by a web url Content = browser; } } Did someone have a solution ? Thank you, Simon have you tried using a "file://" scheme with the url? Hi @JasonAwbrey , Yes, and still not ok. Here's the code to save the file on my app, maybe the problems come from it? @SimonDellise , @JasonAwbrey I am currently having the same issue. There are plenty of example for Android but not for iOS. I tried using success. I am wondering if it is a simulator issue or something else... Hi @hvaughan , I've used this for iOS : The problem was simply the spaces in the file name ... So I replaced all of them by an underscore ( _ ) and now, it works fine ! The webview code : I hope this will help you. @SimonDellise Awesome! Thank you. I think that solved it for me. I also was not using .ApplicationData. One more question if you don't mind, for Android, when you open using another application (such as adobe reader), are you handling the case when the user does not have any PDF viewer installed? I found PDF.js(link below), but just wanted to see if you had a better alternative. Thanks again. @hvaughan You're welcome Unfortunately, I haven't found any better solution at your question. I think PDF.js is a great alternative to the native app.
https://forums.xamarin.com/discussion/comment/128796/
CC-MAIN-2020-24
refinedweb
294
68.16
Elmo's World From Uncyclopedia, the content-free encyclopedia Elmo greeting his next victim to his world. “I only tickled him where he wanted it.” Elmo's World is a place of pure evil that man greatly fears. It is a dark and gruesome place ruled by a mass murderer named Elmo. The world consists of burning brimstone and suffering people, and is filled with the screams of the children who are its only permanent residents. This amuses the sinister Elmo, and makes him very happy to be the king. Those who enter this horrible world never return (except for blithering cowards), or if they do, they die within the next twenty seconds of escape. edit Elmo Elmo moments before his first kill. The story of Elmo's World began with the little monster named Elmo. Elmo was originally constructed as a toy for little children from Fisher-Price. There were many types of Elmos, some played patty cake and others were ticklish. Also, because children loved expensive and interactive toys, all the Elmos were a success. So it wasn't long before there came the plan to make an Elmo that knew children's names. Fisher-Price crowned this as their grand master plan, and they would even jack up the price even more than all previous Elmos. However Fisher-Price was facing a tight economic budget, so to save money, they decided to use thread from old materials that no one ever used anymore. One of these Elmo toys was stitched together from the the very thread that made up the coat of Jack the Ripper, and thus the spirit of the evil killer possessed the toy. Elmo about to claim another life. The toy was later purchased by a man who wanted to be a ventriloquist and since he wasn't very good at thrusting his voice, a talking doll was just what he needed to get his career going. At first, signs of possession went unnoticed. But soon the man's family started to worry when the doll threatened to kill their son, Fisher-Price simply passed it off as a malfunction. Two nights after the threat, the doll made its first kill. The man was doing a show one night with Elmo and was asking Elmo a lot of questions that annoyed the living hell out of him. Then he finally asked Elmo if he liked him, to which the doll responded by literally putting him in the spot light. Elmo then started his career as a mass murderer. He continued this career for years, and soon his blue fur turned red after being stained with so much blood. Due to being possessed by Jack the Ripper, Elmo usually targeted women that he came across, though he would happily kill their husbands if they ever tried to stop him...which they all failed miserably. However, he soon grew fascinated with the children that he also encountered and they soon became a major subject of his kills. The kills garnered much controversy around Fisher-Price who had accidentally brought this monster into the world. But Fisher-Price didn't mind, they were the subject of many newspaper articles and media attention, they ate this all up. There were many attempts by complete and utterly stupid people (including the aforementioned husbands) to put Elmo down, but all who tried to stop him met a bloody and horrible fate. At one point, Elmo devised a horrible plan to kill Mr. Hooper, simply because he forgot to pay him once when he decided to work for him as a grocery bagger. He murdered Mr. Hooper's wife along with her boyfriend Jim Henson by using a shotgun while they were making out in Hooper's bedroom. Since the police were stupid, they magically assumed that Mr. Hooper had murdered his wife rather than Elmo (even though he had written with his crayon "Elmo Wuz Here" on the wall) and he was sentenced to be executed by the electric chair. Mr. Hooper tried to escape from prison using a sewer pipe, but Elmo thwarted his attempt by using his toilet to take a massive diarrhea dump, causing him to nearly drown in the Muppet's foul excrement. During his execution, Elmo swiped the sponge that was needed to give Mr. Hooper a merciful execution while the executioner was off to take a bathroom break, causing him to die a horrible and painful death. He immediately giggled like a schoolgirl. edit The Coming of Elmo's World Elmo in his apartment on Sesame Street. After years of running, Elmo was eventually caught by the police after they lured him into a pool of glue (telling him it was ice cream). Elmo was then forced to wear a strait jacket, was strapped to a operating table, and was then gagged to make sure he could not escape. Even so, the police could barely contain their prisoner, for Elmo was too psychotic and dangerous to keep subdued. Elmo was then placed in a jail cell without food and water for five weeks, during which he almost managed to escape and murdered several guards. After Elmo finally became too weak to move, they sent him to Hell after he was gunned down by Samuel L. Jackson (the only man with enough power to kill him, except for maybe Chuck Norris). Upon entering Hell, Elmo was immediately put through much torture and despair for his hideous atrocities. Through his agony, Elmo was filled with rage and eventually challenged Satan himself for ownership of Hell. Now one would ask, what kind of idiot would risk his own kingdom when there is no need to do so? But unfortunately for Satan, he had a very big ego that forced him to do so. Elmo faced Satan in a game that he had no hope of ever cheating (let alone winning) at, a christian version of the game of Life. Elmo was actually skilled at cheating at this game and cheated his way to victory. Upon winning the game, Elmo took over Hell and enslaved Satan himself. Elmo then brought Hell to the surface... in an apartment building on a place called Sesame Street. This place was full of cute and innocent residence, so none would suspect that Elmo's new world would be located here. Indeed, on the surface, it was a perfectly normal building. Inside the building...well... After his new set up, Elmo lured innocent children into his world using candy and happy giggles, where they would be condemned to an eternity of torture that amused the insane Elmo. Each day Elmo thought of a different torture (usually involving a set of crayons), and his victims were forced to endure that torture until they were driven completely insane, much like Elmo himself. Elmo would start things off by showing his victims what the torture would be like, using his assistant, The Fish You Flushed a Few Years Ago. Satan himself was also used by Elmo to demonstrate these tortures, he was dressed in a bow tie and suit and was given the name Mr. Satan. He was then forced to show Elmo and his victims examples of the type of torture Elmo was thinking about. edit End Elmo's World met its end when Satan finally snapped his last nerve control cell. It happened one day, while Elmo was thinking of an extremely bad torture and ordered Satan to drop his pants in front of all the children. Satan refused to do so and Elmo started to whip him. He then ordered him again and again, but Satan refused and continued to get whipped. Then after the eighteenth whip, Satan finally snapped and unleashed all the hidden power he had kept contained within him for centuries, power that would force you to scream, "HOLY SHIT... that is some colossal power." This uncontrollable power broke Satan free of his chains and severely damaged Elmo's World. After the power finally simmered down, Elmo and his world were left severely injured. Satan then dragged the world and Elmo back underground. Elmo was then subject to an eternity of torture beyond imagination.
http://uncyclopedia.wikia.com/wiki/Elmo%27s_World
CC-MAIN-2017-26
refinedweb
1,364
70.23
Before Netscape, when Mosaic ruled the Web and people needed a straightforward way to exchange information between client and server, the Common Gateway Interface (CGI) was born. CGI applications (usually called scripts) run on the server side. A user initiates a request via HTTP and optionally transmits information, which is handed off to the CGI script. The script processes the information and packages a reply, which the server sends to the user. The Need for Servlets When CGI scripts were first developed, they were often written in C or Perl. C had the advantage of speed, while Perl was cross-platform. Both, however, suffered from the overhead needed to fork a new process each time the Web server needed the CGI script. The Apache Web server mitigates that penalty with modules like mod_perl, but Sun Microsystems came up with a better alternative: the Java servlet. A servlet is just a regular Java class that implements the interface javax. servlet.Servlet as defined by the Java Servlet Specification (). Servlets run in a separate container, which runs a Java Virtual Machine. The JVM then executes the servlet as a thread. A typical setup uses Apache as the Web server and Tomcat as the servlet container. Because the container is persistent, there is no overhead associated with starting a JVM for each servlet. (For more on setting up Tomcat, see the October 2001 article “Hangin’ With Tomcat” at.) Further, the container can keep track of information between requests. HTTP offers no inherent means of doing this, so the Java servlet technology offers a convenient way to remember the state of a client/server session. Figure One shows the cycle of a request/response transaction: information flows from the Web client to the servlet, through the servlet container, and back. Servlet Basics A common situation well suited to Java servlets is the shopping cart. The client initiates a request, but most of the transaction processing takes place at the server, which must remember what else the client did this session. Java servlets refer to the saved session information as attributes. Servlets typically interact with the user through standard HTML markup (just like a CGI script would), presenting a form to the user, who fills in the blanks. Under the hood, each form element (text, radio button, etc.) is given a name in the HTML form, and when the user presses the Submit button, that information is bundled up and transmitted to the Web server as a series of name/value pairs. The server then passes the request to the servlet container, which presents it as an HttpServletRequest object to the servlet. When the servlet returns outputs, it uses an HttpServlet Response object. The container presents the information to the Web server, which in turn sends it to the user. Servlets at Work The SessionServlet in Listing One (available at) demonstrates these concepts. It creates a session when it is first invoked and presents a form that allows you to add and remove attributes (see Figure Two). Listing One: SessionServlet 1 import java.io.*; 2 import java.util.*; 3 import javax.servlet.http.*; 4 5 public class SessionServlet 6 extends HttpServlet { 7 8 protected void doGet 9 ( HttpServletRequest req, 10 HttpServletResponse resp ) 11 throws IOException { 12 handleRequest( req, resp ); 13 } 14 15 protected void doPost 16 ( HttpServletRequest req, 17 HttpServletResponse resp ) 18 throws IOException { 19 handleRequest( req, resp ); 20 } 21 22 private void handleRequest 23 ( HttpServletRequest req, 24 HttpServletResponse resp ) 25 throws IOException { 26 HttpSession session = req.getSession(); 27 processRequest(req, session); 28 resp.setContentType(“text/html”); 29 PrintWriter out = resp.getWriter(); 30 out.println(“<html><body>”); 31 out.println(“<h1>Session Servlet</h1>”); 32 outputForm(out); 33 out.println(“<hr>”); 34 outputSession(out, session); 35 out.println(“</body></html>”); 36 } 37 38 private void processRequest 39 ( HttpServletRequest req, 40 HttpSession session ) { 41 String name = req.getParameter(“InputName”); 42 String value = req.getParameter(“InputValue”); 43 if ( req.getParameter(“AddButton”) != null ) 44 session.setAttribute( name, value ); 45 else if (req.getParameter(“RemoveButton”) != null) 46 session.removeAttribute( name ); 47 } 48 49 private void outputForm( PrintWriter out ) 50 throws IOException { 51 out.println(“<form action=SessionServlet method=post>”); 52 out.println(“Name: <input type=text length=20 name=InputName><br>”); 53 out.println(“Value: <input type=text length=40 name=InputValue><br>”); 54 out.println(“<input type=submit name=AddButton value=add>”); 55 out.println(“<input type=submit name=RemoveButton value=remove>”); 56 out.println(“</form>”); 57 } 58 59 private void outputSession(PrintWriter out, HttpSession session) 60 throws IOException { 61 out.println(“Current attributes:<p>”); 62 Enumeration enum = session.getAttributeNames(); 63 while (enum.hasMoreElements()) { 64 String name = (String) enum.nextElement(); 65 Object value = session.getAttribute(name); 66 out.println(name+” = “+value+”<br>”); 67 } 68 } 69 } To add an attribute, type a name to identify it and a value in the corresponding box and click the “add” button. To remove an attribute, type its name and click the “remove” button. Each time the screen is refreshed the servlet displays all the attributes currently stored in the session. If you visit another address and browse the servlet again later, you will see that the session is still active and the attributes are still there. The SessionServlet inner working is pretty straightforward. In order to handle HTTP requests, all you need to do is extend the class javax.servlet.http. HttpServlet and override the appropriate methods, listed in Table One. Table One: Important HttpServlet Methods The methods doGet (lines 8 through 13) and doPost (lines 15 through 20) receive objects that represent both the request and the response. In this way, they actually perform the work of SessionServlet. The request is handled by the method handleRequest(), which is called by both the doGet() and doPost() methods. This kind of arrangement is common practice, since it allows the servlet to transparently handle both GET and POST HTTP requests. The first thing handleRequest() does is get the current session using the method getSession() of the request received (line 26). A new session is created by getsession() if this is the first time the servlet has been called by the client. The method getSession() of the HttpServletRequest interface creates and returns an HttpSession object where you can store any attributes between requests. The methods associated with the HttpSession object are listed in Table Two. Table Two: HttpSession API Once created, the HttpSession object is associated with all requests from the same client to the same Web application (and can be retrieved using the same get Session() method), until it is destroyed. All the low-level details are managed by the servlet container. The method processRequest() is called in line 27 to actually process the request. All data from the form are made available to the servlet through the appropriate API, which provides several convenient methods to get the request’s parameters. These are shown in Table Three. Once parameters are received, the servlet processes them and can optionally store them as session attributes. It can also retrieve attributes that have already been stored from previous requests in the session. Table Three: Getting Parameters From the HttpServletRequest The processRequest() method gets the text typed into the form fields (InputName and InputValue) in lines 41 and 42, and the name of the button clicked (RemoveButton or AddButton). It then adds or removes the attribute in lines 43 through 46. Once processing is complete, the information is presented through the interface HttpServletResponse (see Table Four). There are methods to set the headers and body of the response, send back errors or redirect the request. In order to send back a normal response, all you need to do is set the MIME type, get a suitable character or binary stream and write the data. Table Four: Sending an HttpServletResponse You set the MIME type of the response you are sending back with the setContentType method. The most common case is “text/html” when you are returning an HTML page, but setting the MIME type and using the appropriate stream lets you return any type of data. In line 28, the handleRequest() method sets the content type of the response to text/html. It gets a text stream in line 29 and outputs the actual page in lines 30 through 35, with the help from both the outputForm() and outputSession() methods. The method outputForm() in lines 49 through 57 outputs the form used to interact with the user. This is where parameters are named InputName and InputValue. The associated values will be those filled in by the user. The method outputSession() in lines 59 through 68 outputs all attributes currently stored in the session. In line 62, the getAttributeNames() method of the session is used to iterate over all attributes. After It’s Written All servlets must be part of a Web application as defined by the Servlet Specification. This includes a set of HTML pages, servlets, JSP pages, classes, and other resources. These conform to a certain directory structure and require a special file, web.xml, which configures security constraints, initial parameters, and the like. Tomcat requires that the web.xml file exist, but if the file provides no parameters, Tomcat uses default values. In order to get our ServletSession example running under Tomcat, follow the steps below. 1. Compile the example: 2. Deploy it into Tomcat: Once the servlet is deployed, you can see it in action by browsing the address. Exploring Further Java servlets are natural replacements for CGI applications. They are easier to develop and offer better performance. Servlets are a good choice when your application has moderate to complex logic or when you need to return data other than HTML pages, especially binary data. The disadvantage of Java Servlets is that they don’t provide, by default, a good separation of program logic and presentation, since statements that output HTML are intermixed with the application logic, making maintenance difficult. One solution to that problem is the Velocity template engine, a Jakarta project (). There’s a wealth of information available for your next steps. A good starting point is the documentation that comes with Tomcat, which shows you how to develop, organize, and deploy Web applications.
http://www.linux-mag.com/id/1031/
CC-MAIN-2017-43
refinedweb
1,691
56.55
Route This is what make a single page app do not refresh. Quick Start It is a big topic, and here I want to make it as quick as possible to read. - Install react-router, react-router-domto your project by npm install --save react-router react-router-dom import {BrowserRouter} from “react-router-dom”;in your App.js - Wrap your application whole App inside <BrowserRouter></BrowserRouter> <BrowserRouter> <div className="App"> ... </div> </BrowserRouter> import {NavLink, Route, Link, Switch} from “react-router-dom”;or any combination of those in your container component. - Can create the <Link> or <NavLink> to the container class like: <nav> <ul> <li><NavLink to={"/"} exact activeClassName={"my-active"}>Home</NavLink></li> <li><NavLink to={"/post"} activeClassName={"my-active"}>New Post</NavLink></li> </ul> </nav> - To display the components based on the URL route, you can do: <Route path="/" exact component={Posts}/> <Switch> <Route path="/post/:id" exact component={FullPost}/> <Route path="/post" exact component={NewPost}/> </Switch> Link, NavLink If we do a <a href=“…”>xxx</a> for a link, the page will refresh, so we need to use <Link>xxx</Link> or <NavLink>xxx</NavLink> to replace it. Details here: They have the following main props: - to - The URL to go to - exact - Will use this route only if the URL match exactly as the one in to - activeClassName - The class name add to this block if it is active, mostly of CSS make up Example: Go to exact path / if this Home link is click, and if it is active, it should have a css class named my-active ... <li><NavLink to={"/"} exact activeClassName={"my-active"}>Home</NavLink></li> ... Route If the url route is match to the path props, show the component, or render the JSX. Note that any URL match the path will be loaded. <Route path="/" exact component={Posts}/> <Route path="/" exact render={()=><div>Demo1</div>}/> <Route path="/" exact> Demo2 </Route> Switch If you only need the very first route to be load on match. You can use Switch. <Switch> <Route path="/:id" exact component={Posts}/> <Route path="/" exact render={()=><div>Demo1</div>}/> </Switch Additional - export default withRouter(COMP_NAME) - Route information on this.props - route lazy loading
https://wiki.chongtin.com/reject/router
CC-MAIN-2021-17
refinedweb
364
57.71
Timeline 04/27/11: - 18:47 Changeset [5aeeafb]stable/1.3.x by - [1.3.X] Fixed #15865 -- correct class name for BaseGenericInlineFormset. … - 18:46 Ticket #15865 (Wrong information about generic inline formset) closed by - fixed: In [16113]: […] - 18:46 Changeset [013ce8a]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixed #15865 -- correct class name for BaseGenericInlineFormset. Thanks … - 17:28 Changeset [fe76955]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fix heading formatting in localflavor docs. git-svn-id: … - 17:26 Ticket #15885 (Update the docs to explain that auth views now return TemplateResponse) closed by - fixed: In [16111]: […] - 17:26 Changeset [e5cf560]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixed #15885 -- Update auth view docs re: TemplateResponse. Thanks … - 17:23 Changeset [637cf5d]stable/1.3.x by - [1.3.X] Fixed #15830 -- Add documentation regarding localflavor i18n. … - 17:20 Ticket #15830 (Document i18n of localflavor) closed by - fixed: In [16109]: […] - 17:20 Changeset [6d98cda0]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixed #15830 -- Add documentation regarding localflavor i18n. Thanks … - 15:09 DjangoFriendlyWebHosts edited by - hostsharing typo correct (diff) - 15:00 DjangoFriendlyWebHosts edited by - hostsharing (diff) - 14:54 Ticket #15911 (In django.contrib.auth.forms.AuthenticationForm there is no separate check ...) closed by - worksforme: I'm going to close this ticket as "worksforme", as with the information … - 14:21 Ticket #15913 (trailing slash) closed by - invalid: According to the line 46 in django/views/static.py file, … - 12:50 Ticket #15913 (trailing slash) created by - For example, if … - 12:37 Ticket #15912 (CharField.widget_attrs should respect its super) created by - The contract of the Field.widget_attrs method is that it returns a … - 11:24 Ticket #15911 (In django.contrib.auth.forms.AuthenticationForm there is no separate check ...) created by - In django.contrib.auth.forms.AuthenticationForm there is no check … - 10:51 Changeset [2706fdb]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Refs #15093 -- Fixed another get_models call missed in r16053. Thanks Luke … - 10:45 Ticket #2115 ('tuple' object has no attribute 'startswith') closed by - fixed: The problem was that I had two different versions of tagging package, and … - 09:16 Ticket #2115 ('tuple' object has no attribute 'startswith') reopened by - I have the same problem. My media_root is MEDIA_ROOT = … - 08:47 Changeset [04654e5]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Refs #15903 -- Added a per-TestCase urlconf to reduce coupling between … - 08:46 Ticket #15903 (Changeset r16053 breaks a few views tests) closed by - fixed: In [16106]: […] - 08:46 Changeset [c85b765]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixed #15903 -- Allowed not-installed models to still be referenced in … - 04:53 Ticket #15910 (show delete links for all admin inline formset rows) created by - When adding a form to an inline formset in the admin interface it has a … - 04:28 DjangoFriendlyWebHosts edited by - Added software.coop (diff) - 04:22 DevelopersForHire edited by - Added software.coop (diff) - 03:48 Ticket #15909 (File Upload is not working for Django 1.2.1) closed by - worksforme: File save works fine -- your example has multiple bugs in it. If you want … - 03:31 Ticket #15909 (File Upload is not working for Django 1.2.1) created by - Here is my url.py file: ##################################### urlpatterns … - 01:51 DjangoJobs edited by - (diff) - 01:20 NoSqlSupport edited by - minor issues belong at the bottom (diff) - 01:02 NoSqlSupport edited by - removed multi-table inheritance explanation (none of the solutions is good … (diff) - 00:57 NoSqlSupport edited by - re-ordered (diff) - 00:31 NoSqlSupport edited by - removed query refactoring section (diff) - 00:28 NoSqlSupport edited by - cascading deletes are probably fine because now ForeignKey allows to … (diff) - 00:22 NoSqlSupport edited by - explain AutoField changes (diff) 04/26/11: - 23:58 NoSqlSupport edited by - (diff) - 15:37 Ticket #15766 (select_related() changes type of DecimalField) closed by - worksforme: I can't get past the c.save() line: With Oracle: […] Which is what … - 15:33 Ticket #8334 (Allow add/create on m2m intermediate tables if all the non-FK fields have ...) closed by - duplicate: Duplicate of #9475. - 15:29 Ticket #11946 (ManyToOneRel.lookup_overrides is unused) closed by - fixed: This has apparently been fixed already. - 14:35 Ticket #15908 (Mention proper i18n approach in documentation for "pluralize" filter) created by - The |pluralize template filter cannot be used to pluralize words in … - 13:18 Ticket #15907 (Generic inlines ignoring the exclude information from a custom form.) created by - Suppose we have the following models: […] and this admin … - 11:17 NoSqlSupport edited by - also discuss serializers (diff) - 11:14 Ticket #15766 (select_related() changes type of DecimalField) reopened by - Ok, sorry for not having provided more info earlier. Using the attached … - 10:58 NoSqlSupport edited by - added Redis backend (diff) - 10:00 Ticket #15906 (New head method needs documentation) created by - The head method added in r16095 & r16105 needs documentation. - 09:56 Changeset [2f9c52d]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixed a failing test in special_headers, and performed a bit of cleanup. … - 09:49 Ticket #15889 (django.core.serializers.get_serializer() should raise a more specific ...) closed by - fixed: In [16104]: […] - 09:49 Changeset [930371e]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixed #15889 -- when trying to access to access a serializer that doesn't … - 07:23 Ticket #15905 (Forms keyword arguments..) closed by - invalid: Looking at the implementation of django.forms.Form, there is really no … - 07:00 Ticket #15905 (Forms keyword arguments..) created by - when i try to validate my form its is_valid function returns False when i … - 06:26 UsingVimWithDjango edited by - Adding a vim plugin that I've been working on. (diff) - 04:58 Ticket #8362 (Reusable Django mechanism for registering plugins / admin classes / ...) closed by - wontfix: Marking WONTFIX on the basis of Malcolm's comments, and the fact that … - 04:28 Ticket #15904 (render_comment_form executes unnecessary query for object) closed by - fixed: In [16103]: […] - 04:28 Changeset [1b6670d]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixed #15904 - render_comment_form executes unnecessary query for object … - 03:19 Ticket #15904 (render_comment_form executes unnecessary query for object) created by - The template tag render_comment_form when given an object like this: … - 02:54 Ticket #15903 (Changeset r16053 breaks a few views tests) created by - Traceback: […] - 02:24 Ticket #15902 (Storing current language in session/cookie) created by - == Related discussion == … - 01:17 DevelopersForHire edited by - Added link to my company. (diff) - 00:57 Tutorials edited by - (diff) 04/25/11: - 23:49 Ticket #15901 (Django should wrap all PEP 249 exceptions in db.utils) created by - There are only two Exceptions defined in db.utils, namely DatabaseError … - 22:54 Ticket #15793 (Filebased email backend should save emails using the ".eml" standard ...) closed by - wontfix: I'm closing this as won't fix then. Using ".eml" as an extension will … - 16:22 Ticket #15900 (reverse() does not properly escape namespaced views) created by - Easier to provide an example than to explain. Given a freshly created … - 13:19 Ticket #15893 (Latin script in Serbian should be @latin, not @Latn) closed by - wontfix: Doing some more research, I found some references for Latn also: … - 13:03 Ticket #15899 (web site link rot ?) closed by - invalid: As far as I can tell, there's never been a page at this address: … - 12:59 Ticket #15899 (web site link rot ?) created by - I followed a link to and there is … - 12:38 Ticket #15897 (Example login form in documentation uses URL incorrectly) closed by - invalid: The behavior of the url tag will change in Django 1.5, and the docs were … - 12:25 Ticket #15898 (Add wsgi.input to RequestFactory's base environ) created by - wsgi.input is required but it is not provided in the base environ of … - 09:39 Ticket #15896 (unittest docs say import django.utils, should be djanto.test) closed by - invalid: It's a different thing. django.utils.unittest is a copy of the … - 09:36 Ticket #15897 (Example login form in documentation uses URL incorrectly) created by - In what I'm guessing is a holdover from a previous version (though I don't … - 08:32 Ticket #15696 (Add pre_insert signal to loaddata command) closed by - wontfix: I find myself agreeing with Russ that a custom serializer is a better … - 08:28 Ticket #15896 (unittest docs say import django.utils, should be djanto.test) reopened by - Hmm, OK, I read this a little more carefully and see what had me going. … - 08:24 Ticket #15895 (incorect error description due to naming convensions) closed by - needsinfo: That doesn't make any sense. The traceback doesn't match the code showed … - 08:14 Ticket #15896 (unittest docs say import django.utils, should be djanto.test) closed by - invalid: Ever tried to do so? […] - 08:09 Ticket #15896 (unittest docs say import django.utils, should be djanto.test) created by - At … - 07:25 Ticket #15895 (incorect error description due to naming convensions) created by - the situation is reported here - … - 04:38 Ticket #15894 (SITE_CACHE does not invalidate in multiprocess environments) created by - In a configuration where multiple python processes are created to serve … - 02:18 Ticket #15891 (flushing session on auth.logout) closed by - wontfix: It's tight coupling between auth and session, but it's by design. I'm … - 02:10 Ticket #15893 (Latin script in Serbian should be @latin, not @Latn) created by - The locale directories for Latin Serbian should be renamed from sr_Latn to … - 02:08 DjangoResources edited by - fix libravatar link (diff) - 02:07 DjangoResources edited by - Mention Libravatar in the list of Open Source projects written in Django (diff) - 02:07 Ticket #10378 (authenticate() method should not continue on built-in or generic ...) closed by - wontfix: Backing up Malcolm's -1 and closing the issue. Unfortunate, but that's … - 02:05 DjangoResources edited by - sslauth is unfortunately no longer accessible :( (diff) 04/24/11: - 22:59 Ticket #15892 (Duplicate 'settings' import in settings_tests/tests.py) closed by - fixed: In [16102]: […] - 22:59 Changeset [d8bfd395]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixes #15892 -- Duplicate 'settings' import (and some unused imports) in … - 22:43 Ticket #14543 (ContentTypes tests fails if auth app is not installed) closed by - fixed: In [16101]: […] - 22:43 Changeset [a6c08a5]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixes #14543 -- ContentTypes tests failing if auth app is not installed. … - 16:53 Ticket #15801 (Logging docs: Incorrect external link for dictConfig) closed by - fixed: In [16100]: […] - 16:53 Changeset [449e84a2]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixed #15801 - Incorrect external link for dictConfig; thanks David … - 16:47 Changeset [44dbac64]stable/1.3.x by - [1.3.X] Fixed #15853 - typo in m2m_changed signal documentation; thanks … - 16:47 Ticket #15853 (Error in m2m_changed signal documentation) closed by - fixed: In [16098]: […] - 16:47 Changeset [f9fa932]stable/1.4.xstable/1.5.xstable/1.6.xstable/1.7.x by - Fixed #15853 - typo in m2m_changed signal documentation; thanks elbarto. … - 14:57 Ticket #15886 (Improve django.core.serializers.get_serializer() docs) closed by - duplicate: Closing this in favor of #15889. - 13:14 Ticket #13182 (Remove useless whitespaces in JSON dump with indent option) closed by - wontfix: In that case I'm going to mark this wontfix. An explicitly installed … - 12:58 Ticket #15892 (Duplicate 'settings' import in settings_tests/tests.py) created by - 'settings' is imported from django.conf twice. - 12:33 Ticket #15833 (Exclude not working with ForeignKey in admin Inlnes) closed by - needsinfo: I'm closing this ticket as "needsinfo", so please, if this is definitely a … - 12:05 Ticket #15890 (uWsgi + empty POST request causes Django to hang/crash) closed by - duplicate: This appears to be a consequence of the problem described in #15785. The … - 04:32 Ticket #15891 (flushing session on auth.logout) created by - Flushing the session on logout or logging in with another user before … - 02:09 DevelopersForHire edited by - (diff) - 02:07 DevelopersForHire edited by - (diff) - 01:13 DevelopersForHire edited by - (diff) Note: See TracTimeline for information about the timeline view.
https://code.djangoproject.com/timeline?from=2011-04-27T06%3A05%3A13-07%3A00&precision=second
CC-MAIN-2014-15
refinedweb
2,059
53.92
Campbell Ritchie wrote: Algorithm:Create empty StringWhile i > 2Find i % 2.Add that number to the left end of your String.Divide i by 2 in integer arithmeticEnd of whileDisplay your String.Much better than the algorithm you had. Campbell Ritchie wrote:I would still prefer a StringBuilder to using the + operator on Strings. Sudhir Srinivasan wrote:Awaiting your response... John Jai wrote:and you are creating different StringBuilder objects in the loop. Winston Gutkowski wrote: Don't overthink this. You've got all the basic components there; you just need to put them in the right order. (Big Hint: try it by hand, and work out when you do the 'reverse' bit). Campbell Ritchie wrote:If you use the insert() method of StringBuilder, and use index 0 throughout, you can get the binary output without needing to reverse anything. Campbell Ritchie wrote: I would still prefer a StringBuilder to using the + operator on Strings. Campbell Ritchie wrote:I don’t think anybody will post a better explanation than what you have just shown. You can see how much effort you have put into it: well done Campbell Ritchie wrote: When you have ten minutes to spare, try this class:public class StringAddition { public static void main(String[] args) { System.out.println("Using StringBuilder without size"); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 1000000; i++) { builder.append("Campbell"); } System.out.println("Finished StringBuilder without size: using StringBuilder with size"); builder = new StringBuilder(1000000 * "Campbell".length()); for (int i = 0; i < 1000000; i++) { builder.append("Campbell"); } System.out.println("Finished StringBuilder with size: Using +="); String output = ""; for (int i = 0; i < 1000000; i++) { output += "Campbell"; } System.out.println("Finished :-)"); } }You can see how quickly the lines with a StringBuilder local variable are completed, and how much slower multiple += calls on a String are. You can time it with some System class methods. I tried that program; I could see the delay after “Stringbuilder without size”, but not after “Stringbuilder with size”, because it was so fast. But “Using +=” has been sitting running for over 10 minutes and not completed. Sudhir Srinivasan wrote: . . . I'll certainly do as suggested and get back to you once I'm ready with my response. regards, Sudhir Sudhir Srinivasan wrote:A more sophisticated explanation from you would help me understand better... Campbell Ritchie wrote:Don’t worry; it will complete in under a week
http://www.coderanch.com/t/556340/java/java/Convert-decimal-binary
CC-MAIN-2014-15
refinedweb
400
65.73
Let's say you want to implement a rough little search for an application without a proper backend. You could do it through lunr and generate a static search index to serve. The problem is that the index can be sizable depending on the amount of the content. The good thing is that you don't need the search index straight from the start. You can do something smarter instead. You can start loading the index when the user selects a search field. Doing this defers the loading and moves it to a place where it's more acceptable for performance. The initial search is going to be slower than the subsequent ones, and you should display a loading indicator. But that's fine from the user's point of view. Webpack's Code Splitting feature allows doing this. To implement code splitting, you need to decide where to put the split point, put it there, and then handle the Promise: import("./asset").then(asset => ...).catch(err => ...) The beautiful thing is that this gives error handling in case something goes wrong (network is down, etc.) and gives a chance to recover. You can also use Promise based utilities like Promise.all for composing more complicated queries. In this case, you need to detect when the user selects the search element, load the data unless it has been loaded already, and then execute search logic against it. Consider the React implementation below: App.js import React from "react"; const App = () => { const [index, setIndex] = React.useState(null); const [value, setValue] = React.useState(""); const [lines, setLines] = React.useState([]); const [results, setResults] = React.useState([]); const search = (lines, index, query) => index.search(query.trim()).map((match) => lines[match.ref]); const onChange = ({ target: { value } }) => { setValue(value); // Search against lines and index if they exist if (lines && index) { setResults(search(lines, index, value)); return; } // If the index doesn't exist, it has to be set it up. // You could show loading indicator here as loading might // take a while depending on the size of the index. loadIndex() .then(({ index, lines }) => { setIndex(index); setLines(lines); setResults(search(lines, index, value)); }) .catch((err) => console.error(err)); }; return ( <div className="app-container"> <div className="search-container"> <label>Search against README:</label> <input type="text" value={value} onChange={onChange} /> </div> <div className="results-container"> <Results results={results} /> </div> </div> ); }; const Results = ({ results }) => { if (results.length) { return ( <ul> {results.map((result, i) => ( <li key={i}>{result}</li> ))} </ul> ); } return <span>No results</span>; }; function loadIndex() { // Here's the magic. Set up `import` to tell Webpack // to split here and load our search index dynamically. // // Shim Promise.all for older browsers and Internet Explorer! return Promise.all([ import("lunr"), import("../search_index.json"), ]).then(([{ Index }, { index, lines }]) => ({ index: Index.load(index), lines, })); } In the example, webpack detects the import statically. It can generate a separate bundle based on this split point. Given it relies on static analysis, you cannot generalize loadIndex in this case and pass the search index path as a parameter. Beyond search, the approach can be used with routers too. As the user enters a route, you can load the dependencies the resulting view needs. Alternately, you can start loading dependencies as the user scrolls a page and gets adjacent parts with actual functionality. import provides a lot of power and allows you to keep your application lean. You can find the full example showing how it all goes together with lunr, React, and webpack. The basic idea is the same, but there's more setup in place. To recap: This book is available through Leanpub (digital), Amazon (paperback), and Kindle (digital). By purchasing the book you support the development of further content. A part of profit (~30%) goes to Tobias Koppers, the author of webpack.
https://survivejs.com/webpack/appendices/searching-with-react/
CC-MAIN-2021-04
refinedweb
625
58.48
In this ESP32 tutorial, we will check how to remotely control a relay using the Arduino core and the HTTP async web server libraries for the ESP32. Introduction In this ESP32 tutorial, we will check how to remotely control a relay. To do it, we will use the HTTP async web server library, which will allow us to set a web server on the ESP32, listening for requests that will change the state of the relay. For an introduction on how to control a relay using the ESP32, please consult this previous tutorial. The relay is a device that can be used to control circuits powered by the mains. In this tutorial, we will only cover the ESP32 code and the electric diagram to control the state of the relay. Please stay safe and don’t work with the mains if you don’t have experience with it, since it is dangerous. The ESP32 board used for this tutorial was a NodeMCU. The relay board used was this one from Elecrow, which can also be obtained as part of this kit. You can check the specs of the relay here. The electric diagram The electric diagram needed for this tutorial is basically the same as the previous tutorial and is shown in figure 1. If you need more information about it, please consult the previous post which contains a more detailed explanation. Figure 1 – Electric diagram for connecting the ESP32 to the relay board. Depending on your ESP32 board, you may be able to power the relay from a 5 v digital pin that some boards have. If you are not sure if you can power the relay from your board, the best option is to use an external power supply. You can find very cheap 5 v power supplies for breadboards here. Note that the code that we are using is agnostic to the type of actuator, as long as it can be controlled by a digital output pin. So, instead of controlling a relay, you can use it to control a LED or a motor, for example, as long you use the correct electronic schematic for the device to control. The code As mentioned in the introductory section, we will use the async HTTP web server libraries to set a web server on the ESP32 and to control the relay from a client over WiFi. You can check how to setup these libraries here. So, the first part will be equal to what we have been doing in previous posts about the async web server. We include all the libraries and declare the global variables needed to connect the ESP32 to a WiFi network and to set the server. #include <WiFi.h> #include <FS.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPass"; AsyncWebServer server(80); We will declare an additional global variable to hold the number of the digital pin that will control the relay. This way, we have a centralized place to change the pin number, which prevents having to go through all the code when we want to use a different pin. int relayPin = 23; Moving on to the Arduino setup, we will first set our GPIO as an output pin, so we can use it to control the relay. To do it, we call the Arduino pinMode function, which receives as first input the number of the pin we want to configure and as second a constant indicating the mode. We want our pin to work as output, so we pass to the function the constant OUTPUT. pinMode(relayPin, OUTPUT); We will explicitly set the state of the pin to low, so we always know the state of the relay when our program starts running. This is done by calling the Arduino digitalWrite function, which receives as input the pin number and the state. For the state we pass the constant LOW, so the pin is set to GND. digitalWrite(relayPin, LOW); Note that if we wanted to initialize the pin with a digital high value, we would pass the HIGH constant, so the pin would be set to VCC. Followed by that we will open a serial connection and then connect the ESP to the WiFi network, using the credentials we previously declared as global variables. After the procedure finishes, we will print the local IP assigned to the device, so the client knows the address where it can reach the server. Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.println(WiFi.localIP()); Once we finish the WiFi connection procedure, we need to declare the routes of our server. In our case and to illustrate a slightly more complex API, we are going to have three routes for actuating on the relay: one for turning it on, one for turning it off and another to toggle it. Additionally, we will set a route to get the current state of the relay. Note that this is one of the many options that we can follow to model our API. Another one could be having a single route taking a parameter that indicates the action to perform. Nonetheless, one interesting pattern that we can take advantage of by using different routes is that their name can already reflect the action that will be performed, making it easier to understand for clients just by reading the URL. Since we are going to update the state of a resource (the relay) that already exists in our server, we can follow an approach more aligned with the REST pattern and use a PATCH HTTP method [1]. Note that the HTTP method that should be used depends on what we consider a resource and if we are doing a partial or total update. Thus the use of the PATCH method may be arguable accordingly to what we consider a resource, but since we didn’t do that more conceptual analysis, the main point to highlight is that we should not use a GET method, since we are going to affect the state of the relay. The first route we will declare will be used to turn off the relay. We will call it “/relay/off“. In order to listen to PATCH methods, we need to pass the HTTP_PATCH enum value as second argument of the on method. Remember from previous tutorials that we use the on method of the server object to bind a handling function to a route and that its second argument receives an enum that specifies the HTTP methods allowed on the route. Our handling function will simply correspond to setting the state of the digital pin that controls the relay to low. This is done by calling the digitalWrite function with the same arguments we used in the setup function (the pin number and the constant LOW). Note that before the mentioned operation, we return the answer to the client right away, so the actual execution of the command is performed after answering the client. This is a common pattern to avoid leaving the client hanging, specially when the commands may take some time to execute. Naturally, this is an optimistically approach since we return an “OK” answer to the client before actually making sure that the command is successfully executed. In our case there’s not much to fail and thus it is safe to follow this approach, but in more complex procedures we need to carefully analyze before going to this asynchronous command execution approach. server.on("/relay/off", HTTP_PATCH, [](AsyncWebServerRequest *request){ request->send(200, "text/plain", "ok"); digitalWrite(relayPin, LOW); }); The next method will turn the relay on. Thus, following the previous pattern, the route will be “/relay/on”. The method allowed on the route will again be PATCH and the handling function will set the pin to a high value. server.on("/relay/on", HTTP_PATCH, [](AsyncWebServerRequest *request){ request->send(200, "text/plain","ok"); digitalWrite(relayPin, HIGH); }); The route for the toggle operation will be “/relay/toggle” and it will again listen to the PATCH method. Our handling function will be similar to the previous ones, with the particularity that the new state of the pin will depend on the current one. So, to get the current state of the pin, we can call the Arduino digitalRead function, passing as input the number of the pin. This will return the current state of the pin, which can be zero (LOW) or one (HIGH). You can confirm the values defined for these constants here. So, we can obtain the next state by negating the current state with the “!” operator (logical not). Negating 1 will give 0 and negating 0 will give 1, which is the toggle we want. Taking this in consideration, we can call the digitalRead function, apply the “!” operator and pass the result to the second argument of the digitalWrite function and the state of the pin will be toggled. server.on("/relay/toggle", HTTP_PATCH, [](AsyncWebServerRequest *request){ request->send(200, "text/plain","ok"); digitalWrite(relayPin, !digitalRead(relayPin)); }); To finalize our route declaration, we will have an endpoint to return to the client the current state of the relay. It will be listening on the “/relay” route and HTTP GET methods. To obtain the current state of the relay we use again the digitalRead function. Then, we convert the result to a string and return its value to the client. Just as a comparison note regarding the previous commands, when the client asks for information to the server, the execution is usually synchronous so the client gets the result in the same request. Alternative approaches may be triggering the information fetch asynchronously with a first request and then having the client polling for the result in subsequent requests. In our case, our operation of fetching the relay state is really fast, so we opt for the simplest synchronous approach. server.on("/relay", HTTP_GET, [](AsyncWebServerRequest *request){ request->send(200, "text/plain", String(digitalRead(relayPin))); }); To finalize, we need to call the begin method on our server object, so it starts listening to incoming requests. The final source code for this tutorial can be seen below and already includes this call. #include <WiFi.h> #include <FS.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPass"; AsyncWebServer server(80); int relayPin = 23; void setup(){ pinMode(relayPin, OUTPUT); digitalWrite(relayPin, LOW); Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } Serial.println(WiFi.localIP()); server.on("/relay/off", HTTP_PATCH, [](AsyncWebServerRequest *request){ request->send(200, "text/plain", "ok"); digitalWrite(relayPin, LOW); }); server.on("/relay/on", HTTP_PATCH, [](AsyncWebServerRequest *request){ request->send(200, "text/plain","ok"); digitalWrite(relayPin, HIGH); }); server.on("/relay/toggle", HTTP_PATCH, [](AsyncWebServerRequest *request){ request->send(200, "text/plain","ok"); digitalWrite(relayPin, !digitalRead(relayPin)); }); server.on("/relay", HTTP_GET, [](AsyncWebServerRequest *request){ request->send(200, "text/plain", String(digitalRead(relayPin))); }); server.begin(); } void loop(){} Testing the code To test the code, simply compile it and upload it to your ESP32, after finishing all the electronic wiring needed. After the procedure finishes, open the Arduino IDE serial monitor and wait for the device to connect to the WiFi network. Once the connection is established, the local IP of the ESP32 on the network will be printed. Copy that IP. In order to send commands to the ESP32, we need to use a tool such as Postman, which allows us to perform HTTP PATCH requests, amongst many other functionalities. So, open Postman and put the following in the URL bar, changing #yourDeviceIp# by the IP you have just copied and #command# by one of the 3 commands we have defined. Then, on the method dropdown of Postman, select PATCH and click the send button. You should get an output similar to figure 2, where we have sent a toggle command. Figure 2 – Sending the toggle command using Postman. You can also get the current state of the relay by sending a GET HTTP request to the server. For this, you don’t need Postman and can simply access the URL below on a web browser. In the video below you can check a live demo of toggling the relay. References [1] 8 Replies to “ESP32 Arduino HTTP server: controlling a relay remotely” What Arduino IDE do you use ? J have problem with Arduino IDE 1.6.8 and test Arduino IDE 1.5.8 and always error in compilation AsyncTCP.h not found please help LikeLiked by 1 person Hi! I’m using version 1.8.5 of the IDE. Did you install the ayncTCP libraries like shown here? Best regards, Nuno Santos
https://techtutorialsx.com/2018/03/02/esp32-arduino-http-server-controlling-a-relay-remotely/
CC-MAIN-2019-04
refinedweb
2,114
61.97
junit junit why we are going to junit? Hi, Junit is unit testing framework to unit test Java applications. It is advisable to the java developers to write Unit test to test their code. Junit test is used to test junit junit Explain about junit? Junit is new framework designed for Java to perform unit testing. It is an Open source framework. Junit... ). It helps the developers in designing and writing test cases. Junit also have Junit Junit Hi sir My question to you is - What is JUnit? Hi Friend, Junit is a Unit testing framework for java programming.......CPPUnit for C++, JSUnit for java script, PHPUnit for PHP unit testing. I hope, java - JUNIT java junit tool which purpose is used Hi Friend, junit is used for testing java programs. For more information, visit the following link: Thanks java - JUNIT java i am doing junit testing for a website,i required to check the value of text(ex:refund=0)inside a // refund 0 // tag from a web page...:// Hope that it will be helpful for you. Thanks Need of JUnit Need of JUnit Hi sir, What makes JUnit better than other testing tools for Java Unit testing? Hi friend.. It is better to know... features which make JUnit better for Unit testing : 1.JUnit tests allow you to write Junit JUnit Junit is new framework designed for Java to perform unit testing. It is an Open source framework. Junit is an instance of xUnit architecture... and writing test cases. Junit also have a Graphical User Interface which allows JUNIT - JUNIT JUNIT Hi, all please help me ..... how to Generate Cactus Report for JUNIT Testcase... These Test cases are written for JSFPages..it's very Urgent in our Project. Thanks in Advance.... The problem is that many Java applications are too brittle to extend and enhance Ant and JUnit for the compiling and building the Java based application. With the help of JUnit and other... Ant and JUnit This example illustrates how to implement junit test case JUnit 4.3.1 involved in testing with JUnit. In this section, we will be creating a java file...JUnit 4.3.1 JUnit... designed for the purpose of writing and running tests in the Java programming JUnit Training JUnit Training JUnit is an open... in the Java programming language. It's a regression-testing framework that developers.... JUnit helps us to code and test any time when you make any changes in your code Ask JUnit Questions Online Ask JUnit Questions Online JUnit is a free, open source Java framework that makes.... JUnit has become a popular framework for writing and testing the Java Code JUnit and its benefits JUnit and its benefits JUnit is an open source framework that has been designed for the purpose of writing and running tests in the Java programming language. JUnit was originally spring with junit and mock testing spring with junit and mock testing spring with junit mock testing junit - Framework Testcases - JUNIT connectivity - JUNIT testcases - JUNIT JUnit 4.3.1 JUnit 4.3.1 JUnit and its benefits Unit is an open source framework that has been designed for the purpose of writing and running tests in the Java Stub or Mock in JUnit Stub or Mock in JUnit What is stub and Mock in JUnit? Please give one real time example so that i can understand easily. Consider a situation, where you have a class Calculator, that needs a dao (Data Access Object Running 'assertEquals' method in Junit Test From Ant class. JUnit and Ant are necessary tools for Java development. JUnit provide... Running 'assertEquals' method in Junit Test From Ant... (excepted, actual) method are used to test the application with the JUnit test case - JUNIT What's the proper way to test a class with private methods using JUnit? What's the proper way to test a class with private methods using JUnit? What's the proper way to test a class with private methods using JUnit Downloading and installing JUnit 4.3.1 s Downloading and installing JUnit 4.3.1 s In this section, downloading JUnit 4.3.1 address... JUnit 4.3.1 from in the zipped format mca entrance sample papers - SQL mca entrance sample papers please send me sample papers of MCA entrance exam.. thanks in advance JUnit Test 'assertTrue' Example Using Ant JUnit Test 'assertTrue' Example Using Ant... build.xml file is used to compile, test and run the java file. The <property name... Sample java program Sample java program I want a sample program: to produce summary information on sales report. The program will input Data of Salesman Id, Item code, and number of cuestomer. Sales id is 5digit long, and items code range from java sample code - Java Beginners java sample code hai...... i need a full sample program fo inheritance......... Hi Friend, Please visit the following link: Thanks error in sample example error in sample example hi can u please help me XmlBeanFactory class is deprecation in java 6.0 so, pls send advance version class Use XmlBeanFactory(Resource) with an InputStreamResource parameter Sample Code For ArrayLlist - Java Beginners Sample Code For ArrayLlist Hi Friend, I want sample... ArrayList.Give sample code for Arraylist with realtime application. Hi I... about ArrayList. java sample program - Java Beginners java sample program hai i need a sample program for polymorphism Hi Friend, Try the following code: class Shape { int x,y; void area(){ } } class Square extends Shape { int l=2; void area Sample program of JSP Sample program of JSP <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " Sample program of JSP Input program in JSP <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " need a Sample code - Development process need a Sample code i want run the python script in java code by using Runtime class and output should be formed like XML format.please help me. Advanced Thanks, Krishna Java with EJB 3 Java with EJB 3 Position Vacant: Java with EJB 3 Job Description ... at writing JUNIT test cases. DBUnit experience is a plus.  Iterator Java Sample Java Sample Iterator interface makes the traversing of the elements easy...() Java Sample Iterator Example import java.util.ArrayList; import... sample { public static void main(String[] args) { List list = new ArrayList Eclipse Plunging/Testing service from Agitar. Send us Java code, and JUnit Factory sends back JUnit code... structure. Java developers are used to unit testing because of JUnit and its tight... Test provides powerful JUnit test case generation and code coverage analysys Looking for sample project in java using netbeans Looking for sample project in java using netbeans Hi all, i am novice in developing desktop application in java using netbeans. can anyone pls help...;Please visit the following link: Writing and testing method of addition of two numbers is passed. How to run JUnit in text mode : Execute java junit.textui.TestRunner... example that will illustrate the basic concepts involved in testing with JUnit. In this section, we will be creating a java file named Calculator.java which has java - IDE Questions java how do you do junit test in eclips Hi friend... of writing and running tests in the Java programming language. Read for more information, Java and SQL - SQL Java and SQL i have a problem with regard to connecting my java code in getting a data to SQL. my problem is on how to come up with a pop up alert message in the user interface where in the message will be coming from the SQL java,sql java,sql Hello sir,iam sireesha studying MCA.i want a project on educational details of a student by using jdbc,odbc connection including sql queries.please send me the reply. Hi, Please visit sql,java sql,java i am writing some code in java.that values are stored in database.plz send me one example for this for example taking the fields as s.no,category,name of the candidate,age,title of the project,video uploading,photo Collection of Large Number of Java Sample Programs and Tutorials Collection of Large Number of Java Sample Programs and Tutorials Java Collection Examples Java 6.0 New Features (Collection Framework... will read the advantages and disadvantages of Java Collection Framework DbUnit Training the popular JUnit test framework DbUnit provides a very simple XML based... subsequent test to fail. Prerequisites: Candidate should have basic Java programming java - SQL java hi . i am asifa and i for the last few days i was trying to display the backend fields to the frontend ,am using sql as the backend am using ecclipseeuropa IDE .can u please send the code for displaying the backend fields java .sql java .sql where are the interfaces of java.sql like STATEMENT,CONNECTION are defined insertion in SQL - SQL in the database because of single code in the name. dbase is MS-SQL emp.name data type... as I know string parameter in SQL is denoted as 'john' . I think thats why... str = "John's"; str = str.replace("'","\\'"); String sql java,sql java,sql Hello sir,iam an MCA student.I want a project code of jdbc,odbc connection for educational details of a student.please send me the code. you din't send me the reply,please send it fastly sir Java sql Exception Java sql Exception difference between sql exception class and sql warning class JAVA to SQL JAVA to SQL package abhijeet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import...; } } plzzz help mw wid dis... 1: i hav read and Excel file in java java,sql java,sql Hello sir,iam sireesha studying MCA.I want a project code on JDBC,ODBC connection to display student administration system (or) student information system (or) college administraion system.Please send me the code sir java - SQL SQL or UNICODE - SQL SQL or UNICODE Hi again............ I have got something new that........... i was using MS Access as the database with my JAVA Japplet... ...... I had also change my backhand to SQL SERVER but retrieves same for UNICODE CoViewDeveloper code by designing and creating JUnit tests and measuring path coverage... create JUnit tests. Simply select your method and start the CoView JUnit Wizard. Answer some questions and some advanced JUnit stubs (often times complete sql connectivity through java sql connectivity through java i want an example for java db through sql connection. Thanks in advance Executing anonymous pl/sql block and get resultset in Java names will be same always. Here i am giving sample pl sql block. BEGIN RETURN...Executing anonymous pl/sql block and get resultset in Java Hello All, I would like to execute the anonymous pl sql block and need to get Sample Java program for beginners Here beginners in Java can learn to create there first Hello World program in Java. To install Java one needs JDK (Java Development Kit), which can..., a programmer is ready to create their own Java program. Here we have also described createdatabase - SQL createdatabase hello please help me... I'm a student and I want to create database using SQL how I can Connect java with SQL. thanks Hi Friend, Please visit the following link: Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/96175
CC-MAIN-2015-32
refinedweb
1,924
57.06
Hi guys... my question is about implementation of wait and notify to simulate threading...here is the Problem description: I have an application to simulate 2 trains travelling in the same direction on a loop from station, through a tunnel and back to the station ;normaly on 2 seperate tracks.however both tracks pass through the tunnel wich has one single track: so there should be one train at a time in the tunnel... what i need is to rewrite method useTunnel() given below so that train 1 and 2 are allowed to enter tunnel in strict rotation:train 2 should be allowed to enter first then train 1 then 2 and so on...method useTunnel should contain code to enforce the ordring of which train can enter at a given time...for this we should use wait and notify and maybe change the Tunnel constractor...how can i do this? the code is below (classes Train.java , Tunnel.java ans Simulate.java) many thanks for helping //Train class public class Train extends Thread { private int id; // id identifies each train public Train(int id) { // each train has a different identifing number this.id = id; } private static Tunnel tun = new Tunnel(); // only one tunnel public void run() { // each train makes 2 loops for (int j=0; j < 2; j++) { System.out.println("Train " + id + " leaves station"); travel(10); // train takes 10 time units to travel from station to tunnel System.out.println("Train " + id + " arrives at tunnel"); tun.useTunnel(this); // current train uses tunnel travel(15); // train takes 15 time units to travel from tunnel to station System.out.println("Train " + id + " arrives at station"); travel(5); // train stays in station for 5 time units } } public int getId () { return id; } public void travel(int time) { int limit = 500000*id; for (int j=0; j < time; j++) { for (int k=0; k < limit; k++) {double r = j / 2 * 2;} } } } //Tunnel class public class Tunnel { public void Tunnel () {} public void useTunnel (Train t) { /* the tunnel is a shared resource between Train 1 and 2 .so we should use a synchronized block to lock the object "Tunnel" from being accessed simultaneousely by Train 1 and 2 */ synchronized(this){ System.out.println("Train " + t.getId() + " enters tunnel"); t.travel(20); // train takes 20 time unit to go through tunnel System.out.println("Train " + t.getId() + " exits tunnel"); } } } //Simulate class public class Simulate { public static void main(String [] args) { // *************************************** Train t1=new Train(1); t1.start(); Train t2=new Train(2); t2.start(); // Keeps output on screen until Return is pressed System.out.println("Type return to terminate program"); try { System.in.read(); } catch (IOException e){} } } Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?136286-Threading-wait-notify...please-help-!&p=402700&mode=threaded
CC-MAIN-2016-18
refinedweb
459
53.51
However, if you're out of town or something, you may email the writeup (in text, postscript, or pdf format only, i.e. not ms word) to aistaff, but then of course you have to send this in by midnight sunday. For the problem 5b web tester, i will ask you to include your state calculation code (same procedures as problem 1) in the file you upload for this problem. This is because the state calculation procedures you use for this problem need not be the same as the procedures you upload for problem 1. The argument player-hand will consist of a list of two cards that the player was initially dealt; dealer-hand will consist of a list of one card, the dealer's face-up card. This procedure must return a valid reinforcement learning state (a nonnegative integer between zero, inclusive, and the number of states declared to create-tables, exclusive). Needless to say, calc-new-state should also return a valid reinforcement learning state. I've updated the assignment handout on the handouts page. You don't need to use a lot of states for this assignment, however, the states should represent different situations of the game. At one extreme, you could have separate states for each possible combination of cards. However, there's a lot of "duplication" here. for example, the following initial hands: 2 and 9, 3 and 8, 4 and 7, 5 and 6, would be played the same way, so it's fine for them to be represented by the same state. At the other extreme, you could get away with using only two states: one for "still playing the hand" and one terminal state. This, however, would treat all hands in exactly the same way, whereas you really should play hands differently depending on the value, soft hand or not, dealer's face-up card, etc. You should use some knowledge to structure the states, but you should leave some room for the program to learn. For example, if you think you should always stand on 14 or higher and always hit on 13 or less, you might use just those two states as initial states. Your program will learn the utilities for those states so it can make an optimal decision based on what action to take in those two states. However, you have deprived your program the opportunity to learn whether it might be better to hit on 9 or less and double down on 10-13 because those two situations fall into the same initial state. If you structure the layout of your states well, calculating the states shouldn't be much work. For my 400 state implementation, my calc-initial-state and calc-new-state are (together) about 40 lines of code (nicely broken and indented). You can take some ideas from a7example.scm. (define e-strat (create-exploring-rl-strategy 5.0 10)) ; in the example tables i got, state 4 is one of the nonterminal ; states, so i am testing my code on that state (map (lambda (a) (get-action-transitions 4 a)) '(hit stand double-down)) ;Value: (0 0 0) (do ((i 0 (+ i 1))) ((= i 30)) (let ((a (e-strat 4 '(hit stand double-down)))) (print a " ") (increment-action-transition 4 a))) ; here's all the actions my strategy chose double-down stand double-down stand double-down double-down double-down hit stand double-down hit stand double-down double-down double-down hit stand stand hit stand double-down stand hit hit stand stand hit hit hit hit (map (lambda (a) (get-action-transitions 4 a)) '(hit stand double-down)) ;Value: (10 10 10) ; now it should pick the action with the maximum expected utility (e-strat 4 '(hit stand double-down)) ;Value: hit ; note that this is what the basic-rl-strategy does all the time (basic-rl-strategy 4 '(hit stand double-down)) ;Value: hit A few clarifications: the value returned by a learning procedure is ignored. For this problem, it must update the utility of state fs. My utility values did not converge as nicely as I would have liked them to. I don't think I ever saw a maximum utility value change (after a round of maybe 1000 or 10,000 hands) of less that 0.001. A maximum change of less than 0.05 or even 0.01 occurred after not too many rounds. You may want to try changing your alpha value, i.e. play some number of rounds with an alpha of 0.05 or 0.01 and then create a new learning procedure that is going to use an alpha of say 0.001 for the remainder of the rounds. You could let the maximum utility value change be your guide — if you have max changes of say 0.1 or 0.2, then decreasing alpha to 0.001 is probably not appropriate at that point. Note that you can stop learning at any time and test how well your utility values work by playing, I would suggest, 100,000 hands with the basic-rl-strategy. (I'd keep table updates turned off here.) Remember that the policy will converge before the utility values do. The thing is that a strategy procedure is given only the state number — not the player's cards. Therefore, you have to set up the states that that strategy needs and then encode the actions that should be taken from each state. This is essentially hardcoding a policy in the strategy procedure. Version 1.1.3 (released 12/5) contains two minor bug fixes and some changes we needed for the web testers. the bugs fixed include: printing bug for exact numbers used as utilities or rewards, the bj-value and soft-hand? procedures now signal an error if you give them an invalid card (actually, they don't check the suit, only the value). Version 1.1.2 (released 12/4) contains a bug fix (the dealer's face-up card was passed to calc-initial-state as it should, but the dealer's face-down card was passed to calc-new-state for transitions to nonterminal states) so this was corrected; when dealer and player both have blackjack, it's a push but wasn't treated as such (this doesn't affect learning but does affect the net winnings); there are a few new procedures in the support code (documented below) though you probably don't need these; and finally, the error checking on arguments passed to the support code was slightly improved. Version 1.1.1 (released 11/29) contains no changes to the functionality of the support code. There was one minor bug fix and a little cleaning up of the namespace. Version 1.1 (released 11/26) was the initial release of the support code. (print-rl)This procedure calls print-transitions, print-rewards, and print-utilities. This web tester only checks to make sure that you have uploaded a working (and consistent) set of state calculation procedures. I'd advise you to wait until you have done at least an initial implementation of your game-state to reinforcement-learning-state idea and have tested it by learning a blackjack player. The a7example.scm file will pass this test; however, you will (after the fact) receive 0 credit (and still use one of your submissions) if you just submit this file (or trivial variations of it). You should upload something much closer to your final state calculation scheme. This web tester will have your basic-rl-strategy procedure choose actions in a randomly generated (but still blackjack-like) state space. This web tester will make sure that a strategy procedure returned by your code actually does explore the different actions from a state but later picks the action with the maximum expected utility. This web tester will check that your code does updates using the temporal differencing update rule correctly. This web tester will simply collect a file; there will be no tests run online The file you turn in must have the tables you saved after learning a model of blackjack (e.g., by playing the random player for at least 10,000 (though preferrably 100,000 or more) hands). You must also include your state calculation procedures (i.e., the same procedures as for problem 1) that you used to create these tables.. This web tester will simply collect a file; there will be no tests run online The file you submit must have your final tables, and you should include any code you wrote for this part, e.g., any code to "automate" the temporal differencing learning.. (get-action-alist 0) ;Value: ((hit (1 .583) (0 .208) (6 .209)) ; (stand (2 1.)) ; (double-down (4 .801) (6 .199))) (get-transition-actions 0) ;Value: (hit stand double-down)
http://www.cs.rpi.edu/academics/courses/fall04/ai/assign/assign7/
crawl-002
refinedweb
1,478
59.74
Mapper component The Mapper component handles the mapping of CQL table columns to fields in your classes. The Mapper component (previously known as cqlpoco) is a lightweight object mapper for Apache Cassandra. It lets you write queries with CQL, while it takes care of mapping rows returned from Cassandra to your classes. It was inspired by PetaPoco, NPoco, Dapper.NET and the cqlengine project. To use the Mapper: 1.- Add the following using statement to your class: using Cassandra.Mapping; 2.- Retrieve an ISession instance in the usual way and reuse that session within all the classes in your client application. 3.- Instantiate a Mapper object using its constructor: IMapper mapper = new Mapper(session); New Mapper instances can be created each time they are needed, as short-lived instances, as long as you are reusing the same ISession instance and mapping configuration. The Mapper works by mapping the column names in your CQL statement to the property names on your classes. For example: public class User { public Guid UserId { get; set; } public string Name { get; set; } } // Get a list of users from Cassandra IEnumerable<User> users = mapper.Fetch<User>("SELECT userid, name FROM users"); IEnumerable<User> users = mapper.Fetch<User>("SELECT * FROM users WHERE name = ?", someName); Simple scenarios such as this are possible without doing any further mapping configuration. When using parameters, use query markers ( ?) instead of hardcoded stringified values, this improves serialization performance and lower memory consumption. The Mapper will create new instances of your classes using the parameter-less constructor. Configuring mappings In many scenarios, you need more control over how your class maps to a CQL table. You have two ways of configuring Mapper component of the driver will use the configuration defined when creating the Mapper instance to determine to which keyspace and table it maps to, using MappingConfiguration.Global when not specified. Mapper API example A simple query example is great, but the Mapper has many other methods for doing things like Inserts, Updates, Deletes, selecting a single record and more. And all methods have async counterparts. Here’s a quick sampling. // All query methods (Fetch, Single, First, etc.) will auto generate // the SELECT and FROM clauses if not specified. IEnumerable<User> users = mapper.Fetch<User>(); IEnumerable<User> users = mapper.Fetch<User>("FROM users WHERE name = ?", someName); IEnumerable<User> users = mapper.Fetch<User>("WHERE name = ?", someName); // Single and SingleOrDefault for getting a single record var user = mapper.Single<User>("WHERE userid = ?", userId); var user = mapper.SingleOrDefault<User>("WHERE userid = ?", userId); // First and FirstOrDefault for getting first record var user = mapper.First<User>("SELECT * FROM users"); var user = mapper.FirstOrDefault<User>("SELECT * FROM users"); // All query methods also support "flattening" to just the column's value type when // selecting a single column Guid userId = mapper.First<Guid>("SELECT userid FROM users"); IEnumerable<string> names = mapper.Fetch<string>("SELECT name FROM users"); // Insert a POCO var newUser = new User { UserId = Guid.NewGuid(), Name = "SomeNewUser" }; mapper.Insert(newUser); // Update with POCO someUser.Name = "A new name!"; mapper.Update(someUser); // Update with CQL (will prepend table name to CQL) mapper.Update<User>("SET name = ? WHERE id = ?", someNewName, userId); // Delete with POCO mapper.Delete(someUser); // Delete with CQL (will prepend table name to CQL) mapper.Delete<User>("WHERE id = ?", userId);
https://docs.datastax.com/en/developer/csharp-driver/3.7/features/components/mapper/
CC-MAIN-2019-43
refinedweb
540
51.44
CPSC 124 (Winter 1998): Lab 3 Subroutines (Part 1) THE THIRD LAB IN COMPUTER SCIENCE 124 deals with using subroutines that have been written for you and with writing the insides of subroutines whose basic format is already written for you. In the process, you will create an applet and learn something about how applets respond to event and how they can use multi-threading. You will also get more experience with using while statements and if statements. Next week, we'll move on to designing and writing complete programs that include subroutines that you write from scratch. You'll need several project folders from the cpsc124 folder on the network. Copy the following folders into the java folder on your M drive: "Jumping Square Starter", "Mosaic Starter #1", and "Mosaic Starter #2". Each of these is the starting point for one of the exercises at the end of the lab. Sample solutions for each of the exercises can be found on the following separate pages: Exercise 1. Exercise 2. Exercise 3. The exercises at the end of the lab are due in class on the Monday following the lab. Outline of the Lab: - About the MosaicFrame Class - A Better Random Walk - Conversion Experience - An Applet with Action - Exercises About the MosaicFrame Class A subroutine is a set of instructions for performing some task, chunked together into a "black box" and given a name. A programming language can have some built-in subroutines, like Math.random(), that are a part of the basic language and are always available. A programmer can also write new subroutines and then use them in the same way that built-in subroutines can be used. Of course, one programmer can also use subroutines written by another programmer. For example, you have already used subroutines defined in the Console class, which is not a standard part of Java but was provided to you to perform certain kinds of input/output tasks. In the first two exercises of the lab, you will again be using subroutines that have already been written as methods in a class that is provided to you. The class is called MosaicFrame. An object in this class represents a window containing a grid of colored rectangles. Initially, all the rectangles are black, but methods are provided for setting the color of a given rectangle and for checking on the current color of a given rectangle. You should open the folder "Mosaic Starter #1." (If you have not already copied it into the java folder of your M drive, do that now.) Execute the program. You'll see a small red rectangle that wanders around in a black window. (Actually, the "motion" is an illusion that is achieved by turning various little squares in the window from red to black and back again.) You will want to read the source file, MosaicApplication.java, since you will have to modify this file to do Exercise 1. You might also want to look at the comments in MosaicFrame.java, since that is the file that defines all the methods that have been provided for working with MosaicFrame windows. You'll only need a few of the methods, though, and those are mentioned below. A MosaicFrame window can be created and opened with a statement such as: MosaicFrame mosaic = new MosaicFrame(20,30); The window created will have 20 rows and 30 columns of rectangle. Each rectangle will be 10 pixels by 10 pixels (so it is, in fact, a square). The name of the window is "mosaic", and this variable can be used to call methods for checking as setting colors. You can, of course, use a different name for the window, and you can use different numbers of rows and columns. It is also possible to specify the width and the height to be used for the rectangles. See the Java source code files for details. If there are R rows in the window, then they are numbered from 0 to R-1. Similarly, if there are C columns, they are numbered from 0 to C-1. You can specify a particular rectangle by giving the number of the row that it is in and the number of the column that it is in. If you use row or column numbers outside the valid ranges, it won't crash the program. However, it's still an error and you might not get the effect that you want. I will be looking for this type of error when I grade your lab reports. You should try to avoid them by careful and thoughtful programming. To use a MosaicFrame, you have to know a little about the way colors are specified on a computer. Any color that can be displayed on a computer is made up of some combination of the "primary colors," red, green, and blue. In MosaicFrame, the level of each primary color is given as an int number in the range 0 to 255. A color is specified by three numbers giving the levels of red, green, and blue in the color. Colors specified in this way are referred to as "RGB colors." A color with a red component equal to 0 contains no red at all; a color with a red component equal to 255 contains the maximum possible amount of red. Black is given by red, blue, and green components all equal to 0. White is given by all components equal to 255. (In MosaicFrame, if you try to use numbers outside the range 0 to 255 to specify a color, any number less than 0 will be treated the same as 0, and any number bigger than 255 will be treated the same as 255.) Here are some methods that you can use with a variable, mosaic, of type MosaicFrame: - mosaic.setColor(row, column, r, g, b) sets the color of the specified rectangle, where r, g, and b are the red, green, and blue components of the color (in the range 0 to 255). - mosaic.fill(r, g, b) fills the window with a uniform color by setting the color of each rectangle to the color specified by red, blue, and green components r, g, b. - mosaic.fillRandomly() fills the window with randomly colored rectangles. - mosaic.delay(n), where n is an integers, will cause the program to wait, without doing anything, for about n milliseconds. 1000 milliseconds are equal to one second. The timing is not very exact. This can be used to control the speed at which a program executes. The following methods are used to find out the current levels of red, green, and blue in a given rectangle. The value returned by the routine would ordinarily be assigned to a variable of type int, as in: "b = mosaic.getBlue(r,c);" - mosaic.getRed(row, column) returns an integer in the range from 0 to 255 giving the red component of the current color of the rectangle in the specified row and column. - mosaic.getGreen(row, column) returns an integer in the range from 0 to 255 giving the green component of the current color of the rectangle in the specified row and column. - mosaic.getBlue(row, column) returns an integer in the range from 0 to 255 giving the blue component of the current color of the rectangle in the specified row and column. Finally, here is a useful method that indicates whether or not the mosaic window has been closed by the user. The method returns a boolean value. In the sample program in "Mosaic Starter #1", this method is used in a while loop that continues as long as the window is open. - mosaic.stillOpen() returns a boolean value indicating whether or not the MosaicFrame window has been closed by the user. This value is true if the window is still open and is false if the user has closed the window. (Note, by the way, that the mosaic window is similar to the one that I describe in Section 3.6 of the text. However, in the text, color components are specified as real numbers between 0.0 and 1.0 instead of an integers between 0 and 255. I decided to switch to integers because integers are what are actually used in the computer to represent colors. Here is the source code for MosaicFrame and for another class, MosaicCanvas which it uses. You should not expect to understant the source code at this point in the course.) A Better Random Walk For your first exercise, you will modify the program in "Mosaic Starter #1" so that it does a more interesting kind of random walk. The effect that you will try to achieve is shown in a sample applet on a separate page. You should look at the example and read the comment on that page. The changes that you have to make to MosaicApplication.java are actually fairly small, but you won't be able to do them easily unless you really understand how the original random walk program works. Read the source code, read the comments, and make sure you understand what is going on. (You can also read the source code here.) You want to modify the program so that a "disturbance" wanders around the window. This is not much different from the wandering red square, except that the disturbance itself is invisible. Each time the disturbance visits a square, you want to read the level of green in that square, add 10 to that level (up to a limit of 255), and reset the color of the square. You'll want to make the "delay" in the while loop pretty small to get a good effect. I use "mosaic.delay(5)" in my applet. You might want to try this program using red, blue, or gray instead of green. (A gray color is one that has equal red, blue, and green components.) Conversion Experience For your second exercise, you should use the starter folder "Mosaic Starter #2." Copy it into the java folder on your M drive, if you have not already done so. Open the project in this folder, and execute the program. You get a window filled with randomly colored squares. This is produced by a single call to the method mosaic.fillRandomly(). (You can read the source code here.) Your assignment is to add a while loop to the main() routine so that the program will behave like the sample solution to this exercise, which is shown as an applet on a separate page. In your loop, you should first choose a random square by choosing a random row and a random column. Randomly select one of the four neighbors of that square, and convert the color of the selected square to the color of its selected neighbor. (This program models, in a vague way, a population where people have a tendency to be like their neighbors or to join coalitions with their neighbors. Let's say each color represents a political party. Initially, everyone belongs to a different party. However, people look around at what their neighbors are thinking, and they have some tendency to be converted by their neighbor's opinion. What will happen in the long run? Remember that "extinction is forever." Once the last square of a give color is converted, that color is gone forever.) The while loop you want to write has some similarities to the loop in "Mosaic Starter #1." In fact, you might want to copy-and-paste that loop into the program in "Mosaic Starter #2." However, the problem here is significantly different and you should not expect everything to carry over exactly. Think about what you want to do, and plan your while loop before you start working on it. An Applet with Action For the third exercise of the lab, you will be working on an applet. The starting point is the folder "Jumping Square Starter." Copy it to your M drive if you have not already done so. Open the project in the "Jumping Square Starter" folder and execute it. (You can also read the source code here.) The applet displays a red square in a random position. Each time the user clicks on the red square, it jumps to a new location. You'll also see that the number of seconds that have elapsed since the applet started is displayed in the upper left corner of the applet. (Note that the applet might flicker a bit when the time changes or when the square jumps. There is a way to fix this, but I am trying to keep things simple for now. We will return to this problem later in the course.) Your assignment is to turn this modest little applet into a duplicate of the rather annoying applet that is shown on a separate page. The new version is a kind of game. The square jumps around randomly. The user tries to click on it. The applet keeps track of how may time the user hits the square and how many times the user misses. These numbers are displayed on the applet along with the elapsed time. There are two different things going on in this applet: It responds to the event that occurs when the user clicks on the applet. And it has another process or thread that runs continuously, like a separate program. It is this thread that keeps track of the time. In the final version of the applet, the same thread also moves the square around even when the user doesn't click on it. Here's how it works. First of all, the class MosaicApplet has a so-called "mouseDown" method, which takes the form:public boolean mouseDown(Event evt, int x, int y) { . . // commands to be executed when user clicks in the applet . return true; } This method is an event handler. It is a routine that is called by the system when the user clicks on the mouse. It is not ordinarily called from elsewhere in the program. Your job as a programmer is to write the inside of the mouseDown() routine to specify what should happen when the user clicks on the applet. The x and y parameters, which are provided by the system when the routine is called, tell you the horizontal and vertical coordinates of the point in the applet where the user clicked. The other aspect of this applet is the separate thread that runs independently of user-generated events. The MosaicApplet class begins with the line public class MosaicApplet extends Applet implements Runnable To say that a class "implements Runnable" means, essential that it has a "public void run()" method that can be run as the program of an independent thread. In this example, the thread is created in the applet's start() method, which is called by the system when the applet starts to run. As soon as the thread starts, it begins to execute the run() method of the applet. The run() method is provided for the use of this thread, and it is not meant to be called directly. By filling in the run() method, you are in effect writing a program for the thread. Any class that contains a run() method can be used to create threads in the same way, and it is possible for a program to create many threads that are executed concurrently (in addition to the basic, original thread that I have been referring to as the "system.") Your job is to make several modifications to the MosaicApplet class: - Add variables to count the number of times that the user hits the square and the number of times that the user misses. Since these variables are to be used in several methods, they must be declared outside of any method, just like the existing variable, elapsedTime. - Modify the paint() method so that in addition to displaying the square and the elapsed time, it also displays the number of hits and the number of misses. - Modify the mouseDown() method so that in addition to checking whether the user has clicked inside the square, it also keeps track of the number of hits and the number of misses. - Modify the run() method so that in addition to keeping track of the elapsed time, it also makes the square jump at random occasionally. Note that a method, doJump(), is provided to make the square jump. Check out how it is done in mouseDown(). In my applet, in the run() method, I make the square jump with a probability of 0.1 each time the while loop is executed. After your applet is created, you will want to publish it on the Web so that you can annoy your friends in California. To do this, you will have to use FTP to copy the files JumpingSquare.class and JumpingSquare.html to your account on hws3.hws.edu. If you don't remember how to do this, review Lab 1. You might want to edit JumpingSquare.html to add some text or make the page look a bit fancier. If you want some hints on maintaining your Web site, look back at Lab 2. Exercises to Turn in Exercise 1. Turn in a print out of the "random walk" program that you modified above. The work you did was all in the file MosaicApplication.java, and that is the only file you should turn in. Make sure that it follows good programming style. You will have to erase some of the comments that are there and replace them with your own. Exercise 2. Turn in a print out of the MosaicApplication.java file for the "conversion" program that you wrote above. Again, make sure it follows proper style. Exercise 3. For this exercise, turn in a copy of the JumpingSquare.java program that you modified above. For this one time, you don't have to worry about getting the comments right. I also want to check that you have successfully added the applet to your web site on hws3.hws.edu. Please give me the URL for your page. Optional Extra-credit Exercise. If you like, you can get a few points of extra credit by making one of your "mosaic" programs from Exercise 1 or Exercise 2 into an applet and adding it to your Web site. Use the folder "Mosaic Applet Starter" as a starting point. Like the JumpingSquare applet, the MosaicApplet has a run() method. You should be able to copy your program (except for the line that creates the MosaicFrame) into the run method of the MosaicApplet. You might want to make up your own mosaic program. Be creative! You could even make the applet respond to mouse clicks by providing a "public void boolean mouseDown(Event evt, int x, int y)" method.
http://math.hws.edu/eck/cs124/labs98/lab3/index.html
crawl-001
refinedweb
3,140
71.65
I have video features (Batch, Time, Spatial, Feature_dim), like (32,15,4,2048). and I need first a dimension transform using a nn.Liear(2048,512) . But some features are masked according the associating mask (B,T,S) (True means yes,False means no) How do I avoid updating this layer with unwanted features ? I have video features (Batch, Time, Spatial, Feature_dim), like (32,15,4,2048). How is the mask applied? How do you update the parameters of this layer? Is there a loss function? For example : in attention models the mask is multiplied by the attention scores to avoid taking them into account in the calculation of the output: everything is managed at the model level in classification it is also common to provide a weight parameter to the loss function (binary_cross_entropy_with_logits, cross_entropy…) to avoid the update of some neuron in output : everything is managed at the loss level. Or if we have to deal with a regression, we can play on the loss like this: import torch import torch.nn.functional as F B, n = 4, 6 torch.manual_seed(0) y = torch.empty((B, n)).uniform_(-10, 10) torch.manual_seed(1) y_pred = torch.empty((B, n)).uniform_(-10, 10) if True : # if the mask is batch wise mask = torch.empty(B).random_(2).bool() loss = F.mse_loss(y_pred, y, reduction='none').sum(dim=1) * mask else : # if the mask is element wise mask = torch.empty((B, n)).random_(2).bool() loss = ( F.mse_loss(y_pred, y, reduction='none') * mask ).sum(dim=1) loss = loss.mean() # loss.sum() loss If possible provide more details about your task.
https://discuss.pytorch.org/t/how-to-mask-linear-layer-input-to-prevent-invalid-feature-input-from-updating-parameters/121641
CC-MAIN-2022-33
refinedweb
268
69.38
This article is a step-by-step procedure of creating Windows Azure Web Role ASP.NET application protected using Windows Azure AppFabric Access Control Service v.2.0. After completing this walkthrough you will have a web application running in Windows Azure production environment that requires authentication using Windows Live ID or Google account. Live demo is available here As a prerequisite of completing this walkthrough you should have an active Windows Azure account (sign up here, fees apply) and active Windows Azure AppFabric labs account (sign up free here) Content in this step adopted and adapted from Code Quick Launch: Create and deploy an ASP.NET application To launch the ACS v2.0 Management Portal On the Project page, once the service namespace you created in Step 2 is active, click Access Control. You are redirected to the page that displays your project ID, allows you to delete the Service Namespace, or launch the ACS v2.0 Management Portal. To launch the ACS v2.0 Management Portal, click Manage Access! The Add Google Identity Provider page prompts you to enter a login link text (the default is Google) and an image URL. This URL points to a file of an image that can be used as the login link for this identity provider (in this case, Google). Editing these fields is optional. For this demo, do not edit them, and click Save. On Identity Providers page, click Return to Access Control Service to go back to the ACS v2.0 management portal main page.> Content in this step is adapted from Exercise 1: Enabling Federated Authentication for ASP.NET applications in Windows Azure This step helps you prepare your ASP.NET cloud web application to be deployed to Windows Azure with its prerequisites such as WIF assembly. WIF runtime is not installed as part of Windows Azure environment. It also helps creating and configuring server certificates to enable secure communications over SSL. Server certificate is also required for WIF related functions work properly on Windows Azure. To prepare application’s dependencies to be deployed to Windows Azure using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Web; using Microsoft.IdentityModel.Web.Configuration;); } void Application_Start(object sender, EventArgs e) { FederatedAuthentication.ServiceConfigurationCreated += OnServiceConfigurationCreated; } The following procedure will help you create self signed certificate and configure it for Compute Emulator and the application’s usage To create and configure self signed certificate This procedure will help you configure the certificate for usage in your Compute Emulator. To configure certificate for Compute Emulator This procedure will help you configure Windows Azure Role’s Endpoint to use the certificate for SSL/HTTPS communications. To configure Windows Azure Role’s Endpoint for SSL/HTTPS Next procedure will help you configure the certificate for usage by WIF related functionality. To configure certificate for WIF functionality <serviceCertificate> <certificateReference x509FindType="FindByThumbprint" findValue="YOURTHUMBPRINTFROMPREVSTEP" storeLocation="LocalMachine" storeName="My" /> </serviceCertificate> This procedure helps you configure your ACS v2.0 configuration to proper values. Since the URL changed (HTTPS vs. HTTP and the port number) it needs also to be updated in the ACS v2.0 Management Portal To update your relying party configuration on ACS v2.0 Management Portal This procedure will help you configure permissions for the application to access your certificate. The application by default runs in application pool under Network Service account. You need to grant permissions to this account so that it can use the certificate. To grant certificate access permissions to application pool account This procedure tests your configuration and validates its readiness to be deployed to Windows Azure environment. To test readiness for Windows Azure deployment In this step you will deploy the application to the cloud using the Windows Azure management portal. First you’ll need to create a service and a service configuration file, called service package, and then upload it to Windows Azure environment using Windows Azure management portal. For Configuration file, click the corresponding Browse Locally… button, navigate to the folder where your ServiceConfiguration.cscfg is, and select the file. Click on Add Certificate button to add your certificate to be deployed, but first you need to export the certificate into file. To export the certificate into file follow these steps: Open mmc console by first clicking on Windows button in task bar and typing mmc. You should see mmc.exe appears in search results. Click on it. When mmc console appears click on File option and then on Add/Remove Snap-in… option. In the Add or Remove Snap-ins dialog box choose Certificates from the available snap-ins list and click on Add> button. Choose Computer Account option and click Finish button. In the Select Computer wizard page select Local Computer (the computer this console is running on) and click Finish button. The click OK button. Expand Console Root folder. Expand Certificates(Local Computer) folder. Expand Personal folder. Click on Certificates folder to list available certificates. Locate your certificate in the list. Right click on the certificate and choose All Tasks and then Export… option. Click Next on the welcome page of the wizard. On the Export Private Key page choose Yes, export the private key option and click Next button. On the Export File Format leave the default option which is Personal Information Exchange - PKCS #12 (.PFX) and click Next button. On the Password page of the wizard specify password. You will need it when uploading the certificate to Windows Azure environment via management portal. On the File to Export page of the wizard specify destination file and click Next button. Make a note where you are saving the file. Note, since the certificate being exported has private key extra care should be taken to not exposing it to the public. It’s best if you delete the file altogether after uploading it to Windows Azure environment. Click Finish to complete the wizard. You should be presented with The export was successful message, click OK button to dismiss the message. Switch back to Windows Azure management portal where you opened a dialog box to locate your certificate (.PFX) file and locate the certificate file you have just exported. Specify the password for your certificate in the Certificate Password field. Click OK. You will receive a warning after you click OK because there is only one instance of the web role defined for your application (this setting is contained in the ServiceConfiguration.cscfg file). For purposes of this walk-through, override the warning by clicking Yes, but realize that you likely will want more than one instance of a web role for a robust application. You can monitor the status of the deployment in the Windows Azure management portal by navigating to the Hosted Services section. Because this was a deployment to a staging environment, the DNS will be of the form http://<guid>.cloudapp.net. You can see the DNS name if you click the deployment name in the Windows Azure management portal (you may need to expand the Hosted Service node to see the deployment name); the DNS name is in the right hand pane of the portal. Once your deployment has a status of Ready (as indicated by the Windows Azure management portal), you can enter the DNS name in your browser (or click it from the Windows Azure management portal) to see that your application is deployed to the cloud. Although this walk-through was for a deployment to the staging environment, a deployment to production follows the same steps, except you pick the production environment instead of staging. A deployment to production results in a DNS name based on the URL of your choice, instead of a GUID as used for staging. If this is your first exposure to the Windows Azure management portal, take some time to familiarize yourself with its functionality. For example, similar to the way you deployed your application, the portal provides functionality for stopping, starting, deleting, or upgrading a deployment. Important Assuming no issues were encountered, at this point you have deployed your Windows Azure application to the cloud. However, before proceeding, realize that a deployed application, even if it is not running, will continue to accrue billable time for your subscription. Therefore, it is extremely important that you delete unwanted deployments from your Windows Azure subscription. To delete the deployment, use the Windows Azure management portal to first stop your deployment, and then delete your deployment. These steps take place within the Hosted Services section of the Windows Azure management portal: Navigate to your deployment, select it, and then click the Stop icon. After it is stopped, delete it by clicking the Delete icon. If you do not delete the deployment, billable charges will continue to accrue for your deployment, even if it is stopped. Publish to production clicking on you deployment node so that Swap VIP ribbon appears. Click on Swap VIP ribbon and then OK button. The deployment to production should take couple of minutes. In the next procedure you will update the the package and the ACSv2 to reflect on the address changes from staging environment to production. Next procedure helps you to verify your application is functional when running in Windows Azure environment. Cant read the code... no bar on bottom to move right. :( VS 2012 doesn't have 'Add STS Reference'. WIF SDK doesn't create it in 2012. However, use the Identity and Access Tool. Open Tools ->Extensions and Updates. Click “Online”, search for “Identity” in the Search box. Click “Identity and Access Tool”, and install it. Restart Visual Studio. When you right click on the WebRole, you should see a new menu item, “Identity and Access...". kplaxmaster: just select the code, and copy-paste to a Notepad. Good work
http://social.technet.microsoft.com/wiki/contents/articles/2590.secure-windows-azure-web-role-asp-net-web-application-using-access-control-service-v2-0.aspx
CC-MAIN-2014-15
refinedweb
1,617
56.45
use strict; use warnings; package Jifty::Plugin; use base qw/Class::Accessor::Fast Jifty::Object/; __PACKAGE__->mk_accessors('_pre_init'); =head1 NAME Jifty::Plugin - Describes a plugin to the Jifty framework =head1 DESCRIPTION C<Plugins:> line in the C<config.yml> file: Plugins: - SpiffyThing: {} - SomePlugin: arguments: to the: constructor The dispatcher for a plugin should live in C<Jifty::Plugin::I<name>::Dispatcher>; it is written like any other L<Jifty::Dispatcher>. Plugin dispatcher rules are checked before the application's rules; however, see L<Jifty::Dispatcher/Plugins and rule ordering> for how to manually specify exceptions to this. Actions and models under a plugin's namespace are automatically discovered and made available to applications. =cut =head2 new Sets up a new instance of this plugin. This is called by L<Jifty> after reading the configuration file, and is supplied whatever plugin-specific settings were in the config file. Note that because plugins affect Mason's component roots, adding plugins during runtime is not supported. =cut sub new { my $class = shift; my $self = $class->SUPER::new( { @_ }); # XXX TODO: Add .po path $self->init(@_); Jifty->plugins( Jifty->plugins, $self ); # Pull in the dispatcher Jifty::Util->require($class->dispatcher); return $self; } =head2 init [ARGS] Called by L</new>, this does any custom configuration that the plugin might need. It is passed the same parameters as L</new>, gleaned from the configuration file. =cut sub init { 1; } =head2 new_request Called right before every request. By default, does nothing. =cut sub new_request { } sub _calculate_share { my $self = shift; my $class = ref($self); return $self->{share} if exists $self->{share}; my $class_to_path = $class; $class_to_path =~ s|::|/|g; unless ( $self->{share} and -d $self->{share} ) { # If we've got a Jifty in @INC, and the plugin is core, the # right thing to do is to strip off lib/ and replace it with # share/plugins/Jifty/Plugin/Whatever/ $self->{share} = $INC{ $class_to_path . '.pm' }; $self->{share} =~ s{lib/+\Q$class_to_path.pm}{share/plugins/$class_to_path}; $self->{share} = File::Spec->rel2abs( $self->{share} ); } unless ( $self->{share} and -d $self->{share} ) { # As above, but only tack on share/, for when we have a # non-core plugin in @INC. We do this before the # File::ShareDir, because File::ShareDir only looks at install # locations, and the plugin could be hand-set in @INC. $self->{share} = $INC{ $class_to_path . '.pm' }; $self->{share} =~ s{lib/+\Q$class_to_path.pm}{share}; $self->{share} = File::Spec->rel2abs( $self->{share} ); } unless ( $self->{share} and -d $self->{share} ) { # If it's an installed non-core plugin, File::ShareDir's # dist_dir will find it for us my $dist = $class; $dist =~ s/::/-/g; local $@; eval { $self->{share} = File::ShareDir::dist_dir($dist) }; } unless ( $self->{share} and -d $self->{share} ) { # We try this last, so plugins that moved out of core, but # were installed at when they _were_ in core, will get the # updated plugin # Core plugins live in jifty's share/plugins/Jifty/Plugin/Whatever/ $self->{share} = Jifty::Util->share_root; $self->{share} .= "/plugins/" . $class_to_path; } unless ( $self->{share} and -d $self->{share} ) { $self->{share} = undef; } return $self->{share}; } =head2 template_root Returns the root of the C<HTML::Mason> template directory for this plugin =cut sub template_root { my $self = shift; my $dir = $self->_calculate_share(); return unless $dir; return $dir."/web/templates"; } =head2 po_root Returns the plugin's message catalog directory. Returns undef if it doesn't exist. =cut sub po_root { my $self = shift; my $dir = $self->_calculate_share(); return unless $dir; return $dir."/po"; } =head2 template_class Returns the Template::Declare view package for this plugin =cut sub template_class { my $self = shift; my $class = ref($self) || $self; return $class.'::View'; } =head2 static_root Returns the root of the static directory for this plugin =cut sub static_root { my $self = shift; my $dir = $self->_calculate_share(); return unless $dir; return $dir."/web/static"; } =head2 dispatcher Returns the classname of the dispatcher class for this plugin =cut sub dispatcher { my $self = shift; my $class = ref($self) || $self; return $class."::Dispatcher"; } =head2 prereq_plugins Returns an array of plugin module names that this plugin depends on. =cut sub prereq_plugins { return (); } =head2 version Returns the database version of the plugin. Needs to be bumped any time the database schema needs to be updated. Plugins that do not directly define any models don't need to worry about this. =cut sub version { return '0.0.1'; } =head2 bootstrapper Returns the name of the class that can be used to bootstrap the database models. This normally returns the plugin's class name with C<::Bootstrap> added to the end. Plugin bootstrappers can be built in exactly the same way as application bootstraps. See L<Jifty::Bootstrap>. =cut sub bootstrapper { my $self = shift; my $class = ref $self; return $class . '::Bootstrap'; } =head2 upgrade_class Returns the name of the class that can be used to upgrade the database models and schema (such as adding new data, fixing default values, and renaming columns). This normally returns the plugin's class name with C<::Upgrade> added to the end. Plugin upgrade classes can be built in exactly the same was as application upgrade classes. See L<Jifty::Upgrade>. =cut sub upgrade_class { my $self = shift; my $class = ref $self; return $class . '::Upgrade'; } =head2 table_prefix Returns a prefix that will be placed in the front of all table names for plugin models. Be default, the plugin name is converted to an identifier based upon the class name. =cut sub table_prefix { my $self = shift; my $class = ref $self; $class =~ s/\W+/_/g; $class .= '_'; return lc $class; } =head2 wrap Takes a PSGI-$app closure and returns the wrapped one if your plugin wants to do something to the request handling process. See also L<Plack::Middleware>. =cut sub wrap { my ($self, $app) = @_; return $app; } =head2 psgi_app_static Returns a PSGI-$app that serves the static content of the plugin if any. The default is a <Plack::App::File> app with root set to plugin's C<static_root> =cut sub psgi_app_static { my $self = shift; my $static_root = $self->static_root; return unless defined $static_root && -d $static_root && -r $static_root; Plack::App::File->new(root => $static_root)->to_app } 1;
https://metacpan.org/release/Jifty/source/lib/Jifty/Plugin.pm
CC-MAIN-2019-47
refinedweb
997
52.8
Put character back. The function checks if c matches the character right before the current position of the input sequence, if so, the get pointer is moved back one character, making the character once again available to input functions. Parameters. Return Value. The value of the character put back. If parameter c doesn't match the expected character or if the get pointer is at the beginning of the input sequence, the value returned is EOF. Example. // sputbackc #include <iostream> using namespace std; int main () { char ch; long n; streambuf * pbuf; pbuf = cin.rdbuf(); cout << "Please enter some letters and after a number: "; do { ch=pbuf->sbumpc(); if ( (ch>='0') && (ch <='9') ) { pbuf->sputbackc (ch); cin >> n; cout << "You entered number " << n << endl; break; } } while (ch != EOF); return 0; } This example gets characters form standard input one by one. When the first numeric digit is found, sputback is called to restore the position in the stream to that digit in order to be extracted as part of a number using standard operator >>. Basic template member declaration ( basic_streambuf<charT,traits> ): See also. sungetc, sgetc, sbumpc, sputc streambuf class
http://www.kev.pulo.com.au/pp/RESOURCES/cplusplus/ref/iostream/streambuf/sputbackc.html
CC-MAIN-2018-05
refinedweb
187
53.31
Topeka’s guide to art, entertainment, lifestyle + local flavor WINTER 2016 | DEC + JAN • Vol. XI Issue III lettuce talk about local flavor entertainment arts FREE bite pick up Downtown • • • • • • • • • • Sign up for the seveneightfive weekender and be in the know. Our weekender is sent every Friday with the latest Topeka events, weekly karaoke spots, food news and more. Advertise your event or business for $75 a week, limited space available. To place an ad, email seveneightfive@gmail.com. The weekender is currently sent to over 4,000 people. #785Weekender #785Live TEXT 785 TO 66866 Celtic Fox Irish Pub Hanover Pancake House Juli’s Bistro Luis’ Place Oddfellow’s Ramada Inn / Uncle Bo's RowHouse Restaurant The BreakRoom Midwest Barter TPAC 29th + gage / West • • • • • • • La Rocca’s Pizza Marian Lane Candles Pigskins + Boss Hawgs Southwind Gallery The Lazy Toad Tailgator's Pizagels south east / east topeka • • • • • Abigail’s Bar & Grill Blind Tiger The Landing Grille Mainstream Boutique Tacos el Mexicana north topeka / oakland • • • • • • • • Bradley’s Cafe NOTO Burrito J&J Gallery Bar Matryoshka Tattoo Serendipity Studio 831 Wellers Brass Rail Tavern college hill / midtown • • • • • • • • • • • • • • • The Burger Stand Oscars Louie's Lounge Mulvane Art Museum PT's College Hill The Trap Backs by Popular Demand The Dutch Goose Live Music Institute Anytime Fitness Speck's Tavern TSCPL (Library) Via's Pizzeria + More Findables Quinton's Contributors Publisher/Owner Kerrice Mapes seveneightfive@gmail.com cover by Amber Farmer I picked this photo for the cover because I was drawn to it's vibrant colors and Georgia O'Keeffe essence. Additionally, I found humor in the juxtaposition of crisp green lettuce in the middle of our Kansas winter and the array of puns lettuce afforded me. So lettuce turnip the beet. Cheers. Contributors Jarrod Boyer DawnMarie Chambers Amber Farmer Ali Hanlon Daryl Hendrix Michael Howe Tom Krebs Karen Alkire Morse Michelle Leivan Noah Neff Elicia Marie Nichols Travis Owens Tricia Peterson Gary Piland Amanda Reynolds Ashley Reynolds Ni’Cole Revell Brandon Rison Martie Rison James Robinson Stephanie Teater accounting Liz Bell editing D O’Brien + Rebecca Radziejeski Advertising Kerrice Mapes about us seveneightfive is a free niche magazine highlighting art, flavor, entertainment, local businesses and more in Topeka, Kan. seveneightfive was created in June 2006 to inform area residents and visitors about a+e events in Topeka. Today, we continue to be a catalyst for cultural and art enhancement in Topeka. seveneightfive is made possible due to ad revenue and only allows locally owned businesses to be represented in print. seveneightfive magazine and its social media incarnations are not intended for readers under 18 years of age. weekender Text 785 to 66866 To sign up for our weekly e-blast which will keep you the most upto-date on Topeka events. To advertise your event, email seveneightfive@gmail.com. Submissions are due Tuesday by 5p. Ads are $75 per week. A discount is given to nonprofits or charity events that fit our mission. Space is limited. ✦ Tuxedo & suits in stock ✦ Sales or rentals ✦ Free pickup & delivery ✦ Brides gown cleaned & preserved for free ✦ Last minutes alternations ✦ Dry cleaning, laundry & spot removal ✦ Done on premises for out of town guests ✦ Special pricing ✦ All Styles and All Colors (785) 271-5008 2930 SW McClure Rd, Topeka, KS 66614 @seveneightfive 4 goldentuxedo.com #1002226885 (FULL PAGE(8in x 10.38in)) 11/18/2016 16:02 EST Inside VOL XI Issue III | WINTER 2016-17 | DEC - JAN $5 Tapas + 4-part wine tasting First Thursdays | Luis' Place | 5th + Kansas 7 23 26 30 31 31 32 34 36 11 parallel lives 12 kathleen cobbs - artist 14 kris lager band 15 q's live 16 soul expressions + 20 weekender events 22 specials 24 paradize band 24 faces by mayfield Uncle Bo's | January 13 topeka2go new voodoo insta-hungry boozy brunch taco tuesday alfresco dining give them some love calcan food ninja 6 Another successful franchise - tested and built in the Top City. Topeka 2 go Andrea Leon | photos by Elicia Marie Nichols W e've all had those days; you get home and all you want to do is to relax. You don't feel like cooking and the thought of getting back out and driving to XYZ restaurant makes your head hurt. You retreat, "delivery it is." You get into your kitchen junk drawer and start perusing to-go menus..."hmmm, let's see...shall we have...Chinese or Pizza?" Your head now hurts a little bit more and your craving for XYZ restaurant is a little bit stronger. You're in a (insert any day that ends in "y") pickle. That is, until now. Topeka2Go is a restaurant food delivery marketing service. You can go to Topeka2Go website or app and have food delivered from almost 40 local restaurants including Pepe and Chelas, The Wheel Barrel, Pizagels and a few national chains. Prior to Topeka2Go, Donovan was running his own Dine Time Taxi service and that is when he met his partners Anthony Swaintek and Mike Hall. It was the "perfect storm." Anthony and Mike manage the software and marketing while Donovan is on the ground with the day-to-day operations, working closely with their drivers and partners. The business started with a franchise in Topeka just over a year ago and now have 25 nationwide (time of printing) and are opening several new franchises each month. "In 24 months we will have 300 franchises open and there is a chance we will be global," said Donovan. "We will be one of the largest delivery services in the United States." Not to shabby for a boy from Carbondale who graduated from Santa Fe Trail. Donovan is proud of his routes, and that his growing business comes straight out of Topeka. “I am proud of Topeka. This is my baby. I have bragging rights.â€? aseveneightfive BONUS: You can order from multiple restaurants for one delivery. SOME RESTAURANTS PART OF TOPEKA2GO TOPEKA2GO Topeka2Go partners with local restaurants and independent contractors to bring you hot, fresh and delicious food quickly and conveniently. Their online site and mobile app allow you to order food hassle-free, delivered directly to you in under an hour. "We understand that life can be hectic and stressful at times, but eating well should never be!" Golden Dragon Boss Hawg's Petro Deli Pizagel's Pizza + Bakery Cookies by Gayla The Wheel Barrel CoCo Asian + Chinese Tuptim Thai Restaurant El Maguey Mexican Diceky's BBQ Pit Hazel Hill Chocolate Billy Vanilly Breakers Sports Bar + Grill Chef's Crazy Tasty Chicken Le Petit Bon Bon Cafe Globe Indian Cuisine Bunker Coffee Company Pepe and Chela's Mexican NOTO Burrito Cafe Holliday Mexican Taco Shop 7 don’t await it CREATE IT Success does not lead to happiness. Happiness leads to success. Plan for 2017 today. Use this retreat to gain fresh perspectives and learn tools to ignite change and accelerate success. Kansas City, Hotel Sorello The Plaza March 24-26, 2017 Washington, DC, Hotel Palomar January 13-15, 2017. Use the promo code HERLIFE for a special discount and take three days for yourself and your future. Or call 785-554-0247 If you’re ready to transform your impact and increase your income, we’re ready for you! We’re FRESH in the morning 2830 SW FAIRLAWN RD OPEN Sun-Thurs: 6 a.m. - 9 p.m. Fri & Sat: 6 a.m. - 10 p.m. 8 and HOT at night. Prognosticatio with Ruprecht Roosterdamus, The Psychic Chicken TM December - January ‘16‘17 Dear Mr. Roosterdamus, I was wondering if you had any influence with a rather plump elf currently living at the North Pole? If so, could you please ask him to approve my request for a visit from the Swedish Bikini Team? Just Turned 15 with Aspirations Dear JTFWA, I do have influence with Mr. C. and I’ll do what I can, but yer down the list a bit with so many people asking for things like a compatible liver transplant and cancer cures. But, ya never know, right? - RR ____________________________ A R I E S I know the election didn’t turn out quite like the majority hoped, but look on the bright side—at least it wasn’t Cruz or Carson. Those guys were scary! T A U R U S ‘Tis the season, my bullish friend, so try not to run over those slow walkers in the WalMart parking lot, okay? I know it’s tempting, but ya’d just get high centered. G E M I N I When The Donald says he’s going to make America great again, it’s probably best to remember, he only means for ignorant racist white guys. The rest of us are on our own. C A N C E R I checked, there is no term limit on mass murder so yer plan to take out a bunch of bubbas with a weed whipper just fell apart. L E O Facebook okay list: • Okay - trash ex-lovers • Okay - share tasty meal photos • Okay - cute pet photos • Okay - bag on bubbas • NO! - Photos of recent surgeries V I R G O Explain why ya won’t celebrate Christmas but yer still going to keep all the presents again? I keep getting lost at the “I don’t like the pagan origins” part. Are ya anti-pagan or something? V I R G O Explain why ya won’t celebrate Christmas but yer still going to keep all the presents again? I keep getting lost at the “I don’t like the pagan origins” part. Are ya anti-pagan or something? L I B R A Science is not a crackput left-wing Dear Mr. Roosterdamus, conspiracy, it’s science, Bucko. The very same stuff that let’s ya I was wondering if you had any post cat photos on Facebook at influence with a rather plump elf currently living at the North Pole? 90 mph on I-70. If so, could you please ask him to S C O R P I O approve my request for a visit Dear Scorpios, from the Swedish Bikini Team? Thanks for coming to Earth! Just Turned 15 with Aspirations -The rest of us. Dear JTFWA, S A G I T T A R I U S Love of money (e.g., greed) is not I do have influence with Mr. C. the root of all evil—it is the root, and I’ll do what I can, but yer the trunk, the limbs, the twigs, the down the list a bit with so many leaves and the poisoned fruit of people asking for things like a compatible liver transplant and all evil. cancer cures. But, ya never know, C A P R I C O R N right? - RR When bribing politicians it is always ____________________________ better to start small and work yer way up. And by small, I don’t mean A R I E S by position, I mean by IQ. So, this I know the election didn’t turn means starting January 21, 2017, ya out quite like the majority hoped, can start at the top! but look on the bright side—at least it wasn’t Cruz or Carson. A Q U A R I U S There was this, uh, guy who kept Those guys were scary! trying to find the perfect mate. He T A U R U S tried Tinder, Ashley Madison, ‘Tis the season, my bullish friend, SnapChat and a host of other so try not to run over those slow dating sites but in the end just walkers in the WalMart parking kept ending up dating himself, lot, okay? I know it’s tempting, pretending to be a 16 year old but ya’d just get high centered. teenage cheerleader. He’s very happy by the way. G E M I N I L I B R A Science is not a crackput left-wing conspiracy, it’s science, Bucko. The very same stuff that let’s ya post cat photos on Facebook at 90 mph on I-70. When The Donald says he’s going to make America great again, it’s probably best to remember, he only means for ignorant racist white guys. The rest of us are on our own. P I S C E S As I travel around the Universe and meet lots of alien life forms it gets tiring explaining why people vote for people who are the exact opposite of who they really need. Very tiring. ___________________________ P I S C E S As I travel around the Universe and meet lots of alien life forms it gets tiring explaining why people vote for people who are the exact opposite of who they really need. Very tiring. ___________________________ C A N C E R I checked, there is no term limit Question for the Blue Guru? on mass murder so yer plan to Something on yer mind? Need an take out a bunch of bubbas with answer to a burning (and itching) a weed whipper just fell apart. personal question? Find out L E O before it’s too late. Email me! Ruprecht@PsychicChicken.com Facebook okay list: • Okay - trash ex-lovers ___________________________ • Okay - share tasty meal photos * Astrological predictions are to actual • Okay - cute pet photos life what Kris “Voter Suppression” • Okay - bag on bubbas Kobach is to free and fair elections. • NO! - Photos of recent surgeries #Kobachistan - Ruprecht S C O R P I O Dear Scorpios, Thanks for coming to Earth! -The rest of us. S A G I T T A R I U S Love of money (e.g., greed) is not the root of all evil—it is the root, the trunk, the limbs, the twigs, the leaves and the poisoned fruit of all evil. C A P R I C O R N When bribing politicians it is always better to start small and work yer way up. And by small, I don’t mean by position, I mean by IQ. So, this means starting January 21, 2017, ya can start at the top! A Q U A R I U S There was this, uh, guy who kept trying to find the perfect mate. He tried Tinder, Ashley Madison, SnapChat and a host of other dating sites but in the end just kept ending up dating himself, pretending to be a 16 year old teenage cheerleader. He’s very happy by the way. Question for the Blue Guru? Something on yer mind? Need an answer to a burning (and itching) personal question? Find out before it’s too late. Email me! Ruprecht@PsychicChicken.com ___________________________ * Astrological predictions are to actual life what Kris “Voter Suppression” Kobach is to free and fair elections. #Kobachistan - Ruprecht 9 DINE LOCAL DINE FINE DINE AT THE TOP SATURDAY NIGHT SPECIAL 2 FOR $35 STEAK DINNER + 1/2 PRICE HOUSE WINE Inclusive and Accessible Yoga Initative for ALL PEOPLE from ALL WALKS of LIFE. 745 NE Chester Ave. | OAKLAND | WildYogaTopeka.com TOP OF THE TOWER 354-7746 * NO MEMBERSHIP REQUIRED SPECIAL Inclusive and Accessible Yoga Initative for ALL PEOPLE from ALL WALKS of LIFE. DUDE! There’s nowhere to park! Topeka Metro Bikes has 2,000 members, but our city has less than 100 bike parking racks. Open your business to a new audience by adding bike parking! Contact Topeka Metro today: (785) 730-8615 • info@topekametrobikes.org 10 #785MUSIC PARALLEL LIVES fo x / w ills c olla b oration Tom Krebs | photos provided CD Review W ould it be wrong for me to describe the twelve tunes on the new Greg Fox/Ryan Wills collaboration, "Parallel Lives," as especially tasty and exceptionally crafted? No, I don't think so… because they are." Fox writes in the liner notes, “Ryan and I have had a lot of parallels in our life.” What is clear to me, after giving the CD a number of attentive listenings that is this effort is about their musical lives, rather than running parallel, becoming blended into one. At the heart of their effort are three key ingredients of a good set of tunes: insightful and compelling lyrics; wonderfully woven, tight harmonies; and backing guitar work, with some occasional strings and keyboards, that complements, not overwhelms, the melodies and harmonies. The opening track, "What Defines A Man," sets the standard for the introspective and catchy lyrics that permeate the entire CD: Is it his beard and mustache, is it muscle is it mass, or is it heart, or is it cash? His rights or his wrongs, his fists or his songs, his first words or his last? Just what defines a man? ….is what defines a man. Other songs I found particularly compelling were "Run," "Dragonfly" and "It’s Not the End." "Run" certainly has a Simon/Garfunkel quality to it with both a call and response component on the verse as well as tight harmonies on the chorus. "Dragonfly" offers a fun little play on words between the title and the lyrics. The harmonies on the chorus are again very tight, with Wills taking the high part and Fox providing the melody. "It’s Not the End" showcases the two men’s voices, dancing and weaving around each other through the verses, coming together during the uplifting chorus. Also in the liner notes are shout out from both Fox and Wills for Ryan’s dad, Randy, who produced the album. Perhaps the last song, "Thirsty for the Water," is the best example of a song being amped up with some additional voices and other studio effects that really make the song vibrate. "Parallel Lives" is a collaboration in the truest sense. The songwriting credits are shared equally; all songs but one are performed by both; and themes important to both run throughout. In my perfect world, I would be lucky enough to have the two sitting around my fire pit with a few other friends on a crisp fall evening and playing these tunes. Warmth, smiles, and personal reflection would abound. aseveneightfive ‘‘ It started with a random conversation about everyone in the world experiencing similar pains, joys and struggles. This was an effort to express some of that from our vantage points." #785ART comfort food for the soul ARTtitude by Michelle Leivan | Kansas Art Gallery | ArtsPrintExpress.com Featured Artist: Kathleen Cobb W. [LEFT EDGE] Edge of a Kansas Meadow [LEFT} Garlic [BELOW] Kathleen Cobb, artist [RIGHT] Light on the Past One such artist is Kathleen Cobb, who creates cozy comfortable wistful paintings that conjures memories and prompts images in our dreams. Seeking out the stillness of nature and the perfect scene to express her love of the land, Kathleen regularly finds inspiration throughout the Flint Hills and for when she returns to her studio to complete the quiet images. These adventures result in misty visions created with her distinctive color pallet with soft brush strokes that echo lazy days in nature. ‘‘ I hope to draw the viewer into feeling as though they're there, and wanting to go around the bend to explore more. Kathleen inspires. A collection of Kathleen Cobb’s work “For the Love of the Land” is presented through the rest of the year at the new Kansas Art Gallery located with Art Print Express at 1047 SW Gage, Suite B. Studio hours are 10a-6p Tuesday through Friday and Saturday 10a-1p. aseveneightfive stick it to the haters + support the arts A RTSConnect has a new twist on their annual giving campaign. They are asking you to throw some support to our small, but fierce, nonprofit arts organization and in return (besides all the amazing art events you attend) you'll get a Topeka Proud sticker. ARTSConnect is responsible for the Topeka Mural Project and First Friday Art Walk, which are efforts to include everyone in the great benefits of arts. They also award annual grants to arts organizations and initiatives, advocate for the arts by calculating its economic impact and more. So what is this sticker worth? Aside from an organic, philanthropic high - ARTSConnect is encouraging donors to make a monthly financial contribution of $5 to $10. Donate at artsconnect.kindful.com aseveneightfive #topekaproud #785LIVE kris lager b an d taking you to church this nye Kerrice Mapes | photos provided I've got a New Years resolution for you....go to church. M any consider Kris Lager Band (KLB) to be one of the most exciting bands on the scene today and deservedly so. Their electrifying and uplifting performances have garnered them a strong grassroots following. They embody a "Celebrate Life" mantra that resonates throughout their live performances. Their music is infectious and uplifting, demanding the attention of your soul and feet. "The Feel Good Band of the Century." A KLB show is a legitimate Rock ‘n’ Roll Revival and an Electric Church. The energy this band throws out from the drop of the first note creates a feel good dancing, singing and hollering.” 14." Kris Lager Band isn't a peg you can fit into some square genre box, albeit whose musical tastes do? This is why they are the perfect headliner for Topeka's New Years Eve Party at the Ramada Inn, where they will complement the other seven bands playing around the hotel and take you into 2017 with high spirits and tired dancing feet. As one might holler when music commands your undivided attention and fills your entire soul with positive vibrations; KLB is "taking you to church" this new year. aseveneightfive also performing 12.31.16 Dan Bliss Queen Anne's Revenge Boogie Wonderland Amanda Fish Band Groovement Zac Harmon Biscuit Miller + the Mix NYETopeka.com for Tickets q's live san d w i c h ing good food with music Kerrice Mapes | photos provided Restaurant takes music focus what saying people are Loved playing this place! George was an amazing sound guy and made us feel very comfortable on a stage that we have never gigged on before! We will return, great venue! Wow!! So pleasantly surprised at how awesome this place was last night. Excited for the future nights here. One thing is for sure, there is definitely one place that will keep raising the bar for live entertainment in Topeka and that place is Quintons, Topeka. Q uinton's Bar & Deli is a staple in Lawrence, known for great sandwiches and attractive, friendly staff. So when owner Steve Gaudreau opened a Quinton's in Topeka seven years ago, foodies and college students were elated. Over the years the Topeka Quinton's, as many businesses, have seen ups and downs but always strived to provide a high quality product to their consumer. However, some might argue that consumers become less than desirable as the night progressed and safety was at times a concern. Add that it was located in a Lindenmuth property which was as questionable as the "Bermuda Triangle" - [the nickname for the bar trio located at Huntoon and Gage.] The peak of speculation for some was a shooting that occurred in the adjacent parking lot last summer. For some, Quinton's could not provide the comfort food needed to move forward. Until now. Konner Slattery, assistant general manager and Kansas University graduate ('15) with a degree in marketing has a vision to elevate Quinton's food, staff and entertainment offerings while rebuilding their reputation. Konner wants Quinton's to be an active community partner, a neighborhood champion, and supporter of the arts. Konner made a strategically smart move last August and hired George Vayler IV, owner of Rundown Studios, to collaborate with him. The result is Q's Live - a new venue where people can enjoy good company, great food, a few adult beverages and experience outstanding live music performances from local and regional acts. New sound, stage and lighting were installed and the team quickly created a schedule that included live music on Fridays and Saturday, plus acoustic sets during the week [Tuesday Bluesday 8-11p / Acoustic Thursday]. Q's Live is a testament to putting your money where your mouth is. The whole outfit is top of the line, from the late-night menu, to the service, to the way the room is divided up without a break in the acoustics. Q's Live has put itself on the dial as the go-to place for live music and in just a short few months. If you haven't visited for a while, check it out. Tuesday is acoustic night with 1/2 price burgers; or visit on a weekend night for some great bands. aseveneightfive Soul Expressions: Coloring for Transformation by Jancy Pettit © Jancy Pettit 2016 soul expressions coloring for transformation by Jancy Pettit E artist you njoy this coloring page sample (left) from "Soul Expressions: Coloring for Transformation" by Jancy Pettit. The designs in the book are charged with energy from Tai Chi and Qugong, which helps you relax, focus and be creatively inspired. The designs will connect with you at a deep level, almost like a language of the soul. Take a deep breath, relax and dive in. Don't feel like you have to fill in every space. Look for patterns and larger areas, if you would like, there is no wrong way to color this. When you complete your page, take a few moments to enjoy what you have created and allow the energy of the completed drawing to soak into you a bit. Put it in a place where you will see it often in your day and enjoy the peaceful feelings it will awaken within you. To learn more about Jancy Pettit, "Soul Expressions" or get your own copy of the book, go to JancyPettit.com. aseveneightfive "Burning with creativity that ignites the soul." -Judy James "Dynamic, rich, moving, personal." -Lois VanLiew “Kinetic, spirited, colorful, expressive” – Kelley Wade Hunt "Language Two" mixed media block print 36 x 42 MOOD S Historic & Uniquely Chic Perfect for weddings, meetings, events and more. Customized to fit your needs. 816 N Kansas Ave 17 a notorious mobster was shot there and that was over twenty years ago. What if someone could get murdered in their restaurant? Flaming Idiots is a contemporary farce with slap stick comedy, animated and colorful characters, dozens of door slams and a cop who raps Morse code into the phone with a kitchen knife. jan 20 11 thru feb topekacivictheatre.com 18 #785WEEKENDER 2017 foo d events compiled by Karen Alkire Morse resource websites include: KS Expo Center Downtown Topeka, Inc Visit Topeka + Topeka 365 INTER-TRIBAL POW WOW NATIVE AMERICAN CUISINE, DANCING AND ARTISANS Shawnee County Allied Tribes Lake Shawnee | SEPT 1-3 CIDER DAYS KS Expo Center | SEPT 23-24 CAPITAL CITY JAZZ + FOOD TRUCK Almost 40 food trucks, one big concert, thousands of people MULVANE MOUNTAIN/PLAINS ART FAIR ENJOY HANDS ON ART MAKING, VIEW STUNNING WORKS AND ENJOY SOME GREAT LOCAL VENDORS Washburn Campus | JUNE 2-4 SPIRIT OF KANSAS BLUES FEST July 4th fair with a full day of blues music, vendors, car show+ Downtown Topeka Inc. + Visit Topeka Kansas Ave | JULY Topeka Blues Society Shawnee Lake | JULY APPLE FESTIVAL Variety of fair + entertainment Sampling of all things apple plus pioneer history demonstrations Old Prairie Town | OCT ST. PATRICK'S DAY CELEBRATION Fun for all, outdoors. parade, Irish food, beer, whiskey and music. Downtown | MARCH 11 PLUS 785+ Dutch Goose Annual Breakfast at 9a. TULIP TIME tulips and daffodils in bloom. full day of activities with lots of food trucks for the sampling Shawnee Lake | APRIL 9 DOWNTOWN FARMER'S MARKET fresh foods and home baked goods, along with arts and crafts Shawnee County Allied Tribes 12th + Harrison | MID-APRIL - NOV FIESTA MEXICANA Authentic Mexican food featured along with music, entertainment and a carnival. Oakland | JULY 11-15 RAILROAD FEST Great Overland Station | AUG 19 CYCLOVIA TOPEKA 3 days of fun, trail-ride, scavenger hunt, cycling events. food trucks and vendors line streets. Downtown Topeka | JULY INDIA FEST This event offers diverse, homemade food, jewelry and art from the Indian Culture. India Assoc. of Topeka Gage Park | SEPT MARIACHI FESTIVAL fiesta street party with music, margaritas, beer, sangria, tequila, food and more. 9th + Quincy | DIA DE LOS MUERTOS in a fusion of old and new worlds. art show, crafts and cuisine. The Tonantzin Society Kansas Ave Varies | OCT HOLIDAY FOOD + GIFT MART food sampling, unique gifts Exhibition Hall, KS EXPO | NOV COMMUNITY THANKSGIVING DINNER Serving food to any that may be in need Agriculture Hall, KS EXPO | NOV 23 BREW AT THE ZOO Beer and food stations set up around the zoo along with music and activities. Friends of the Topeka Zoo Topeka Zoo KANSAS CHOCOLATE FESTIVAL Chocolate is an ingredient in one food item in every food truck features Visit Topeka + Partners Downtown Topeka | SEPT TOPEKA SCIENCE + TECH FEST food trucks line avenue. hands on activities and demonstrations. Downtown | OCT ART OF MURDER party for a cause. interactive murder mystery performed in six scenes on a variety of stages. in-between stop for food from over a dozen vendors. Location TBD | JULY VETERAN TO BREAKFAST Beer and food stations set up around the zoo along with music and activities. Shawnee County Parks + Recreation, Perkins Perkins | Veteran's Day BLINTZ BRUNCH ASHKENAZI JEWISH TRADITIONAL FOOD Temple Beth Sholom APRIL 30 19 #785WEEKENDER DEC + JAN events compiled by Dawn Marie Chambers + Kerrice Mapes WEEKLY EVENTS KARAOKE M: MONDAY 3rd of Month Celtic Jam Blind Tiger | 6p M: Flamingo Bar, 7p The Trap, 8p T: Flamingo Bar, 7p Hookah House, 9p W: The Lazy Toad, 9p Flamingo Bar, 7p The Trap, 9p Quinton's, 10p R: Abigail's, 9p Flamingo Bar, 7p Skinny's, 10p Lupita's, 6p The Brass Rail, 8p F: Pigskins, 9p The Dugout, 9p Skinny's, 10p Abigail's, 9p T: TUESDAY Acoustic | Q's Live | 8p Pigskins | 8p (every other) W: WEDNESDAY 1st WED: Speak Easy Open Mic Bunker Coffee Co. | 6:30p R: THURSDAY Acoustic Music w/Justin Fowler Q's Live | 6p Southern Rock + Blues Jam The Lazy Toad | 7p F: FRIDAY 1st: TopCity Comedy Showcase The Break Room | 8p go to the events tab at seveneightfive.com for more events and sign up for the weekender text 785 to 66866 { SUN: SUNDAY FUNDAY Jam | Speck's Tavern | 7p S: Abigail's, 9p The Dugout, 9p Skinny's, 10p The Burger Stand, 9p SUN: The Brass Rail, 8p Just Chillen', 8p The Trap, 8p Wild Horse Saloon, 8:30p TRIVIA T: The Brass Rail, 8p W: Quinton's, 7p Pigskin's, 8p The Burger Stand, 9p R: AJ's Pizza, 8p DEC 16-22 F: Blues Mark + the Sharks Uncle Bo's | 8p F: ROCK / BLUES Delta Haze VFW 1650 Huntoon | 7+11p F: BLUES / Holiday The Michael Powers Trio Flamingo Bar + Grill | 9p S: HOCKEY Topeka RoadRunners KS Expo Center | 7:05p S: R+B / SOUL Platinum Express Uncle Bo's | 8p SUN: CHILI + CHIEFS Chili Cook Off + Game Louie's Lounge | noon W: UGLY SWEATER PARTY Santa Karaoke The Trap | 10p M: FESTIVAL SINGERS Old Chestnuts, New Fire Topeka Festival Singers White Concert Hall | 7:30p DEC 23-29 F: Blues Mark + the Sharks Uncle Bo's | 8p F: MASQUERADE 3rd Annual Black Tie Affair New Midwest Entertainment TPAC | 9p F: MIXED MARTIAL ARTS VFC 55: Victory Fighting KS Expo Center | 7p R: HUNKS THE SHOW Topeka Sports Cabaret | 7p R: PARTY Awkward Elephant Norsemen Brewing Co | 6p DEC 30-JAN 5 F: HOCKEY Topeka RoadRunners KS Expo Center | 7:05p F: Hip-Hop EXO presents King Mane The Trap | 10p new year's eve Blacklight, fog + body paint The Famous Door | 9p Biggest Party in Topeka Ramada Inn | 3p Fantasy Ball / Karaoke The Trap | 10p Reggae Party w/Urban Safari The Lazy Toad | 9p SUN: HOCKEY Topeka RoadRunners KS Expo Center | 2:05p F/S: COMEDY Laugh Lines Improv Topeka Civic Theatre | 8p R: HOCKEY Topeka RoadRunners KS Expo Center | 2:05p JAN 13-19 F: BLUES Toronzo Cannon Uncle Bo's | 6:30p JAN 27-FEB 2 FEB 3 + + F: ALTERNATIVE Invisible Bike - Reunion Show Q's Live | 10p F: OPENING WEEKEND "The Other Place" a drama about alztimers Helen Hocker Theater 3: ART + FOOD First Friday ArtWalk by ARTSConnect #FFAW | Various | 5-8p 11: BURLESQUE The Lalas Burlesque Prairie Band | 8p 11: COMEDY Chicago Comedy All-Stars TPAC | 7:30p F/S/SUN: JAM4DAN Three days of live, local music The Celtic Fox F: R+B / SOUL / FUNK KNowBe! Q's Live | 10p F: RAP Exo Bday Bash J+J Gallery Bar | 8p W: POWER POP Rich Yarges + the Pop Mechanics Q's Live | 10p JAN 20-26 JAN 6-12 F: OPENING WEEKEND "Flaming Idiots" a farce Topeka Civic Theatre F: ACOUSTIC Andy McKee Bottleneck (Lawrence) | 9p F: FUNK Funk Trek Q's Live | 10p S: COMEDY Brian Regan TPAC | 8p F: RAP Deuce Alley presents Haystak J+J Gallery Bar | 9p 21 seveneightfive specials Dutch Goose Featuring Ping Pong Voted Topeka Best Burger 1601 SW Lane 785.8900 $3 Dom Headaches $2 Dom Pints or Btls 75c Tacos $4 Bloodys $1.5 Cheap Cans $3 Sangrias $2.5 Wells $5 Cheeseburger + Fries sun mon tues hump thurs The Lazy Toad Louie's Lounge + tailgators vias pizza + more Featuring 51 beers on tap 5331 SW 22nd Pl 272.8623 Laundromat $3.5 Big Dom Draws $3 Mimosas $4 Bloody Mary SUNDAY FUNDAY $3.5 Captain Morgan $4 Jack Daniels $4 House Wines $4 Hurricanes $3.25 22oz Dom Draft $5.5 Dom Pitchers $4 Bloody Mary $1.5 12oz oz Cans $3 Bloody Marys $6.5 Wings $3.25 Dom Btls $3.25 Dom Drafts $3.25 Bloddy Marys $3.25 Otis* $1 Off Dom Btls $1 Off Craft Btls $2 PBR Pints $5 DBL Vodka Redbull OPEN MIC 10p $1 Off All Btls $5 Double Calls $4 Glasses of Wine TACO MONDAY $3 22 Dom Drafts $2.75 Wells $4 House Wines $4 Long Island $4 Grateful Deads $3 Malibu Drinks 9a-4p 50¢ off Dom Drafts 4p-close 50¢ off Dom Btls $3 Aluminum Btls $4 Naked Jay Vodka $6.5 Pulled Pork Sand $3 ALL Drafts $2.5 Dom Btls $4.5 Red Bull Bombs $4.5 Goose Sandwich + Fries $1 Off Micro Brew draws from the tap $1 off Jim, Jack and Jameson $5 Bomb Shots COLLEGE NIGHT 1/2 price burgers 5-10p $1 off all Pints $3 Vegas Bombs $4 Summer Brews Power Hour 10-11p TASTY TUESDAY $3 22oz Dom Drafts $2.75 Wells $4 House Wines $4 Bahama Mamas $4 Alabama Slammers $3 Jim Beam $3 Lord Calvert 9a-4p 50¢ off Dom Drafts 4p-close 50¢ off Dom Btls $3 Juarez Margs $2.5 Dom Btls $5 Taco Burger $6 Taco Salad $.75 Tacos $3 Dom Btls $6 Dom Pitchers $2.75 Import Btls $3.5 Wellers + Coke $2 Fireball $5 Chburger + Fries 25% off Wine (Glass + Btls) $5 Call Martinis $5 Manhattans $3 Blvd Wheat $3 Blue Moon SIN 10p-1a LIVE TRIVIA 7p KARAOKE 10p $2.5 Wells $4 Double Wells $3 Dom Btls $3 Tuaca Bombs WHISKEY WED $4 Jack Daniels $3 22 Dom Drafts $2.75 Wells $4 House Wines $4 Hurricanes $3 Captain Morgan $3 Bacardi Drinks 9a-4p 50¢ off Dom Drafts 4p-close 50¢ off Dom Btls $2.5 Dom Pints $3 Wells $6 Cheeseburger $3 Wine $3 Dom Drafts $3 Dom Headaches $2 Dom Pints $5.5 Chicken Strip Meal $1 Off Kansas Beers $4 Long Islands $4 Long Beach $3 Fireball Shots SIN 10p-1a ACOUSTIC THURS Q'S LIVE 6-8p $3 Dom Pints $2.5 Wells / $4 Double 1/2 price with WU ID PONG TOURNEY 10p OPEN JAM SESSION CRAFT BEER THURSDAY $4.25 Import 22oz $4.25 Micro 22 oz $3.5 Mexican Beers $3 Skyy Drinks $3 Seagrams Drinks 9a-4p 50¢ off Dom Drafts 4p-close 50¢ off Dom Btls $3 Import Btls $3 Import Pints $6.5 Philly Sand $2.75 Dom Btls $2.75 Dom Drafts $2.75 Otis* $2.5 Aluminum Btls $4.5 Red Bull Bombs $2 Dom Btls $3 Free State Pints $4 Tito’s $4 Bacardi Q'S LIVE | MUSIC $4 Big Dom $1 Off All Mules $3 Fireball Shots FIREBALL FRIDAY $4 Absolute Drinks $4 House Wines $4 Fireball Shots $3.25 Dom Drafts $2.5 Wells $2 Fireball $3 Bombs + Barrels 9a-4p 50¢ off Crafts Drafts 4p-close $3 Aluminum Btls $3.5 Skol Vodka + Energy drink $6.5 Chicken Fried Steak $3 Otis* $2.5 Dom Btls $5 Jumbo Wing’s Basket (8) $2 Fireball Shots $3 Fruit Ales $3 Cider Beers $1 off Craft Cans $3 Rumchata and Fireball Shots Q'S LIVE | MUSIC $4 Long Island $3 Dom Btls $2 Kamikaze Shots SEXY SATURDAY $3.5 UV Vodka (7 different flavors) $4 Sex on the Beach $4 Blue Hawaiians $3.25 Dom Drafts $4 House Wines KU/KSTATE Football Specials $2 Dom Btls $3 Craft Btls $2.5 Wells $2 Fireball $3 Bombs / Barrels $2.5 Dom Btls $4 Jack Daniels $6.5 Brisket Sand $3.5 Dom Btls Reverse HH 10p-12a SIN WED/THURS $5 Late night Burger $1 Off Pints $2 Dom Btls $3 Fireball Shots HAPPY HOUR M-F 3-5p 1/2 Price Appetizers $1.5 Wells $3 Double Wells HOPPY HOUR Daily 3-6p EVERYDAY: $5 Bombs with Full Throttle DROP OFF EVERYDAY: LAUNDRY SERVICE $4 Jager Bombs $1 lb (15lb min) $2.5 Apple Pie Shots includes soap, softener and folding fri sat quinton's Q'S LIVE Featuring Live Music every FRI + SAT 4121 SW Huntoon 215.8172 Established 1935 3203 10th St. 357.8474 @thedutchgoose 22 the burger stand food | drink Whiskey while you wash, is the only way. 21st + Washburn 408.5091 Featuring screened patio and great food. 21st & Urish 272.1432 TailgatorsTopeka Unique appetizers and beers 738 SW Gage Blvd. 215.8421 Find us on Yelp *OTIS: Via’s Adult lemonade (Think summer brew, but better.) ne w voo d oo C heers New Belgium, who is celebrating 25 years of craft brewing. They've also found themselves, for the eighth year in a row, named a top company to work for by "Outside" magazine. The reasons, stated by their 800 stake-holding employees including some stellar perks. "After a year of employment, a new cruiser bike; five years means a free flight to Belgium; after ten years, each worker receives a paid sabbatical. Oh, and everyone gets a free beer every day and a 12-pack each week.â€? Along with these success, New Belgium will ring in the new year with the most ambitious portfolio re-imagining in their history, according to spokesperson Bryan Simpson in a press release. "We've got a lot of excitement, momentum and energy coming out of the pilot system and that makes for a bounty of great beers with interesting twists." These abmitious twists are the rebranding of three of their IPA's in a series called Voodoo IPA (homage to their voodoo rangers), the addition of four year-round beers and the last call for three flagship brews. aseveneightfive LAST CALL: Slow Ride Session IPA, Snapshot Wheat and Shift Pale Lager Fat Tire, Citradelic Tangerine IPA, Sunshine Wheat, 1554 Black Ale, Abbey Belgian Ale, Trippel, Glutiny Pale Ale and Glutiny Golden Ale remain as other New Belgium flagship year-round offerings. REBRANDED VOODOO HOPPY BEER LINE VOODOO RANGER IPA [replaces Ranger IPA] A bold imperial IPA with a rare blend of Mosaic, Calypso, Bravo and Delta hops. Notes of pine and citrus flavors are ramped. VOODOO RANGER IMPERIAL IPA [replaces Rampant Double IPA] Golden IPA with tropical aromas and fruit flavors. NEW BELGIUM BOHEMIAN PILSENER [replaces New Belgium Pilsener - the first larger released in 2013.] Clean, easy pilsener. Light and welcoming. NEW YEAR-ROUND BREWS VOODOO RANGER 8 HOP ALE Pale ale packed with citrus and tropical fruit flavors from eight different hop varieties. DAYBLAZER EASYGOING ALE A refreshing and slightly sweet golden ale with a finish of honeycomb. This will be the brewery's first 24-ounce can release, but also available in 12-ounce cans. CITRADELIC EXOTIC LIME ALE Persian lime, fresh coriander and pepper make this crisp gold ale burst with flavor. TARTASTIC LEMON GINGER SOUR Tank-soured ale with lemon and ginger flavors. It's refreshing, if you like sour flavors. Topeka Beer news, Events + Tastings Follow @TopekaBeer and fan Strathman Sales 23 paradize band ‘‘ making music for 40 years Tom Krebs | photos provided T music, originating in the '60s, according to a story written as the band prepared for its 30th anniversary. Since then it has embedded many genres Okay, the Stones made it, of music, according to Ray minus Pete Wyman. The Dead Ortega, a member since 1980. only made it to 30 with Jerry. The members of the band, then Most bands, at least local ones, and now, were very connected don’t even come close. (I’m to the Oakland area and its thinking 15 years may be the Catholic Church, Our Lady of number for even the most long Guadalupe. of tooth.) The band has been influenced urning 40, for many, is a dark day. (But let’s face it, 40 is the new 30.) But for a band to turn 40, now that’s a different tune. But a Topeka band celebrated its 40th anniversary on November 12, 2016 at the Topeka Performing Arts Center with a very special performance that featured different iterations, past and present, of the band performing. by many types of music from the '60s to the present and continues to incorporate them in their performances. Referring to the current iteration of the band, Mr. Ortega said, “We are a mosaic of all our past musicians and La Familia Mexicana played continue to build on our its first job in 1976. Started by many musical influences.” Steve and Art Ortega, it was an aseveneightfive early covert of playing tejano superfly Faces By mayfield F aces By Mayfield is as cool at John Coltrane, as sultry as Lady Day's voice and Superfly. The new night club located in NOTO is an art gallery upon entrance, with life-size portraits and paintings created by George Mayfield, artist and father of owner Lamika Jones, on the walls surrounding by large white columns and ivy and African decore. In the back is a restaurant and lounge where you'll find a sophisticated crowd, mid-30s and older, dressed to the nines (no athletic shoes or attire here) enjoying food and sounds that echoes the lounge, blues / jazz / r+b. 24 We are a mosaic of all our past musicians and continue to build on our many musical influences." Kerrice Mapes | photos provided live music venue It's the type of place you find in New Orleans or Chicago, said music writer Tom Krebs to me when we ecstatically told me about the new venue. "It's got that old school jazz vibe to it." aseveneightfive FACES BY MAYFIELD 802 N Kansas Ave Look for music by Ric Barron, Frank Ace Band, Santiago Brothers and more This isn’t heaven, it just feels like it. wings, beers, bands O 2016 Winners ne of the best, newer events in Topeka, is the annual Wing Fling at the Kansas Expocenter. A dozen restaurants flexed their culinary muscles and competed in various wing categories while participants enjoyed all-you-can-eat wings, music, games, beer and more on a Saturday afternoon. Congratulations to the winners - be sure to visit them and try their wings, among other great items. aseveneightfive best bbq wings Abigail's Grill + Bar ____________________ best twisted wings Abigail's Grill + Bar ____________________ best hot wings front door catering ____________________ best nest the landing grille + bar ____________________ wing fling king the palette restaurant ____________________ thanks to everyone who participated. we hope you will again next year! It was delicious! ____________________ Abigail's grill + bar tailgator's sports pub + grub the landing grille + bar Henry T's via's Pizza + more the burger stand mikey's bar + grill front door catering hhb bbq hooters the palette restaurant Backs By Popular Demand 301 Gage Suite 161 785-234-1548 Juan Diaz Aguirre | Taqueria Mexico Lindo Facebook groups, local food blogs and instagram feeds your stomach likes # insta-hungry Jennifer Goetz | Tacos El Sol N Kerrice Mapes | photos provided o question social media has altered the dining experience, creating a new consumer: the snap happy, social media savvy, food blogger. Instagram has made the importance of plate presentation almost equivalent to taste. Food blogging has built communities of food enthusiasts and Facebook groups have connected people to reviews. Now all your restaurant news is on the fly - but it's being reported, for the most part, by the consumer. The consumer is now the authority to raise a restaurant's reputation or expose their faults with just a few keystrokes, and why shouldn't they be - they are the ones footing the bill... We have social proof at our fingertips, and we have the power to make or break local eateries and shape our local cultural food landscape. Personally, I've begun to limit my chair standing photo sessions with my plates (I used to go to lengths to position my plate in the perfect lighting for that photo, much to my dining guest's despair), not out of laziness but because there is a plethora of great sites and people doing the work for me. Therefore, here is a list of some of some of my favorites. aseveneightfive 26 { Topeka Restaurants Members: 4,129 Photos: 1,319 Created by Martie Rison This active Facebook group allows anyone to post about their dining experience, share photos and the most useful tool, ask questions. Questions range from where to get a small turkey for Thanksgiving to who has the best onion rings in town to what patios are dog friendly. With an average of 20 comments per question, it's crowd sourcing answers for your stomach. EverythingTopeka.com Database of restaurants Daily food specials Kim Schultz, creator of the Topeka Newsletter, has created a database of information about and for Topekans. Here you will find a list of Topeka restaurants with notes as to if they are locally owned, a locally owned franchise or franchise, food specials , events and more. Topeka, What's Cookin? FB group dedicated to sharing recipes. The group for those who put that Pin to action. Topeka, What's Cooking? is a private group (although membership is as easy as a click to join) of over 500 people sharing recipes and real photos of new food ideas. It's social proof that a Pinterest idea could really work. Monsoon Express from TastingTopeka.com Andrea Smith is a transplant to Topeka and after being active on a few foodie FB pages, decided there was a need for a dedicated website directory of local restaurants. The is the most aesthetically pleasing database to date, in my opinion. She recently partnered with Arminda Guerrero, founder of Topeka Dining Group, whose focus is on local area restaurants and bringing people together. The group meets once a month at different local restaurants (JAN MLK Day at Thelma's Corner). Everyone is invited to join, combining good ol' fashion networking with food. Pedro Concepciรณn | The Burger Stand College Hill Hungry in Topeka Andrea Smith Topeka Dining Group Arminda Guerrero ." TastingTopeka .blogspot.com Tricia Peterson Tricia Peterson is a graduate of Le Cordon Bleu Scottsdale in Arizona as is her husband. She then moved to Topeka and graduated from Washburn University. She combines her love of writing and photography with her love of food checking out local places to eat and blogging about her experience. (Her experiences have also been featured in seveneightfive magazine.) Food Porn from Hungry in Topeka Tag @seveneightfive and use hashtag #785Flavor to have your photos featured in the weekender. Sarah Williams | Wheel Barrel 515 VanBuren Topeka 785.235.1700 RowHouseRestaurant.net F or B reak f a s t a nd L unc h it’s . . . 1034 S. Kansas Avenue - (785) 232-1111 - Hanover Pancake House...need I say more? 28 EDITOR'S NOTE Keeping her fork on the pulse of Topeka WHATS NEW, CHANGED and JUST WORTH SHARING.... The Lazy Toad remodeled and it's worth a look. A pool table is now located in the entry way, giving it ample room to move around. A large window brightens up the main bar area and allows paswerbyers inside Fairlawn Plaza a clear view of the scene prior to entering, and the wall between the main bar and the music area has been opened - achieving a more balanced and connected venue. Henry t's menu has been updated with notable changes including their use of fresh avocados (no packaged guac.), Yankee Tank brews (well, not so new but worth mentioning) and the addition of desserts to their gluten free menu, thanks to a partnership with Shana Cakes, located in downtown Topeka. LAROCCA'S PIZZA has opened a second location at 5145 SW Topeka Blvd. They are open Tuesday Sunday from 11a to 9p with delivery. The flagship store, located on Gage is closed Monday - Wednesday, open 11a-9p Thursday - Saturday and 11a-7p Sunday. Look at the #785weekender for music on select Saturday evenings. seen + noted #785flavor YOU CAN'T DRINK ALL DAY IF.... Abigail's Bar + Grill and Louie's Lounge + Laundromat open at 9am. Cheers third-shifters. [$1 off drinks, 9-11a at Abigail's - Drop-off laundry service at Louie's.] The Lazy Toad has 51 beers on tap - that's more than Topeka's Old Chicago. @TopekaBeer Terry's Bar + Grill on 6th serves food nightly 'til 1a. [Chili dog Monday is a must.] fuzzy's taco shop The burger stand now serves food late night Monday - Saturday, 11p-2a. rumors of Topeka location, let's taco 'bout it I Daryl Hendrix | photos provided f you mention Fuzzy's (Fuzzy's Taco Shop), you'll get an almost orgasmic reaction from those in the know "Ohhhhhh, Fuzzy's" they sing, drawing out the "z" with a purr. Not a bad reaction for a little taco shop with a naughty name and "Eat Me" tshirts. Albeit a locally owned franchise (something we don't highlight very often), Fuzzy's is coming to Topeka and it's too good to not share. John Records along with his wife and daughter opened the Lawrence store five years ago and in March 2017 plan to fuzz up Topeka at 2614 SW 17th, in the old Teams Sporting Goods store. The family-friendly Mexican restaurant will offer their fantastic menu with different dishes to stimulate your sense including Baja fish tacos, smothered burritos and salads that are out of the world. The quality, quantity and servings are plentiful and priced moderately. They will be stocked with a full bar and also serve breakfast. If you have driven the 20 minutes to experience this gem in Lawrence at the corner of 11th and Mass, then you know the euphoric rush. If you have not, what are you waiting for? Oh, you can wait 'til Fuzzy's opens in Topeka, but that might make for a long, lonely winter. Welcome to your new addiction. aseveneightfive Grovers BB Sauce + The Landing Grille + Bar G rover's Smokehouse was a Topeka culinary tradition for over 40 years, prior to closing in June 2015, probably best known and loved for their sauce. If you've been craving this sweet, flavorful meat enhancement, look no further than The Landing by Shawnee Lake. Owner Tommy Lewis received the secret recipe, hand-written on an old piece of paper, missing some key measurements. After several attempts, the sauce is now being reproduced in house and tastes just like the original. It is served on all of The Landing's barbecue dishes. [above: BBQ platter: Quarter smoked chicken and three large smoked spare ribs with homemade coleslaw and baked beans. Served with Grovers original BBQ sauce $11.99 #785FLAVOR [ The Breakfast Burger | The Burger Stand ] brunch boozy brunch at eight local restaurants The burger stand Annie's Place The landing grille + bar SUNDAY | 11a-2p Menu includes the breakfast burger, a Kobe beef pattie topped with an egg cooked over easy SATURDAY+ SUNDAY | 7a-9p Menu items includes quiche, Grandma's Old Fashioned Bread Pudding, Cinnamon Rolls SATURDAY + SUNDAY | 8a-noon Buffet with traditional offerings $7.99 Boozy Special Boozy Special Bloody Mary Bar [DIY] $4 Bloody Mary $$ Salty Dog - Salt of the dog that bit you. Tanqueray Gin and Grapefruit juice in a salted rim glass. College Hill ______________________ topeka civic theatre Blue Moose 32nd + Wanamaker ______________________ SUNDAY | 10a-2p Buffet with traditional offerings 8th + Oakley ______________________ Select SUNDAY | 12:30p Buffet catered by Aboud's - changes with each Mainstage Theatre show Unique Item(s) = #785Flavor Unique Item(s) The carrot cake (extra $) Bagels + Lox, Eggs Benedict plus comfort lunch food like mashed potatoes and ham Boozy Special TCT Bloody Mary 4014 SW Gage ______________________ falling water grille Capitol Plaza Hotel ______________________ SUNDAY | 9a-2p Buffet with traditional offerings including an omelet, waffle and carving stations. Shawnee Lake ______________________ Unique Item(s) = #785Flavor Order off the menu - Steak + Eggs Boozy Special Bloody Mary and cocktails The Bar'N Grill 2121 SW Belle Ave ______________________ SUNDAY | 10a-12:30p Buffet with traditional offerings $10 Boozy Special $3.5 Bloody Mary Bar [DIY] Boozy Special $3.5 Bloody Marys $3.5 Mimosas The wheel barrel NOTO - 925 N KS Ave ______________________ SUNDAY | 10a-3p Handcrafted sandwiches mixing sweet and savory ingredients to kickstart your morning Boozy Special $6 Bloody Mary Bar [DIY] $4 Mimosas { Do it yourself bloody mary bar | Bar 'N Grill | HungryInTopeka 30 alfr es c o taco tuesday tailgators 21st + urish ____________________ TUESDAY $.75 tacos lupita's 7th + Kansas Ave ____________________ patio side dinning abigail's 37th + Mayo ____________________ TUESDAY: $1 tacos + $6.95 taco platter which includes 2 tacos, grilled burrito, housemade queso and chips TUESDAY + THURSDAY $1 tacos, shredded chicken or beef. Crispy or soft, served any style - we suggest traditional street style. terry's bar + grill noto burrito mexican taco shop noto ____________________ TUESDAY + THURSDAY $.99 beef, pork or chicken Several unique salsas to pair. glazed goose 29th + Arrowhead ____________________ TUESDAY: $1 crunchy tacos, $1.50 soft tacos + $3 fish tacos what makes Tuesday so special? todos los dias 6th + Topeka Blvd ____________________ Blue Moose PT's College Hill The Burger Stand Quinton's SUNDAY 3 tacos for $2.25 Abigail's The Landing dutch goose Blind Tiger Specks El Mexcal Tailgators Boss Hawg's The Wheel Barrel The Celtic Fox The Classic Bean Pizza Pub Pizagels Henry T's Blackbird Cafe Glazed Goose Lupita's Dutch Goose Weller's Jeremiah Oscar's Bullfrog's Skinny's Las Fuentas The Rowhouse The Lazy Toad Margaritas jalisco Paisano's ...any more! Let us know about your favorite patio #785Flavor tortilla jack's 17th + Lane ____________________ TUESDAY + SATURDAY $.75 Tacos + $2 16oz margaritas 10th + Mulvane ____________________ 10th + watson ____________________ TUESDAY $1 street tacos SATURDAY $.75 hard tacos (go early, they sell out) Brass rail oakland ______________________ oscar's 15th + Lane ______________________ TUESDAY + WEDNESDAY $.99 hard tacos and on Wednesday $1.50 tostados FRIDAY $.69 hard tacos. Must add on a sour cream and chicken enchilada or a pork burrito. el taquito express Weller's 29th + fairlawn ____________________ North Topeka Blvd. ______________________ TUESDAY $1 street tacos SUNDAY $1.49 soft tacos ta c o T [ Taco Tuesday Special Abigail's Bar + Grill ] u e * Look for an updated article this spring with patios that are dog friendly To date, we can only confirm Lupita's at 7th and Kansas has dog friendly. Experience adds The Celtic Fox to that list. s d a y Pepe + Chela's 31 5 easy steps to support local restaurants EAT LOCAL REVIEW F A N D O N ' T B L A S T S H A R E 32 give them some love! W by Martie Rison | graphics LinkedIn.com e all have that favorite place, that one restaurant that feels like a real treat to visit. If you are lucky, your place is a mom + pop that is as unique in atmosphere as it is in flavor. Writing this now I can think of some places in Topeka that fit the bill: Bobo's, the Wheel Barrel and Juli's, just to name a few. There are some restaurants that were so fantastic, like Pore Richards and China Inn, they still stir real love and loyalty from their customers many years after their doors closed. When a place that has been so beloved for so many years closes, there is often an outcry in the community. We hate to see them go. Have you ever wondered what you can do today to help keep your favorite local restaurants in business for many years to come? There are a few things you can do that take very little time and effort that make a huge impact on the restaurants you love. To put it quite simply, be their biggest fan. Your words are powerful. One of the greatest gifts you can give to your favorite restaurant is to tell your friends and family about why you love the place. Don't just keep your adoration for their dishes to yourself, shout it from the rooftops! Your words will plant a seed in the minds of many people and that seed will either spark curiosity or fond memories. You could even help the community get excited about a new restaurant that is just getting started. Owning a small business is hard, plain and simple. You give it your all every day and you hope that your hard work will be enough to support the business, and maybe one day, if you're lucky, your family too. There is no boss to guide you through decisions, there is no performance review to give you praise for a job well done. There is just the daily grind and the friendly faces of your regulars to get you through. Buying advertising is expensive and while it helps, nothing is more powerful than word-ofmouth within a community. > continued on next page Ready to put your words to good use? Here are five tips to help you get started! 1 2 3 4 5 Eat Local – When trying to decide where to go for a meal, skip the big chain restaurants. Sure they are fun every now and then, but they are all the same nationwide. Why not make an investment in your community instead? Eat local! You will discover restaurants that are unique to Topeka and full of local culture. Share Your Experience - Love your meal? The atmosphere? Did you get outstanding service? These are all things that you can share with your friends and family on social media. Chances are, your photo will motivate someone else to visit the restaurant soon. Not sure how to share? Here are some tips.. • Love the retro sign outside? Take a photo! Post it to Instagram, Facebook or whatever social network is your favorite. • Was that locally brewed beer amazing? Order another! Before you start on your second glass, take a photo of it with the angle just right to show off the great atmosphere in the background. • Did your server go above and beyond? Ask their permission and take a selfie with them! Tell everyone how great they are! • These are just a few tips to try, get creative and celebrate the experience of visiting this restaurant! Be Their Biggest Fan – follow their Facebook page and tune into their posts. When they announce a special, share it! Tell everyone why you love the place so much and share link to their page. Nothing means more to a business owner than hearing how their customers love their product and sharing their posts helps them get the word out to a much bigger audience. Give Them a Review – An online review is a powerful thing for a small business for a couple of reasons. First and foremost, it lets the business owner know what they are doing right and what they are doing wrong. Your point of view is immensely valuable to them. Second, your review helps others learn about the restaurant. For people who are visiting from out of town or are curious to try something new, your words are a big help in their decision making process. So if you love a restaurant, take five minutes and go onto their Facebook page, Google or Yelp and leave them a review. It is one small step that has a huge impact. Don't Put Them On Blast – No matter how fantastic a place is, it is inevitable that someone is going to have a bad experience. It happens. It could have been a server with a bad attitude, or a new chef over cooking your food, sometimes things just go wrong. Please, if you have a bad experience, before you go public with your displeasure, talk to the manager or business owner. They will want to address the issue, not only for you but for future customers as well. Give them a chance to make things right before you force them to defend their business in a public forum. So that is it, you can make a huge impact on a small business just by telling your friends. It takes very little time and effort. Just remember, spreading the word about a small business is always in good taste. aseveneightfive #785LIFESTYLE A field of greens, field of dreams by Tom Krebs | photos by Amber Farmer "Our families are here to provide a vehicle for their success, we're just in the backseat enjoying the ride." ‘‘ 34 Just what is opportunity? Colby and André are on the autism spectrum and Luke was born with Down Syndrome. All three participated in the special education program at Auburn-Washburn USD 437, which earned a shout out from André’s father, Luis Guillén. “André was in an awesome program. It helped him open up a lot.” Opportunity is clearly different for different people. For three young men in Topeka, all with, in a parent’s words, “different abilities,” opportunity has a different face than for many of their peers. But thanks to an collaborated effort by family and friends, Colby Myers, André Guillén and Luke Gerhardt will have the opportunity to enjoy personal success All three earned a high school and meaningful employment through diploma and are currently enrolled in the special education program their lifetime. that allows them to continue their They will achieve this dream through an work on building life skills until amazing indoor field of greens. their 21st birthdays. There is nothing small in scale about But knowing they would be aged either the field of greens or the dreams out soon, questioning government these parents have for their children and services, now and in the future, but others. (The families dream to replicate, wanting more for their children, over time, these opportunities for other Chuck and Kris Myers, Luis and local citizens with "different abilities.") Marisol Guillén, and Tim and About one in every 66 children born in the US is diagnosed with autism, but the severity ranges across a wide spectrum. About one in every 700 children born in the US is born with Down Syndrome. Rhonda Gerhardt set about creating a food production facility that could be fiscally viable as well as providing a work environment that aligned with the young men’s capabilities The mission of CALCan “is to enhance the lives of our local citizens with disabilities by providing the opportunities for personal success and meaningful employment.” Luke Colby with his dad Chuck Andre + Luis Guillén CALCan was born. Greens and hydroponics A state of the art, 5,400 square foot green house located south of Washburn Rural High School allows for a variety of greens to be grown hydroponically and harvested year around. And that’s what the three families do: plant, nurture, harvest, market, and deliver huge amounts of fresh greens to markets in Topeka, including Guillén’s restaurant, Luis’ Place, Lawrence and as far as Kansas City and Wichita. The 2000 plants a week that come out of the greenhouse are grown in a network of high density polyethylene channels, dependent on pumps and computers using Topeka city water, delivered by RWD #3, which is treated to meet a strict PH balance. That’s it. No soil, no fertilizers, no pesticides. All pest control is done without chemicals. The green house, located on land owned by the Gerharts, was finished and outfitted with the sophisticated network of computers, water storage and pumps, and plastic trays and troughs used in the process - in time for planting the first seeds. The first harvest started last January. An earlier visit by Luke to relatives in Wichita set in motion the idea to become hydroponic farmers. As part of developing job skills, all three young men, after filling out job applications, were put on the CALCan payroll. All three young men participate in the regular tasks: seeding, transplanting, harvesting and maintenance. The families’ work in the greenhouse centers around three days: Tuesdays, Wednesdays and Saturdays. Those days all three families, including André’s and Colby’s sisters, Alyssa Guillén and Sydney Myers and Luke’s cousin, Brooke Schucknecht, are at the greenhouse seeding, transplanting and harvesting. Prior to work, all involved enjoy a meal together, which is considered an essential element of the families’ efforts. where to buy calcan products The process, from planting to harvest takes six to eight weeks: two weeks as seedlings, two weeks in the nursery, then two to four weeks in a finishing stage. The business and looking ahead The families know they have to have a good product to make a profit, which is key to sustainability. In order to do so, lots of data pertaining to costs/ overhead, sales, and of particular importance, the man-hours the young men contribute to the production is being collected. If this model is to be replicated, others will need to have a thorough understanding of what a labor force with disabilities brings to the table and what others will need to contribute. They are looking at other models, such as expanding on their own, looking for partners, or taking the initiative to schools themselves, which would provide both a group of students seeking the opportunities as well as a group of consumers looking for fresh greens on the salad bar. Guillén offered up this assessment of their efforts to date, “Our families are here to provide a vehicle for their success, we’re just in the backseat enjoying the ride.” aseveneightfive hyvee Wanamaker 35 #785FLAVOR FOOD NINJA Quintons 4.0 Fists T he wind is brisk, the air chill and calm. Night settles in like a blanket over a sleeping child and no one is aware of the epic battle about to ensue. This ninja strikes once, nay, twice more to infiltrate the establishments that will satiate a warrior’s appetite. Quinton’s is the first foe I will confront. My skills are honed, my blade is sharp, and my resolve is unwaivering... Atmosphere I enter undetected to find a warm, inviting, spacious establishment. I cross the floor to a comfy booth where I will be hidden in the shadows until it is my time to strike. Each table feels somewhat private in this place and I am alone with my thoughts. Friendliness I am greeted with a smile and a menu immediately. For a moment I am distracted from my mission, but I regain control of the situation and order. During my meal the waitress is attentive, friendly and accommodates my needs with ninja-like speed. Ninja’s RecommendationCajun Fries and Grilled Cheese 36 Menu Quinton’s offers deli style fare, with enough variety to satisfy the pickiest of ninjas. Not overwhelming but plenty of choices, I make my selection and wait for my opponent’s next move. Food Splendid flavor, well prepared, and portions that fill this ninja’s belly. The Peppercorn Ranch dipping sauce is an assault on my ninja tastebuds and the Grilled Cheese and Tomato Soup is surprisingly well executed for such a common dish. The bread is buttered to perfection, the soup creamy and warm on a cold fall night. Funds Quinton’s doesn’t break the bank for what you receive. For less than $12 I procure a meal and drink fit for the fiercest warrior. Lunch or dinner, Quinton’s is a perfect choice for the mightiest ninja’s needs. aseveneightfive pizza o Double Edge Edition I Lings move on to my second opponent and find the challenge waiting for me when I arrive. Ling’s Express sits unassuming in the shops by the lake at 29th and Croco. Little do they know their challenge is about to be met by the fierce, unrelenting, and hungry FOOD NINJA! Atmosphere Designed for, as the name suggests, express dining, the dining area is sparse and unwelcoming, but very clean. A few tables are available but this is clearly an in and out establishment. The drive through is most likely the better option. Friendliness I am greeted with a smile, but not much enthusiasm. My order is politely taken, and although there is nothing outstanding about the exchange, this ninja is not put off by it. Short, to the point, but friendly. Menu Standard fare for Chinese style dining. A variety of options and combination plates are sure to satisfy any ninja’s thirst and hunger. Looking at the menu, I am a little 3 Fists overwhelmed by the choices, but soon find the pattern in my foe’s attack and find my counter-strike, making my selection. Food General Tso’s Chicken is the choice I make to eliminate my hunger. I am disappointed. The flavor is quite bland, though there is the hint of something more that keeps me eating. The chicken is somewhat chewy and I am finding myself wishing I had made a different choice. Next time… Funds Excellent price for the portion. This is more than enough food for this ninja to be full and a generous egg roll is included with my plate. Less than $10 will gain you enough food for two ninjas. aseveneightfive Ninja’s RecommendationEgg Rolls take a drive GAME DAY BAR + GRILL 23RD STREET BREWERY by Kerrice Mapes T he small, locally owned brewpub on the West side of Lawrence by Clinton Lake is a 15 BBL brewery that averages just under 1,000 barrels a year and distributes draught beer throughout Kansas. Impressive. But for me, it's not the beer that gets me out to 23rd Street Brewery - it's the amazing food (and the off-leash dog park down the street at Clinton Lake is a bonus). Their menu is filled with signature dishes: the Danny Manning Marsala Chicken, the 23rd Street Meatloaf (made from a blend of bison and beef), the London Phog Fish + Chips, the Hank Booth Burger (burger topped with bacon, caramelized onion, sautéed mushrooms, homemade BBQ sauce and cheddar cheese) and The Bill Shelf (made from scratch mac and cheese topped with buffalo chicken tenders). Once again, I go against the grain. Sure, all of these dishes are delicious, but the MVP for me is their New Orleans Style Fish. The blackened salmon is always cooked to perfection, medium and served on a bed of rice with their creamy, spicy Cajun sauce. This sauce is so good, if they filled Clinton Lake with it, I would swim daily. The recommended side is broccoli, which is fantastic, but their green beans are dynamite: crispy, seasoned fresh snap beans that rival a main entrée. Also notable are several of their appetizers. The Romos' Cheese on Bread is a mozzarella and provolone cheese blend, brick over toasted with fresh garlic Italian crust and seasoning and served with marinara and their signature roasted garlic dressing. Two appetizers perfect for sharing and forcing you to get a to-go box for your entrée are the 23rd St Deconstructed Guacamole, a plate of fresh avocado served sliced with pico de gallo, sea salt on the side and fresh lime, ready for you to dip - and the Naked Nachos (smartest appetizer I've seen ever) your regular nacho all stars, meat, cheese, jalapeños, black beans and black olives plus tomatoes and scallions all served in a bowl with a side of sour cream, salsa and chips. Now you can actually share nachos politely and still have every chip topped with nacho goodness, and even take it home. Brilliant. Check out 23rd Street Brewery for their beer or for their signature dishes - or for pretty much everything else on the menu. They are all winners. aseveneightfive 38 by Daryl Hendrix T ake a 15-minute drive on KS-4 to Meridan and find yourself at Game Day Bar + Grill, a small town "Cheers" where you'll experience great food and meet two of the kindest people I've ever had the change to meet. Cheers, groans, beer and big screens - Game Day is the place to meet your buddies for wings, nachos and a full slab of football, baseball and basketball. Or come alone and count on finding a crowd to hang with, it doesn't matter what colors or logo you are wearing. I've had the privilege of knowing Jackie Kern Cummings for over 25 years and with that the opportunity to meet her husband, Nick, her two boys, Creston and Hayden. The Cummings have been foster parents for a number of years and always opened their home to many in need. Jackie is a former teacher at Topeka West where she coached volleyball and softball; Nick is a special education teacher at Effingham and football coach at Valley Falls High School. Jarron is a student and plays football at Emporia State University while Jaime is a senior at Highland park High School. The couple purchased the former Watering Hole in Meridan last January, closed for a month of renovations, changed the name and opened February 9. They patronized the Watering Hole and felt it was a diamond in the rough, so when they learned it was for sale, they knew it was their time to play entrepreneurial ball. Game Day highlights include outdoor seating, bands, during the summer participating as a stop in various fundraising motorcycle rides and food specials including $1 Taco Tuesday, $2 chili dog Wednesday and their Sunday favorite, the Hangover, a burger topped with egg, bacon, shredded cheese and hot sauce. Cheers! aseveneightfive 13 23 17 12 9 First Friday artwalk map GORDON 22 11 20 15 14 19 10 7 21 8 3 & shopping guide 6 4 noto/north topeka STREET 3 14 17 23 11 2 5 9 21 19 1 15 AVE 13 KANSAS 20 17 10 8 2 LANE 1 17 6 4 2 JACKSO N 9 HUNTOON 4 6 17TH 4 3 9 10 18 22 16 15 19 7 20 KANSAS 5 3 7 1 6 8 12 22 6TH 21 QUINCY 1 WASHBURN GAGE BLVD OAKLEY 5 6TH downtown topeka 7TH 18 4 8 14 3 8TH 10TH 10 16 20 19 15 21 22 GAGE BLVD 9 7 14 17 8 9 29TH 2 4 FAIRLAWN 1 21ST 21ST 29TH 7 6 CALIFORNIA TOPEKA! 10 712 Innovations | 712 S Kansas Absolute Design | 629 S Kansas Boho Mojo | 631 S Kansas Capitol Federal | 700 S Kansas Cashmere Popcorn | 728 S Kansas Contemporary Jewelry Studio | 929 S Kansas Hazel Hill | 724 S Kansas H&R Block | 726 S Kansas Jerry Clark Photographer | 112 SE 7th Leaping Llamas Artisan Shop | 725 S Kansas NexLynx | 123 SW 6th Ave Oddfellows Fine Books | 117 SW 6th Prairie Glass Studio | 110 SE 8th Topeka Performing Arts Center | 214 SE 8th Trails Gallery | 109 N Kansas Warehouse 414 | 414 SE 2nd Wolfe’s Camera | 635 S Kansas westboro/midtown 6 Topeka Community Foundation 4 Girls’ Garage | 837 N Kansas aMUSEd Gallery | 115 NW Laurent Ballet Folklorico | 814 N Kansas Darcie Lane Studios | 922 N Kansas Generations Antiques | 918 N Kansas Habitat for Humanity ReStore | 121 NE Gordon Haven Arts | 837 1/2 N Kansas Kaw River Rustics | 901 N Kansas Matryoshka Tattoo | 902 N Kansas NOTO Arts Center | 935 N Kansas NOTO ArtsPlace | 905 N Kansas The Open Window | 927 N Kansas Portico | 900 N Kansas Rewind Antiques | 840 N Kansas Rusty Haggles Antiques | 826 N Kansas Stonewall Gallery | 826 N Kansas Studio 831 | 831 N Kansas Two Days Monthly Market | 829 N Kansas Two Wolves Studio & Den | 824 1/2 N Kansas Vintage Vibe | 833 N Kansas Yeldarb Gallery | 909 N Kansas Yeldarb Studio Artists | 907 N Kansas 1 3 9 2 3 6 5 5 4 Alice C. Sabatini Gallery | 1515 SW 10th Art Print Express | 1047 SW Gage - Fleming Place Beauchamp’s Gallery | 3113 SW Huntoon Mulvane Art Museum | 1700 SW Jewell Porterfield’s | 3101 SW Huntoon PT’s Cafe College Hill | 1635 SW 17th Soho Interiors | 3129 SW Huntoon surrounding complete exhibit information at artsconnecttopeka.org ArtsConnectTopeka 6 8 5 @artsTopeka 9 3 DEC 2 JAN 6 FEB 3 Support Topeka’s art community! Donate at: 7 2 4 10 2900 MacVicar | 2900 MacVicar Discover Nature Gallery | 1100 SE Rice Glaciers Edge Winery | 1636 SE 85th (Wakarusa) God's Storehouse | 2111 SW Chelsea Prairie Meadow Greenhouse | 7321 SE 45th Ricks Advanced Dermatology | 5121 SW 28th Southwind Gallery | 3074 SW 29th Tasteful Olive | 2900A Oakley-Brookwood Topeka Art Guild | 5331 SW 22nd
https://issuu.com/seveneightfive/docs/sefm_xi_iii_final_lowres
CC-MAIN-2017-09
refinedweb
12,972
67.99
You can subscribe to this list here. Showing 3 results of 3 On Dec 29, 2007 5:11 PM, Stefan Richter <stefanr@...> wrote: > Damien Douxchamps wrote: > > Isn't all this leading to the fact that we must interpret the ROM while > > we read it, instead of just grabbing all the ROM at once? ... >. The ioctl interface have an ioctl that lets you get the config rom too, which is what the lidb1394 juju backend uses when enumerating the cameras, in other words, this part does not generate any IO. Kristian Damien Douxchamps wrote: > Isn't all this leading to the fact that we must interpret the ROM while > we read it, instead of just grabbing all the ROM at once? Alas there doesn't seem to be a single strategy that yields the very best performance with all existing cameras. Especially if bus_info_block.max_rom == 0, you can only guess to which extent block reads might work. The ieee1394 driver does interpret the config ROM while reading it. It tries to read it in chunks up to the size indicated by max_rom and falls back to quadlet reads if it encounters any problems. I don't think we honor the alignment restriction of block reads in case of max_rom == 1. The firewire-core driver also interprets the config ROM while reading. But it always only reads quadlets. The cost to do so is lower than with ieee1394 because of gap count optimization, at least on 1394a only buses. (1394b Beta only buses already have a low arbitration overhead; only the transaction overhead of the hardware/ firmware/ OS remain. Mixed 1394a and 1394b buses would profit from gap count optimization but we don't do it if 1394b PHYs act as repeaters, because then it becomes hard to figure out a suitable gap count.). Note, if you are keen on getting also config ROM contents which are located outside the 400...7ff range, you (a) have to interpret the ROM and (b) can't entirely rely on firewire-core's config ROM cache. (Firewire-core only looks into the 400...7ff range.) However, I don't know if there are any IIDC devices out there with config ROM outside that range. It seems unlikely. -- Stefan Richter -=====-=-=== ==-- ===-= Thank you, that's it. Maybe a little note in the installation instruction would be very helpfull. Tonio Am 28.12.2007 um 04:29 schrieb David Moore: > On Dec 27, 2007, at 11:53 AM, Tonio Seiler wrote: > >> I installed libdc1394 on my macbook. >> >> In Ecplise, I can compile an example programm, but when I try to run >> the programm, I get the following error message: >> >> dyld: Symbol not found: ___CFConstantStringClassReference >> Referenced from: /usr/local/lib/libdc1394.21.dylib >> Expected in: flat namespace >> >> >> How can I get the example to run. Do I have to include any Libraries >> in the Linker? Which one? >> > > Yes, try adding the CoreFoundation framework to your compilation. > > -David > > ---------------------------------------------------------------------- > --- > This SF.net email is sponsored by: Microsoft > Defy all challenges. Microsoft(R) Visual Studio 2005. > > _______________________________________________ > Mailing list for libdc1394-devel > libdc1394-devel@... >
http://sourceforge.net/p/libdc1394/mailman/libdc1394-devel/?viewmonth=200712&viewday=29
CC-MAIN-2015-48
refinedweb
512
73.58
Routing is the first and foremost phenomenon in the ASP.NET MVC pipeline. Here, you will learn about routing, it's working, and its variants. Introduction Routing is the first and foremost phenomenon in the ASP.NET MVC pipeline. Here, you will learn about routing, how it works, and its variants. Background Last week one of my friends asked this question: "Can we make our custom route with some constraints and what is attribute routing?" I am dedicating this article to him. I hope he will like this. The topics to be covered are, Routing Routing is the first step in ASP.NET MVC pipeline. This is the replacement of the concrete, physical files used in the URLs. In other words, routing is the phenomenon in which controller and actions execute rather than the concrete physical files. Why do we need routing? Traditionally, the URL of the browser represents the physical file. A file can be HTML file, ASPX page etc. Let’s understand this traditional way, This URL shows that first we go to “images” folder then access the “john.aspx” file having id is 2. Hence it is not the good way to expose your precious information to the URLs of the browser, so with these URLs sites can be hacked. As a result, Routing comes into action and solves this problem of the traditional file-based system. Implementation of routing starts with route table. The route table is a collection of all possible, correct routes that can be used to map the HTTP request URLs. Let’s understand RouteTable and the working of Routing in detail. Routing is a pattern matching system that matches the incoming request to the registered URL patterns reside in the Route Table. When an ASP.NET MVC application starts, it registers patterns to the RouteTable to tell the routing engine to give a response to the requests that match these patterns. An application has only one RouteTable and it resides in the Application_Start event of Global.asax of the application. The routes are registered to the RouteConfig class that has the route URLs to be mapped and ignored in the application. Let's have a look at it, The Global.asax file looks like, The Figure is illustrating the working of routes and depicts how the routing engine processes URL requests and gives the response to the browser. When the UrlRoutingModule finds a perfect matching route for the incoming URL from the RouteTable then Routing Engine forwards this request to RouteHandler. When it matches successfully, then IRouteHandler comes into action for that route and its GetHttpHandler() method is invoked. IRouteHandler is looking like this, After finding the route successfully, ProcessRequest() method is invoked, as shown in the figure; otherwise if the requested URL doesn’t match with any pattern in the RoutTable then the user will be redirected to HTTP 404 error page. Parts of a Route When you are going to register the routes you have to use the overloaded version of the MapRoute method in the RouteConfig class. There are 6 overloaded versions of the MapRoute method, the last method having all parameters is explained below, Above MapRoute method has the following parameters, Let’s understand each! Name of Route First of all, I want to say, there are very ambiguous ideas in the community about Name of the Route. So I highly recommend reading this section carefully and please leave your comment about this because I have learned it myself. So, please correct me if I'm wrong. The route that is registered in the RouteTable must have a unique name to differentiate from other routes. This name refers to a specific URL pattern in the RouteTable. The most important thing is that this name is only used for URL generation. Hence I concluded that Routing does not happen on the basis of Name, it happens on the basis of its URL pattern. In fact, URL pattern tells the UrlRoutingModule what to do with the request, not the name of the route. Then the question comes why it should be unique, it should be because of it the thing that creates uniqueness for the URL generation. Let’s understand it practically. Student.cshtml Index.cshtml When we click on URL then it will direct us to View of Second Route. As you can see, we pass the name of route “Second Route” in the ancher tag and while clicking it will redirect us to that route whose name is given in ancher tag. So the conclusion is, route names are used for URL generation. If the route name is not unique then how UrlRoutingModule will know about the Second Route and it will throw a runtime error as shown below, URL Pattern of the Route URL pattern of the route consists of literal values and variable placeholders. These variables are also called URL parameters. All these literal values and placeholders are separated by forwarding slash (/) and called Segments. Literal means a “fixed” value and variable placeholder mean “replacement of some value”. In a URL pattern, you can define a placeholder with the help of curly braces {}. You can define more than one placeholders in a segment with the help of literal. For examples, see the figure. Hence, if you want to add more than one placeholders in a segment then you have to use a literal between those placeholders. Defaults of Route When you define a route, you can assign defaults values for each segment of the URL, these default values come into action when no parameter is provided in the URL. You can set defaults values for the route by making the anonymous object of the RouteValueDictionary class. Constraints to Route Constraints are limitations on Route parameters. When you set any constraint to a route then if the URL consists of values that do not fulfill the constraint requirements then that route will not work. And request goes to route that has defaults parameters. You add constraints to route to ensure that it will work according to your application requirements. You will see its more detail on this topic. Namespaces to the Route You can set your own namespaces for the web application. Namespaces can be added into routes by making objects of RouteValueDictionary class. This parameter used when you want to redirect your URL to a specific controller having a specific namespace. Default Route and Custom Route The figure illustrates that a route is going to be registered in the RouteCollection (routes.RouteTable) having a unique name Defaults, a URL pattern in which controller, action, id all are placeholders, then there is a defaults property whose responsibility is to initialize the controller and action automatically if it doesn’t include the requested URL. Custom Route Let’s create a custom route to understand Routing. As we have HomeContoller and the Index action method. Let’s create another action method name as Student, Now we have to create a custom route in RoutConfig class Before going to execute the application I want to tell you a very crucial thing about Routing, that is, “Always define your routes from Specific to General”. In the above code, the default route is most general so it should be at the end of the RouteTable. And our most specific route is the first route that we defined earlier. Routing flow is as follows, Now when you execute your application and write the URLs as given below then the output is as follows, Query String has question mark sign (?) in its URL. But this way of passing data is not a good way because through this method your data can be exposed to the hackers or penetrators. Better than a query string, the way of passing data is: What is the purpose of IgnoreRoute() method? In the above code of RouteConfig class you can see the IgnoreRoute() method as shown below: As you know, the URL pattern {controller}/{action}/{id} is handled by UrlRoutingModule by default. But the point of interest is if you want the RoutingModule to handle the above-mentioned pattern then you have to set the RouteExistingFiles property of the RouteCollection to true. You can see in the above code, the datatype of RouteExistingFiles property is bool so it can be true or false. When it is true, then the RoutingModule will handle all the requests that match the defined URL pattern in RouteConfig class. Otherwise, when this property is set to false, UrlRoutingModule will never handle any request. Now, the problem is, when you have set RouteExistingFiles property to true, routing module handle all the requests. But when you want to stop the access of some routes to the browser, then how can you do that? This can be done by using IgnoreRoute() method. The ignoreroute method will stop accessing the routes defined in IgnoreRoute parameters. The method looks like, This will ignore the specified URL route from the list of available routes in RouteTable. Now in RouteConfig class, what does the following code means? The above code of IgnoreRoute() shows that resource.axd files are ban for the access. The last point is, these .axd files are not present in our project, and these are reserved for HTTP handling. How to apply constraints to Custom Route? Constraints are limitations on Route parameters. When you set any constraint to a route then if the URL consists of values that do not fulfill the constraint requirements then that route will not work. Let’s understand it in a practical way, suppose you want to limit the roll number of the student to only 5 digits, then how can you do that? This can be done with the help of constraints. Let’s play with it. As shown above, roll number digits must be 5. When we execute the following URL: Output: Roll Number is 12345 @”\d{5}” has @ sign as prefix which is called verbatim literal. Its opposite and bad way is using Escape sequences. Escape sequences and their use is defined in figure below, Let’s know about the difference between both: As we can see verbatim literal gives us great readability. Hence in this way you can make your own constraints on your custom routes. What is Attribute Routing? Attribute routing is the new type of routing in ASP.NET MVC 5. According to the name Attribute Routing, one can suppose that this type of methodology will use Attribute to define routes. Yes! Let’s understand it in detail. Why do we need Attribute Routing? First of all, look at our previous custom route Now let’s move to use Attribute Routing. First of all, you have to enable the access to attribute routing. So RouteConfig class becomes, Now, let’s go into controller and take a look at its working. A [Route] attribute is used at the top of the action method. Output is, If you want to make a parameter optional in attribute routing then simply place a question mark at the end or parameter like below, You may see that many routes have the same portion from its start, it means their prefixes are the same. For example: Both the above URLs have the same prefix which is Home. So, rather than repeatedly typing the same prefix, again and again, we use RoutePrefix attribute. This attribute will be set at the controller level. As shown below, In the above code, RoutePrefix is set to controller level and on action methods, we don’t have to use Home prefix again and again. The output is as follows: The second Route attribute at the top of controller sets the default value for an action method. As you had seen in the routing section, we can set Name for the route. So, Can we set the Name in attribute routing for specific URL? Yes! Here also the name is only for URL generation. We can set the name as, The above code shows how can we set the name of the route in attribute routing. After reading the section of Route Names in convention-based routing, you can repeat the procedure of URL generation in this Route attribute. As you had seen in routing section, we should create our routes from more specific to more general flow. Then how can we do that in attribute routing? Can we set the preference of routes in attribute routing? Yes! You have to use Order parameter in route attribute. Suppose we have a controller having two action methods named as First and Second. And they have Order parameter set to 1 and 2. The action method will execute according to FCFS (First Come First Server) and its value can be from -2,147,483,648 to 2,147,483,647 (size of int). When we run this code, our Second action method will execute because it has higher order. But if no order is specified in the Route attribute then action methods will execute according to the order in which the routes are registered in the RouteTable. As you had seen in the routing section, we can set constraints to the convention-based routing. Can we set the constraints for attribute routing? If yes then how? Yes! You can set the constraints in attribute routing. The syntax is as follows, First of all, take a look at different constraints that can be used in attribute routing. View All
https://www.c-sharpcorner.com/article/convention-routing-vs-attribute-routing/
CC-MAIN-2019-22
refinedweb
2,237
72.36
DBIx::Class::Manual::FAQ - Frequently Asked Questions (in theory). How Do I:. Install Catalyst::Model::DBIC::Schema from CPAN. See its documentation, or below, for further details. Install DBIx::Class::Schema::Loader from CPAN, and read its documentation. Look at the DBIx::Class::Manual::Example and come back here if you get lost. Create your classes manually, as above. Write a script that calls "deploy" in DBIx::Class::Schema. See there for details, or the DBIx::Class::Manual::Cookbook. Make sure you database supports Unicode and set the connect attributes appropriately - see "Using Unicode" in DBIx::Class::Manual::Cookbook. using one "load_namespaces" in DBIx::Class::Schema call. Add the name of the schema to the table name, when invoking table, and make sure the user you are about to connect as has permissions to read/write all the schemas/tables as necessary. There are a variety of relationship types that come pre-defined for you to use. These are all listed in DBIx::Class::Relationship. If you need a non-standard type, or more information, look in DBIx::Class::Relationship::Base. This is called a has_many relationship on the one side, and a belongs_to relationship on the many side. Currently these need to be set up individually on each side. See DBIx::Class::Relationship for details. Create a belongs_to relationship for the field containing the foreign key. See "belongs_to" in DBIx::Class::Relationship. Just create a belongs_to relationship,. Instead of supplying a single column name, all relationship types also allow you to supply a hashref containing the condition across which the tables are to be joined. The condition may contain as many fields as you like. See DBIx::Class::Relationship::Base.') and call search on it. See "search" in DBIx::Class::ResultSet.()'}) Supply a list of columns you want to sort by to the order_by attribute. See "order_by" in DBIx::Class::ResultSet. as? You a scalar reference: ->search({'created_time' => { '>=', \'yesterday()' } }) To search in two related tables, you first need to set up appropriate relationships between their respective classes. When searching you then supply the name of the relationship to the join attribute. Currently, DBIx::Class can only create join conditions using equality, so you're probably better off creating a view in your database, and using that as your source. A view is a stored SQL query, which can be accessed similarly to a table, see your database documentation for details. To use an SQL function on the left hand side of a comparison you currently need to resort to literal SQL: ->search( \[ 'YEAR(date_of_birth) = ?',. $result->discard_changes Discarding changes and refreshing from storage are two sides of.. Set the shell environment variable DBIC_TRACE to a true value. For more info see DBIx::Class::Storage for details of how to turn on debugging in the environment, pass your own filehandle to save debug to, or create your own callback. DBIx::Class runs the actual SQL statement as late as possible, thus if you create a resultset using search in scalar context, no query is executed. You can create further resultset refinements by calling search again or relationship accessors. The SQL query is only run when you ask the resultset for an actual:. Check the list of additional DBIC resources. This module is free software copyright by the DBIx::Class (DBIC) authors. You can redistribute it and/or modify it under the same terms as the DBIx::Class library.
http://search.cpan.org/~ribasushi/DBIx-Class-0.082810/lib/DBIx/Class/Manual/FAQ.pod
CC-MAIN-2014-52
refinedweb
567
50.33
How can I slice the array, avoiding duplicate values in each chunk? Suppose I have this array: a = [1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7,8,9,10,11] a.each_slice (2) .to_a will generate pairs, but these pairs will contain non-unique values such as [3,3]. So I guess I am looking for some sort of unique_each_slice method. I want to be able to shuffle this array until I get to the point where I have unique pairs of 2 (doesn't have to be 2, can be anything), for example (using 2 example) [3, 1, 3, 7, 6, 3, 4, 5, 8, 3, 9, 3, 2, 3, 6, 3, 3, 11, 10, 3] If you do each_slice (2) on this array, you get unique pairs: [[3, 1], [3, 7], [6, 3], [4, 5], [8, 3], [9, 3], [2, 3], [6, 3], [3, 11], [10, 3]] compared to the original where you have: [[1, 2], [3, 3], [3, 3], [3, 3], [3, 3], [3, 4], [5, 6], [6, 7], [8, 9], [10, 11]] with non-repeating pairs in each, like [3,3] Another example, suppose I have: a = [1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7,8,9,10,11,12,13,14,15,16,17] Now, suppose there is some function a.unique_slices_of (3), I would get: [[4, 16, 3], [1, 9, 3], [3, 6, 17], [3, 6, 10], [15, 3, 2], [3, 8, 12], [11, 3, 14], [7, 13, 3], [3, 5]] By "unique slice" I mean a slice where the same number is not repeated twice: [1,2,3] is a unique slice, [3,1,3] is not. So far, I have come up with the following method, which seems to take several iterations before everything turns out right: class Array def unique_slices_of!(slices) loop do unique = true self.each_slice(slices) do |slice| if slice != slice.uniq self.shuffle! unique = false # so we know whether to loop again break end end break if unique # if unique didn't change, that means all slices were equal if unique == false then unique == true end # reset and start again end self end end The main problem with my code is that a) I don't think I'm using some idiomatic Ruby method that can cut this process in half or more. b) Possibility of an infinite loop if the array simply cannot contain unique slices. I will probably need to use some combination theory here, but I'm not sure how. source to share a = [1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7,8,9,10,11] You can check if slices are "unique": a.each_slice(2).all?{|x| x == x.uniq} So now you just shuffle until you get what you want: a.shuffle! until a.each_slice(2).all?{|x| x == x.uniq} The easiest way to avoid an infinite loop is timeout : require 'timeout' # raise an error if it takes more than 1 second timeout(1){ a.shuffle! until a.each_slice(3).all?{|x| x == x.uniq} } source to share Unique sample combinations If you are looking for something more idiomatic and if algorithm efficiency is not your main concern, you can try the following: a = [1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 6, 7, 8, 9, 10, 11] a.combination(2).reject { |pair| pair[0] == pair[1] }.sample(a.size / 2) The main disadvantage of this approach is speed when a is large, because the combination of Array # will generate all possible combinations before you start down the results with Array # reject and Array # sample . However, for modest sized arrays, this certainly seems to be fast enough. Evaluating Solution Performance Routine testing shows that this is more than fast enough for modest-sized arrays. Consider: require 'benchmark' a = [1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 6, 7, 8, 9, 10, 11] Benchmark.measure do a.combination(2).reject { |pair| pair[0] == pair[1] }.sample(a.size / 2) end.to_s #=> " 0.000000 0.000000 0.000000 ( 0.000052)\n" Even with 100,000 iterations, my system still only had 3,650299 seconds. This seems fast enough for practical use given your placed enclosure, but your mileage may vary. Allowing Arbitrary Subarray Sizing Comparing terms with a graph In the comments, the OP asked if this could be generalized to winnow sub-arrays with 2, 3, or 4 elements each. Yes, with a little refactoring, although performance degrades as the number of items in combination increases. Consider: array = [1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 6, 7, 8, 9, 10, 11] element_size = 4 array.combination(element_size). reject { |element| element.map { |member| element.count(member) > 1 }.any? }. sample(array.size / element_size) The desired element_size is used to determine the number of samples that are required dynamically. This has the side effect of discarding any partially filled arrays, eliminating the "saggy" elements you get with # each_slice . The workhorse here is still the rejection method, which now iterates over each member of each submatrix using # count and rejects the elements that have # any? terms that appear more than once in this submatrix. Even with better variable names, this is a little more complicated than when we have a fixed element size, but it is definitely more flexible. More readable (and slightly faster) comparison With a hat tip to @pguardiario (see this linked answer ), you can shorten this a little more and make it more readable by only selecting sub-arrays where all members of the array are # uniq . For example: array.combination(element_size). select { |subarray| subarray == subarray.uniq }. sample(array.size / element_size) source to share I have a solution that seems to work. The main idea is to distribute the elements with the maximum number of samples to the maximum possible number of fragments. Add a few shuffle to make them seem random. class Array def unique_slices_of(slice_length) buf = [] arr = [] hash = Hash.new 0 self.each {|i| hash[i] += 1} sorted = hash.sort_by {|k, v| v}.reverse # sorted[][0] holds the element and sorted[][1] holds the count return nil if sorted[0][1] > ((self.length * 1.0) / slice_length).ceil index = 0 until sorted.length.zero? # Add element to buf and decrement count # if count == 0, remove the entry from sorted buf << sorted[index][0] sorted[index][1] -= 1 if sorted[index][1] == 0 sorted.delete_at index break if sorted.length == 0 index -= 1 end index = (index + 1) % sorted.length if buf.length == slice_length arr << buf.shuffle buf.clear index = 0 end end arr << buf.shuffle if buf.length > 0 arr.shuffle end end Output: [2) [ ].unique_slices_of(3)].unique_slices_of( source to share A non-random way to do it The idea here is to put different values in bins. Then, if there are leftover bins: - Order bins by size, biggest baskets first - Make a snippet by taking a number for each of the first max_slice_size boxes - Remove empty cells Since each value within a slice is taken from a different bin, it is guaranteed that the slice will contain different values. Code: def slices_without_repeats(a, max_slice_size) slices = [] bins = a.group_by { |e| e }.values until bins.empty? bins = bins.sort_by(&:size).reverse slice_size = [max_slice_size, bins.size].min slice = slice_size.times.map do |i| bins[i].pop end slices << slice bins.reject!(&:empty?) if slice.size < max_slice_size && !bins.empty? raise ArgumentError, "An element repeats too much" end end slices end This algorithm does not use sheer randomness. It uses Ruby's quicksort, which is unstable and can potentially exploit randomness (as when choosing pivot points). Using: a = [1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7,8,9,10,11] p slices_without_repeats(a, 2) # [[3, 6], [3, 9], [3, 7], [3, 2], [3, 6], # [3, 10], [3, 11], [3, 4], [1, 8], [3, 5]] Determines when this is not possible: p slices_without_repeats(a, 3) # An element repeats too much (ArgumentError) And it handles the case where the last chunk is not full: p slices_without_repeats([1, 2, 3, 3, 4, 4, 4], 3) # [[4, 3, 2], [4, 3, 1], [4]] source to share
https://daily-blog.netlify.app/questions/2168660/index.html
CC-MAIN-2021-49
refinedweb
1,384
63.39