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
|
|---|---|---|---|---|---|
Introduction :
React native button component is used to show one button on both Android and iOS. If you have worked on Android and iOS projects before, you must be aware of the fact that button looks different on both platforms. React native provides a couple of customization props that we can use to customize a button.
In this tutorial, we will learn how to create one button and how to customize it using props. If you want more customization, you can use other view like components TouchableOpacity or TouchableNativeFeedback.
Button props :
onPress :
function type. It is called when the user taps on a button.
title :
Text to display in the button.
accessibilityLabel :
Used to show text for blindness accessibility features.
color :
This is used to add color to a button. On iOS, it will color the text of the button and on Android, it will color the background of the button.
disabled :
This is a boolean value. It is used to enable/disable a button.
testID :
Id used to locate a view.
hasTVPreferredFocus :
Used for apple TV preferred focus.
nextFocusDown :
For android, it designates the next view to receive focus when navigates down.
nextFocusForward :
For android, it designates the next view to receive focus when navigates forward.
nextFocusLeft, nextFocusRight, nextFocusUp :
For android, it designates the next view to receive focus when navigates left, right, up.
touchSoundDisabled :
Used for android to enable/disable system sound on touch.
Example :
Create one sample React native project and change your App.js file as below :
import React from 'react'; import { SafeAreaView, StatusBar, StyleSheet, View, Button, Alert, } from 'react-native'; const App = () => { return ( <> <StatusBar barStyle="dark-content" /> <SafeAreaView style={styles.container}> <View style={styles.parent}> <View style={styles.button}> <Button title="Click Me" onPress={() => Alert.alert('Hello')} /> </View> <View style={styles.button}> <Button title="Click Me" color="red" onPress={() => Alert.alert('Hello')} /> </View> <View style={styles.button}> <Button title="Click Me" disabled={true} onPress={() => Alert.alert('Hello')} /> </View> </View> </SafeAreaView> </> ); }; const styles = StyleSheet.create({ container: { flex: 1, }, parent: { flex: 1, justifyContent: 'center', }, button: { margin: 20, }, }); export default App;
Explanation :
- We have three buttons here.
- All buttons have the same title and onPress. It shows one Alert if you press.
- The second button has color red and the third button has disabled true. We can’t click on the third button.
If you run this program, it will produce the below output on Android :
And, similarly, on iOS, it looks as like below :
As you can see here, it looks different on iOS. But this is what is expected. iOS system buttons are different than Android. If you want more customization, you can use TouchableOpacity or TouchableNativeFeedback.
|
https://www.codevscolor.com/react-native-button
|
CC-MAIN-2021-04
|
refinedweb
| 441
| 60.51
|
Alle dine kammerater fra skoletiden er flyttet i hus. Hvad gør du?
- Grant Goodwin
- 1 years ago
- Views:
Transcription
1
2 Alle dine kammerater fra skoletiden er flyttet i hus. Hvad gør du? A. Materielle goder interesserer mig ikke. B. Guerilla gardening?! C. Ved ikke. Din cykel er blevet stjålet, og du har ingen forsikring. Hvad gør du? A. Jeg stjæler en cykel. B. Jeg aflyser alle aftaler uden for zone 2 i HTområdet. C. Jeg tager chancen med S-toget.
3 I The life of a young art worker - art writers, artists and curators - is conditioned by several factors, one of the main being working conditions. In the last few years both in Denmark and beyond, the working conditions of art workers have been changing dramatically, and the 2008 crisis has emphasized how precariously situated cultural producers are in these changes. Working on temporary projects, raising your own funding, depending on invitations from curators and editors, and relying on an unpredictable art market and your networking skills make the art world a profession that puts its workers under pressure. Art workers internationally are questioning the consequences of this pressure and starting initiatives to change both the attitude and the national rules and regulations. Nevertheless, in a Danish context, little is known about how the precarious situation affects art workers, let alone young art workers and the conditions under which they work and live. How do recently educated art workers establish themselves as newcomers on the art scene? How do they negotiate between creating a career, maintaining a practice, and living a daily life with increasingly high living expenses? How do they navigate in an art scene with unwritten rules, little circulation of money, and the silent acceptance that working for free is for your own good, i.e. looks good on your CV? Being an organization fighting for the rights of young art workers, UKK Young Art Workers feels the need to start a discussion about the working conditions of young art workers. We have the impression that our members have an urge to articulate their situations and share it with others. And yet, we hear among our members a difficulty in articulating precisely how the working conditions affect their lives. There is a struggle in finding a way to productively act upon a working situation where private economy and career success is dependent on intimate matters such as personality, network, family, and educational background and on public matters such as policies, working norms, and funding opportunities. This publication is an attempt to start articulating some of the patterns and common situations of young art workers that the current working conditions have made them accustomed to. When we started our research we did not find information and material to inform us, so we quickly realized that we had to create it ourselves. Making a survey, building a set of questions and asking our members to answer them, was one way of starting the articulation, beginning with forming a more clear image of who we represent: who are our members? Under what conditions do they live and work? What is their main source of income? How are their norms of working relations? What is considered work? How does it relate to economic value? Does work mean that one is paid to do what one does? With this publication and survey we wish to address three groups: Danish art institutions and politicians, members of UKK, and international collaborators of UKK. Primarily, we want to question the current situation and ask if it has to be the way it is now. Can we do it differently? Can we change the attitude and possibly also the norms? Can we, all together, help to make future generations more protected? And how should this protection look? Can we find the limit for what is just and what is not?
4 II Before commenting on some of the main findings of the survey we want to turn our attention to the Danish context. UKK was created in 2002 in response to changes in the political landscape that threatened to de-stabilize the possibilities and milieus for the experimental art scene. Since then, the situation and working conditions have changed dramatically and young art workers - young art or the new - are paradoxically probably wanted more than ever. The unsettling element is that they do not get paid for what they do, which we find is related to two elements more or less specific to the Danish context: the welfare benefit system and the creative industries. Moving forward in the aforementioned order, the welfare benefit system has made it increasingly difficult to accommodate people working on temporary contracts, making it time consuming and essential to go in and out of the system. Young art workers often depend on the benefit system in the first few years after graduating as it is common to get paid next to nothing when starting up as an artist. One is supposed to be happy to have work shown or published and that happiness counts as payment. Increasing bureaucratic requirements while being on benefits has also prevented many from focusing on their career and job possibilities though the opposite was intended. Subsidized labor and internships were introduced more and more in order to help the unemployed find a contract, but instead it created a cheap solution for art institutions to obtain more staff. Today many museums and exhibition spaces depend on those temporary positions, and the reality is that they do not have the economy to open new positions. The economic crisis also brings the difficult situation to the fore in that there are fewer jobs for art workers both in and outside of the art scene. The focus on creative industries and the finding that art and culture generates money has changed the understanding of art as something exceptional into a self-reproductive norm that necessarily has to be there in a society. We want art in our society, but we want it to mainly serve society. Focus on audience numbers in opposition to experiment has forced art institutions to create blockbuster exhibitions rather than nurturing the new. With the creative industries also comes a management culture that values administration and branding and less content. Increasingly, this is the case in universities as well, where the tendency to apply for private funding also is becoming the norm, however, research shows that this tendency does not create successful scholars; on the contrary, they get stuck doing management and not research. Parallel to understanding art and culture as an industry, the art scene in Denmark has also experienced a professionalization and an internationalization. This change has had positive consequences, but it has not caused a greater awareness of the working conditions of art workers. Generally artists do not get paid for exhibiting their work nor do art writers for writing articles. On the contrary, our members bring us cases where they have been asked to pay to exhibit or publish. The change into an industry has opened the eyes for people wanting to make a business out of art and here the
5 Din ny svigerfar spørger, hvad du arbejder med. Hvad gør du? A. Jeg bliver fornærmet. B. Jeg parafraserer Marx. C. Jeg siger, at jeg i øjeblikket er på dagpenge. D. Jeg viser ham min produktion på hjemmesiden. E. Jeg lader som om jeg ikke hører spørgsmålet. Din frisør hæver prisen. Hvad gør du? A. Jeg lader håret vokse, hvad ellers? B. Jeg flytter til Bramming (hvor er det?). C. Jeg klipper det selv. D. Ingenting. Dine produktionspenge rækker alligevel ikke til materialer. Hvad gør du? A. Jeg bruger af honoraret. B. Jeg ringer til banken. C. Jeg ringer til mor. D. Jeg sælger mine lp er.
6 young and inexperienced seem to be attacked. For many young art workers the route to a stable income is not clear, they are confused about unspoken rules and habits in the art scene and are in need of front figures and paths to choose from that do not include endless years of working for free. III The UKK survey 2012 was created between autumn 2011 and April 2012 and was open for replies from 1 May to 3 June Answers were anonymous and the survey consisted of five parts: I. General information II. Income 2011 III. Working conditions IV. Membership UKK V. Your opinion We received 64 completed surveys from our 350 members. This low response was partially due to the fact that during the spring of 2012, UKK had a problem with its list, which was only confirmed and fixed a week before the deadline for completing the survey. Consequently, about 150 of our members actually got the chance to participate. While the 64 who answered do reflect the members in terms of their combination, this fact does not, however, make their answers representational of all the members and the results should rather be seen as a qualitative study of 64 young Danish art workers. The survey was made on the internet-based portal surveymonkey.com, whose logic and possibilities ultimately shaped the questions we asked. We had to bend questions in order to get coherent answers that could fit into easily readable diagrams. With the help of a sociologist throughout the process we learned that the survey format has limitations in that it copes best with answers that can become a model and copes less well with open questions. Nevertheless, we chose to include a last section of open questions because we wanted to hear the opinions of the members in their own words instead of just reducing them to numbers or percentages. All this taken into account makes it clear that the survey results are to be understood as a starting point for further investigation and not as definitive answers. We will now highlight three relevant components of the results: Who the UKK members are, what their source of income is and how it is distributed, and what constitutes their working conditions in terms of working norms. UKK members: The UKK members who answered are mainly in their 30 s, 2/3 are women and the majority is artists. They live for the most part in Copenhagen and otherwise in the regions of Denmark and Scandinavia, as well as in Berlin. Out of 63 answers (one opted not to list income range), 16 have an income of up till DKK ( USD), 27 from till DKK ( USD), and 11 from
7 till ( USD). The most common media they work with are installation art, video, text and research. Mentioned reasons for being a member are: that they have been part of the organization since the beginning feeling sympathy for its cause, that it is the only organization that combines artists and academics, that it is the only organization focusing on the experimental part of the art scene, that it is a way to show and feel solidarity, and that they want to support the political work of UKK. The 9 most popular activities of UKK are: representing the interests of UKK in the Danish Arts Council, writing statements, lobbying, representing UKK in the Danish Council for Artists (Dansk Kunstnerråd), organizing talks and seminars, facilitating UKK s own working groups (Fagudvalg og Arbejdsgrupper), representing UKK in the committee that buys art for the municipality of Copenhagen, advocating experimental art, and writing letters to the editor. Even though a few of the 64 are older than 50 and earn more than DKK we can conclude that most are entering the art scene and are in the process of establishing themselves as art writers, artists, and curators. Income: One of the main sources of income is for 35 out of 63 a stable job contract (one opted not to list income range), which 24 found related to their art practice. Even though exhibiting should be the most obvious source of income for an artist, very little of the income comes from exhibition fees. Instead, it comes from activities around the artistic practice of art making itself such as teaching and talks. Very few live from selling art works and those who sell do it primarily through their own contacts and not through galleries. 41 out of 53 applied for the Danish Arts Council in 2011 (11 opted not to answer), mainly for funding for the production of art works (26 out of 41), exhibition of foreign art in Denmark (12 out of 41), exhibition of Danish art abroad (12 out of 41), and for webpage construction for artists (11 out of 41). Even though a large amount applied for the Danish Arts Council, 14 out of 34 answered that they received only 0-5% of their total income from it, 6 received 6-10% and 5 received 11-15%. The Danish Arts Council thus made up a relatively small amount of their income. Working norms and relations: Regarding habits of collaboration, exchange, working for free, and payment, we can see that different attitudes apply. Some find it OK to work for free at this state in their career if it makes them move forward. Their attitude is thus related to the development and to their position in their career. Some find it OK to work for free or to exchange favors among peers, but not when an institution is asking for their work. Some are willing to do a lot as long as it expands their network ( Network - friendship is my capital ), whereas others find it exploitative that institutions depend on internships, free work, and subsidized labor ( It hardly pays my bills ). Some ask for regulations so that it is clear what the free labor gives in return of skills and knowledge. A majority supports the use of contracts, especially when dealing with institutions, and finds them a proper way of verbalizing expectations. To sum up, we can see that young art workers combine their income from a patchwork of sources and that they work on temporary projects more or less related to their art practice with more or less payment because of the need of moving forward in their
8 Du er indkaldt til møde i a-kassen. Hvad gør du? A. Jeg lyver om, at jeg har søgt et job hos Dansk Supermarked. B. Jeg opgiver den kunstneriske løbebane midlertidigt. C. Jeg opgiver den kunstneriske løbebane permanent. D. Jeg fortæller, at jeg har fået et 10-timers undervisningsjob. Dit barn skal på lejrskole. Hvad gør du? A. Jeg køber et telt og nogle nye sko og en sovepose. B. Jeg efterlyser udstyr gennem venner på facebook. C. Jeg spørger, om det ikke er sjovere at blive hjemme hos mor og far i weekenden. Du fylder 40. Hvad gør du? A. Jeg booker et festlokale og hyrer en kok. B. Jeg inviterer de nærmeste til et sammenskudsgilde. C. Jeg rejser langt væk på et arbejdsophold. D. Jeg benægter fakta og fjerner fødselsdatoen fra facebook.
9 career and because they get something out of it professionally. One of the challenges in the future will therefore be to implement a higher degree of payment and use of contract in art institutional working relations. This request goes especially to one of the three groups we are addressing with this survey, Danish art institutions and politicians. We hear that there is a misuse of the free will among young art workers and that the limit of exploitation is blurred. It should be defined. What is just and not just in a project society of creative industries should be articulated and defined in order to avoid exploitation. To discuss and productively develop the art scene, the members of UKK can help heighten the awareness of the just when practically coping with the use of contracts, and the international collaborators of UKK can help bring in new and solid solutions for consideration in our situation. There are many more challenges to confront, which a further dialogue between all parts ideally will accommodate. IIII To better the working conditions for young art workers we need to work politically on a local level and to be informed and inspired by developments on an international level. Therefore, this folder will be launched in a seminar about working conditions on an international scale (in the moment of writing this seminar yet has to take place). The seminar will bring insights and questions from international contributors to broaden the perspective of our local, Danish situation. Participants are Arts and Labor (New York), Carrotworkers Collective (London), Consejo Nacional de la Cultura y las Artes (Chile) and openhagen (Copenhagen). In bringing together artistic and institutional perspectives from very different contexts we wish to develop the concerns we share despite geo-political differences. To equip our survey and this folder with other perspectives concerning the working conditions of art workers, writer Lene Asp (Copenhagen) contributes with a series of intimate, economic questions that young art workers are sometimes confronted with. They appear throughout in speech bubbles. Cultural researcher and activist Jaron Rowan (Barcelona) contributes with reflections on the creative industries and the emergence of the cultural entrepreneur. He unfolds how the personal and collective is brought into conflict when the discourse and enactment of the creative industries focus on subject-branding and individual talent and skill even though most creative practices are brought about through a collective endeavor. In the mid section you will find quotations from the open questions in the survey and a selection of diagrams picturing the results of the survey. We have left their meaning open for interpretation and further dialogue.
10 ACTIVITIES
11 CONTRACT
12 EDUCA
13 TION
14 INCOME
15 MEDIUM
16 because i see myself as a Danish artist, but also an international curator, i am considering to sign up for the BBK artist union in Germany also, because i want to be a member of KSK, social insurance for artists in Germany. I would still keep my membership of UKK, to support the organisation FOR THE POSITIVE KOMBINATION OF ACADEMIA AND ARTISTRY Solidarity Because ukk fights for non commercial artist survival. partly working as a handicap-assistant and teacher in fine arts I do small projects wich last from few days and up to few weeks at a time and are paid by the hour rengøring om natten og forskeligt teknikerjops alt på del/lånt tidits important cause they are much more concern about those who really struggle! art hosting i call it, it is very close to the work of a turist guide, but i insist it comes out of an artists sensibility and insight. but nothing near what they should have been paid. Mostly symbolic IT WAS AN EQUAL COLLABORATION WITH OTHER ARTISTS man hjælper hinanden my producer takes care of that or I do with smaller projects but museums are absolutely horible with contracts it takes forever to get one, if they ever give you one not in 2011 but I preffere to have a contract and have tried to get one for more projects in 2011 with no succes.- state institutions! All via A-kassen. Mostly pro forma. really hope there are other activities than this! most and only importance to me is improving legal rights, contracts, salarys for artists. i had to pick one of the above to move on in this survey... improving artists rights (f.ex. that the working scholarships from the state are being considered as work... and not a gift... if that not is work... then what is?... when you are an experimental /performance artist? if you want to change the world we have to do it together, and forget for moment our own practice. derudover er der mange ældre kunstnere, der sidder i råd og som er ude af trit med udviklingen af den nye og internationale kunst. det er vigtigt, at ukk repræsenterer det nye og det uafhængige/ikke-institutionelle (det er nemlig ikke repræsenteret særlig mange steder). og så er det et af de eneste steder, hvor kunstformidlere kan være med i en målrette politisk organisation, der kæmper for deres rettigheder - som er lige så dårlige, hvis ikke dårligere, som kunstneres, når man arbejder som uafhængig. I like the idea of being united :-) I am a new member. I am curious, an interested in an organization that works for art practitioners rights. Maybe im to old to support the work for better conditions for my colleague art workers - even when I m not working directly with art today. I work with design projects in a design agency Because your spokes person (when presenting UKK at the academy) said it would be IMBERRESING not to be : ) it is importent to be a member because contemporay art is importent
17 IT IS ALRIGHT WORKING FOR FREE IF YOU DO COLLABORATIONS WITH YOUR COLLEAGUES AND IT IS NON PROFIT PROJECTS. Internships can be useful in order to get to know a particular field or practice, and working for free on my own projects is also okay (but would prefer to be able to pay myself) Jeg er egentlig imod gratis arbejde, og vil helst have penge for det arbejde jeg laver. Men for det meste kan man ikke forvente at blive betalt for at være med på en udstilling. It s ok for nonprofit organisations othervise not I am very fortunate to receive lifelong grant from the danish state. Even though the sum is fairly small and regulated by other income, l am gratefull and don t mind working for free. Without such grant, working for no fee is abuse of the artist! For a free art we are working for free I don t mind working for free if I choose to - I recent the fact that many institutions expect artists to work for free! Det er også en slags gratis arbejde kun at få kr for en stor udstilling på xxx! Det burde være kr. Basically I m against it, but if I gain something in return (i.e. exhibitions, network,, fun and experience) I am ready to accept it at this stage in my career. Network - frindship is my capital As a curator, I always pay the artists before I pay myself, which usually results in me not getting payed. DON T LIKE NOT BEING ABLE TO PAY FOR OTHER PEOPLE S CONTRIBUTIONS. ALWAYS GO OUT OF MY WAY TO THANK PEOPLE PUBLICLY AND AS OFTEN AS POSSIBLE Honorar og ordnede forhold giver større seriøsitet og et godt udgangspunkt for et samarbejde. I have never paid anyone for their work/participation, but I ve always tried to give them something in return - repaying the favour by working on their project for instance. I m proud when I generate money for my colegues Only oral agreements Hos kunstnere: Det er generelt godt, men det kunne være fint med nogle kodekser for hvad de skal have ud af det, så vi kunstnere sørger for at give noget igen. Hos institutioner er det dybt problematisk at de er afhængige af at ansætte pratikanter og løntilskudsfolk. Vi har folk i løntilskud, og ganske som md praktikanter er det en god idé, hvis og så fremt institutionen er sig sit sociale ansvar bevidst, og personen i løntilskud opnår nye kompetencer der kan styrke ham/hende i det videre arbejdsliv. Jeg synes ikke der er optimalt at være på dagpenge og ville gerne kunne tjene flere penge på det kunstarbejde jeg laver, men har lidt svært ved at finde ud af hvordan det kan lade sig gøre, som min situation er lige nu. It s getting better except from at galleries and museums It is higly critical in this very visual culture that art is not a natural subject in schools, newspapers, tv etc! Jeg klarer mig fint nu, efter 10 års kamp. Men det er ofte at kunstinstitutioner betaler dårligst. Jeg tjener mest ved at søge private og ikke specifikke kunst fonde. YOU GUYS ROCK! Why do I have to make thise answers in English??? We have to stand of for our individual rights collectively!...
18 Du har begyndende paradentose. Hvad gør du? A. Jeg gifter mig med en tandlæge. B. Ingenting. C. Jeg søger et arbejdslegat. D. Jeg børster tænder flere gange om dagen. Du har skimmelsvamp i lejligheden. Hvad gør du? A. Jeg lufter ud hele tiden. B. Kan den mon tilberedes? C. Jeg maler lejligheden med skibsmaling, som jeg har fået gratis. Du skal på barsel men har ikke dagpengeret. Hvad gør du? A. Jeg kontakter alle de forlag, jeg kan komme i tanke om, for at finde ud af, om de ikke mangler en børnebogsillustrator. B. Jeg får en abort. C. Jeg går i panik og tegner små kruseduller på post-its. D. Jeg flytter ind på mit gamle værelse hos mine forældre. Du skal spare op til pension. Hvad gør du? A. Jeg håber på det livsvarige. B. Jeg forestiller mig, at jeg kan fortsætte som yogalærer som 70-årig. C. Jeg går ikke på pension! D. Jeg sætter 7% af mine indtægter ind på en opsparing. E. Ved ikke. Du skal til møde i banken, og din rådgiver har bedt dig om en kopi af årsopgørelsen. Hvad gør du? A. Jeg pynter på den i Photoshop. B. Jeg laver nogle flere lønsedler til mig selv. C. Græder. D. Jeg siger at alle mine aktiver pt er investeret i kunst, hvorfor skulle jeg ellers bede om et lån! E. Jeg sender dokumentet og krydser fingre.
19 I Would Rather Not: or the Need to Challenge Cultural Entrepreneurship In the following article I intend to make visible a conflict that is currently affecting the cultural field, in which self-organized forms of work, informal networks and individual artists have been prompted to transform themselves into small enterprises following certain schemes and models that have little or nothing to do with the ways in which cultural production usually operates. I will show how this encouragement of cultural entrepreneurship leads to at least three serious problems that we must address: a) it individualizes collective creativity, b) it rests on a basis of precarious and non-paid work and, c) it constitutes a serious menace to what I will define as the cultural commons. In the following pages I will discuss some of the issues and their repercussions for contemporary cultural work. The first schemes and programmes aimed at promoting cultural entrepreneurship coincided with the growth of neo-liberalism in the Western world. This ideology, that challenges the role of the State and its ability to guarantee the fundamental right of access to culture, introduced the idea that the production and distribution of culture should take place following market rules. In this sense a number of discourses were put into place that started describing culture as an economic asset or resource and no longer as a right (Yúdice 2004). Because of this, since the early eighties a series of subjects and practices that had functioned under a different logic, based more on collective work and networks of trust and friendship, were suddenly encouraged to become enterprises. To capture the value generated by these social pools, the government established copyright as the most effective tool in order to transform knowledge into economic returns. These were the first steps and measures that lead to the creation of the so called Creative Industries, defined by the Department for Culture, Media and Sport (DCMS) of the United Kingdom government as: those industries which have their origin in individual creativity, skill and talent which have a potential for job and wealth creation through the generation and exploitation of intellectual property. 1 If we look at this definition two relevant issues arise. First, we notice how the notion of individual creativity is introduced through a focus on individual skill and talent, which excludes forms of collective- or commons based creativity. Secondly, intellectual property (a method of privatization or enclosure of knowledge) is imposed as the way to extract value from creativity. These two points set out a very specific agenda and define the economic models that constitute the creative industries. In this sense, this prescriptive definition helps to shape and make understood most of the schemes aimed at promoting creative entrepreneurship and all the models imposed on budding enterprises by public organizations and schemes. One can argue, following the ideas put forward by some post-autonomist authors (for instance Maurizio Lazzarato, Anthony Negri and Poul Virno), that the whole project of the creative industries is devised to define, enclose and extract the wealth generated by social production, that is, forms of production that exceed the office, the factory or the lab. Creativity has always been a collective endeavor: music seeks inspiration from other music, novels feed from other novels and art discovers itself through art. Sampling, sharing and paraphrasing are essential elements to understand how creativity takes place. Cities, networks, and communities are all places where ideas are spread, transformed and re-mixed. In this sense, the creative
20 industries were born to pool from these common flows of creativity. They promote the capture of these ideas that later become branded and sold as pieces of individual creativity. The promotion of entrepreneurship seeks to establish these processes of capture as legitimate ways of extracting value from these social pools. Artists and creative subjects must function as enterprises that follow market rules. However, we must remember that the idea of society as an entity composed of a myriad of enterprises and self-enterprises that interact together following market laws is one of the greatest achievements of neoliberal ideology. In his lectures on the Birth of Biopolitics at the Collège de France, French philosopher Michel Foucault engaged with the history of liberalism in order to identify the main discourses and events that gave birth to neo-liberalism as we now know it. Among them we see the progressive growth of the so-called homo economicus, the subject that acts as an enterprise following market dynamics, maximizing his individual benefits and seeking in every moment to transform his assets (social capital, knowledge, skills) into wealth. When this same logic is transferred onto the cultural sphere we see how agents start to think of themselves as enterprises, which implies the need to privatize oneself, to turn one s personal experiences into a set of assets, and finally to exploit the ideas and trends that have been produced collectively and privatize them. This model not only provides a route for artists, designers, developers or film-makers to follow, but also produces individualized subjectivities in an arena traditionally shaped by collective work. It is in this context in which we understand the emergence of brand-subjects, that is, artists and cultural producers who work constantly and invest their efforts to enhance their brand value. These subjects inhabit social networks (virtual and physical) where they must constantly be visible; attention becomes opportunity in this context. The brand cannot rest; it must be able to perform and mediate in every single moment. Work and leisure become inextricably linked, the brand-subject must attend openings, twitter its success and be able to capture its peers attention. Following Paolo Virno s (2003) insights, the creative subject becomes an opportunist waiting to promote him- or herself at any moment. The discourses that promote entrepreneurship are based on the assumption that this entrepreneurial model is the best way to sustain cultural production economically. A number of figures and documents have been produced in order to show the economic possibilities of the creative industries, but these figures have been seriously challenged. Kate Oakley, in her study Not so cool Britannia: the role of the creative industries in economic development (2004), has clearly shown how most of these estimates have never been confirmed, and in many cases there is evidence that proves them wrong. In this sense, another interesting document to look into was put forward in 2007 by Alan Freeman of the Greater London Authority. Freeman questions some of the figures generated by the DCMS by showing how creative accounting works, and thereby how the figures can be easily challenged because growth expectations become mixed with actual figures. Also, in 2011 The Work Foundation (a British not-for-profit organization, which gives advice about the future of work) published a paper showing how the creative industries have been seriously affected by the current economic downturn, proving that this sector is not as resilient as first thought. 2 These reports help us see that not everything is as glossy as it seems in the
Sustainable Models for Shared Culture Case Studies and Policy Issues
Sustainable Models for Shared Culture Case Studies and Policy Issues CONSERVAS/Xnet, Barcelona Stichting Kennisland, Amsterdam World-Information Institute, Vienna National Hellenic Research Foundation/
ARTISTIC INTERVENTIONS IN ORGANISATIONS: FINDING EVIDENCE OF VALUES ADDED
ARTISTIC INTERVENTIONS IN ORGANISATIONS: FINDING EVIDENCE OF VALUES ADDED Ariane Berthoin Antal and Anke Strauß Citation: Berthoin Antal, Ariane & Strauß, Anke (2013). Artistic interventions in organisations:,
What skills and knowledge should a PhD have? Changing preconditions for PhD education and post doc work
11 What skills and knowledge should a PhD have? Changing preconditions for PhD education and post doc work Göran Melin* 1 and Kerstin Janson 2 *Swedish Institute for Studies in Education and
Human resource management
Human resource management J. Coyle-Shapiro, K. Hoque, I. Kessler, A. Pepper, R. Richardson and L. Walker MN3075 2013 Undergraduate study in Economics, Management, Finance and the Social Sciences This is
Here is Your Money: Using the Standard Cost Model to Measure Regulatory Compliance Costs in Developing Countries
Here is Your Money: Using the Standard Cost Model to Measure Regulatory Compliance Costs in Developing Countries Investment Climate Advisory Services I World Bank Group Here Is Your Money! Using the Standard
CAN SOCIAL FINANCE MEET SOCIAL NEED?
Report June 2013 CAN SOCIAL FINANCE MEET SOCIAL NEED? Robbie Davison Director, Can Cook CIC Helen Heap Social Investment Manager, Tomorrow s People 1 Foreword This paper is a follow-up to Does Social Finance:
A Foot in Both Worlds
PROGRAM FOR ENVIRONMENTAL AND REGIONAL EQUIT Y PERE December 2013 A Foot in Both Worlds Institutionalizing Progressive Community-Engaged Research Centers within Universities Jeffrey O. Sacha, Jared P.
Summary. Remotivation. Closure
Steve Davis: Tips for Better Teaching and Learning 1. Faculty Development Tidbit: Presentation Principles they never change! Tell them what you re going to tell them, tell them, tell them what you told
Turn Your Organisation Into A Volunteer Magnet
Turn Your Organisation Into A Volunteer Magnet Second edition Edited by Andy Fryar, Rob Jackson & Fraser Dyer Copyright 2007 This book has been produced as a free resource by, and for, members of the international
Business Succession Planning Guide
Business Succession Planning Guide NOTE: This book provides only a basic overview on the subject of succession planning and the publisher makes no warranties as to the accuracy of information as it relates
Education for Global Responsibility Finnish Perspectives
Opetusministeriö Ministry of Education Education for Global Responsibility Finnish Perspectives Publications of the Ministry of Education 2007:31 Edited by Taina Kaivola Monica MelénPaaso Education for
Do you really expect to get
Do you really expect to get paid? An economic study of professional artists in Australia David Throsby Anita Zednik Do you really expect to get paid? An economic study of professional artists in Austral
|
http://docplayer.net/1649413-Alle-dine-kammerater-fra-skoletiden-er-flyttet-i-hus-hvad-gor-du.html
|
CC-MAIN-2016-44
|
refinedweb
| 5,873
| 59.03
|
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?; this thesis has not been submitted previously in full or partial fulfilment of the requirements for an equivalent or higher qualification at any other recognised educational institution.
________________________________ SIGNATURE
January 2003 DATE
i
Acknowledgements
Acknowledgements
This thesis would not have been possible without the support, advice and encouragement of many individuals. I would like to express my sincere thanks to the following people for their contributions: To Mary West, my supervisor, for her guidance in the field of study To Dr Michael Marais for his constructive comments and valuable recommendations To Prof Chris Jeffery for his sound advice and words of encouragement To my mother who typed the bulk of this thesis and who was always willing to help in any way possible To Franz for his continued encouragement and support
ii
Emma. her work retains an undying appeal. Northanger Abbey. it is possible to explore the legacy that modern women have inherited. During the last decade the English-speaking world has experienced an Austen renaissance as it has been treated to a number of film and television adaptations of her work. Women’s experiences in Austen’s time are compared to women’s experiences in society today in order to illustrate. Literary critics such as André Brink (1998). In addition. however. Mansfield Park and Sense and Sensibility. Nancy Armstrong writes in Desire and Domestic Fiction (1987) that Austen’s objective is not a critique of the iii .Pride and Prejudice.Abstract Abstract Although many might consider Jane Austen to be outdated and clichéd. the tremendous progress the feminist movement has made. and Gilbert and Gubar (1979) believe Austen to create feminist awareness in her novels. Mansfield Park. This thesis follows a gynocritical approach and applies a feminist point of view when reading and discussing Austen. Austen’s novels . The reasons for viewers and readers enjoying and identifying with Austen’s fiction are numerous. Readers of varying persuasions have different agendas and hence different views and interpretations of Austen. by examining what Austen reveals about the material reality of women in her time. in some way. who do not view Austen as necessarily feminist in her writing. Sense and Sensibility. Film critics such as Bill De Lapp (1996) and Sherry Dean (1996) have commented on the phenomenal response these productions received and have been amazed by Austen’s ability to compete with current movie scripts. and Persuasion – are re-read and reevaluated from a feminist perspective in order to call attention to Austen’s awareness of women’s second-class position in her society. including Pride and Prejudice. There are critics. Emma. Claudia Johnson (1988).
My own reading of Austen takes into consideration her social milieu and patriarchal inheritance. they failed to produce great women artists like Chaucer or Cézanne. it illustrates some of the realities and pitfalls of marriage. and women’s identity. leaving women powerless and without any means of self-protection in a male-dominated world. In Culture and Imperialism (1993) Edward Said implicates Austen in the rationale for imperial expansion. Austen’s fiction draws our attention to issues such as women’s (lack of) education. Austen’s fiction also exposes the economic and social system (of which education constitutes a major part) for enforcing marriage and for enfeebling women. Her fiction reveals the effects of educating women for a life of domesticity. While Austen only subtly refers to iv . her critique needs to be covert. and illustrates that such an education is biased. believe Austen’s fiction primarily to be about marriage since all her novels end with matrimony. In addition. It argues that Austen writes within the framework of patriarchy (for example by marrying off her heroines) possibly because she is aware that in order to survive as a woman (writer) in a male-favouring world and in a publishing world dominated by men. such as Patricia Beer (1974). If read from a feminist perspective. Feminist writers such as Flis Henwood (2000) show that contemporary women believe certain areas of expertise belong to men exclusively. while Barbara Seeber argues in “The Schooling of Marianne Dashwood” (1999) that Austen’s texts should be understood as dialogic. marriage as a patriarchal institution of entrapment. Others such as Linda Nochlin (1994) reveal that because women did not have access to higher education for so many years. the effects of not being given access to knowledge. Others.Abstract old order but rather a redefinition of wealth and status. they suffer the consequences of a legacy which denied them access to a proper education. Although contemporary women in the Western world mostly enjoy equal education opportunities to men.
v . In addition. are not merely novels of powerlessness but of empowerment. one could argue that she contributes. we are made aware of the social construction of power. contemporary feminist scholars such as Germaine Greer (1999) and Arnot. bell hooks comments in Feminist Theory: From Margin to Center (2000) on the importance of revealing unfair power relations in order to eliminate oppression of any kind. to the transformation of existing power relations and to the eradication of women’s servile position in society. Deliyanni. and this makes us aware of women’s lack of power in her time. From her fiction we can infer that male power is enshrined in the very structure of society.Abstract women’s disempowerment within marriage. Because she suggests ways in which women might empower themselves. albeit within patriarchal parameters. The issue of marriage as a patriarchal institution has been thought important and has been addressed by feminists because it contributes to women’s powerlessness. in a small way. By creating rounded women characters and by giving them the power to judge. Austen does not necessarily express the wish to eradicate forms of power or oppression in her novels. to refuse and to write. if we read her work from a feminist point of view. Yet. Austen’s novels. her novels seem to question women’s inherited identity and to suggest that qualities such as emotionality and mothering are not natural aspects of being a woman. Araújo. and Ivinson (2000) explicitly warn women that marriage is a patriarchal institution of entrapment and that it often leaves women feeling unfulfilled. Austen challenges the stereotyped view of woman as either overpowering monster or weak and fragile angel. Feminist scholars today find it imperative to expose all forms of power in order to eradicate women’s subordination. however.
en Persuasion. Gedurende die laaste dekade het die Engelssprekende wêreld met die verfilming van onder andere Pride and Prejudice. Edward Said impliseer in vi . Verskillende tipe lesers het verskillende agendas en derhalwe uiteenlopende interpretasies van Austen. en Gilbert en Gubar (1979) glo dat Austen ‘n feministiese bewussyn in haar romans laat blyk. In hierdie verhandeling word Austen se werke vanuit ‘n feministiese oogpunt beskou. soos André Brink (1998). Rolprent resensente soos Bill De Lapp (1996) en Sherry Dean (1996) het al kommentaar gelewer oor die geweldige reaksie wat hierdie produksies gekry het. Austen se grootste werke. en het hul verbasing uitgespreek oor Austen se vaardigheid om met huidige draaiboeke te kompeteer. insig kry in die tipe erfenis waarmee kontemporêre vroue gelaat is. en nie om die ou orde te kritiseer nie. Emma. Northanger Abbey. Daarbenewens kan ons. word herlees en her geëvalueer in ‘n poging om Austen se bewussyn van vroue se tweede-klas posisie in die samelewing uit te lig. Mansfield Park en Sense and Sensibility ‘n Austen-renaissance beleef. Emma. naamlik Pride and Prejudice. Daar is verskeie redes dat Austen se fiksie aanklank by kykers en lesers vind. Mansfield Park. Literêre kritici. het haar werk nog steeds geweldige trefkrag vir die een-en-twintigste eeu en sy mense. deur te kyk na wat Austen aan die lig bring oor agtiende-eeuse vroue en hulle probleme. Daar is egter diegene wat nie daarvan oortuig is dat Austen noodwendig feministies is nie. Vroue se ondervindinge in Austen se tyd word vergelyk met hoe vroue in vandag se tyd die samelewing ondervind om aan te dui watter vooruitgang die feministiese beweging gemaak het. Sense and Sensibility. Nancy Armstrong skryf in Desire and Domestic Fiction (1987) dat dit Austen se doel is om rykdom en status te her definieer.Uittreksel Opsomming Alhoewel Jane Austen deur sommige as konserwatief en vervelig beskou mag word. Claudia Johnson (1988).
Wanneer ons kyk na wat haar fiksie te sê het oor die gevolge van ‘n opvoeding wat vrouens op ‘n lewe van huishouding voorberei. is van die mening dat. glo dat Austen se fiksie primêr oor troues handel. Huidige feministiese skrywers soos Flis Henwood (2000) wys dat vroue glo dat sekere studierigtings eksklusief aan die man behoort. omdat vroue vir baie jare toegang tot ‘n hoër opvoeding geweier is. Ander. die huwelik as ‘n patriargale institusie van gevangenskap. Indien ons Austen vanuit ‘n feministiese oogpunt lees. en Barbara Seeber is van die mening in The Schooling of Marianne Dashwood (1999) dat Austen se boeke as dialoë verstaan moet word. Alhoewel die moderne vrou in die Westerse wêreld meestal gelyke regte het tot ‘n opvoeding as die man. soos Linda Nochlin (1994). soos Patricia Beer (1974). en vroue se identiteit. Ander. en stel voor dat Austen binne die patriargale raamwerk skryf (soos wanneer sy haar heldinne laat trou) moontlik omdat sy besef wat sy moet doen om te oorleef in ‘n samelewing en in ‘n publisiteitswêreld wat deur mans bestem word. die gevolge daarvan om van kennis weerhou te word. dui haar romans op die gebrek aan opvoeding vir vroue. My evaluasie van Austen se oeuvre hou haar sosiale milieu asook haar patriargale erfenis in rekening.Uittreksel Culture and Imperialism (1993) dat Austen die prinsiepe van imperialisme deur haar werke ondersteun. Austen se fiksie ontbloot ook die ekonomiese en sosiale stelsel (waarvan opvoeding ‘n wesentlike deel opmaak) omdat dit ‘n getroude lewe op vrouens afdwing en omdat dit vii . hulle daarin misluk het om vroulike kunstenaars en skrywers soos Chaucer of Cézanne te produseer. blyk dit dat so ‘n opvoeding partydig is en dat dit vrouens magteloos en sonder enige middel van selfverdediging laat in ‘n wêreld wat deur mans bestem word. ly sy onder die gevolge van ‘n erfenis wat haar van ‘n behoorlike opvoeding weerhou het. siende dat al haar boeke eindig met die vereniging van die hoofkarakters in die huwelik.
as ons haar werke vanuit ‘n feministiese oogpunt beskou. Die kwessie van die huwelik as patriargale institusie word as belangrik geag en word aangespreek. Deur geronde vroue karakters daar te stel. Nogtans. die mag om te weier en die mag om te skryf te gee. Boonop skyn haar werke vroue se identiteit te bevraagteken en stel dit voor dat eienskappe soos emosionaliteit en moederlikheid nie ‘n natuurlike aspek van vrou-wees is nie. Waar Austen slegs subtiel na vroue se magteloosheid verwys. waarsku huidige feministe soos Germaine Greer (1999) en Arnot. en deur aan hulle die mag van onderskeiding. Ons kan van haar romans aflei dat die manlike mag in die struktuur van die samelewing verweef is. bell hooks verwys in Feminist Theory: From Margin to Center (2000) na die belangrikheid daarvan om onregverdige magsverhoudinge te openbaar sodat onderdrukking van enige aard geëlimineer kan word. tot ‘n klein mate. Austen se romans gaan egter nie slegs oor magteloosheid nie. Deliyanni. en Ivinson (2000) vroue eksplisiet dat die huwelik ‘n patriargale institusie van gevangenskap is en dat dit dikwels vrouens onvervuld laat voel. maar ook oor bemagtiging. Daarby illustreer dit die realiteite en valstrikke van die huwelik. Araújo. al is dit binne-in die patriargale raamwerk. maak hulle ons bewus van die sosiale konstruksie van mag. aangesien dit bydrae tot vroue se magteloosheid. Feministe vandag vind dit van uiterste belang om alle vorme van mag bloot te lê sodat die onderdanige rol van vroue beëindig kan word.Uittreksel daardeur vrouens verswak. en dit maak ons bewus van vroue se tekort aan mag teen die einde van die agtiende eeu. om by te dra tot die transformasie van bestaande magsverhoudinge en tot die eliminering van vroue se onderdanige posisie in viii . daag sy die stereotipe van vrou as dominerende monster of van vrou as magtelose engel uit. slaag sy daarin. Omdat sy maniere voorstel waarop vroue hulle-self kan bemagtig. Austen skyn nie te wens dat alle vorme van mag en onderdrukking geëlimineer word nie.
ix .Uittreksel die samelewing.
2 Laying Down the Harp 3.1 Catching Men 2.Index Index Introduction Chapter One – Women and Education Introduction 1. Marriage as Entrapment 1. Investigating Knowledge 4. Unequal Education Opportunities 6.3 Approval and Acknowledgement 1. Self-Deprecation 5. Privileged Education for Boys 5.1 Economic Security 1. Silly Women and Men Chapter Three – Women and Marriage Introduction 1. Empty Conversation. Finding a New Discourse 3. Trite Remarks and the Conduct Books 2. Consequences of a Poor Education Chapter Two – Women and Knowledge Introduction 1. Cultivating Accomplished Ladies 2.4 Surviving Patriarchy 1 17 17 20 25 27 29 32 35 38 39 46 46 50 55 58 60 65 71 76 76 78 83 88 94 96 x . Self-knowledge 4.2 Escaping Home 1. Sweet Orderings of Domesticity 2. Literariness 6.
3 The Power to Write 4.2 The Power to Refuse 4.1 Marrying for Money 2.1 The Power to Judge 4. Fairytale Endings Chapter Four – Women and Identity Introduction 1.Index 2.2 Unfulfilled Wives 2. Rationality and Emotion 3. Dissident Views on Marriage 2.1 Male Texts 1. Women Empowered 4.3 Husband-Hunting 3.2 Austen’s Texts 2.4 Domestic Power(lessness) Conclusion Bibliography 100 100 105 111 113 119 119 123 123 126 131 135 139 141 144 147 148 153 163 xi . Women’s Representation 1. Natural Mothers 4.
(Edward Said. but they keep disappearing. They do re-emerge. but that she hides this consciousness behind a decorous façade. Yet others believe Austen to address women’s issues. omissions. sometimes strong ones. stories that do not make sense. Amongst them there are those who argue that Austen does not only display a feminist awareness. I Married Him) …Austen makes us aware of gaps. (Barbara Seeber. in a different guise: as the ambiguities. discrepancies and illogic of a creative artist… (Patricia Beer. stories that sense cannot tell. The Schooling of Marianne Dashwood) There is a paradox here in reading Jane Austen which I have been impressed by but can in no way resolve. and contradictions. Reader. Culture and Imperialism) I had always considered Jane Austen to be an unequivocal advocate for women’s emancipation until statements such as the above decidedly confused me when I started doing my reading for this dissertation. I found that the ideology of Austen’s work is not clear-cut and that it has been interpreted in different ways throughout the years. however. thus giving us a glimpse of the polyphonic world that the dominant ideology…needs to repress. While some scholars maintain that Austen’s novels are mostly concerned with matters of courtship and marriage. By incorporating contradictions. that [Jane Austen] is dissatisfied with the traditional status of woman. 1 . Austen incorporates contrary discourses.Introduction Introduction There are hints. others have implicated her work in the rationale for imperial expansion.
While Claudia Johnson has mentioned that women writers in the late eighteenth/early nineteenth century often felt “too marginal as women in their society [so that they had to] smuggle in their social criticism” (1988:xxiii). their work remains seminal since it offers one of the first feminist readings of Austen’s novels. Austen may have found it necessary in her time to hide her dissatisfaction with women’s status in a man-made and male-favouring world. Johnson and Brink call attention to the fact that the society Austen was living in was one which favoured men. Although Sandra Gilbert and Susan Gubar’s The Madwoman in the Attic (1979) may be considered outdated. then surely this does not mean that she accepts it. so much so that it may seem that she accepts quite uncritically the social prescriptions of her time” (43. Rosalind Miles seems to agree when she writes in The Female Form: Women Writers and the Conquest of the Novel (1987) that “[m]arriage in all its variations is the cornerstone of [Austen’s] moral and imaginative structures. Those who support the theory of Austen’s concealment posit that. If we entertain the notion that Austen hides her defiance behind the façade of seemingly endorsing the status quo. Austen manages to subvert existing power relations in society without arousing the suspicion of a literary world dominated by male publishers. Gilbert and Gubar argue that Austen hides her feminist consciousness behind the façade of submitting to patriarchy. Claudia Johnson has called it “double plotting” (xxiv) and “strategies of subversion and indirection” (19) in Jane Austen: Women Politics and the Novel (1988).Introduction Indeed. While André Brink has referred to this as Austen’s “double play” (115) in The Novel: Language and Narrative from Cervantes to Calvino (1998). André Brink has commented on 2 . my emphasis). They suggest that she only adds the traditional elements of marriage and happy endings to her novels in order to hide her dissent (169). by appearing to submit to patriarchy.
Introduction
Austen’s “acute awareness of her position as a woman trying to demarcate her own space in a man’s world” (1998:112). Nancy Armstrong notes in Desire and Domestic Fiction (1987) that Austen was fully aware of the fact that patriarchal society required women writers to produce “a non-aristocratic kind of writing that was both polite and particularly suitable for a female readership” (97). Because Austen knew that intellectual women in her time were treated with suspicion and that women novelists were ostracized from the community if they did not admit their writing to be a mere diversion (Gilbert and Gubar, 1979:10), it is possible that she made a deliberate effort to conceal her dissent. In A Literature of Their Own: British Women Novelists from Brontë to Lessing (1977) Elaine Showalter comments on the necessity for late eighteenth/early nineteenth-century women writers to hide their intellectualism (21). They published anonymously, wrote under a male pseudonym or were self-deprecating, in the hope that “[their] female audience would both read the messages between [their] lines and refrain from betraying what they deciphered” (16). Owing to the “far-reaching and vigorous moral censorship upon [the middle class’s] chief entertainment, fiction” (Watt, 1971:465), it could very well be that Austen realised she too had to write within the patriarchal framework of marriage and women’s subordination in general, or else run the risk of not being published. In order, then, to have her work published, as well as protect herself from the kind of ostracism that Gilbert and Gubar suggest would be her fate, Austen may have concealed her feminist awareness. As modern readers we should keep in mind, as Andrea Nye has pointed out in Feminist Theories and the Philosophies of Man (1988), that “the situations in which women struggle have a history, a familial history both social and individual, and [that] their reactions are shaped in that history” (115). Austen was struggling in the context of a patriarchal world
3
Introduction
which, according to Jackie Stacey’s definition in “Untangling Feminist Theory” (1993), refers to “the systematic organisation of male supremacy and female subordination” (53). Claudia Johnson mentions that the society Austen was living in was one which dictated “fundamentally different codes of morality for men and women” (1988:14). André Brink writes that underlying a novel such as Emma is “the crude and inescapable fact that the social code by which all the characters exist and survive is different for men and women” (1998:123). The social code for women, as Judith Lowder Newton shows in “Women Power and Subversion” (1981), included submitting to patriarchal institutions such as marriage in order to survive financially (119-129). Jane Austen was not exempt from the code by which her women characters had to exist and survive. Another possibility then, and one which I would favour, is not so much that Austen deliberately hides her rebellion behind the façade of submission but that she submits to patriarchy because she has no other choice if she wants to survive in a male-dominated society. There are quite a number of critics who disagree with the view that Austen is necessarily feminist in her writing. Nancy Armstrong clearly states that she does “not subscribe to the view of Austen as a proto-feminist rebel who thrashed against the constraints that bound an author of her sex unwillingly to convention” (1987:156). She believes “Austen’s objective is not to dispute the hierarchical principle underlying the old society, but to redefine wealth and status as so many signs that must then be read and evaluated in terms of the more fundamental currency of language” (138). Armstrong seems to suggest that Austen could not escape the ideology she was born into when she comments that Jane Austen “appeared more than willing to leave the rest of the world alone and deal only with matters of courtship and marriage”
4
Introduction
(135). In addition, she maintains that Austen’s work shows how social status has the power to define individuals and thereby disrupt the stability of the community (155). In Culture and Imperialism (1993:58-59) Edward Said argues that it is Austen’s interest in imperial England which comes to the fore in Mansfield Park. According to Said, Austen in this novel shows how colonies are important “to the process of maintaining a particular style of life in England” (66). Though he focuses on Mansfield Park, he extends his findings to Austen’s work as a whole by suggesting that Mansfield Park “defines the moral and social values informing her other novels” (62). Said also mentions that authors are shaped by the history of their societies and by their social experiences (xxii). It is possible that Jane Austen was unaware of the ideology of her society and that she therefore remained a product of her times. This could possibly explain why her work, according to Said, consolidates the
authority of the status quo, including the hierarchy of the patriarchal family, while only rarely challenging institutions such as private property and marriage (77-79). Published in the mid-seventies, Patricia Beer’s Reader I Married Him: A Study of the Women Characters of Jane Austen, Charlotte Brontë, Elizabeth Gaskell and George Elliot (1974) may have been superseded by the above readings by Armstrong and Said. Her work, however, provides us with yet another way in which Austen can be read. The seventies are of significance since Austen’s work had been regarded up to this time as that of an essentially conservative writer, as Isobel Armstrong shows in Jane Austen: Mansfield Park (1988:95). Patricia Beer does not regard Austen as being radically or even liberally feminist in her approach. She feels that Austen “not only accepted the limitations of women’s scope but seems in her own life to have found happiness within them” (1974:25). Though Beer
mentions an occasionally “suspicious piece of bravado about husband-hunting” (2) in
5
she feels. This. with some exceptions. including Jane Austen as satirical writer and as feminist writer (101-103). she believes her interpretation of this specific novel “sets a precedent for dialogism in Austen” (223). Armstrong discusses the essentially conservative interpretation of Austen which was assumed. 6 . and suggests that. and dedicates a section of her book to informing the reader “about the ways in which Jane Austen has been discussed and to strike a cautionary note” (95). up to the 1970s. In addition. In “I See Every Thing As You Desire Me To Do”: The Scolding and Schooling of Marianne Dashwood (1999) Barbara Seeber makes a case for a dialogic reading of Austen’s work. is unfortunate since it “obscures the text’s dialogism” (224) and restricts it to a single truth. she sees Austen’s ‘ambivalence’ as the result of a conflict between Austen’s ideals for women and her acceptance of a male-dominated society (82). Although she focuses on Sense and Sensibility in order to expose what she calls “Austen’s polyphonic vision” (225). “it is possible to mediate between…opposing interpretations” (103). Isobel Armstrong concurs that there is no single truth when reading and interpreting Austen. she believes Austen does not examine women’s role in society (46). She explains how this was followed by all kinds of interpretations. She writes “[i]t is clear that there can be no single view about a novel of such complexity [as Mansfield Park]” (1988:10). Seeber notes that readers of Austen often place great emphasis on her heroines and believe their values to be those of Jane Austen herself. She ends off by warning scholars “against the hubris of believing that ‘their’ historical methodology is the only one which will lead to a ‘correct’ reading” (102).Introduction Austen’s work. alternatively.
I looked for signs of women’s subordination in the late eighteenth/early nineteenth century. Sense and Sensibility. In What Does a Woman Want? (1993) Shoshana Felman takes issue with the accentuation of feminist awareness in texts written by women.women’s subjugated position in society. He believes that “none of us is outside or beyond geography” (1993:7). He suggests that we as readers should keep in 7 . Claudia Johnson similarly calls attention to the necessity of adopting historical approaches to Austen’s work so that feminists may “reconceptualize the stylistic and thematic coherence of Austen’s fiction” (1988:xix). extend. While I reread and re-evaluated Austen’s work. and that writers are shaped by their history and by the society they live in. feminists need to enter old texts from new critical directions (5-6). I do not want to suggest that it is the only way. and limited my field of study to Austen’s six novels – Pride and Prejudice. Being fully aware that this type of reading is one possible way of interpreting Austen. Northanger Abbey. As I examined Austen’s novels. while Edward Said comments on the urgent need “to draw out.and accentuating . One of my aims while writing this thesis was to emphasise the ways in which Austen’s novels address women. give emphasis and voice to what is silent or marginally present” (1993:66) in canonical texts.Introduction This thesis will provide a feminist reading of Austen’s work. trying to pinpoint which women’s issues she addresses. Often this entailed delineating . Toril Moi states in Sexual/Textual Politics: Feminist Literary Theory (1985) that feminists “strive to make explicit the politics of the socalled ‘neutral’ or ‘objective’ works of their colleagues” (87). Mansfield Park. Persuasion and Emma. To this end she suggests the “elaboration and the reinvention – of new (feminist) strategies of reading…[and] new procedures of approach” (7). in order to amplify the intention of women writers. She states that. I found that Said offers further valuable insight into reading and interpreting texts.
the ‘ruling class’” (Johnson. Hence. I shall be drawing from a number of disparate feminisms including popular best sellers such as the work of Germaine Greer as well as scholarly work by feminists such as Nancy Armstrong.Introduction mind the historical and social background of a writer and focus on drawing out or making explicit underlying meanings in texts (66-67). I shall in addition be crossing discipline boundaries between feminist literary theory and sociology. there are points of common interest and relevance which can be used in identifying some of the ‘shared’ as opposed to ‘universal’ aspects of women’s experience. This entailed remembering that Austen was a woman of European descent who lived and wrote in England at the end of the eighteenth/beginning of the nineteenth century. Since this thesis aims at reconsidering the longevity and relevance of Austen’s work. One might wonder. I shall consider white and black feminist perspectives in order to demonstrate that. despite the plurality evident in feminist discourse(s). Clearly. she has a very different political agenda to that of white Western women in academe. It was therefore important to keep Austen’s geographical and social background in mind while reading and assessing her work. 1988:xviii). and that her work first and foremost addresses them. Because I believe there is a relevancy beyond the distinctions imposed by the academe. 1993:66). While being “a socially confident member of the landed gentry and. Though it is apparent that Austen’s work is aimed at white women of the Western world and that it primarily 8 . and between popular culture (film adaptations) and ‘high art’ (canonised narrative fiction). she “wrote with an exclusively Western audience in mind” (Said. how someone like bell hooks (from whom I shall be quoting quite a bit) can be used in support of my reading of the Austen oeuvre. I am aware that her message comes across most loudly to white middle-class women of the Western world. with that. when I argue in this thesis that Austen addresses women’s issues. then.
in order to reveal what may be regarded as her feminist consciousness. there are areas that overlap in disparate fields of feminist study and I shall be drawing from these to illustrate some of the ways in which feminist politics has developed since Austen’s day. which offers a re-reading and deconstruction of three novels written by women: Jane Eyre. Applying such a deconstructive approach leads her. While deconstruction in poststructuralist terms refers to the “‘free play’ of meaning in literary texts” (Weedon. By applying her knowledge of the history of Britain’s imperialist reign. She argues that “[i]t should not be possible to read nineteenth-century British literature without remembering that imperialism. such as taking into account the historical. and in feminist terms. was a crucial part of the cultural representation of England to the English” (896). as she has been generally understood. understood as England’s social mission. Gayatri Spivak does something similar in her paper “Three Women’s Texts and a Critique of Imperialism” (1985). 1993:66). to pulling apart “the ways in which the different meanings of femininity have been cemented together” (Stacey. I have used some of the principles of deconstruction. to consider the figure of Bertha Mason in Jane Eyre as “a figure produced by the axiomatics of imperialism” (899) and not merely as Jane’s dark double. 1987:19). Just as Spivak believes that an informed critique of imperialism will lead to new insight into novels such as Jane Eyre. Wide Sargasso Sea and Frankenstein. she is able to uncover and emphasise the underlying ideology of imperialism in these texts. for example. 9 .Introduction addresses their needs. geographical and especially social background against which Austen was writing. I feel that re-reading Jane Austen against the background of the male-dominated and malefavouring world in which she was living and writing may lead to a new understanding of her awareness of the disempowerment of women in her society.
Introduction My reading of Austen takes into account that she not only lived in a male-favouring society. her novels are. which can be described as a “‘dual voice’…in which the voices of the narrator and character are blended” (Schellinger. and seeking “to interpret elements of authentic female experience in women’s writing” (235) is known as ‘gynocritics’. and male mastery over the text. 1987:35). literature was for Austen and her contemporaries a medium through which they could express the need for change (Miles. 1998:320). applying specifically a woman’s perspective. Writing and Language: Making the Silences Speak” (1993) Gill Frith addresses that feminist criticism which asks what “men’s texts. “not already the territory of men” (1988:xiv). seen from the heroine’s perspective. as Claudia Johnson has suggested. According to the Encyclopedia of Feminist Theories (2000). edited by Lorraine Code. Austen makes full use of the narrative structure of the novel in order to create feminist awareness. In an article entitled “Women. While she alternates between limited omniscience and limited third-person point of view. women” (1988:xxiv). The novel proved to be a popular site precisely because it was. to a large degree. This narrative strategy “reinforce[s] the reader’s empathetic identification with a character” (320). and allows Austen to turn the reader’s attention towards her women protagonists and their needs. [have] done to women’s heads” (153). the practice of delimiting one’s field of study to exclusively women writers. Claudia Johnson states that Austen employs the “device of centering her novels in the consciousness of unempowered characters – that is. Despite being born into a world where women were at a disadvantage in more than one way. but that she had to confront an almost exclusively male literary tradition. Austen thus employs the narrative technique of free indirect discourse. Following a gynocritical approach I have 10 .
in some way. I have attempted to evaluate her fiction within the framework of her social milieu and patriarchal inheritance. while the BBC’s television production of Pride and Prejudice enjoyed “a phenomenal reception” in the UK. art-house audiences flocked to Persuasion last fall. many of her books are current movie hits”. and just last month TV's Arts & Entertainment channel broadcast an acclaimed British miniseries based on Pride and Prejudice. My primary undertaking is then to offer a re-reading of Austen’s oeuvre in order to account. essentially. She adds that the film adaptation of Sense and Sensibility was one of the contenders for the 1996 Best Picture Academy Award.believe it or not from Austen's Emma.Introduction included a wider consideration of Austen’s work. the celebrated 19th-century author who's enjoying a brisk renaissance of her classic works: Last summer's teen hit Clueless was culled . Alicia Silverstone and Sandra Bullock? None other than Jane Austen. One only has to do a Jane Austen search on the Internet to be presented with loads of information on film and television adaptations of her work in the last ten years. we need to consider the Austenian renaissance of the past decade. In order to understand how Austen’s two hundred year-old work could have any impact on especially women in Britain. for her continued relevance and popularity in the twentyfirst century. Furthermore. the United States and in former colonies of Britain. Although Austen…died 179 years ago. CNN correspondent Sherry Dean (1996) writes “Hollywood…has made Jane Austen one of the hottest novelists of the '90s. I have drawn on current sociological and feminist theory since. While Don Harlow notes that this production “follows the story with much faith and attention to detail 11 . this thesis seeks to relate her findings in the late eighteenth/early nineteenth century to how women in our own time experience society. Film critics such as Bill De Lapp (1996) comment on Austen’s extraordinary ability to compete with current film scripts: Who's on the Hollywood fast track these days next to John Travolta.
believes “the ruthless business of money. who wrote the screenplay for the 1996 film version of Sense and Sensibility as well as portrayed the role of Elinor Dashwood. One possibility relates to the ‘comforting fiction’ and distance maintained in ‘period piece’ narratives. marriage and family fortune is brilliantly illustrated” (141) in the big screen adaptation of Mansfield Park. Here it needs to be noted that this thesis does not engage with reader response theory. for example. That South African women’s magazine Fair Lady should write a review on one of Austen’s works simply reinforces the appeal she has to white women of the Western world. The question remains why. neither does it offer statistics in support of Austen’s ‘comeback’. My supposition is based on continued academic research on Austen and on the spate of film adaptations in the last two decades. 1996). Though such a comparison may be regarded as a futile exercise. believes “[Austen’s] work survives because she wrote about subjects that never die” (Dean. I believe 12 . In this thesis I shall be comparing women’s position in the twenty-first century to that of women in the late eighteenth/early nineteenth century. some film critics have used what I call ‘Hollywood rhetoric’ to attract moviegoers.Introduction [and] never deviates from the general tone of the dialogue in the book”. While there is a distinction to be made between fictional characters in novels and real life experiences of women. I believe that it could give us some idea of the extent to which feminism has developed since the beginning of the nineteenth century. It would seem that contemporary women remain interested in the way in which women experienced society in Austen’s time. Another possible answer (and one which this thesis engages in particular) might be that Austen’s subject matter continues to be of interest. In the film review of Fair Lady of 26 April 2000 Karena du Plessis. Emma Thompson. We know that Austen is enjoying renewed popularity.
I was able to identify four main issues that are of interest to readers of a feminist persuasion: women’s education. as Andrea Nye (1988:5) reports. Moreover. After rereading Austen’s novels. [and] the prohibitions on female labour” (141) as some of the key issues identified by feminist writers. and women’s identity. the “lack of education. It does not privilege women over men. among others. Alexander lists. marriage as a patriarchal institution of economic and social entrapment. feminist writers became explicit in their struggle to end sexist oppression1.Introduction there are significant contrasts between the experiences of Austen’s women characters and the experiences of women living in today’s society. In contrast to Austen’s subtle reference to women’s issues. It has the power to transform in a meaningful way all our lives ” (20-21). investigating the role women played in society at the end of the eighteenth century could help us understand the legacy contemporary women have inherited. any particular race or class of women.…‘domestic drudgery’. In Austen’s fiction reference is made to some of 1 bell hooks states in Feminist Theory From Margin to Center (2000) that “[F]eminism is the struggle to end sexist oppression. while during the twentieth century. the first great wave of feminist activity in the 1840s was characterized by an open discussion of issues such as property rights and marriage reform. and that I needed to make assumptions about women’s subjugation in the late eighteenth/early nineteenth century. Sally Alexander writes in Becoming a Woman and Other Essays in 19th and 20th Century Feminist History (1994) that feminists from the seventeenth century up until the twentieth had similar starting points of dissatisfaction (101). In this regard I found Austen to be extremely subtle in her approach. for example that the male-favouring social system of the time often not only denied women the right to a proper education but also left them with no choice but to get married. women’s access to knowledge. Its aim is not to benefit solely any specific group of women. 13 .
Introduction
these issues. Being made aware of women’s disempowerment in patriarchal society in the early nineteenth century could help us understand why women were dissatisfied and why they started insisting on equal rights later on in that century. It could also help explain the legacy contemporary women have been left with. If we look for example at what Austen’s novels reveal about women’s education in the late eighteenth century, it is evident that a decent education and certain areas of expertise were the prerogative of men. Comparing this to education today, it would appear that maleprivileged education belongs to the past2. In most of the contemporary Western world, men and women have access to equal educational opportunities. Yet signs of a legacy, which kept women from enjoying equal educational opportunities to men, can be seen in the present day. In scholarly feminist journals such as the February 2000 edition of The European Journal of Women’s Studies, edited by Magda Michielsens and Mary Evans, the ways in which modern women suffer the effects of having been deprived of an education equal to that of men are explored. In “Balancing Gender in Higher Education: A Study of the Experience of Senior Women in a ‘New’ UK University”, one of the articles which features in this journal, Sue Ledwith and Simonetta Manfredi comment on the marginal position of women in the higher educational sector. In another article, entitled “From The Woman Question in Technology to the Technology Question in Feminism: Rethinking Gender Equality in IT Education”, Flis Henwood mentions that patriarchal discourse excludes women from certain academic terrains. A feminist reading of Austen sheds some light on the ways in which women were kept from empowering themselves, such as being denied access to a proper education and
2
Rosalind Miles mentions that, while women in the nineteenth century lost their educational advantage, women in the twentieth century generally had access to free public education (1987:27).
14
Introduction
knowledge, thereby ensuring an imbalance of power. In addition, it would seem that Austen questions general assumptions about women’s identity. She, for instance, seems to subvert the view that all women are born natural mothers and that they find fulfillment in marriage. Once again Austen is not blatantly critical, and therefore her dissatisfaction with gender roles needs to be inferred. Today, in contrast, feminists are very outspoken when it comes to predetermined gender roles and are constantly warning women against having their identity prescribed for them. Contemporary feminist scholars such as Patricia Waugh in Feminine Fictions: Revisiting the Postmodern (1989) focus on the social construction of gender and reject assumptions about the ‘natural’ predisposition of women (3-8). In Knowing Women: Feminism and Knowledge (1992), the first of a series of four books on women and society published by Polity Press, Helen Crowley and Susan Himmelweit point out that society expects women to play a specific role and in this way determines their identity for them (1718). Barbara Darby comments in an article entitled “The More Things Change: ‘The Rules’ and Late Eighteenth-Century Conduct Books for Women” (2000) that today women’s identity is often prescribed, or at least partly determined, by society and the media (333-343). Mary Eagleton writes in Working with Feminist Criticism (1996) that women novelists and theorists are able to re-construct and re-define the subject ‘woman’ by what they write (189). From Austen’s novels we can infer that women were rendered weak by being relegated to wife- and motherhood and by being subjected to patriarchal institutions such as education and marriage. In addition to creating an awareness of women’s disempowerment, possible ways in which women might empower themselves are hinted at (as I shall show in this study). The kind of power available to women, Austen seems to suggest, can only be exercised within patriarchal parameters. This type of moderate empowerment differs greatly from current
15
Introduction
feminist writing which emphasises the importance of bringing to an end women’s subordination. Toril Moi defines feminism as “a struggle mainly concerned with social and political change” (1985:23), “a political criticism, sustained by a commitment to combat all forms of patriarchy and sexism” (52). bell hooks - though she is writing against white Western feminist discourse which seeks to homogenise women’s experience - stresses in Feminist Theory: From Margin to Center (2000) that feminism needs to aim at eradicating domination and at transforming society (26). Austen’s texts could be read as questioning male domination and as subtly suggesting women’s empowerment. Some scholars may argue that Austen hardly succeeds in offering women the prospect of empowerment since all her heroines end up submitting to their traditional role and to patriarchal authority when they marry. It is possible, however, that Austen lets her heroines marry for the sake of her own survival in a male-favouring society. This does not mean that we should discard her feminist awareness. Instead, it would seem useful to infer from Austen’s novels women’s second-class position in society in the late eighteenth/early nineteenth century. By doing so, we may begin to see the ways in which feminism has progressed as well as start to understand the kind of legacy contemporary women have inherited.
16
edited by Linda Schmittroth and Mary Reilly McCall. the narrator patiently explained that women at this time were enrolled for special household courses that would teach them the finer art of home-making. Included in the programme was archival footage of a television commercial broadcast at the time. and states that although “small changes” (410) have been recorded in men’s domestic services. in contemporary society. In addition. 3 17 . no longer exists. Despite this type of progress. The idea was that such wives would transform their homes into a refuge. As if it were a concept alien to modern viewers. women in the Western world are not educated to lead exclusively domestic lives but mostly have access to the same type and level of education as their male counterparts3. the point is made that although women and men enjoy equal levels of education. salaries for men continue to be significantly higher than salaries for women who are doing the same work (405). 5 The Routledge International Encyclopedia of Women: Global Women’s Issues and Knowledge (2000) is edited by Cheris Kramarae and Dale Spender. such blatant propaganda encouraging women to lead a life of domesticity. and refers to the “increasingly important role [women] play as economic providers for families/households” (321). “men’s involvement in domestic labor has not increased to match women’s involvement in the labor market” (410). 4 Janet Chafetz mentions in the Handbook of the Sociology of Gender (1999) that in 1999 women represented almost one half of the labour force in industrial nations. featuring women stuffing turkeys in home domestic classes and the voice of a man in the background reminding the ladies that the way to a man’s heart is through his stomach. women have increasingly become part of the world’s workforce4 and have started sharing household duties with their husbands or partners5. which would have women believe In Women’s Almanac (1997). traces of a legacy. Perhaps. Today. which in turn would boost the morale of their soldier husbands who had returned from the war.Chapter One: Women and Education Chapter One – Women and Education Introduction Recently I was watching a German documentary on women’s education in post Second World War Germany.
Notice the qualities of light and the variations of shadow. move with deliberation. is seen as a very efficient. One might wonder what this has to do with Jane Austen. can be found. 18 . feeling both the support of the floor beneath your feet and the protection of the ceiling overhead. And experience the fragility and strength of your own body as it goes about its work. In this chapter I shall be investigating the late eighteenth-century practice of educating women to lead a life of domesticity. According to the writer.Chapter One: Women and Education that it is their duty and calling to take care of the home and the family. cost-saving form of therapy: Next time you sweep a floor. entitled “Dust Your Way to Nirvana”. I shall be positing that traces of such a practice can be seen in contemporary society. purpose and ease of motion that is exhibited in a timeless piece of choreography. In addition. the point is that he has managed to have it published in one of South Africa’s most popular women’s magazines and that it has been read by thousands of women all over the country. While it is clear that women today are no longer explicitly encouraged to develop their domestic talents in order to attract a husband (as they were in Austen’s day). Sweeping the floor. An article in Fair Lady of 25 April 2001. (58) Even if Thorp’s ‘theory’ that domestic chores are fulfilling might be dismissed by those who read this dissertation as quite silly. housework should not be regarded as some mundane activity but seized as an opportunity to come to oneself. features an extract from a book written by Gary Thorp called Sweeping Changes (2001). for instance. The uncomplicated act of moving a broom back and forth across the floor can contain all the grace. there are still some individuals who would have them believe that overseeing the housework is their responsibility.
It will be argued that her work reveals such an education to be biased and debilitating. she advocates one which will help women discover who they really are and one which in this way will empower them.Chapter One: Women and Education I believe Austen’s novels. create an awareness of the consequences of educating women for a life of domesticity. is that she shows a concern for women’s education in her novels. it may become apparent that modern women have inherited a particularly compromised educational legacy. we may begin to understand the effects that such a legacy has had. More recently. leaving women powerless and without any means of self-protection in a male-dominated world. by looking at what feminists are currently writing about. Not all critics would agree that Jane Austen encourages women’s education. Moreover. as well as become aware of just how much things have changed from Austen’s period until our own. In addition I shall be suggesting that. if read from a feminist point of view. Patricia Beer maintains that “Austen distrusted intelligence in women and the learning which an intelligent mind can hardly help acquiring” (1974:26). 19 . and which I shall be focusing on. Rather. One way of interpreting Austen. Upon closer examination of Austen’s depiction of the educational system in her time. as an alternative to the existing education system. Nancy Armstrong posited that Austen is not critical of Emma’s failure to observe “the strictures of female education…[and of] her failure to read” (1987:149). a refusal to be written by culture” (149). Austen’s work seems to lend itself to different kinds of interpretations. she believes Austen regards Emma’s lack of diligence in this respect as “a virtue.
The general attitude towards women’s intellect seemed to be. 1988:6) and that they should receive a practical and religious training for their domestic role. The narrator in Sense and Sensibility (1811) seems to be critical of Lady Middleton whose only resources are her children and her home: Lady Middleton piqued herself upon the elegance of her table. They believed that because the business of a woman was marriage. Nancy Armstrong argues that these men assumed in their writing that “an education ideally made a woman desire to be what a prosperous man desires…[and that] her desirability hinged upon an education in frugal domestic practices” (1987:59). They were of the popular and entrenched opinion that women were to be educated “to please men and to be mothers” (Nye. and of all her domestic arrangements… (30) and 20 . she should be taught those things that would attract a husband. 1979:24). She notes that influential eighteenth-century educational writers like John Locke and Jean-Jacques Rousseau insisted that “the goal of education for women [was] the development of good nature” (135). as John Ruskin so quaintly put it. In her novels we are presented with women whose minds have not been enhanced by their education. but for sweet orderings of domesticity” (Gilbert and Gubar. “Sweet orderings of domesticity” Training women for their domestic role is one of the results of an inequality of education and one of the causes of an inequality of intellectual achievement. It is the notion of education as preparation for a domestic life and its effects that Austen appears to expose. that it was meant to function “not for invention or creation. Barbara Horwitz provides valuable background information on the state of women’s education in Austen’s time in her essay “Women’s Education During the Regency: Jane Austen’s Quiet Rebellion” (1994).Chapter One: Women and Education 1.
Chapter One: Women and Education
Lady Middleton seemed to be roused to enjoyment only by the entrance of her four noisy children… (33) Although her traditional education prepares her for a life of domesticity, it appears neither to enhance her mind nor teach her social skills. We are told that “though perfectly well-bred, she was reserved, cold and had nothing to say for herself beyond the most common-place inquiry or remark” (29). In Pride and Prejudice (1813) Mrs Bennet’s education helps her only to find a husband. It fails to improve her understanding which, in turn, places a strain on the couple’s relationship. We are told that Mr Bennet was captivated by his wife’s “youth and beauty, and that appearance of good humour, which youth and beauty generally give” (262), but that her weak understanding had soon put an end to any affection he had for her. Mrs Bennet then is subjected to the double bind of ‘femininity’: first she is deprived of an education, and then she is punished for not having one. Judith Lowder Newton, however, seems neither to hold Mrs Bennet, nor the type of education she received, responsible for her being unhappily married. Instead, she believes Mr Bennet is to blame and writes that “Mr Bennet’s own imprudence must account for his unhappy domestic life” (1981:128). Emma’s sister, Isabella Knightley, provides the perfect example of a woman’s “sweet nature” that Locke and Rousseau were writing about. Her education has made her a specimen of the ideal wife for she is described as “a pretty, elegant little woman, of gentle, quiet manners, and a disposition remarkably amiable and affectionate; wrapt up in her family; a devoted wife, a doating mother” (Emma, 1816:72). Yet, as is the case with Mrs Bennet, her education does not improve her mental abilities, rendering her a woman of weak
21
Chapter One: Women and Education
understanding. Her slow wit leads to irritations in her marriage and verbal abuse by her husband: [Mr John Knightley] had all the clearness and quickness of mind which [his wife] wanted, and he could sometimes act as ungracious, or say a severe thing. (73) In Northanger Abbey (1819) we are presented with another couple who are not intellectually matched. Although Mr Allen does not explicitly get irritated with his wife’s “vacancy of mind, and incapacity for thinking” (48), the narrator apparently does. She comments that Mrs Allen “had neither beauty, genius, accomplishment, nor manner” (7), and argues that “[t]he air of a gentlewoman, a great deal of quiet, inactive good temper, and a trifling turn of mind, were all that could account for her being the choice of a sensible, intelligent man, like Mr. Allen” (7-8). Mrs Allen’s lack of insight and weak understanding may be attributed in part to the limited education to which she, as a middle-class woman living in the late eighteenth century, had access. When Catherine and Mr Allen discuss the propriety of young men and women driving about the country in open carriages, Mrs Allen is not able to follow the conversation (92). She seems incapable of having her own opinion, while often thinking Mr Allen’s expression “quite good enough to be immediately made use of again by herself” (222). Mary Musgrove’s education appears to be a double disaster in Persuasion (1818): she not only lacks understanding (33), but fails to achieve domestic happiness. While her husband uses any excuse to go hunting (34) or dine out (49-50), leaving her home alone, her children (though they may love her) respect her sister Anne more (39). Her education, then, does not seem to have equipped her, in particular, for her domestic life.
22
Chapter One: Women and Education
All these examples serve to illustrate the shortcomings of an education aimed at teaching women how to take care of their family and home.6 Although such an education belongs to the past, it remains of interest since it is part of women’s heritage. If we compare women’s education in the twenty-first century to women’s education in Austen’s time, we can appreciate the progress women have made. Today women are no longer formally educated to be home-makers and mothers. Girls have the same subject choices as boys do, at school, and attend the same universities7. Despite these crucial steps forward, feminist writers believe women not to be wholly liberated from their domestic role. Feminists seem concerned about the fact that many women are primed at an early age to accept a life of domesticity. This means that they will end up taking responsibility for the household and the children one day while their husbands will further their own careers. Germaine Greer believes this to be true and argues in The Whole Woman (1999) that, as a result, women are not only kept from climbing the rungs at work, but that they earn less than their male counterparts. She seems to assign it all to gender role socialization which starts at home: When I was a little girl, little girls were kept in to do the housework while little boys were sent out to play. (155) Feminists aim at raising awareness among contemporary women that they (mostly) believe it
6
Writing a century after Austen, Cicely Hamilton openly states in Marriage as a Trade (1909) that “ [t]he insistent and deliberate stunting of woman’s intellectual growth is…the best proof of her essentially servile position in the household” (39). 7 Kramarae and Spender argue that “[a]lthough girls and boys in coeducational schools usually begin their schooling in the same classrooms and study the same curriculum, as they get older, and as options become available in the school system, they move into different curriculum ‘tracks’ or ‘streams’ or ‘programs’” (2000:498). They also mention that, despite the fact that women are often enrolled in subjects like languages and the humanities, in wealthy industrialized nations such as the United States and Australia, and in parts of Europe, female university participation in recent years has matched or slightly exceeded that of men (500).
23
(339) Paula Wilcox maintains in an article published in “Women’s Studies International Forum and called ‘Me Mother’s Bank and Me Nanan’s. Cyborgs and Women” (2000). as the pure space of ‘home’” (339). Irene Gedalof ascribes this state of affairs to so-called identity narratives which “repeatedly position ‘Woman’ as place. In her study on the displacement of Kosovo women refugees across Europe she found that these women were expected to sacrifice themselves in order to re-create a home for their family: Women’s domestic responsibilities mean that their activities are bound up with materially creating and recreating that home/place. 24 . fortunately. This may be attributed largely to the efforts of feminist scholars who created an awareness of an education which. husband and children” (182). such as keeping the family together” (36). In an article entitled “Identity in Transit: Nomads. In Austen’s time women were explicitly told to be selfless and to take care of their home and their family. even when violence. which appeared in the sociological journal The European Journal of Women’s Studies. migration or dispersal oblige them to make that place in the context of displacement.Chapter One: Women and Education is their duty to do the domestic chores. the practice of having overtly prescriptive norms for women. Over the years. died out. You Know. in the words of Nancy Armstrong. Support!’: Women who left Domestic Violence in England and Issues of Informal Support” (2000) that “[w]omen’s lower status in the gender hierarchy leads them to experience greater pressure to conform to social norms. In the early nineties feminist scholar Stevi Jackson published an essay entitled “Women and the Family in Introducing Women’s Studies: Feminist Theory and Practice” (1993) in which she comments that “even today…the idea persists that a woman’s purpose in life is to care for home.
Western Europe and the United States. Cultivating ‘accomplished’ ladies In addition to training women for a domestic life.Chapter One: Women and Education “subordinate[s] the body to a set of mental processes that [guarantee] domesticity” (1987:76). another 38% were in ‘two-housekeeper’ couples in which wives were employed full time and did 60% or less of the unpaid work” (679). edited by Judith Worell. and Deviance as Discourses of Voluntary Childlessness (2000) that “[i]n the United Kingdom. sing. Disregard. It reminds us of the variability in couples’ domestic work sharing. the efforts of feminists over the years have paid off. 8 25 . be attributed to the legacy which persistently prepared women for domesticity. labeled ‘drudge-wives’. women are having fewer children and having them later in life” (23). or speak modern languages. states that “[f]rom 1970 to the present. 9 The Encyclopedia of Women and Gender: Sex Similarities and Differences and the Impact of Society on Gender (2001). a fact that may. especially when these women manage a full-time job9. and states that “[f]indings from a representative sample of dual-earner households showed that while 29% of the sample. Contemporary life sees wives increasingly sharing the household chores with their partners. The aim of such a ‘curriculum’ for girls was to produce marriageable daughters by making them desirable to men (Armstrong. play music. However. individual choice” (16). while Rosemary Gillespie notes in an essay entitled When No Means No: Disbelief. women today are (mostly) aware of their right to decline such a life8. Austen seems to be critical of the notion of accomplishments Chris Weedon writes in Feminist Practice and Poststructuralist Theory (1987) that Liberal feminists “argue that family life and the decision to have children should result from free. in part. many women still choose to give up their careers and become housewives. 2. attitudes regarding gendered family roles have become increasingly egalitarian” (678-679). such as the ability to draw. had full-time jobs and did more than 60% of the housework. 1987:19-20). While women in the late eighteenth/early nineteenth century seemed to casually accept their domestic role. although most women continue to become mothers at some time in their lives. Though the world is yet to experience an overall transformation of attitude regarding women’s role as domestic caretaker. education of the ‘genteel’ classes in the late eighteenth/early nineteenth century was often the acquisition of ‘accomplishments’.
in all spheres of social life. Judith Lowder Newton writes that Austen’s novels show that women “are prepared for nothing but display [since] their goal is not to accomplish but to be ‘accomplished’” (1981:120). 10 26 . middle-class interests. (xiii. Whereas nineteenth-century readers of Austen’s fiction in all probability were oblivious to the intersectedness of gender. it was necessarily a strategy in preserving white. his views on Austen’s endings provide insight into the traditional way of reading Jane Austen’s fiction. as Chow. Given that the notion of accomplishments was limited to women of the Western world and of the middle class. and then subverting this convention by making her heroines indifferent to being accomplished. and other cultural groups. Firstly. Wilkinson and Baca Zinn (1996) point out in Race. Halperin does make some valid points (such as the one mentioned above). critiques of feminist scholarship have provided intellectual challenges to reassess the salience and influence of race and class. should be aware of their interrelatedness and of the implication that these narratives foreground the predicament of the (rising) middle-class woman at the expense of the working classes. my emphasis) Here it would seem necessary to account briefly for quoting from what may be considered an outdated source.10 This she achieves by illustrating the tradition of using one’s accomplishments to attract suitors. race and class politics we. During the past two decades debates in feminist theory have highlighted the unavoidable intersectedness of class. Class & Gender (1996): Feminist scholarship has illuminated the significance of gender as a basic principle of social organisation and as a central category in theoretical analysis. Western. Secondly. as twenty-first century readers. Since the 1980s.Chapter One: Women and Education in her work. as well as gender. race and gender. John Halperin mentions in The Life of Jane Austen (1984) that Austen takes “an impatient swipe” (85) at ladies’ accomplishments in all of her novels.
Mary Crawford realises that of all the accomplishments music especially can 27 . feminists have the task of making society aware of their interrelatedness in an attempt to end all forms of oppression: Feminism as a movement to end sexist oppression directs our attention to systems of domination and the interrelatedness of sex. In an article entitled “Pandora’s Box: Subjectivity. Maria Bertram seems “by her amiable qualities and accomplishments. gender. Similarly. race. According to bell hooks. the best adapted to make [her son] happy” (38. according to Kaplan.Chapter One: Women and Education Since we live in a society characterised. ethnic and national strata” (7) we can no longer separate class. conversely. “by the oppression of subordinate class. steeped in and spoken through the language of sexual differentiation” (957). Class. In Mansfield Park (1814) Mrs Rushworth feels that of all the young ladies she has ever seen. accomplished girl” (42. sex and race. and Sexuality in Socialist Feminist Criticism” (1985) Cora Kaplan argues that a feminist literary criticism which privileges gender in isolation from class and race offers only a “partial reading of the role played by sexual difference in literary discourse” (957). as Douglas Kellner points out in “Cultural Studies. handsome. and this appears to be a central concern in Austen’s novels. good-humoured. Mrs Grant thinks Julia Bertram would make Henry Crawford very happy if he married her for she is “a nice. and class oppression…The foundation of future feminist struggle must be solidly based on a recognition of the need to eradicate the underlying cultural basis and causes of sexism and other forms of group oppression. my emphasis). This is because. race.1 Catching Men Patricia Beer states that accomplishments were “all aimed at catching men” (1974:64). Multiculturalism and Media Culture” (1995). my emphasis). “class and race ideologies are. (2000:33) 2.
even if he thinks he has Elinor’s interests at heart.Chapter One: Women and Education be construed as a “sexual gesture” (Miles. In Persuasion Anne Elliot indicates her indifference to appearing accomplished when she professes to be “a very poor Italian scholar” (165). Mr Dashwood is trying to make a sale. for she played it with the greatest obligingness…Edmund was at the Parsonage every day. Possibly because John Dashwood wants to see his sister marry and settle in life. 1987:64) between the sexes when she courts Edmund by playing his favourite pieces on the harp: The harp arrived. the otherwise talented Emma Woodhouse never achieves excellence in either drawing or singing. In effect. 2). Mr Owens. 65) The narrator concludes tongue-in-cheek that a woman as well accomplished as Miss Crawford will inevitably succeed in catching “any man’s heart” (65). music or learning French and shirks her lessons whenever she can (Northanger Abbey. wit. to be indulged with his favourite instrument… (Mansfield Park. 17). and when Mary is anxious to know from Fanny whether the Miss Owens are very accomplished. and rather added to her beauty. Austen seems to challenge this very convention by making her heroines indifferent to being accomplished. 28 . he calls Brandon’s attention to Elinor’s drawing skills in Sense and Sensibility (229). presumably for fear of Edmund’s being attracted to one of them (292-293). The practice of using one’s accomplishments to attract a husband is illustrated when Edmund Bertram visits his friend. Similarly. 35). Catherine Morland for example shows no interest in drawing. and is “not much deceived as to her own skill either as an artist or a musician” (Emma. and good humour. while Fanny Price is ridiculed by her cousins for not wanting to learn either music or drawing (Mansfield Park. Having illustrated the convention of using one’s accomplishments to attract suitors.
however. and the modern languages” (85) in order to be accomplished.Chapter One: Women and Education Although the narrator in Sense and Sensibility draws our attention to Marianne’s musicality (33) she does not omit to mention that Marianne practises music for the love of it (45). The narrator comments. singing. Furthermore. nor affecting to be so” (243). Elizabeth Bennet’s music performance in Pride and Prejudice is judged to be “pleasing. Elizabeth “had been listened to with much more pleasure” (71). nor do they necessarily contribute to enhancing her mind. when she states that the room which Elinor and Marianne are given 29 . While Marianne loves music. though by no means capital” (71). It is therefore likely that Marianne does not see music as a means of catching a husband. Being accomplished. stop practising them once they are married. and therefore desirable to men. 33. Likewise. Darcy chooses Elizabeth to be his wife. Lady Middleton is admonished for giving up singing after her marriage: …the chief of the songs which Lady Middleton had brought into the family on her marriage…perhaps had lain ever since in the same position on the pianoforte. then. drawing.2 Laying down the harp Austen shows that often women who only use their accomplishments to catch a husband. Austen appears to be suggesting that accomplishments can neither guarantee any woman a husband. for her ladyship had celebrated that event by giving up music… (Sense and Sensibility. 2. had taught Mary “neither genius nor taste” (71). her sister Elinor is “neither musical. my emphasis) The narrator also seems to be critical of schools in which girls (like Mrs Palmer) are taught only to be accomplished. dancing. that despite her sister Mary’s effort to be accomplished. even though Miss Bingley says that “[a] woman must have a thorough knowledge of music.
In Emma Mrs Elton seems to imply that women should master music and drawing for their own sakes when she comments that “there is a sad story against [married women] in general [that they] are but too apt to give up music” (209). In comparison with this kind of pre-occupation with finding a husband. contemporary studies show that being married does not ensure women of a fulfilled and happy life11. What I am suggesting is that. In addition. married men as well as single people of both genders “reported greater positive affect than did married women” (2001:674). it was believed that women needed to marry in order to lead a meaningful life. there remains a difference at the level of representation when one compares the ways in which Austen’s fictional characters and women in real life experience society. and writes that in a novel such as Pride and Prejudice “the action in almost the entire first volume of the novel consists of very little but women talking or thinking or scheming about men” (1981:129). Feminists are currently concerned with women’s preoccupation with cosmetic Judith Worell writes that. I do not mean to elide the history of feminism by comparing women’s obsession with male attention in Austen’s time to our own. my emphasis). Not only has two centuries passed since Austen wrote her last novel. the quality of their relationships with their children is highly related to their level of satisfaction with their life overall” (674). 11 30 .Chapter One: Women and Education in London. Yet many women seem to be obsessed with men and especially male attention. Judith Lowder Newton comments on women’s obsession with men as portrayed by Austen. While in the late eighteenth century. in proof of her having spent seven years at a great school in town to some effect” (154. in twenty-first century studies on married life and life satisfaction. despite the tremendous strides the feminist movement has made. women still show some signs of a legacy which taught them they needed men in order to survive in this world. “having children does not appear to increase people’s life satisfaction…for those who have children. women today appear to be less compromised. features “a landscape in coloured silks of [Charlotte’s] performance.
(212) It is possible that Austen illustrates how in her own time the female body is made an object of male desire when Mary Crawford plays the harp obligingly and Edmund watches her with indulgence (Mansfield Park. They add that patriarchy is largely to be blamed for this: The female body is made object. a spectacle for (hetero)sexual voyeurism. By making her heroines indifferent to being accomplished and by criticising married women who “celebrate their marriage by giving up music altogether” (Beer. the tininess of their waists. Women then become. Alison and Schneider comment in a sociological essay entitled “The Lived Body Experience of Domestic Violence Survivors: An Interrogation of Female Identity” (2000) that women have become preoccupied with their bodies. Germaine Greer is critical of contemporary women who spend their time and energy making themselves attractive for men.Chapter One: Women and Education surgery because they believe it is an indication of their obsession with male attention. the longness of their legs and the size and shape of their breasts. undergo cosmetic surgery and have their breasts enlarged in an attempt to attract male attention: Women are illusionists. colour and curliness of their hair. absurdly. Instead of acquiring 31 . These women. Men do not seem to have demanded this of them. girlishness and orgasm. 65). according to Greer. both estranged and obsessed with their bodies. rather women seem to have bedizened themselves in an all-out last-ditch attempt to grab the attention of otherwise uninterested males. Making oneself attractive for men seems to be an age-old custom among women. they also fake the roses in their cheeks. (1999:33) Wesely. They fake light-heartedness. 1974:65) Austen appears to show contempt for this convention. the thickness. the male spectator’s gaze upon her becomes her own critical gaze upon herself.
women struggle with identity: Women as a group in our society are both produced and inhibited by contradictory discourses. In Mansfield Park it appears that she perceives education to play a role in this regard: instead of teaching young girls how to become wives it should. Very broadly. generosity. She argues that women’s ‘self’ is inevitably constructed and that. and having many feminist precursors to refer to. relative inadequacy and irrational intuition. against the prescription imposed on them by patriarchy. 3. “ in everything but . In Austen’s novels there are subtle references to what could be interpreted as her encouraging women to discover their own identities. “it is not very wonderful that. living and writing in the twentieth century. The attempt to locate a single and coherent subject-position within these contradictory discourses…can create intolerable pressures. clearly has the confidence and the freedom to speak plainly on the need for women to discover their own identities. partly at least. The narrator in Mansfield Park comments that. Self-knowledge Catherine Belsey states in “Constructing the Subject: Deconstructing the Text” (1985) that the cultural construction of women’s subjectivity is one of the central concerns for feminism. aim at equipping them with self-knowledge. we participate both in the liberal-humanist discourse of freedom. self-determination and rationality and at the same time in the specifically feminine discourse offered by society of submission.Chapter One: Women and Education skills in order to be desirable to men. and humility” (18). with all [Maria’s and Julia’s] promising talents and early information. they should be entirely deficient in the less common acquirements of self-knowledge. she seems to suggest that women should practise the art of music or of drawing for its own sake. owing to contradictory discourses. 32 According to her. (661-662) Belsey.
when Henry Crawford prefers Maria to her. she fails to see their true intentions. much research by feminist scholars in the twentieth century has shown that rigid sociallyconstructed gender roles are responsible for women and men not knowing themselves. Sir Thomas realises too late that “elegance and accomplishments [have] no moral effect on the mind” (468). Fanny Price sees Henry Crawford for what he is and resists his charms because of her deep-rooted love for Edmund (Mansfield Park. Although she is an intelligent girl. they were admirably taught” (18). This makes her misjudge both Darcy and Wickham (Pride and Prejudice. Julia’s misery. Emma. 353-358). Possibly because she herself loses the man she loves to another woman. Barbara Horwitz writes that in Austen’s novels “it is the heroines who do not know their own hearts who are blind to the emotions of others” (1994:142). In Sense and Sensibility Elinor Dashwood knows her own heart and realises how much she loves Edward Ferrars. 294-295). on the other hand. is attributed to the fact that “knowledge of her own heart…had not formed any essential part of her education” (92). In 1967 in an essay entitled “Sex Roles and the Socialization Process” Sverre Brun-Gulbrandsen 33 . While Austen possibly attributes the lack of self-knowledge to an inadequate education. In addition. While Edmund believes “the most valuable knowledge we could any of us acquire [is] the knowledge of ourselves” (464). she shows compassion and understanding for Marianne’s suffering (180-184). The want of self-knowledge causes her to misinterpret Mr Elton’s affections and blinds her to Frank Churchill’s and Jane Fairfax’s conspiracy.Chapter One: Women and Education disposition. only realises that she loves Mr Knightley right at the end of the novel. Elizabeth Bennet does not know her own heart either.
one becomes one” (1985:65). into the particular positions allocated to each sex in any specific way” (Crowley and Himmelweit. This view is echoed by Shoshana Felman: Becoming a feminist is undertaking to investigate what it means to be a woman and discovering that one is not a woman but rather becomes (somewhat interminably) a woman. now young men and women. discovering. whether as a social/political practice. that one is not born a woman. masculine or feminine. one has become (perhaps never quite sufficiently) a woman. behaviour deviating from these norms is punished. or as a literary/theoretical enterprise. Behaviour conforming to these norms is rewarded. Feminist writers of varying persuasions 34 . 1992:18). or Sex and Class as Culture” (2000) that we are all gendered as male or female. Feminism. and socialized into being men or women. (1993:12) In the Spring/Summer 2000 issue of the journal Women: A Cultural Review. (61) When they grow up these children. Regenia Gagnier argues in her article “The Functions of Class at the Present Time: Including Taste. They learn these norms through innumerable environmental influences but particularly from their rearers as these ‘norm-senders’ encourage certain forms of behaviour on the part of the ‘norm-receivers’. edited by Isobel Armstrong. or a relationship of inequality between things that might not on the surface have to do with masculine or feminine” (37). through others’ reading and through the way in which other women are addressed by one’s own writing.Chapter One: Women and Education explained the ways in which little boys and girls are first introduced to their gender roles at home: Children must learn to behave in certain ways in certain situations. aims at making women aware of their socially-constructed gender roles. Toril Moi writes “‘[f]emininity’ is a cultural construct: one isn’t born a woman. She points out that “[g]ender is a role. “fit into the structures of society.
96). She constantly refers to the fact that higher education is a man’s prerogative by mentioning that many of her male characters attended either a university or a private school. not only because it produces dull-witted women whose sole interests are their homes and their families. middle class boys had the opportunity to attend educational institutions. and that in this way prevent them from developing a sense of self. over time and space. The inequality of education leads to 35 . 206). is of great importance. It could be argued that Austen is critical of domestic education. Privileged education for boys I believe Austen to expose the late eighteenth-century educational system for women as unfair by focusing our attention on the biased nature of higher education. 4. rather as a preparation for motherhood [that] Jane Austen may be considered as a feminist writer” (1994: 145). It would seem that for feminist scholars in the twenty-first century. Whereas Henry Tilney went to Oxford (Northanger Abbey. Austen seems aware of women’s educational deficit when she has Anne Elliot say that “[e]ducation has been [the men’s] in so much higher a degree” (Persuasion. as Barbara Horwitz puts it. Catherine Morland received her education from her parents (2).Chapter One: Women and Education and from many discipline bases expose gender roles and patriarchally-constructed norms that dictate to women how they ought to behave. While girls were mostly taught at home either by their parents or a governess. In Austen’s work we can find early signs of what may be regarded as the concern for the lack of self-knowledge among women. It is therefore. knowing oneself and realising that one is constituted out of different discourses. but also because it keeps women from knowing their own minds. by “stressing women’s education for its own sake.
She emphasises the informal education girls receive at home by making Lady Catherine react in utter disbelief to the fact that the Bennet sisters had no governess (Pride and Prejudice. “the deficiency of nature had been but little assisted by education” (114). sends money only for Mrs Price’s sons to be educated. His brother. In Sense and Sensibility we learn that Edward Ferrars was “entered at Oxford” (100). Though the educational bias of the late eighteenth/early nineteenth century has been eradicated. and not her daughters (19). While he sends Edmund to Eton and then to Oxford. He does not encourage them as he does his sons when he listens to them enacting Julius Caesar and wishes them “as schoolboys. Here Austen may be implying that though a tertiary education does not guarantee quick understanding. is that women enter neither. to speak well” (130). my emphasis) in Mansfield Park.Chapter One: Women and Education Henry’s pedantic attitude and enables him to correct Catherine’s grammar constantly (96-98). his own daughters receive their education at home. But the narrator also points out that even though Mr Collins attended one of the universities. In this novel Austen seems to imply that being a woman means being deprived of a decent education. a staunch patriarch. Because they were deprived of a higher education equal to that of men. The underlying implication. introduces the debate as to whether a private or a public school aids a man best (244). Sir Thomas. women did 36 . Robert Ferrars. 199). the lack of one guarantees a subordinate role in society. By having Edmund and Henry discuss the neglect of reading in “the ordinary school-system for boys” (343) Austen implicitly draws attention to the absence of such a system for girls. of course. Isobel Armstrong argues that although Austen’s critique “of women’s education is oddly akin to that of a more radical writer” (1988:10) it remains an “indirect concern” (9. it would seem to have had some long-term effects on women and their position in society.
It would seem plausible that contemporary women have no legacy of great women artists precisely because they were subjected to a prejudiced education system for many years. male. 5. in the arts as in a hundred other areas. 1999:155). a don was heard to sardonically remark. women among them. Cambridge.Chapter One: Women and Education not feature in literature for many years. our hormones. her work may help us understand the ways in which women were kept from developing their intellectual abilities. composers and mathematicians equivalent to male artists like Chaucer or Cézanne. Unequal education opportunities In Mansfield Park Austen calls attention to the patriarchal grand narrative of her time which would have it that extensive education creates vanity in women. but in our institutions and education… (96) Since Austen’s novels provide us with an account of the biased nature of education in the late eighteenth/early nineteenth century. who did not have the good fortune to be born white. are stultifying. race and sex works effectively to keep women from developing their artistic capabilities: …things as they are and as they have been. She comes to the conclusion that discrimination based on class. preferably middle class and. The fault lies not in our stars. Germaine Greer points out that women were only fairly recently granted equal educational opportunities and allowed to attend universities12. 12 37 . oppressive and discouraging to all those. or our empty internal spaces. above all. Sir Thomas expresses the This was such a novel idea to some patriarchal stalwarts that “when women were admitted to King’s College. ‘Now the men will get their laundry done free’” (Greer. philosophers. our menstrual cycles. In an essay entitled “Why Have There Been No Great Women Artists?” Linda Nochlin (1994) asks why the Western world has failed to produce women writers.
or an establishment. the franchise. public life and the labour market have been on terms designed to meet the needs of individual men…” (1987:2). In the years that followed Austen’s writing.Chapter One: Women and Education generally held viewpoint that “self-conceit. Fanny answers it is “[t]he effect of education” (272). women are prevented from a proper education. or any thing which professed…to combine liberal acquirements with elegant morality…. without any danger of coming back prodigies. Today. When Edmund mentions to Fanny that Mary Crawford’s conversation and opinions sometimes have a tinge of wrong. The narrator’s observation regarding Mrs Goddard’s “old-fashioned Boardingschool” (17) could be a condemnation of the patriarchal system for preventing women from receiving a decent education: Mrs Goddard was the mistress of a School . old-fashioned Boarding-school.but a real. and every tendency to that independence of spirit…in young women is offensive and disgusting” (320-321). honest. In Emma Austen refers to the fact that because education is believed to lead to vanity. While the male monopoly has been eliminated in most Chris Weedon points out that although “[m]any of the social and political gains made by women over the last 100 years have been the result of struggles to include women in the rights and privileges which men have instituted to serve their own interests…women’s inclusion in education. women and men of the Western world mostly enjoy an equality of education. my emphasis) Austen seems to suggest that men deliberately keep women from an extensive education in order to render them weak. feminists increasingly demanded equal educational opportunities13. where a reasonable quantity of accomplishments were sold at a reasonable price and where girls might be sent to be out of the way and scramble themselves into a little education.not of a seminary. 13 38 . (17.and where young ladies for enormous pay might be screwed out of health and into vanity .
Nevertheless. particularly in the industrial sector” (268). is class specific. since only women belonging to the middle-class had governesses or attended schools (Levine. Seeing that the effects of a poor education would be felt by the middle-class women of the late eighteenth/early nineteenth century. 6. 1987:26-27) her criticism. her criticism of women’s limited education creates a consciousness of Margaret McFadden writes in Ready Reference: Women’s Issues (1997) that by 1990 “[m]ost professions remained under male control…[and that] women still faced a glass ceiling…barring them from higher-level authority positions. Biased education. Austen is almost exclusively addressing their needs. it should be kept in mind that Austen writes with a specific readership in mind. However.Chapter One: Women and Education of the educational realm. once again.14 Linda Schmittroth and Mary Reilly McCall show in Women’s Almanac (1997) that women with similar levels of education to men still earn less than their male counterparts (405). Consequences of a poor education I believe Austen illustrates the consequences of an inadequate education for women in her novels. Germaine Greer found as recently as 1997 that “across all types of work in higher education…62 per cent of the jobs done by women were consistently undervalued as against 37 per cent of the jobs done by men” (1999. feminist writers believe it has spilt over into the workplace. “tend to predominate in higher-level occupations…while women tend to be concentrated in lower professional and clerical jobs” (499). 157). as Lorraine Code remarks. Throughout the following section. 14 39 . Because men had the educational monopoly for so many years they now. then. appears to have had far-reaching consequences: it not only favoured boys at the time but weakened girls for many years to come.
In Northanger Abbey Austen may be implying the absence of a women’s literary canon by listing male poets only. Because men had privileged access to writing and producing knowledge (as I illustrate in Chapter Two). Thompson and Shakespeare (3-4). including Pope. In Mansfield Park Austen comments on the god-like powers of the author when she informs the reader that she personally likes restoring her characters to reasonable comfort (466). he was assuming her subordinate position in society. Gray. Austen herself appears to see the pen as a symbol of power when she equates a person’s writing to strength of character in Emma (224). She shows how writing can establish a woman’s subordination by quoting a single line of poetry: it is clear that when the poet compared a wife to “Heaven’s last best gift” (42). they were able to keep women subjugated and to maintain their powerful position in society. That men had privileged access to writing has further consequences. they were able to control 40 . Sandra Gilbert and Susan Gubar see the pen as “an instrument of generative power like [the] penis” (1979:6) and therefore as “essentially a male ‘tool’” (8). Austen’s findings show an awareness of what French psychoanalyst Jacques Lacan has identified as ‘the law of the father’. It would seem that men in the late eighteenth/early nineteenth century experienced the act of writing as threatening.Chapter One: Women and Education the type of legacy contemporary women have inherited and an awareness of some of the ways in which this has affected them. In Ecrits (1966) he states that the phallus represents the law of the father – la loi primordiale – and fixes meaning in language (277). By reserving education solely for men. Being rendered powerless is one of the first consequences of a poor education.
the sexual harassment of schoolgirls. Chris Weedon argues that “women’s absence from the active production of most theory within a whole range of discourses over the last 300 years…[is] a mark of the particular conditions under which prestigious and powerful bodies of knowledge were and are produced” (1987:13. 16 Rosalind Miles writes that by the late twentieth century “[t]housands of women [were] writers who would previously have thronged with the ranks of the illiterate” (1987:27). my emphasis).Chapter One: Women and Education what was written and in so doing keep women subordinated. bell hooks comments on the implications that this type of patriarchal discourse has for women: . Writing on the theoretical and political influences which have helped constitute current poststructuralist theory. 15 41 . it has proved extremely difficult to improve the plight of girls and women… (2000:161) Flis Henwood contributes to Code’s findings when he argues that the falling number of women entering computer science courses is due to dominant discourse which offers women “only marginal or outsider status within technological cultures” (2000:213).15 Though in our own time women have just as much right to the act of writing as men16. a hidden curriculum in misogyny and anti-domesticity. among them: a chill coeducational classroom climate for girls and women…the androcentric bias of the subjects of the liberal curriculum. and to modern society in which “the acquisition of technical skills by women is perceived by many as a threat to the masculinity of men and to the gender order more generally” (210). prevails in the educational realm. Feminist writers have identified some of the consequences that women’s literary legacy has led to. Despite the advent of women’s studies programmes. the underrepresentation of women in the higher ranks of the professorate. contemporary schoolgirls continue to suffer the consequences of what she calls an “education-gender system”: Feminist research and scholarship has uncovered many elements of this education-gender system. Lorraine Code comments that since Western ideology. which associates men with mind and women with emotionality. they have been left with a very different type of literary inheritance to that of their male counterparts.
race. it would appear that they suffer the consequences of a 42 . 1987:2). (2000:7-8) Diane Reay writes in “‘Drim Dros’: Marginalised Women both Inside and Outside of the Academia” (2000) the reason for the academic status quo is that the higher education sector is “a territory ruled by men. This deprivation leads women to feel insecure about intellectual work and to fear grappling with new ideas and information. Elaine Showalter comments in “Laughing Medusa: Feminist Intellectuals at the Millennium” (2000) that women rarely come up in debates about the dilemma of the intellectual in society since the woman intellectual “is camouflaged by her gender” (132). Contributing to the idea of the invisibility of women. There has been much presentation of data and increasing feminist analyses and commentary on the position of women in the higher education sector. Though women have managed to eradicate male-dominated education and despite the fact that they enjoy equal education opportunities to men (Schmittroth and Reilly McCall. 1997:362.Chapter One: Women and Education As a group. where the vast majority of women if they count at all count for less” (14). Weedon. Most women are deprived of access to modes of thought that promote the kind of critical and analytical understanding necessary for the liberation struggle. and class exploitation and oppression) the right and privilege to develop intellectually. (2000:114-115) Sue Ledwith and Simonetta Manfredi express their concern about the under-representation of women in the higher education sector in general: The poor showing of women in the higher reaches of universities across Europe is seen as being among the worst in the labour market. which becomes “reconstituted as a low-level activity…in which women undertake invisible labour which services men and contributes to relations of ruling” (15). women have been denied (via sex. She goes on to argue that many women are employed as contract researchers only.
which was usually around the age of seventeen (Cruse. as She pays their education “not the smallest illustrated in Austen’s novels. By then. Instead. she 43 . to be caused by the lack of a proper education.Chapter One: Women and Education male-dominated education legacy. The Bertram sisters in Mansfield Park feel there is a great deal for them to learn. 1931:78). and a very frequent ignorance of grammar” (15). Because of the inattention to academic development. being under-represented in the higher education sector and the belief that certain academic terrains are the prerogative of men. These include a male-favouring education system. In Northanger Abbey Henry Tilney believes women to display in their usual style of letter-writing “[a] general deficiency of subject. Where an inadequate education does not cause ignorance. Another aspect of late eighteenth and early nineteenth-century education which Austen seems concerned about is the view held by most women of the time that they need only study until they ‘come out’. does not believe women’s boredom. remains ignorant and illiterate precisely because “her powers had received no aid from education” (123-124). ignorance and deficient grammar were often found among women of the middle class. attention” (18). though she is naturally clever. Judith Lowder Newton. but only up to their seventeenth birthday (17). it may be responsible for women being bored. they would know everything a girl needed to know in order to fulfill her domestic role. In Sense and Sensibility we are told that Lucy Steele. however. In Northanger Abbey Austen more directly addresses the issue of girls studying only until their seventeenth birthday when the narrator comments that Catherine’s mind is “about as ignorant and uninformed as the female mind at seventeen usually is” (6). it would seem. Their lack of interest in acquiring knowledge is partly their mother’s doing. a total inattention to stops.
She welcomes new inhabitants to the country for she has grown used to the absurdities of people like Sir William Lucas whom she has known all her life. Emma relishes gossip (130) and enjoys meddling in other people’s affairs. it is no wonder that she finds amusement in the domestic and the mundane. She has a lively disposition and delights “in anything ridiculous” (59). Elizabeth Bennet admits to being a “studier of character” (Pride and Prejudice. 269). 88) to keep herself amused. Austen draws our attention to the intellectual loneliness of married women by having Mrs Elton say that even if a woman has “ever so many resources. She is easily bored and even gets agitated with Frank Churchill and Harriet for being “dull” (278). She admits that playing matchmaker to people like the Westons “is the greatest amusement in the world” (10). Grant. The narrator comments that Mrs Grant welcomed the news that Mary was to come and live with her “for Mrs. it is not possible for her to be shut up at home” (Emma. having by this time run through the usual resources of ladies residing in the country without a family of children – having more than filled her favourite sitting-room with pretty furniture. Educated for domesticity. We are told that Emma suffers from “intellectual solitude” (Emma. Newcomers like the Bingley sisters provide welcome entertainment for Elizabeth whose “quickness of observation” (63) enables her to recognize their superciliousness (68). In Mansfield Park Mrs Grant is pitied for the monotonous duties that make up a married woman’s life. and to laugh at especially Caroline Bingley’s desperate attempt to attract Darcy’s attention (92). and made a choice collection of plants and poultry – was very much in want of some variety at home” 44 . To alleviate the boredom.Chapter One: Women and Education sees it as a result of “women’s usual state [which] is not to move at all but to hear news or to read letters about the arrivals and departures of males” (1981:126). 6) since her father cannot provide stimulating conversation.
Austen creates an awareness of the importance of an equality of education between men and women. being ignorant and deficient in grammar. In the following chapter it will be shown that Austen seems to be aware and critical of the fact that knowledge has been produced by men for centuries. being interested in only the domestic and the trivial. not being intellectually stimulated. Mary Crawford’s response to her sister’s plight possibly reflects that of the narrator: ‘The sweets of housekeeping in a country village!’ said Miss Crawford. In addition to investigating the type of education women receive and the effects thereof. The consequences of such an education system for women include not having access to the power of the pen. ‘Commend me to the nurseryman and the poulterer. It can therefore be argued that by showing how a limited education debilitates women in many different ways. and that it has always excluded women. and finally being bored . Austen could also be read as exposing the access that women have to knowledge (or the lack thereof).Chapter One: Women and Education (40). 45 . and a world in which women are subjected to an inferior education.’ (215) Austen’s novels depict a world in which men enjoy the privilege of having access to a higher education. archly. We see that Mrs Grant’s main concerns in life consist of nothing more than cultivating her plants and deciding on which meal to cook her husband (214).especially within the marriage state.
It is not In 1987 Chris Weedon wrote that “[t]he last fifteen years [had] seen the beginnings of a radical shift in the degree to which women are represented in knowledge production and in the production of theory both inside and outside official education and research” (13-14). and not at all applicable to our modern world. expected women to be ignorant and to “minister men’s conversation” (1974:65). provided they did not display their knowledge. Instead of being told to agree with men. It is possible that Austen is being critical of a society which. “can offer women alternative perspectives on negotiation techniques and communication styles…[and] can educate women to be more expressive and candid” (2000:95). edited by Rhoda Unger.Chapter Two: Women and Knowledge Chapter Two – Women and Knowledge Introduction In Austen’s day women were not expected to know about politics or history – these topics were reserved for men – nor were they expected to make intelligent conversation. 1931:15). [she] should conceal it as well as she can” (99) may be interpreted as tongue-in-cheek. Kramarae and Spender comment that assertiveness training. The narrator’s observation in Northanger Abbey that “if [a woman] have the misfortune of knowing anything. “it was not thought proper for a young lady to study very conspicuously” (Cruse. they are encouraged (and often praised) for displaying assertive and independent characters18. 18 The Handbook of the Psychology of Women and Gender (2001). She adds that girls were allowed to study the classics. In the early nineteenth century. Barbara Horwitz mentions that renowned eighteenth-century educational writer Fenelon “had declared woman’s intellect was normally feebler than a man’s [and] that learning would make a girl vain” (1994:137). 17 46 . states that “American society today is more accepting of women who display assertive and independent characteristics” (413). In contemporary society women are not forbidden to display their knowledge17. which was popular in particularly the United States in the 1970s and 1980s. as Patricia Beer has shown. then. Yet feminist scholars have found that women today often defer to men in conversation. These social prescriptions may seem very far removed from the twenty-first century.
however. while Mary Eagleton suggests that “social and cultural pressures…undermine [women’s] confidence and make them hesitant about speaking” (1996:16). Sally Alexander believes “[w]omen are subordinated and silenced because they live in a world shaped in the interests of and dominated by men” (1994:101). Araújo. Andrea Nye suggests it is on account of men generally wielding more power than women in relationships that women feel they have to “listen. There are also other explanations for women’s reluctance to speak out. While Catherine Belsey refers to the “feminine discourse offered by society of submission. and further develop [men’s] ideas” (1988:173). but not too good. Mort and Weedon postulate in their article “Psychoanalysis and the Cultural Acquisition of Sexuality and Subjectivity” (1978) that owing to “the social structuring of the unconscious through language” (115) women are silenced. relative inadequacy and irrational intuition” (1985:662). to appear quiet and mysterious (2000:343). Arnot. my emphasis) Barbara Darby. dress well but not too expensively. that is.Chapter Two: Women and Knowledge implausible that the reluctance of women to disagree with male arguments and views has its origins in the conduct books of the late eighteenth century. instead. to something inherently spoken for” (1993:24). Changing Concepts of 47 . Germaine Greer points out how this discourse expects women to exist in relation to their husbands only: The politician’s wife is expected to display all the wifely virtues. Burniston. mentions that in our own time women are advised by certain writers not to start up a conversation with men but. and Shoshana Felman argues that by “the oppressive gesture of representation…man has reduced the woman to the status of a silent and subordinate object. (1999:322. come when she is called and laugh at her husband’s jokes. Deliyanni and Ivinson suggest in “Changing Femininity. make comments. she must look good. speak when she is spoken to. writing on the ways in which women’s identity is determined by society.
as Henry moves on from discussing the landscape to politics. the narrator comments that from there “it was an easy step to silence” (100). crown lands and government – he shortly found himself arrived at politics… (Northanger Abbey. I would argue that the narrator is critical of Henry’s abusing his power. When he talks to Catherine and arrives at the subject of politics. However. from her novels we can infer that she lived in a society which rendered women ignorant and which expected them to be passive when conversing with men.Chapter Two: Women and Knowledge Citizenship in Public and Private Spheres” (2000) that women today are not operating “on the same terms as men” (152). Austen never overtly challenges patriarchy for rendering women silent. and the withered oak…to oaks in general – to forests. In their study on women’s subordination in society. 100) 48 . In accordance with their findings. the enclosure of them. While contemporary feminist scholars openly blame society for women keeping quiet when men speak. “the narrator. Whereas Sandra Gilbert and Susan Gubar suggest that. Janet Saltzman Chafetz comments in Handbook of the Sociology of Gender (1999) that “the mere knowledge of another’s sex…has been shown to affect willingness to accept influence from that person” (263). The narrator’s disapproval of his dominating the conversation is evident in her rendition of the rapid and illogical progression of his discourse: …by an easy transition from a piece of rocky fragment. In Northanger Abbey we see that such a society enables a man like Henry Tilney to abuse his privileged male education. like Catherine keeps still [because] etiquette. it seems. they found that men and women regard the male sex as having more control over decision-making in various areas (2000:153). would forbid such discussions” (1979:134). waste lands.
women who may never carry out programs of reading literature” (1987:150). There are critics. who seem to disagree with the above-mentioned view. partly at least. My aim is not to speculate about Austen’s personal views. Whatever her intent may have been. but to show that depicting the type of conversation generally found among women raises an awareness. 49 . It would seem possible that women’s ignorance led. She argues that Austen thereby manages to grant “priority to the verbal practices of women. of women’s general ignorance during the time in which her novels were written and of the dire need for intelligent conversation among them.Chapter Two: Women and Knowledge Nancy Armstrong argues that women narrators of Austen’s time were identified by their gender as having no claim to especially political knowledge and power (1987:29). it was just a few decades earlier that Mary Wollstonecraft posited in A Vindication of the Rights of Woman (1792) that women were politically incompetent because they had not been educated like men (265). Indeed. amongst feminist scholars at least. Austen appears to encourage stimulating conversation among women by creating intelligent women characters who yearn for interesting conversation and who are not afraid to disagree with what men have to say. Nancy Armstrong believes Austen’s writing to support gossip and conversation among women. and there is some evidence to suggest that she is critical of empty women-talk. conversation makes up an essential part in Jane Austen’s novels. I believe Austen to show an awareness of the fact that many women in her time were uninformed about subjects beyond their domestic sphere (such as politics and current affairs). however. Austen vividly illustrates the type of conversation generally found among women. In addition. to empty conversation among them.
Isabella and Mr Woodhouse. and one subject only engaged the ladies till coffee came in. and [that] nothing could be less interesting than the whole of their discourse” (137). and Lady Middleton’s second son. and to laugh at girls who can talk of nothing but “dress.Chapter Two: Women and Knowledge 1. William. flirtations and quizzes” (20). and breaking horses – but then it was all over. In Sense and Sensibility the narrator is undoubtedly critical of women who busy themselves with uninteresting conversation: When the ladies withdrew to the drawing-room after dinner. whose conversation can be classified as ‘typically female’ owing to his hypochondria (Horwitz. In contrast. the women talk about people and fashion (59). she ironically thinks she is faring better herself by talking about the house and the furniture. discuss their respective apothecaries (Emma. In Northanger Abbey Austen shows that to talk does not mean to be having a conversation. 50 . The narrator seems to be critical of women’s “maternal effusions” (19) when Mrs Thorpe and Mrs Allen meet in Bath. Trite Remarks and the Conduct Books By contrasting topics of conversation generally found among men and women. this poverty was particularly evident. While men discuss political and news-making events. In Emma Mr John Knightley and his brother talk about the law and about farming (78). 1994:140). balls. Once again Austen contrasts ‘men-talk’ to ‘women-talk’. inclosing land. (228) While Lucy Steele criticises her sister Anne for talking “of nothing but beaux” (120). who were nearly of the same age. for the gentlemen had supplied the discourse with some variety – the variety of politics. Austen alerts us to the lack of stimulating discourse among women in the early nineteenth century. which was the comparative heights of Harry Dashwood. 78-79). Empty conversation. When Elinor dines with the Miss Steeles and Lady Middleton she feels that their meeting “produced not one novelty of thought or expression.
326). it is not to add her own view but merely to stop Mr John Knightley from making any further hurtful remarks to Isabella (Emma. Even Emma’s allegorical interpretation of Elton’s poem is.ironically often written by women19 . When the Knightley brothers discuss legal issues Emma does not partake. as long as they were not too far-ranging or assertive. limited and dreary. This often led to empty conversation among them.was prescribed to women and dictated what they should say. Emma says “[j]ust what she ought [for a] lady always does” (Emma. We see how even an intelligent girl like Emma Woodhouse at times indulges in trite remarks. stereotyped. The lack of intellectual conversation among women may be linked to the kind of literature available to them. 19 51 . Furthermore. “perfectly in keeping with the conduct book’s suggestions about the proper use of classical mythology and history within a female curriculum” (1987:146). as Nancy Armstrong puts it. a conversation in which there is “scarcely ever any exchange of opinion” (23) is hardly a conversation at all. they often evince attitudes Nancy Armstrong writes that the conduct books of the eighteenth and nineteenth centuries “often written by women and directed at female readers…rewrote the female subject for an eighteenth century audience” (1987:94). to show in their conversation that they had read. When she eventually does join in. were held to be perfectly feminine… (1974:66) Austen’s work illustrates the effects of these prescriptive books on women. 81). were published alongside other details of required behaviour. as Patricia Beer points out: Women were allowed. While one might expect Austen’s heroines to be more defiant of patriarchal convention. The various lists of books recommended for them in Jane Austen’s day. even encouraged. when Mr Knightley declares he loves her.Chapter Two: Women and Knowledge To her. The notorious conduct book of the late eighteenth/early nineteenth century . Literary allusions.
In addition. one cannot but notice that the narrator ridicules Mrs Allen for not being able to utter little more than a few standard phrases. This changes to “How glad I am we have met Mrs Thorpe” (23) by Chapter Five. When Catherine and Elinor meet in the Pump Room. She seems to ridicule clichéd idioms like “Despair of nothing we would attain” and “Unwearied diligence our point would gain” (18). Barbara Horwitz writes that Mary “demonstrates her own obtuseness by parroting Mr Villar’s speech 52 . While the narrator refers to Mrs Allen’s “remarks and ejaculations…vacancy of mind. When they first arrive at Bath she keeps on repeating “I wish we had a large acquaintance here [in Bath]” (10).Chapter Two: Women and Knowledge other than a feminist sensibility. In Northanger Abbey Austen most overtly criticises the conduct books and their effects. and appears to be critical of Catherine’s use of “pretty expressions” (20). not an expression used by either which had not been made and used some thousands of times before” (60). Nancy Armstrong has noted that in Pride and Prejudice Austen mocks those novels which observed “all the same sense-making procedures as the conduct book…when she [has] Mary Bennet speak the conduct-book clichés in all their tiresome perfection” (1987:108). though one could argue that Austen allows her heroines to utter clichés and empty remarks in order to illustrate that even spirited women know what they have to do and how they have to behave in order to survive in patriarchal society. Henry Tilney describes having only her as company as “a picture of intellectual poverty” (67). the narrator comments that “in all probability not an observation was made. The narrator refers to the abundance of trite remarks (very possibly a result of having recommended books) when she says the heroine of any story should supply her memory “with those quotations which are so serviceable and so soothing” (3). and incapacity for thinking” (48).
Gilbert and Gubar point out that “Marianne is extremely sensitive to language. Lady Bertram is In Sense and Sensibility Austen characterized by speaking “entirely by rote” (196). She has her own ideas and would rather say nothing at all than use “worn and hackneyed” (94-95) language. and make extracts. and read great books. Lady Middleton for example has “nothing to say for herself beyond the most common-place inquiry or remark” (29). repelled by clichés. while the conduct books occasionally enabled women to make an appropriate remark. 55) It would seem that. In the same novel. Marianne admits that she abhors “every common-place phrase by which wit is intended” (Sense and Sensibility. rather than repeating what they have been told. Mary prides herself on being bookish yet has nothing sensible to say. but knew not how. as in the others. that one is sorry to see them give way to the reception of more general opinions” (54). they did not ensure that they would always have something sensible to say. as Mr Bennet is quick to point out: ‘What say you. challenges empty expressions. 210-211) reflects the narrator’s irritation with hackneyed expressions. Colonel Brandon makes a case for young people having their own opinions. when he states that “there is something so amiable in the prejudices of a young mind. This renders her incapable of making 53 . Patricia Beer has made the point that in Mansfield Park Fanny Price recites a speech on memory which comes “almost straight from Dr Johnson” (1974:66). 43) and that she detests “jargon of every kind” (94). and impatient with the polite lies of civility” (1979:156). we see that women often fail to have their own views.Chapter Two: Women and Knowledge from Fanny Burney’s ‘Evelina’” (1994:139). In this novel.’ Mary wished to say something very sensible. (Pride and Prejudice. It is possible that Mary Crawford’s evident boredom with Fanny’s speech (Mansfield Park. Mary? for you are a young lady of deep reflection I know.
[Lady Middleton] could not believe them goodnatured. When Fanny contemplates whether being married to Edmund would change Mary Crawford’s character. and easily given. it creates an awareness of the devastating effects of prescribing reading material for women.Chapter Two: Women and Knowledge interesting conversation (52-53) and of understanding popular clichés. and because they were fond of reading. she fancied them satirical: perhaps without exactly knowing what it was to be satirical. She echoes what Thorpe says (52-53). (240) In Mansfield Park the idea is expressed that women often do not have their own views. think 54 . It was censure in common use. Since her “youthful female mind [is] fearful of hazarding an opinion of its own in opposition to that of a self-assured man” (35) Catherine Morland accepts the views of Henry Tilney and Mr Thorpe. has no views of her own but uses those of her husband (222). but that did not signify. in addition to her trite remarks. though it does not deter her from using them: Because [Elinor and Marianne] neither flattered herself nor her children. material which dictates what they ought to do. we read “impartiality would not have denied to Miss Crawford’s nature that participation of the general nature of women which would lead her to adopt the opinions of the man she loved and respected as her own” (372). She is so dependent on Sir Thomas’s views that she even lets him decide which game she should play (241) and whether or not she can do without Fanny (219). Lady Bertram provides a good example of a woman who has adopted the opinions of the man she loves. In addition. In Northanger Abbey Mrs Allen. Austen’s depiction of women’s deferral to men provides us with insight into the powerful position men held at the time. and starts to see things from Henry’s perspective (100) because she assumes that he “must know best” (137).
2. Elinor Dashwood is one of Austen’s women characters who yearns for intelligent conversation (52). When talking to Captain Benwick her “seniority of mind” (90) puts her in a position to recommend that he read more prose. While Frederick 55 . The effects include women engaging in empty conversation.Chapter Two: Women and Knowledge and say. well-informed people. uttering trite remarks. When Sir Walter and Mr Shepherd talk about the rich Navy Officers returning to England. She remarks that women of any class who are intelligent. Elinor. who feels that “nothing could be less interesting” (Sense and Sensibility. Anne adds her own view on the navy (Persuasion. She finds him “capable of giving [her] much information on various subjects” (49) and derives “more satisfaction from conversing with him than from any other daily occurrence” (162). enjoys Brandon’s company. Finding a new discourse Austen not only depicts empty talk among women. Anne’s idea of good company is “clever. who have a great deal of conversation” (134). I would agree with Patricia Beer who believes that Austen manages to create “considerable equality between the sexes in conversation” (1974:66). 137) than typical women-talk. 18-19). which contradicts the ideology of the time that women should not know about politics. and failing to have their own views. Anne’s ability to make intellectual conversation comes to the fore especially when she converses with members of the opposite sex. Austen challenges the view that women should not argue with men by having women characters like Anne Elliot disagree with the opposite sex. not having anything sensible to say. “may well be worth listening to” (139). In addition she makes Anne au fait with public affairs. She achieves this by introducing intelligent conversation among women and by having her heroines argue with men. she also shows that there are women who engage in stimulating conversation.
While Elizabeth joins in Darcy’s and Bingley’s conversation and offers her own views. at [Elizabeth’s] manner of talking to her brother…[she] by Elizabeth’s instructions…began to comprehend that a woman may take liberties with her husband” (395). of course. the narrator informs us that Elizabeth continued to engage in a “lively. she argues that Elizabeth renounces all her pertness and liveliness of mind the instant she agrees to marry Darcy (51). Elizabeth’s outspoken. Armstrong believes that this apparent discontinuity within Elizabeth’s character “demonstrates this novel’s reliance on the figure of sexual exchange” (51). They. what he really wants is for her to agree with everything he says and 56 . Once married.Chapter Two: Women and Knowledge Wentworth values her sound advice (105). Elizabeth Bennet similarly manages to hold her own with men. Although Nancy Armstrong agrees that Elizabeth has been endowed with “rational intelligence…and especially a command of the language”(1987:50). she successfully defends women against Captain Harville’s view on women’s fickleness (206). Tony Tanner writes in Jane Austen (1986) that Elizabeth also “disconcerts Wickham with a nice irony” (115). 85) and exchanges erudite arguments on poetry (90). Though Armstrong’s point is valid. Although Edmund Bertram ostensibly asks Fanny’s advice and wishes to confide in her. 260-261). and he is never quite sure what to make of her words (Pride and Prejudice. She disagrees with Darcy on what makes an accomplished woman (Pride and Prejudice. In Mansfield Park we see the heroine fitting into convention by being quiet and modest and by not arguing with men. sportive. manner of talking” (395) to her husband. the Bingley sisters remain silent (9496). She also mentions that although Georgina at first “listened with an astonishment bordering on alarm. selfassured repartee throughout the novel remains memorable. subscribe to the tradition that women should be seen and not heard. and not argue with men.
For this reason she offers her judgement and opinion very modestly (158). At times she purposefully disagrees with him. Fanny is not used to opposing people. In the following section I shall show that by asking how knowledge was produced and by whom. When she openly disagrees with Henry Crawford. especially when they are men. just for the sake of arguing (Emma. We always say what we like to one another. you know – in a joke – it is all a joke. That they enjoy quarrelling is clear: Mr Knightley loves to find fault with me. I believe that if we read Austen from a feminist point of view. Austen shows that not all women subscribe to the view that they should be ignorant and fail to have their own opinion. 111). (9) By creating women who argue with men and who yearn for intelligent conversation. Austen’s work also gives us a good idea of the type of knowledge women could obtain. her work exposes knowledge to be man-made and leads us to consider how this has affected women’s lives. the experience is so foreign to her that she trembles and blushes “at her own daring” (228). Emma discusses Harriet’s refusal of Robert Martin and talks to Knightley about women’s issues with “all the familiarity of an equal” (223). 57 . we are able to gain insight into the ways in which women were restricted in the past.Chapter Two: Women and Knowledge to quiet his conscience (156-157). Austen appears to create some equality between the sexes in Emma when she presents us with good-humoured bantering between Emma and Mr Knightley. As Rosalind Meyer shows in “Mr Knightley’s Education: Parallels in Emma” (1998). In addition to making us aware of the fact that women in the beginning of the nineteenth century had limited access to knowledge.
and…what counts as knowledge” (1987:7). “ways of producing knowledge. not even in the act of knowing. Investigating ‘knowledge’ In Feminist Practice and Poststructuralist Theory (1987) Chris Weedon states that feminist theory should ask “how and where knowledge is produced and by whom. the child must enter into the symbolic order. Kadiatu Kanneh reminds us in an essay entitled “Love. as stated by this theory. Jane Moore mentions in “An Other Space: A Future for Feminism?” (1992) that postmodern theory. According to Foucault “all knowledge rests upon injustice…there is no right. far less of demonstrating. Mourning and Metaphor: Terms of Identity” (1993) that language is “a legacy of male power” (136). In “Extreme Fidelity” (1984) Hélène Cixous writes that since “we are born into language” (15). the set of signifying systems of culture of which the supreme example is language. and Francois Lyotard in particular. Catherine Belsey reinforces this poststructuralist concern with language: If [a child] is to participate in the society into which it is born. and ways of shaping the world according to that knowledge” (Crowley and Himmelweit. to be able to act deliberately within the social formation. Discourses are. initiated “a rethinking of the status of knowledge and of its relation to the knower” (1992:66). 1982:237) so that “no text is capable of representing determinately. (1985:660) Michel Foucault’s work on the plurality and ‘differance’ of meaning suggests that language is not neutral but that it constructs reality. and used to produce (and shape) knowledge. the ‘truth’ about any subject” (Abrams. Toril Moi’s contention that “the dominant power group at any given time will dominate the intertextual production of meaning” 58 .Chapter Two: Women and Knowledge 3. to truth or a foundation of truth” (1977:163). language plays a vital role in constructing our subjectivity. 1988:203).
206. Anne Elliot points out that books prove nothing since all stories have been written by men: Yes. in Edward Said’s words. emotions. although Mr Tilney. historical sense. If we read Austen from a feminist point of view it becomes possible to perceive a society in which men shaped knowledge and ‘truth’. Education has been theirs in so much higher a degree. Sally Alexander points out that women’s history has to be argued for: 59 . “we all speak from a specific position shaped by cultural. Taking a strong stance when arguing about women’s fickleness with Captain Harville. Catherine Morland. the men all so good for nothing. and hardly any women at all” (97. (Persuasion. no reference to examples in books. my emphasis) As Toril Moi has rightly suggested. it could be argued. with wars or pestilences in every page. She suggests that. “its own perspective. political and personal factors” (1985:43). Mr Allen. a knowledge that excludes women. social. the pen has been in their hands. she herself finds it tiresome because it features “quarrels of popes and kings. yes. Men have had every advantage of telling us their own story.Chapter Two: Women and Knowledge (1985:158) implies that men have used language to produce knowledge . my emphasis). André Brink comments that in Emma “Knightley’s privileged access to truth is based on his position in society as a male” (1998:114). and traditions” (1993:11). This means that each group of people will have its own interpretation of the past and. if you please. her father and two of her brothers like history.a knowledge that passes itself off as truth. 97). I will not allow books to prove anything. anticipates poststructuralist and feminist theory that aims at deconstructing the master narrative of history when she ascertains that a great deal of history “must be invention” (Northanger Abbey.
and that it was ‘unnatural’ for women to write. (Miles. Women were in this way discouraged from writing literature and history. history. when the suggestion was made at a History Workshop session that people working on women’s issues should meet later in the day. 1987:6) In fact. amongst other factors. Gilbert 60 . and hence excluded from producing knowledge: …by the nineteenth century. 4. (1994:141) Language.Chapter Two: Women and Knowledge It is well known that women receive little or no attention in traditional history writing. they managed to hold on to their authority in patriarchal society. but even among radical and socialist historians they are all too often mentioned as an afterthought. delightful” (1988:xv). by extension. surprise or roguish gallantry on all sides. there was a roar of laughter. her novels (especially Northanger Abbey and Persuasion) make us aware of the fact that women in Austen’s time were left powerless by. Because men were in the powerful position of writing (producing) knowledge. Barbara Horwitz mentions that “learned ladies who exhibited their knowledge were made to appear unnatural and therefore ridiculous” (1994:137). wispy. the fear of the intellectual woman was so great that she was labelled a freak. Self-Deprecation Early nineteenth-century women were left with the belief that writing was a man’s domain. the idea that the novel was man’s ‘proper sphere’ was so entrenched that the very idea of a ‘lady novelist’ was enough to rouse suspicion. knowledge have historically worked together to keep women subordinated. if at all. Claudia Johnson writes that fiction by women writers was expected to be “modest. tagged on rather than present in their own right. scorn. As recently as 1971. delicate. having been denied the right to produce knowledge. literature and. If we read Austen with a feminist agenda in mind.
quite undermining their claims about the attractiveness of mind” (1974:50).Chapter Two: Women and Knowledge and Gubar comment that. (1979:61-62) Austen. in light of the above. Patricia Beer has remarked that “[Austen’s] heroines react in the same way [as Austen]. or at least be occasionally abundant in quotations and allusions which a woman…like me…would be totally without the power of giving. because it was believed that it was not normal for women to write. women writers were ostracized if they did not acknowledge their writing to be a mere diversion: If [the woman writer] refused to be modest. 99) could. of which I know nothing.. (Lascelles. One cannot therefore be sure whether her well-known response to James Stanier Clarke. must have been aware of the fact that intellectual women were treated with suspicion. self-deprecating. and that this is all part of her cover story 61 . humiliated. even bullied into sense” (1979:159).. being an early nineteenth-century woman novelist herself. refused to present her artistic productions as mere trifles designed to divert and distract readers in moments of idleness. she could expect to be ignored or (sometimes scurrilously) attacked.and I think I may boast myself to be…the most unlearned and uninformed female who ever dared to be an authoress. that because of her ignorance she cannot accept his suggestions for the hero of her next story. Sandra Gilbert and Susan Gubar believe Austen endows many of her women characters with intelligence and/or strong imaginative powers for which they are later apparently “mortified. Some critics believe that in Austen’s novels self-deprecating remarks are often made in relation to the heroines themselves. subservient. was intended sincerely or not: Such a man’s conversations must at times be on subjects of science and philosophy. 1939:41) Her statement that “imbecility in females is a great enhancement of their personal charms” (Northanger Abbey. be meant ironically.
When she finally discovers the truth. only fully realises the dangers of a wild imagination when she wrongfully assumes the General had killed his wife. We see Henry Tilney making fun of Catherine’s gullibility and fanciful expectation of what the Abbey should look like (Northanger Abbey. 142-145). a result of her ardently reading Gothic novels. restless. she considers Austen to defy. in her intelligent and attractive heroines. No less than three times does her fancy blind her to the truth and 62 . 5). The narrator in Northanger Abbey appears to reprimand Catherine Morland for her “raised. Her first disappointment comes when she discovers nothing more than a washing-bill in the old cabinet (157). Even though Emma is praised for being a clever girl (Emma. Critics such as Judith Lowder Newton and Claudia Johnson do not agree that Austen renounces her heroines or their deeds. and frightened imagination” (39). It would seem that Austen’s heroines do err from time to time and that they are shown to suffer the consequences. Lowder Newton writes that “[w]hen Austen allows Elizabeth [Bennet] to express critical attitudes and to act upon them without penalty. she is shown to make quite a number of mistakes. Claudia Johnson similarly believes that Austen is not being deprecating when she endows Elizabeth Bennet and Emma Woodhouse with “rich and unapologetic senses of self-consequence” (1988:xxiii). She. John Halperin believes that in this novel Austen “attacks the distortions of an overactive imagination” (1984:105). every cliché about women and decorum that was advocated in the conduct books (xxiii). Rather. In addition. she is moving against early nineteenth-century ideologies about feminine behaviour and feminine fate” (1981:135). we witness Catherine’s double humiliation. her humiliation is exacerbated as Henry (whom she wants to impress) realises what she has been thinking all along (181-182). however.Chapter Two: Women and Knowledge (154-159).
Austen seems to contrast Marianne’s rashness to Elinor’s cautiousness and good sense. Barbara Seeber has written on the “parallel situations” (1999:231) and the juxtaposing of Elinor and Marianne. Emma also errs when she assumes with “an ingenious and animating suspicion” (120) that Jane Fairfax and Mr Dixon are in love. could have no moderation” (5). Finally Emma wrongfully assumes Harriet to be of honourable descent. Elinor’s prudence (5). Knightley’s concern that Emma “will never submit to…a subjection of the fancy to the understanding” (29) is justified when she wrongfully assumes that Mr Elton and Harriet are in love. and in so doing “illuminates a world of contesting ideas” (223). Marianne is made to feel the consequences of her “imprudence and want of thought” (55) most severely when Willoughby betrays her (170). She believes the key to making sense of Sense and Sensibility is reading it as a dialogic text. according to the narrator.Chapter Two: Women and Knowledge cause her to make blunders. but eager in everything. In Sense and Sensibility Marianne Dashwood acts emotionally and irrationally and has to suffer the consequences of her actions. and even more so when she makes this suspicion known to Frank Churchill. does Emma fully realise the possible consequences of her vanity and overactive imagination (312-313). She manages to convince Harriet that she is too good for Robert Martin and to refuse his proposal. According to Seeber. her joys. Austen’s novel presents the reader with two heroines who experience the world very differently. We are told that Marianne is “sensible and clever. her sorrows. Only once Harriet falls in love with Mr Knightley. Although her abilities are “quite equal to Elinor’s” (5) Marianne lacks. In 63 . As a result Emma has to ward off Elton’s attentions and also needs to tell Harriet that he has no intention of marrying her. Emma is deeply embarrassed (299). and almost costs Emma her future happiness. When it is finally revealed that Frank and Jane are in fact engaged.
her stubbornness (363-368). The narrator informs us that “[Anne’s] attachment and regrets had. and is able to alleviate Captain Benwick’s pain by recommending prose (90-91). It would appear that the narrator feels sorry for Anne. clouded every enjoyment of youth. Anne is praised for her “elegance of mind and sweetness of character” (7) which she puts to good use: she gives sound financial advice (1314). Anne Elliot is another heroine whom Austen seems to approve of. and when she realises how grossly she has misjudged Darcy. the narrator comments: [Elizabeth] was humbled. she seems to have suffered enough for it. and an early loss of bloom and spirits had been their lasting effect” (Persuasion. or even Marianne. By doing so. a model of female excellence” (142). manners. she repented. What is more. keeps her wits about her when Louisa is injured (98-99). 26). Even when she disagrees with Captain Harville. for a long time. Elizabeth Bennet is known and loved for her intelligence (Pride and Prejudice. she seems to regard her highly. mind. 63). she was grieved. Anne is described by Mr Elliot as being “in her temper. When she discovers the truth about Wickham. and for arguing with men (102). though she hardly knew of what.Chapter Two: Women and Knowledge addition. [but] instead…explores the struggle to achieve ideological dominance” (223). her literariness (90). it “does not side with Elinor. her outspokenness on social conventions (200). he says he cannot argue with her for she is “a good soul” (207). Though she might have erred when she broke off her engagement to Frederick Wentworth. Austen may be suggesting that women ought not to be reduced to comforting stereotypes. Yet she too seems to make mistakes and to be reprimanded for them. (325) 64 .
In Northanger Abbey the narrator claims to have a “wild imagination” (227) and encourages women novelists to display their imaginative powers20. are conveyed to the world in the best chosen language. in which the most thorough knowledge of human nature. She states that women writers are “an injured body” (24) and. only some work in which the greatest powers of the mind are displayed. or at least . in short. riding on horseback. “Yes. 24). Perhaps she is illustrating the complexities of human responses in order to critique the damaging stereotypes inherent in the binary logic of ‘sense’ and ‘sensibility’. 20 65 . of degrading…the very performances to the number of which they are themselves adding…Let us leave it to the Reviewers to abuse such effusions of fancy at their leisure…let us not desert one another…for our foes are almost as many as our readers” (Northanger Abbey. 25) In addition to urging women novelists to write. as Gilbert and Gubar have pointed out. 5. and makes a case for the novel as a literary genre in its own right: [The novel is]. Literariness In her novels Austen appears to encourage literariness among women. (Northanger Abbey. ‘pride’ and ‘prejudice’. for I will not adopt that ungenerous and impolitic custom. She insists that women writers should stand together.Chapter Two: Women and Knowledge Austen’s work features heroines who make mistakes. the liveliest effusions of wit and humour. base-ball. Austen seems to be encouraging literariness among women in general when she reprimands some of her women characters for not being bookish. The narrator appears to be critical of Catherine Morland who prefers “cricket. and running around the country…to books. so common with novel writers. the happiest delineation of its varieties. gently criticises them for being embarrassed about their status as novelists (1979:146). novels.
with sweetness of manner” (55). 85). said Elizabeth.Chapter Two: Women and Knowledge books of information” (Northanger Abbey. 3). silly ones would bore him (359). I really cannot be plaguing myself for ever with all the new poems and states of the nation that come out. he gradually begins to regard her appearance as “uncommonly intelligent” (70). In Mansfield Park Edmund is attracted to Mary’s “lively mind” (65) and feels that. Here it is worth mentioning that Nancy Armstrong is of a different opinion: she believes that Austen is not critical of Emma’s ignorance as a reader. ‘…you may take back that tiresome book she would lend me. When Elizabeth asks him why he 66 . This could be interpreted as Austen encouraging intelligence and literariness among women. he judges Elizabeth’s features as being “tolerable” (59). He is disappointed that Emma is not interested in steady reading (29) and wishes Little Emma to be “infinitely cleverer” (77) than her aunt. 50). when a man has known sensible women. Patricia Beer has suggested that Austen “consistently makes her male characters in speech put greater value on [women’s] minds” (1974:47) than on their beauty or domestic talents. Mr Darcy values a woman whose mind has been improved “by extensive reading” (Pride and Prejudice. In Persuasion Elizabeth Elliot is not only shown to be arrogant and selfish (16) but also to lack the patience to read: ‘Very well’. Instead. In Persuasion Frederick Wentworth pictures the ideal wife as having “[a] strong mind. and pretend I have read it through. Austen has Emma renounce her novelistic practices in order to purify women’s speech of all traces of writing (1987:150). Whereas. Lady Russell quite bores one with new publications. while Mr Knightley feels “[m]en of sense…do not want silly wives” (Emma.’ (190) The narrator in Emma seems wary of Emma’s preference for riddles as opposed to reading (54). at their first meeting.
In Persuasion she displays a familiarity with the poetry of Scott and Byron (90).21 In Northanger Abbey she adds the genre of Gothic novels to her list by mentioning Mrs Radcliffe (36). 231. exposes the fictionality of her characters (7. 227). 231). and draws attention to the art of writing novels (24-25. 234). Despite displaying this type of inevitable blind spot at times. refers to her god-like power as authoress (7. complex treatment of the theme of fiction” (89). while Mansfield Park affords her the opportunity to refer to Cowper (56). She shows that she is intellectual and well-read herself by referring to other writers in her novels. 7. 5. Austen on the whole appears to encourage women to read and study. and not to mention Mrs Inchbald. In addition to referring to other artists. She directly addresses the reader (Northanger Abbey. An implication which cannot be overlooked is that Austen. 234. In Mansfield Park she displays what Edward Said has called “a bit of meta-fictional impatience” (1993:91): 21 In Jane Austen: Mansfield Park (1988) Isobel Armstrong quotes an extract from “The Improper Play. Mrs Inchbald’s Lovers’ Vows” (12-19). 235). living and writing in the late eighteenth/early nineteenth century. Toril Moi states that any writer will inevitably carry with her some of the ideology according to which she was raised.Chapter Two: Women and Knowledge had fallen in love with her. Pope (164). 17. Shakespeare (134). 67 . he answers for the liveliness of her mind (388). and that there “will always be unstated blindspots. Katrin Burlin notes in “‘The Pen of the Contriver’: The Four Fictions of Northanger Abbey” (1975) that especially in this novel Austen “comes to terms with her art in a single. fundamental presuppositions and ‘pre-understandings’ of which [they] are unaware” (1985:44). 227. cannot get away from the patriarchal ideology that it is all about what men want and that it their right to choose. Austen focuses on herself as a writer and on the storytelling process.
Narcissus has always been self-aware. as seen in the still water-mirror – “the shadow of a reflected form”. 22 68 . there is much evidence to suggest that the novel has always been a self-conscious genre to some extent. impatient to restore everybody. Linda Hutcheon in Narcissistic Narrative: The Metafictional Paradox (1980) traces self-aware narrative as far back as Cervantes. has in fact been a characteristic of the novel since its inception” (1998:6-7). not kind. the novel has always displayed an element of self-consciousness: The “narcissistic” change is one of degree. the practice is as old (if not older) than the novel itself” (5). 23 In If Upon a Winter’s Night a Traveller (1993) Italo Calvino especially focuses on the process of writing novels. and to have done with all the rest. 466) Although such artistic self-awareness is usually not ascribed to nineteenth-century writers of fiction. André Brink writes that “what has so persistently been regarded as the prerogative of the Modernist and Postmodern novel…namely an exploitation of the storytelling properties of language. I quit such odious subjects as soon as I can.Chapter Two: Women and Knowledge Let other pens dwell on guilt and misery. not greatly in fault themselves. Richardson and Defoe (9). (13) John Fowles calls attention to the fictionality of his characters and to his god-like powers as author in The French Lieutenant’s Woman (1969). While metafiction is often associated with postmodern writers such as John Fowles22 and Italo Calvino23. (Mansfield Park. In Metafiction: The Theory and Practice of Self-Conscious Fiction (1984) Patricia Waugh argues that “although the term ‘metafiction’ might be new. She argues that even though it has become more evident in the postmodern era. he merely became more physically conscious of his own existence and charm. Similarly. to tolerable comfort.
While for Anne Elliot the “idea of Louisa Musgrove turned into a person of literary taste.’ said Darcy. and sentimental reflection. In Mansfield Park she gives a comic account of the amateur actors fighting over which piece to enact (124-139) and of Mr Rushworth struggling to learn his lines (168).Chapter Two: Women and Knowledge While Austen calls attention to the process of writing. Every thing nourishes what is strong already. was amusing” (149). she also seems to ridicule people who display sentimental attitudes towards literature.’ (90) In Persuasion we are told that Captain Benwick and Louisa “had fallen in love over poetry” (149). stout. an awareness of the general lack of interest in literature among late eighteenth-century women. 69 . albeit implicitly. I am convinced that one good sonnet will starve it entirely away. the narrator is clearly making fun of Benwick’s mawkishness when she says: …he shewed himself so intimately acquainted with all the tenderest songs of the one poet…he repeated. ‘Of a fine. the various lines which imagined a broken heart…and looked so entirely as if he meant to be understood. But if it be only a slight. that [Anne] ventured to hope he did not always read only poetry… (90) It appears that Austen in her novels creates. uncovers some of the ways in which women are often alienated from literary and textual production and engagement. and in examining a variety of responses to reading. and appears to encourage literariness among women. healthy love it may. In Pride and Prejudice Elizabeth ridicules sentimentalists like Darcy who consider poetry as “the food of love”: ‘I have been used to consider poetry as the food of love. thin sort of inclination. with such tremulous feeling.
and finds enjoyment in marrying off her daughters (51). Elizabeth especially is critical of Lydia’s “emptiness of mind” (258) and of her being “idle and vain” (241). Even though Isabella Woodhouse is said to be “slow and diffident” (29). What is more. Silly Women and Men Judith Lowder Newton believes that because Austen undermines the force of economic realities in her novels she makes “most women. Mrs Bennet shares Lydia’s disappointment and remembers “what she had herself endured on a similar occasion. in their helpless fixation on men and marriage. look perverse and merely silly” (1981:132). she features men who are just as silly. Though she creates many ignorant women. to 70 . five and twenty years ago” (256). When the regiment is to leave Meryton. His excessive servility (119) provides so much entertainment especially to Elizabeth and her father that one begins to understand why she believes “stupid men are the only ones worth knowing” (189). In the first chapter the narrator informs the reader of Mrs Bennet’s dull wit (53). Collins’s character illustrates that men can be just as silly as women. Mr Collins is laughed at for being “not a sensible man…[but] a mixture of pride and obsequiousness. Lydia Bennet resembles her mother in more than one way. Harriet to be “certainly…not clever” (21) and Miss Bates to have “no intellectual superiority” (17).Chapter Two: Women and Knowledge 6. We are presented with another stupid man in Emma. self-importance and humility” (114). She has a “weak understanding and illiberal mind” (262). Pride and Prejudice features many silly characters of both sexes. Austen counterbalances intelligent women with silly ones. if not more so. she often ridicules their silliness. Although. and by so doing seems to subvert the view that stupidity is solely a woman’s trait. In addition we are told that Lydia and Kitty “could talk of nothing but officers” (75). none of them is mocked like Mr Elton.
with cordial. 111-112). Elton seems a gentleman. it would seem that gender roles in the late eighteenth/early nineteenth century dictated that men were smart bell hooks has investigated the role women are expected to play and has noted that many women “passively absorb sexism. The narrator is clearly making fun of Elton when she relates his marriage to Miss Hawkins. it is not necessarily what she writes but what we may infer from her writing which remains of interest. makes him more laughable (133). and willingly assume a pre-determined sex role” (2000:87). now addressing all the young ladies of the place. a few weeks ago. fearless smiles. instead. A phenomenon that today is known as socially-reinforced gender roles24 seems to have been prevalent in Austen’s time. Although he has good intentions he is not exempt from stupidity when he fails to understand Marianne and yet laughs “as heartily as if he did” (43). and was just the happy man he ought to be. he had not thrown himself away – he had gained a woman of 10. His marrying into some money does not enhance his reputation but.Chapter Two: Women and Knowledge many. Austen reveals what a silly man he really is. Likewise. talking only of himself and his own concerns – expecting to be congratulated – ready to be laughed at – and. Once again. Sir John is presented as silly because he is overly-gallant and friendly and perseveres to a point “beyond civility” (28). ostensibly from his point of view: …the story told well. Judging by her novels. to whom. (137) In Sense and Sensibility the narrator seems critical of women like Mrs Jennings and Mrs Palmer for finding their solace in gossip and visiting. Margaret McFadden has pointed out how gender roles “impose second-class status on women” (1997:794). he would have been more cautiously gallant. and especially for embarrassing friends and acquaintances by saying silly things (58-62. 24 71 . The women however are not the only ones to bear the brunt.000£ or thereabouts…He had caught both substance and shadow – both fortune and affection.
1984:303) and extremely silly. to some extent. moderation. such as Helen Crowley and Susan Himmelweit. The fact that Croft and Wentworth are ‘unable’ to distinguish between the two sisters. Luce Irigaray claims in Speculum of the Other Woman (1974) that women are denied their subjectivity because they subject themselves to objectivization (133). and both fall in love with Frederick Wentworth (Persuasion. In Persuasion she seems to reverse the typical masculine and feminine role: while Sir Walter Elliot is described as silly and conceited (6-7). In the same novel. as subjects and not objects” (1992:183). Wesely. Whereas. 58-64). Alison and Schneider have suggested that the “female body is…fetishized in its reduction to an object of (hetero)sexual desire” (2000:211). while Lady Elliot lived.Chapter Two: Women and Knowledge and women stupid. Perhaps. making them either the unsuspecting victim or the uncritical perpetrator of the male gaze. Feminist scholars. and economy” (10). the silliness of some of Austen’s characters is related to the rigid gender roles they are forced to play out. Admiral Croft seems to be just as confused by their resemblance when he says that a person can “hardly know one from the other” (83). Henrietta and Louisa both aim at finding a husband. have consistently called upon women to acknowledge this practice and to “claim their status as persons. his wife is said to have been “of very superior character to any thing deserved by his own” (6). By saying men and women are stupid at times Austen manages to subvert rigid gender roles. Sir Walter displays little financial sense and incurs great debts. has the possible implication that these women are not regarded as individuals but are reduced to objects of male desire. as people capable of self-definition. 72 . “there had been method. But the sisters are so much alike that it is “quite doubtful” (67) which of the two he prefers. the Musgrove sisters are shown to be incapable of serious thought (Halperin.
48). on a sopha. Sir Thomas realises that he is “an inferior young man as ignorant in business as in books. Catherine notices his shallowness and concludes with a “bold surmize” (55) that his company is not completely agreeable. with opinions in general unfixed. capable of retaining and uttering only a couple of standard sentences (18.Chapter Two: Women and Knowledge Mrs Allen is a good example of a woman who has not yet discovered her own subjectivity. and spends her days “sitting. Rushworth manages to confuse himself when trying to please Lady Bertram (55) and struggles enormously to learn his forty-two speeches for the play (168). doing some long piece of needlework” (18). pertain to women only. he would be a very stupid fellow” (39). 23). She is known for her “vacancy of mind. Her languor not only makes her incapable of remembering anyone’s dress or place at supper during the ball the night before. Edmund Bertram feels that if Rushworth “had not twelve thousand a year. nicely dressed. Sir Thomas’s own wife is characterized by “incompetency and languor” (342). and is presented as almost dysfunctional. and incapacity for thinking” (Northanger Abbey. In Mansfield Park Mr Rushworth is depicted as an extremely silly man. decisive sentence of praise or condemnation on the face of every woman they met… (35) While the narrator refers to Thorpe’s discourse as “rattle” (53) and as “idle assertions and impudent falsehoods” (53-54). to nothing more than a short. Being silly does not. it also prevents her from making interesting conversation (286-287). Lady Bertram shows no interest in anything much. and without seeming much aware of himself” (201). The narrator is clearly irritated with John Thorpe for making unintelligent remarks: [Mr Thorpe’s] discourse now sunk from its hitherto animated pitch. Ironically. 73 . however.
74 .Chapter Two: Women and Knowledge From Jane Austen’s work we can deduce that women and men in the late eighteenth/early nineteenth century were subjected to rigid gender roles. it could be argued that she dismisses the perception that femininity is aligned with ignorance and masculinity with intelligence. In the following chapter I shall be looking at what Austen’s work reveals about women’s role within marriage. Because Austen presents the reader with foolish women and men. she manages to challenge the view that women are intellectually inferior to men. By doing so. By showing how stupidity can manifest itself in either sex. her work subverts the rigidity of patriarchallyconstructed gender roles.
1995) 75 . “Another Cup Of Coffee”.Chapter Three: Women and Marriage Chapter Three – Women and Marriage Introduction And she pours herself another cup of coffee As she contemplates the stain across the wall and it's in between the cleaning and the washing That's when looking back's The hardest part of all And she always did her best to try and please him While he always did his best to make her cry And she got down on her knees to stop him leaving But he always knew one day he'd say goodbye Where are your friends Where are your children Is this your house Is this your home Does nothing ever last forever Does everybody sleep alone And he tears the business tags from his old suitcase As he packs away the pieces of his life They all love him but they always try to change him That's what happens when a girl becomes a wife And she pours herself another cup of coffee As the pictures leave a clean space on the wall and it's in between the leaving and the loving That's when looking back's The hardest part of all Where are your friends Where are your children Is this your house Is this your home Does nothing ever last forever Does everybody sleep alone Don't look back Don't give up Pour yourself another cup (Mike Rutherford.
primogeniture. There seems to be. Sarah Gamble is in agreement when she maintains in The Routledge Critical Dictionary of Feminism and Postfeminism (1999) that marriage remains an “enduring institution…a form of compulsory heterosexuality. to some extent at least. patriarchy – which patently do not serve her heroines well” (1988:xxiv). A possible reason for contemporary women favouring marriage may be found as far back as Austen’s time. Judith Lowder Newton argues that Austen’s work shows an 76 . general consensus among critics that Austen’s novels deal with marriage. and since husbands seem to receive more psychological support from their wives than they return (545). marriage in most cases is an institution which favours men. Much recent feminist scholarship focuses on the fact that marriage is a patriarchal institution of entrapment and that it more than often leaves women feeling unfulfilled. and the means by which the oppression of women is perpetuated sexually. André Brink argues that Austen shows how marriage describes women’s fortune in Emma (1998:125). Stevi Jackson argues that marriage “binds many women into unequal relationships with men…[and that it] is linked to wider social and economic structures and is sanctioned by the power of the state” (1993:182). Margaret McFadden claims in Ready Reference: Women’s Issues (1997) that since wives are often expected to do the housework as well as maintain a full-time job. economically.Chapter Three: Women and Marriage A song like the one quoted above by popular artist Mike Rutherford illustrates that to many it remains a mystery that women opt to get married. and Claudia Johnson believes “Austen to expose and explore those aspects of traditional institutions – marriage. Looking at what Austen’s fiction tells us about women and marriage could help us understand the legacy of women wanting to get married. Nancy Armstrong feels Austen’s novels “bring to culmination a tradition of ladies fiction that concentrated on the finer points of conduct necessary to secure a good marriage” (1987:134). and socially” (269).
Austen’s novels illustrate some of the reasons that most women of that time decided to get married. I shall examine the notion that Austen may be suggesting perfect matrimonial bliss to be highly improbable. Basing her argument on Austen’s letters. the constraint on women to marry was very considerable. 1994:102) are not restricted to repressing women’s intellectual growth (as I show in the first chapter). was an economic necessity for women. 1. As Judith Lowder Newton (1981:119-123) has shown. she considers Austen’s personal attitude towards the pressure on women to marry as “amused and uncomplaining” (1981:123). Mary Evans argues in Jane Austen and the State (1987) that Austen’s work reveals marriage to be enforced upon women by the type of society they live in: Jane Austen…vividly represents the point which many social historians have made: that marriage. I shall also investigate Gilbert and Gubar’s contention that Austen conceals her ideas on matrimony by ending her novels with having the hero and heroine live happily ever after (1979:169). Far from being a matter of romantic or personal choice. Marriage as entrapment The effects of “an education which fitted women exclusively for marriage and the pleasures of men” (Alexander. and that her fairytale endings should not be taken seriously. in the eighteenth and nineteenth centuries. (46) In this chapter I shall examine the ways in which Austen’s work reveals the malefavouring social and economic system women were living in.Chapter Three: Women and Marriage awareness of the necessity for women to marry. women did not have access to the same level of education 77 . but have far-reaching consequences. It will be shown that this system often enforced marriage on women and rendered them passive recipients of male largesse.
Isabella seems to be oblivious to her husband’s meanness. and discontent of her husband gave her no pain. (1987:114) Nancy Armstrong points out that eighteenth-century Puritan treatises on marriage did not only claim sovereignty for the husband over his home. many women found they had less power than before since the man was traditionally held to be master over his wife.in the nineteenth century. His indifference does not seem to bother her in the least but rather it appears to amuse her: The studied indifference. within marriage. the law defined married women as the property of their husbands. but also “represented the family as a self-enclosed social unit in whose affairs the state could not intervene” (1987:18). (109) 78 . Women therefore often had to submit to patriarchal institutions such as marriage if they wanted to survive financially. Since they could not support themselves financially. she was highly diverted.. In the same way Mrs Palmer patiently endures her husband’s occasional rudeness in Sense and Sensibility.Chapter Three: Women and Marriage as men. In Emma we are confronted with male power within the marital state. What is worse. Ironically. he often makes rude and hurtful remarks (73. autonomous subjectivity. 81). denying them the benefits of legally constituted. and when he scolded or abused her. as Chris Weedon has noted: . We are told that while Emma “was quick in feeling the little injuries to Isabella…Isabella never felt [them] herself” (73). Mr John Knightley seems to be aware of his own powerful position as patriarchal head of the family. As a result they were left economically and socially powerless. and were not expected to have their own career.. insolence. most middle-class women realised the importance of marrying a man who had either inherited some money or who had a profession that did not pay too badly. Irritated by his wife’s hypochondriacal and fragile nature.
may be teazed. women have felt the consequences of being rendered physically powerless. Being a man enables him to own a carriage and to come and go as he pleases. The narrator states that Catherine had “no power of getting away. and kept at a distance from those she wants to be with. as not to be able to spend a week with his father. but one cannot comprehend a young man’s being under such restraint. my emphasis). It also gives him the power to keep on driving when Catherine pleads with him to turn back. We see how John Thorpe abuses his power when he deters Catherine from keeping her engagement with Elinor Tilney. while women are ‘fixed’ by their economic situation. as Linda 79 . A young woman.Chapter Three: Women and Marriage In Pride and Prejudice Elizabeth professes she does not know “any body who seems more to enjoy the power of doing what he likes than Mr Darcy” (216. if she falls into bad hands. [and] was obliged to give up…and submit” (75). they can enter a neighbourhood and presumably leave it at will” (1981:120). In Emma the narrator draws our attention to women’s immobility by having Emma react in disbelief to Frank Churchill’s claim that it is impossible for him to spend a week with his father: …one can hardly conceive a young man’s not having it in his power to do as much as that. Austen seems to comment on the forceful nature of men’s power when she refers to “the violence of such noblemen and baronets as delight in forcing young ladies away to some remote farmhouse” (6). She states that “[s]ingle men appear at liberty. Judith Lowder Newton comments that the first two sentences of this novel illustrate the mobility men used to have. (95) In Northanger Abbey we see that women are physically rendered powerless when men will not allow them to do as they wish. but it is only recently that women have started speaking openly about it. if he likes it. Across the ages.
Germaine Greer points out that often in contemporary society “husbands are meant to take over the role of fathers and assume authority over their wives” (1999:283). This is partly owing to concerted efforts by dedicated feminist activists. while Linda Schmittroth and Mary Reilly McCall argue that in the past. (1999:167) Violence against women has received so much attention in the last two decades that.Chapter Three: Women and Marriage Schmittroth and Mary Reilly McCall report (1997:446). authorities often turned a blind eye to domestic violence owing to “the old and mistaken notion that the man is master of his family and his home” (1997:446). feminist scholars in the current century reveal its damaging effects in an effort to eradicate it altogether. One could say that. it has “increasingly been seen world wide as an important public policy issue” (2000:35). Janet Saltzman Chafetz argues that women today lack power since they are “relegated to the subordinate world of home. as Barbara Schulman points out in “The Unsettling Subject of Violence in Women’s Lives: Encouraging Notes from the Classroom Front” (1999): Nearly three decades of feminist activism and research have demonstrated that some form of gender-related violence is present in the autobiographies of what may be a majority of women around the globe. Wesley. Allison and Schneider believe domestic violence against women to be “a social problem born of patriarchy” (2000:211). although domestic violence is not a new phenomenon. according to Paula Wilcox. Whereas Austen only touches on the tremendous domestic power men have. contemporary society is much more aware of its existence and sensitive to its devastating effects than society in Austen’s time (446-447). For these reasons amongst others. recent feminist scholarship has identified marriage as a means of subjugating women and leaving them weak. 80 . a means by which men maintain control over women.
which are crucial to the maintenance of women’s general subordination and economic dependence. (1992:33. as Helen Tierney reports in Women’s Studies Encyclopedia (1999:892). men have. Patricia Waugh believes gender roles are “a mode of social control” (1989:9) for men whereby they might gain autonomy and marginalise women. and family” (1999:156). reinforced the metanarrative that being a mother and a wife is ‘natural’ for women. In the nature of the institution women are required to surrender that autonomy essential to the practice of any art. is hindered by popular (male) discourses which dictate women’s role as mother and wife. Araújo. in turn. as Rosalind Miles points out: Marriage has in general posed a major threat to the flowering of female talent. The work of feminists to eliminate oppression within marital relations. Women are.Chapter Three: Women and Marriage domestic labour. some feminists regard the abolition of marriage as the only way to end women’s oppression. For these and other reasons marriage today is generally considered to restrain women. and the social beliefs which support them. as Arnot. Helen Crowley and Susan Himmelweit are of the same opinion: …it is women’s mothering and nurturing activities. Since male authority is so deeply entrenched in patriarchal society. but to all men through political and economic dominance” (2000:152). ensures male dominance. (1987:22) 81 . motherhood. 1987:121). albeit sometimes unconsciously. Deliyanni and Ivinson point out. Coaxing women into wife.and motherhood means keeping them in a subservient position and. “subordinated not just to individual men through the marriage contract. my emphasis) Since “power is tolerable only on condition that it mask a substantial part of itself” (Weedon.
and the reason she must marry is that the family inheritance has been settled on a male. She must marry. to escape the confinement at home.Chapter Three: Women and Marriage Whereas contemporary feminist scholars explicitly link women’s powerlessness to marriage. Elaine Showalter reminds us that in the late eighteenth century women “were not accustomed to choosing a vocation [since] womanhood was a vocation in itself” (1977:21). From her writing it can be inferred that marriage is enforced by patriarchy and its laws: women feel compelled to get married in order to have economic security. we need to reread Austen from a feminist point of view in order to infer that women were weakened by patriarchy and by the institution of marriage. simply so that they may survive in a male-dominated world. she must marry with an eye to money. 1. While it was not considered proper for women to have a 82 . Reading Austen from a feminist perspective means being made aware of the necessity for women to get married. as Judith Lowder Newton (with specific reference to Pride and Prejudice) explains: Elizabeth Bennet has no decent fortune whatsoever. (1981:120) The “conditions of economic life” in Austen’s time included an inequality of career opportunities between men and women. Sandra Gilbert and Susan Gubar believe Austen’s work shows that “women have been imprisoned more effectively by miseducation than by walls and more by financial dependency…than by any verbal oath or warning” (1979:135). or even to acquire society’s approval.1 Economic Security The economic conditions of Austen’s time upheld women’s oppression. It would be hard to make a more central point of the fact that the conditions of economic life favoured men and restricted women. in short.
Chapter Three: Women and Marriage career. and then she had to be totally subservient to her husband. 1930:80). claims that her three sons are all “beloved and respected in their different stations” (19). Jane Austen indicates she herself is “fully alert to the social miseries and injustices of her age – including the acute miseries of the governess situation” (1986:186) when she describes the bleak future awaiting Jane the day she will no longer be in the Campbell’s care and will have to eke out an 83 . then. From Austen’s novels we can construe that men and women did not have equal access to career opportunities. while mentioning only the beauty of her daughters. then her life became totally useless. 1987:236. If she did not marry. Nancy Armstrong mentions that although in Austen’s day the governess “belonged to the cast of respectable women…[she] was commonly represented as a threat to the well-being of the household” (1987:78-79). Judith Lowder Newton mentions that Austen illustrates that men “no matter how hapless and undeserving. must be given every opportunity to earn their way [while] women…are prepared for nothing but display” (1981:119-120). As Tony Tanner has noted. it was almost impossible for women to achieve financial prosperity on their own. As a result they were obliged to marry: The only opportunity for achievement for a middle-class woman was to marry and have children. In Sense and Sensibility Edward Ferrars lists the church. and while “almost the only way in which a gently born woman could earn her living was by teaching” (Cruse. the law and the navy as some of the occupations he as a man can choose from (99). must be provided for. being an orphan. men had a number of occupations to choose from. (Potter. is left with no choice but to become a governess. In Austen’s time. for it was not considered proper for a respectable woman to have a career. Jane Fairfax. my emphasis) We see how circumstances can render women powerless and how a woman’s life can become “totally useless” in Emma. and in Northanger Abbey Mrs Thorpe.
He points out that if she refuses him and gets no other offer of marriage. on Mr Bennet’s demise. which generally left the bulk of the estate to the eldest son. peace and hope.Chapter Three: Women and Marriage existence (Emma. on a distant relation” (75). The narrator seems to wonder at fate’s fickleness as Miss Campbell manages for no apparent reason to secure a comfortable future by marrying a wealthy man. she is likely to end up poor and forlorn (Pride and Prejudice. 84 . to penance and mortification forever. turn the Bennet family out of their own home (106) reinforces the tremendous power patriarchy gives men. The mere fact that Collins may. Sense and Sensibility demonstrates the injustice of the inheritance laws. while Jane faces having to be paid a pittance and earning little respect as governess. and retire from all the pleasures of life. (124) According to Sandra Gilbert and Susan Gubar. It is clear that Collins realises the power with which patriarchy has endowed him when he proposes to Elizabeth. With the fortitude of a devoted noviciate. of rational intercourse. and which necessitated that women marry. That the narrator has empathy with her is clear: [Jane] had long resolved that one-and-twenty should be the period. equal society. 124). It is possible that Austen comments on the senselessness of a convention which would have John Dashwood as the only son inherit almost everything despite the fact that he is already wealthy and that his sisters are in far greater need of their father’s money (1-2). she had resolved at one-and-twenty to complete the sacrifice. Jane Austen explores “the specific ways in which patriarchal control of women depends on women being denied the right to earn or even inherit their own money” (1979:136). Roger Gard justifiably refers to Collins in Jane Austen’s Novels: The Art of Clarity (1992) as a symbol of “the reality of male oppression” (100). In Pride and Prejudice the Bennet girls are in a financial predicament since their father’s estate is “entailed in default of heirs male.
for example. and when Charlotte Lucas marries Collins since it is “the only honourable provision for well-educated young women of small fortune” (163). Mrs Ferrars would never approve of a match between her and Edward (129). unable 85 . In Northanger Abbey it is possibly Isabella Thorpe’s small fortune (108) which makes her so determined to find a husband.Chapter Three: Women and Marriage 150-151). however. and even threatens to disinherit him (258-259). must be in want of a wife” (51).almost succeeds in laying her hands on the Tilney fortune by marrying Frederick Tilney. because she has no fortune. After having secured James Morland she . If she had none and failed to find a rich enough husband to provide for her. The plight of the single woman is illustrated. In Sense and Sensibility a woman’s eligibility is defined in terms of her fortune. Mrs Ferrars is so determined that her sons marry well and not be drawn in by any woman (21) that she tries to persuade Edward not to marry Lucy. It could be argued that Austen’s fiction demonstrates that a woman’s inheritance can make or break her. “living in a very humble way. It thus gradually becomes apparent in this and Austen’s other novels why it is “a truth universally acknowledged. Juliet McMaster notes in “Emma Watson: Jane Austen’s Uncompleted Heroine” (1994) that Austen’s novels draw our attention “to the unjustly difficult plight of the single woman who is not in possession of a good fortune” (227). prevents the marriage from taking place.disappointed with his four hundred pounds (121) . the chances were she would end up like Mrs Smith. Persuasion illustrates the sad reality that a girl needed a dowry in order to attract good offers of marriage. Lucy Steele realises that. On account of her “want of consequence and fortune” (192) the General. in Pride and Prejudice when Mr Bennet firmly states Lydia will not be “an object of prey” (258) to any man since she is of no great fortune. that a single man in possession of a good fortune.
“an institution involving lifelong and serious obligations” (16). The middle sister (Mrs Norris) had married “on a narrower income than she had been used to look forward to” (6) so that strict economy in her marriage was necessary. marriage had to make financial sense. while a very young girl. the future baronet. circumstances should have made so much” (414). as soon as she had known [her cousin] to be. William Elliot. While the eldest. made the mistake of marrying a man with neither education. realises that it is her duty to marry her cousin in order to keep the money in the family: She had. Fanny compares the destinies of Lady Bertram and her own mother. a reasonable and a poor match. Not only 86 . Throughout Mansfield Park Austen seems to create an ironic awareness of the reality that it is every woman’s duty to marry as well as she can. in the event of her having no brother. Elizabeth. The match between Maria Bertram and Rushworth is viewed as advantageous by Sir Thomas.Chapter Three: Women and Marriage even to afford herself the comfort of a servant. and wonders at the fact “that where nature had made so little difference. she had to endure poverty and hardship (1-3). In Mansfield Park we see that women’s destiny often depends on how well they marry. Maria. meant to marry him… (8-9) Economic consideration ensured that marriage in Austen’s time was. Marriage is seen by some of the characters as a business transaction from which both parties should benefit. Since many women were not economically provided for. As a result. as David Cecil remarks in A Portrait of Jane Austen (1978). Fanny. fortune nor connections. had the good fortune of marrying Sir Thomas and was raised to the rank of a baronet’s lady (1). and of course almost excluded from society” (136). her sisters were not so lucky. The Elliott sisters could easily share Mrs Smith’s fate since their father’s estate is to be inherited by their cousin. Sir Walter’s eldest daughter. The three Ward sisters illustrate the consequences of a good. the youngest.
87 . While Sir Thomas tells Fanny that “it is every young woman’s duty to accept a very exceptional offer [such as Henry Crawford’s]” (336). Since she believes a “large income is the best recipe for happiness” (215).2 Escaping Home Judging from Austen’s novels it would seem that young women often married in order to escape the confinement at home. but also add “respectability and influence” (203) to the Bertram name. not the only reason women decided to marry. however. and thus the need to escape from home. Neither would she ever consider marrying Edmund since he would most probably stay a penniless clergyman his whole life (Donoghue. motivated women to marry. 1968:43). the low wages of governesses. we are told that “[m]atrimony was [Mary Crawford’s] object. In Northanger Abbey Eleonor Tilney’s marriage to a man of 25 Marilyn Butler mentions in Jane Austen and the War of Ideas (1987) that Austen exposes “[women’s] terribly limited opportunities for employment. [and] the wife’s loss of property rights” (127). In the next section I shall examine the ways in which stifling parental authority. 1. The “true London maxim. Mary argues that “everybody should marry as soon as they can do it to advantage” (43). A feminist reading of Austen draws our attention to the economic injustices suffered by women and the consequences thereof. that everything is to be got with money” (59) is illustrated when Maria agrees to marry a man she finds terribly annoying and dull.25 One of the consequences of the male-favouring economic and social system of Austen’s time was that women felt forced to marry. Economic dependency was. provided she could marry well” (41).Chapter Three: Women and Marriage would it ensure Maria of a large income (37) and Rushworth of a beautiful and accomplished wife (37-38). she cannot comprehend how Fanny could reject Henry.
In the same novel Brandon’s cousin Eliza is forced by her guardian to marry his eldest son (198-199). for instance. Maria Bertram is “prepared for matrimony by an hatred of home” (Mansfield Park. 1988:26). 88 . In Pride and Prejudice Elizabeth and Jane would be spared the embarrassment of their mother’s tactlessness if they were to be married (141-3.’ Elinor. calmly replied – ‘The lady. For Anne Elliot marrying means escaping the “imprisonment” (Persuasion.’ said Mr Dashwood. after a short pause. In Sense and Sensibility Mrs Jennings decides that her daughter should not marry Colonel Brandon (113) but Mr Palmer. In Austen’s time middle-class parents had tremendous power over their children. 204). The Concise Oxford Dictionary defines a bully as “a person who uses strength or power to coerce others by fear”. especially their daughters. would be forced into marriage by fathers and mothers who cared less about their daughters’ needs or wishes (Johnson. I suppose.’ (289) The number of patriarchal bullies that feature in Austen’s fiction focuses our attention on the enormous power men (and especially fathers) used to have.Chapter Three: Women and Marriage her choice is seen as a “removal from all the evils of such a home as Northanger” (234). Young women. 123) at home brought on by her father’s favouring of Elizabeth. 355). Similarly. ‘of Robert’s marrying Miss Morton. smiling at the grave and decisive importance of her brother’s tone. In Emma we see that Jane Fairfax and Frank Churchill are prevented from getting married while Mrs Churchill lives (301). Elinor cannot help but laugh at the absurdity of parents who see women as objects that are to be pawned and swopped at will: ‘We think now. When the wealthy Miss Morton is traded off between the Ferrars brothers. while Lucy Steele and Edward Ferrars keep their engagement a secret for fear of Edward’s mother (127-129). has no choice in the affair.
‘What will become of us? what is to be done now?’ It was a terrible pause… (176) After returning home. for example. Even when he is abroad his family is governed by his rule. every other heart was suggesting. Lady Bertram wants him to wait until his father returns so that “Sir Thomas might settle it all himself” (35). it is “rather from submission…than conviction” (375) that Lady Bertram agrees. when the young people want to put on a play.Chapter Three: Women and Marriage and it is this coercive force that Austen’s work exposes. The narrator comments that “[u]nder his government. Similarly. The narrator seems to use this opportunity to criticise all fathers who do not wish to love their daughters but only to govern them: 89 . His daughters are also made aware of his power from an early age and are said to be “in greater awe of their father” (11) than their brothers are. they know their father would not approve. my emphasis). When he persuades his wife to let Fanny visit her family. It is especially the women in the family who suffer Sir Thomas’s tyranny. In Mansfield Park the authority men automatically assume as head of the family is neatly illustrated by Sir Thomas. Sir Thomas quickly re-establishes his powerful position when he resumes “his seat as master of the house at dinner” (192). Mansfield was an altered place” (197. When he leaves for Antigua they are delighted to be freed from his tyranny for a short while. even though they try to convince themselves otherwise (128-130). Being the head of the family entitles him to make all the decisions. When Edmund wants to buy Fanny a horse. When Sir Thomas unexpectedly arrives at Mansfield Park they realise that it means the end of their show: …but every other heart was sinking under some degree of self-condemnation or undefined alarm. When Yates comes to visit he professes to have “known many disagreeable fathers before…but never…[one] so infamously tyrannical as Sir Thomas” (193).
but for their want of it. The narrator comments on his powerful hold over Fanny when she remarks that his was no ordinary advice but “the advice of absolute power” (285). Henry Crawford believes Sir Thomas “to stand in the place of her parents” (316). Mary Crawford as an outsider immediately notices the power Sir Thomas has over his family. ‘Do you remember Hawkins Browne’s “Address to Tobacco”. Mrs. I will parody them – Blest Knight! whose dictatorial looks dispense To Children affluence. Although Fanny is not his daughter.’ (164) 90 . (31) Because they fear their father. Maria especially is pitied “for to her the father brought a husband” (109). not for their sorrow. the month of his return to England is described as a “black month” (109) for the girls.Chapter Three: Women and Marriage The Miss Bertrams were much to be pitied on the occasion. She fears her uncle from the very start (14) and is probably more relieved than her cousins when he leaves for Antigua (31). Grant? Everything seems to depend upon Sir Thomas’s return. to Rushworth sense.’ said Mary. and indeed he expects her to obey him at all times (279). after a pause. She makes fun of his powerful hold when talking to her sister. to Parsons sense. in imitation of Pope? Blest leaf! whose aromatic gales dispense To Templars modesty. possibly because she realises that his power is patriarchally-engendered: ‘Sir Thomas is to achieve many mighty things when he comes home. She consequently blames him for Edmund’s decision to become a clergyman (251). Will not that do. Patriarchy has made him powerful.
140). Austen’s novels do not only depict fathers and husbands who abuse their power but also show that even all-important men like Sir Thomas and the General are at times rendered powerless. When she and Eleanor disobey him as they snoop around the forbidden chambers. who consider it their sole right to be “happy and indulgent” (187) at home. While all Sir Thomas’s clout cannot re-establish the Bertram family name when Maria runs off with 91 . General Tilney similarly abuses his power as head of the family. and dictates to them whom they should marry (192-193. Edward Said makes the point that “Sir Thomas’s infrequent trips to Antigua as an absentee plantation owner reflect the diminishment in his class’s power” (1993:94). She is not allowed to make any decision on her own and is even told when to go for a walk (161) and which route to take (163). Catherine is filled with “terror upon terror” (176) at the sight of the General himself in the gallery. 228). Catherine quickly realises that the General is not to be contradicted and grows “every moment more in awe of him” (140). He is constantly “a check upon his children’s spirits” (Northanger Abbey. and who enjoy being the one “on whom all [depends]” (435).Chapter Three: Women and Marriage When Austen later on has Mary say that Sir Thomas “is just what the head of such a family should be” (363) it is likely that she is being critical of men like himself who take their resolutions “in quiet independence” (255). that [her] real power is nothing” (209). Once at Northanger. his departure for London gives her “the first experimental conviction that a loss may be sometimes a gain” (203). Eleanor especially bears the brunt of her father’s tyranny. she obeys his orders. Eleanor realises that she is “but a nominal mistress of [Northanger]. While his presence appears “to lengthen…two hours into four” (140) and makes her feel fatigue (151). Because she in all probability fears her father and feels powerless.
It would be incompatible with what she owed to her father. would not do for her. he always manages to have his way. General Tilney is thwarted when Henry marries Catherine. In Persuasion we are presented with a less forceful (but just as effective) bully. and with what she felt for him. induces Anne to call off the engagement. Claudia Johnson believes Austen’s commentary on 92 . Ironically. Despite his delicate disposition. He has such a hold on Emma that she believes her future not to belong to her alone: Marriage. When he decides the family should move to Bath. That women had a limited choice when considering a partner for life can be seen in Austen’s novels. Anne has no say in the matter and is forced to abide by his decision (14). Being made aware of the immense power men have means. One could say that Sir Walter Elliot renders Anne powerless by what he does not do. Since almost the only way a woman could escape her parents’ authority was to marry the man they had chosen for her. even if she were asked by Mr Knightley. She would not marry. Together with Lady Russell’s opposition.Chapter Three: Women and Marriage Crawford and Julia with Yates. (314) Claudia Johnson mentions that Austen was living in a society which “[prohibited] women from making choices about their own lives” (1988:14). his “professed resolution of doing nothing for his daughter” (24). Austen comments tongue-in-cheek that it is up to the reader to decide whether “the tendency of [her] work be altogether to recommend parental tyranny or reward filial disobedience” (Northanger Abbey. women had less free will than is generally assumed. Nothing should separate her from her father. women who married in order to get away from home inevitably subjugated themselves to a substitute form of authority. in fact. in most cases. should she marry Wentworth. being made aware of women’s powerlessness. Although Mr Woodhouse in Emma loves his daughter he loves himself even more. 236).
an attack on ideological state apparatuses (a concept borrowed from Louis Althusser to which I shall return later in this study) which enable men to abuse their power: Considered from within the compelling rhetorical structures conservative novelists build. In Sense and Sensibility Lucy Steele is secretly married to Robert Ferrars (358). to suggest. It can be argued that. possibly a consequence of women trying to escape the confinement at home. The Bertrams are dealt a double blow in Mansfield Park when Maria (a married woman) runs off with Henry Crawford (444-445). in fact. (1988:10. the only way of achieving affluence and thereby society’s approval: 93 . and brothers themselves may be selfish. Though these women believe they have escaped the confinement at home they have in fact merely exchanged it for the enduring confinement of marriage. sons. while Lydia Bennet (Pride and Prejudice) causes her family much embarrassment by eloping with Wickham (291-294). and that the “bonds of domestic attachment” are not always sweet. frequently does.3 Approval and Acknowledgement For most women in Austen’s time marriage was. among others. and by featuring women who elope. as Sandra Gilbert and Susan Gubar have noted. is to attack the institutions which make morality possible and so to contribute to the dissolution of the government. that fathers. 1. and Julia elopes with Yates (447). bullying and unscrupulous. as Austen.Chapter Three: Women and Marriage patriarchal bullies is. by introducing fathers who bully their daughters into marriage. my emphasis) Austen’s novels feature a number of elopements. Austen depicts a society which forces young women from one institution into the next.
one might begin to understand where the stigma surrounding spinsterhood comes from. In Persuasion the narrator remarks tongue-in-cheek that “Mary had acquired a little artificial importance. The average age for women to marry increased. handsome. ‘singlehood’ included feminists. unmarried mothers. In Emma our attention is drawn to the fact that women often need to be married in order to enjoy esteem when Emma jokingly considers getting married so that she no longer has to stand second to Mrs Elton (245). (1979:127) In Mansfield Park Henry Crawford views marriage as the only way for women to acquire “happiness. she would have gained “consideration among her friends” (361). In Sense and Sensibility Elinor states that if Lucy had married Edward. If one considers the important role marriage used to play in women’s acceptance in their society. lesbians.Chapter Three: Women and Marriage [Austen’s] implication is clear: marriage is crucial because it is the only accessible form of self-definition for girls in her society. 26 94 . honour. As the women’s movement gained momentum. In addition. Though today it may be quite ‘normal’ for women to remain single26. and dignity in the world” (301). and those women who were in relationships but who chose not to marry. the narrator seems to be ironic when she comments that Miss Bates “enjoyed a most uncommon degree of popularity for a woman neither young. by becoming Mrs. Just as her mother gained prestige by marrying Sir Thomas and becoming Lady Bertram (1). contemporary Margaret McFadden reports that “[t]he 1960s saw a rise in the number of American women who remained single. Maria intends becoming Rushworth’s wife in order to achieve “fortune and consequence” (204). nor married” (17). while Isabella Thorpe in Northanger Abbey imagines how marriage would win her “the gaze and admiration of every new acquaintance at Fullerton” (111). Charles Musgrove” (7). rich. comfort. and the divorce rate rose dramatically” (1997:805).
Austen is possibly showing that even strong-willed girls do not live in isolation. Anne and Wentworth. (1998:125) 95 . many women feel compelled to marry. but need to adhere to social conventions in order to survive. 1. According to Gamble. and a potential threat to society in her freedom” (1997:819). marriage describes her horizon. Although some feminists have tried to reclaim the image of the spinster. Many women see marriage as the easiest means of integration into the community. Elinor and Edward. 1999: 312-313). This has been noted by André Brink: …no amount of ‘success’ can essentially alter a woman’s fortune: even for Emma with her fierce if often misguided and deftly ironicised sense of independence. women who remain single are often regarded as not fully integrated into the community. still need to marry in order to manage financially and be accepted socially. incapable of finding a husband or respectable work. she remains. Emma and Knightley. as Sarah Gamble reports (1999:269). to be culturally stereotyped as “the unchosen woman who is unattractive to men. no matter how strong or independent they are. all Austen’s heroines get married: Elizabeth and Darcy. For fear of being labelled as such. and have even been described as “wastage” (269). according to Margaret McFadden. Fanny and Edmund. By making her heroines marry.4 Surviving Patriarchy In keeping with the prerequisite that most women. Marianne and Brandon are all shown to tie the knot. even if it means being placed under male authority. Catherine and Henry.Chapter Three: Women and Marriage women often feel pressurized to marry in order to avoid being associated with spinsterhood (Greer.
Similarly. does not openly declare her love for Frederick Wentworth but merely hints at it when she is talking to Captain Harville and is certain that Wentworth is listening (Persuasion. they know that an open defiance would have them ostracized. she patiently waits for him to take it up again (356-357). 352-356). Isobel Armstrong has referred to “Jane Austen’s delicate and probing exploration of the psychology of the dependent woman and the social and emotional constraints upon her” (1988:10). Fanny shares her predicament because she has to wait for Edmund to forget Mary Crawford. This may not indicate that she believes this is the way things should be done. In Sense and Sensibility Elinor Dashwood keeps her feelings for Edward a secret until he declares his love for her (37. at times. Elizabeth. or a great deal better ” (475). 193) as she impatiently waits for Henry Crawford to declare himself. Jane has to infer from Bingley’s absence that he has lost all interest in their relationship (184). does not approach him when she realises that she has erred but waits for him to propose (374-375). Austen’s heroines can get away with covertly challenging some of patriarchy’s traditions. and to consider whether “a very different kind of woman might not do just as well.Chapter Three: Women and Marriage While. We also see other women waiting for men to make the first move. for instance. 205-207). We see Austen’s women characters adhering to convention not only when they decide to marry but also when they wait for the men they are interested in to initiate a relationship. as much as it shows that she knows how to protect herself in a world dictated by male convention. In Pride and Prejudice both Jane and Elizabeth wait for the men they love to propose. who first rejects Darcy (221-222). when Emma 96 . Maria Bertram is in “a good deal of agitation” (Mansfield Park. A feminist reading of Austen’s fiction creates an awareness of the fact that women were left with no choice but to follow social convention in order to survive in a male-dominated world. Anne Elliot. When he finally returns.
has illustrated: As recently as August 1995 Imogen Edwards-Jones agonized in The Times over the fact that a woman still cannot ask a man out for a date. Judging by its popularity. and have initiated relationships and. Right28. Nearly a million copies of the book were in print shortly after its publication. by extension. Some of them have managed to shed this legacy completely.Chapter Three: Women and Marriage realises she loves Knightley. but leaves it up to him to make the first move (Emma. The Rules: Time-tested Secrets for Capturing the Heart of Mr. She only admits that she loves him once he assures her of his affection (227). 325-326). 28 The Rules: Time-Tested Secrets For Capturing the Heart of Mr Right (1995) is by Ellen Fein and Sherrie Schneider. as recent popular feminist writing. They posit that “[s]exually experienced women are more likely to be independent and to take the initiative in dating and sex…[and to] use strategies previously reserved for men” (2000:244). arrange the date. as seen. it seems that many twenty-first century women identify with and Kramarae and Spender note that. make the first phone call. (1999:316) In an aforementioned article. Others still wait for the man to make the first move. In Northanger Abbey the conventional view that “no young lady can be justified in falling in love before the gentleman’s love is declared” (17) is illustrated by having Catherine remain silent about her feelings for Henry Tilney. by its women writers. pay for it. there are observable changes to old norms. Modern women have inherited a legacy of waiting to be asked. Barbara Darby draws parallels between eighteenth-century conduct books (which prescribed women’s role in society) and a book written in 1995. bring presents. These writers believe that it is “the male prerogative to say hello first. marriage and families27. The Rules clearly stipulates the role men and women play in society. she dare not mention it. and propose” (2000:343). 27 97 . such as that of Germaine Greer. although traditional gender roles prevail in dating relationships. interestingly enough. while sequels are in progress.
Though they might have a different appearance they still manage to dictate women’s identity: And although today we find authors neither designing curricula to educate young women at home nor writing fiction to demonstrate the properties of feminine conduct. (1987:62) It is possible that contemporary women are embarrassed to initiate a relationship because they have inherited a legacy of leaving the courting up to men. By “[d]ramatizing the necessity of female submission for female survival” (Gilbert and Gubar. it would seem. 1979:154).Chapter Three: Women and Marriage adhere to this type of prescribed behaviour in the hope that it might attract a husband. While it is possible that Austen. 98 . in order to survive in a male-dominated world. The tradition of waiting to be asked is illustrated in Austen’s novels. need to follow certain conventions. there are also home economics courses that most women must take before graduating from high school. Dissident views on marriage Austen’s fiction offers ideas on marriage that deviate from the (patriarchal) norm: it appears to be critical of marrying for money. Even strong-minded women. Despite these criticisms Austen appears to support domesticity by ending her novels with marriage. such as marriage and leaving the courting up to men. Austen’s work seems to account for most women’s eventually succumbing to patriarchy. and portrays women who chase after men as ridiculous. Nancy Armstrong mentions that ‘conduct books’ continue to exist in the modern era. Besides all the books and advice columns telling women how to catch and keep a man. and besides numerous magazines imaging the beautiful home. the conduct book is still alive and well. shows that wives are often unfulfilled women. 2. I have argued that Austen’s fiction presents us with women who presumably know what they need to do and how they need to behave in order to secure their financial future and be accepted by the society they live in.
she does not stop loving him. Though the marriages of all Austen’s women protagonists are only ever hinted at as a possibility since the novels end before they are enacted. is that Austen’s endings serve as a “blotter” (1979:169). from fairy tale to film” (1999:269). which is favoured by critics such as Sandra Gilbert and Susan Gubar. which enshrines it as the fitting end for all narratives. In Mansfield Park love is said to make up an essential part of a happy marriage. Because she refuses Charles Musgrove. 29 99 . 24-25). This romantic notion of ‘mutual love’ may be a metanarrative that Austen fails to acknowledge as a patriarchal construct29 but at least she is not endorsing the view that marriage should make economic sense. is still “very much in the history of [her] society” (1993:xxii). Another plausible explanation for her apparent inconsistency. Even though she is persuaded to end the relationship. Austen states that women should have the right to marry for love at least once in their lives (Halperin. by doing so. 2. it is also possible that she. and therefore encourages women to lead a domestic life. submits to patriarchy in order to survive. Here it is worth mentioning that although Anhalt’s character from Lovers’ Vows is quoted as saying “[w]hen two sympathetic hearts meet in the Sarah Gamble comments on the popularity of the notion of romantic love in today’s society and states that “marriage remains an enduring institution…[which] is shored up by the ideology of romance. Anne Elliot falls in love with Wentworth despite his having no fortune (Persuasion. This argument entails that when Austen makes her heroines live happily ever after they do so in perfectly dubious matrimonial bliss. 1984:299). these women apparently agree to marry because they are in love. she is free to marry Wentworth when he proposes a second time.Chapter Three: Women and Marriage as Edward Said points out when referring to authors in general.1 Marrying for money In a letter to her sister Cassandra.
and how wicked it [is]. Seemingly for this reason she rejects Collins and initially even refuses Darcy. are seen by Willoughby as deserving no compassion (322). She loves Edmund so sincerely that she repeatedly refuses Henry Crawford. to marry without affection” (327). In Sense and Sensibility a loveless marriage is seen as emotional entrapment. from a woman whom he had long ceased to love” (354). She is ready to accept Darcy’s hand in marriage only when she realises that she loves him (375). In Emma Austen deviates 100 . does not marry Miss Morton. we are never actually shown these ‘happy marriages’. While Mrs Dashwood wants to see her daughters engage in loving relationships (13). Edward. women who marry. Because he feels Jane is indifferent. despite his being hopelessly in love with Mary. Elizabeth herself appears to be resolute in her commitment to marrying for love. how hopeless. despite his promises of fortune. Marianne is concerned that she will never find a man whom she can truly love (16). despite her large fortune. Marrying for love is also supported by other characters in the novel. in turn. While Darcy wants Elizabeth (who has neither money nor connections) to be his wife. he persuades Bingley not to marry her (Pride and Prejudice. Even the no-nonsense Mr Darcy seems to believe in marrying for love. matrimony may be called a happy life” (362). knowing their partners do not love them. She wishes that her uncle would realise “how wretched. and how unpardonable. In addition. The narrator endorses love as the only reason to marry by having Edward (although he is poor) happily married to Elinor (371). 228). Austen’s novel seems to illustrate the strength and the “enthusiasm of a woman’s love” (268-269) when Fanny keeps on loving Edmund.Chapter Three: Women and Marriage marriage state. we read that Edward “was released…from an entanglement which had longed formed his misery. When Lucy marries Robert Ferrars. Fanny seems to value love in a relationship.
in Northanger Abbey.Chapter Three: Women and Marriage from her own norm when she creates a heroine with a large fortune. nobly settled” (Mansfield Park. Towards the end we are told that he became “[s]ick of ambitious and mercenary connexions. Despite Sir Walter’s good looks and his station in life. who marries for financial security (162-166). Similarly. Sir Thomas’s own attitude to his wife. 108) is echoed throughout Austen’s novels. In addition we are shown that marrying for any other reason ruins relationships. further reveals their loveless relationship. It may be argued that partly as a result of Lady Bertram’s marrying Sir Thomas for his money (1). is pitied for being entrapped in 101 . Lady Elliot is said to have been “not the very happiest being in the world” (6). and does not seem anxious for him to return (129). The idea that “[w]here people are really attached. poverty itself is wealth” (Northanger Abbey. his daughter’s unhappy marriage compels him to reconsider his views on matrimony. Despite her firm resolution to remain single (66-67). Because Emma has enough money she does not need to marry for any other reason than love (66). In Pride and Prejudice we once again see how money cannot make a person happy. Although Sir Thomas initially feels that being “eligibly. although she might have gained money and esteem by marrying the General. Like her mother. In Persuasion it becomes clear that a loveless marriage can make one miserable. Charlotte Lucas. prizing more and more the sterling good of principle and temper” (477). Mrs Tilney often “had much to bear” (182). she falls in love with Knightley and agrees to marry him. honourably. she is “not disturbed by any alarm for his safety” (31) when he goes to Antigua. Because she neither loves nor respects Rushworth their marriage is doomed to fail. Maria marries for money and social prestige (37). as when he ponders that “it would not much amuse him to have her for a partner” (242) when playing whist. 321) in life brings happiness.
In Sense and Sensibility Edward Ferrars realises that marrying a girl “inferior in connections” (134) will bring about difficulties and could ruin him (291). she realises that she had chosen such a life “with her eyes open” (244). Rosalind Miles feels that Austen “endorses…marriages which are not really so acceptable or respectable” (1987:44). Austen seems to dispute the view that an “inequality of situations” (193) should keep two people from getting married when she has Henry offer Catherine his hand in marriage (232). Mrs Palmer does not marry Brandon (113). when 102 . In Pride and Prejudice the convention that it is disgraceful to marry beneath one’s station in life is undercut when Darcy proposes to Elizabeth. and how he at times completely ignores her (107-110). Austen implies that domestic happiness is out of the question when one marries for money by showing how Mr Palmer verbally abuses his wife. Austen’s fiction often presents us with matches between two people of different fortunes. Yet he goes ahead and marries Elinor. Although Darcy knows that by marrying Elizabeth he will acquire relations “whose condition in life is so decidedly beneath [his] own” (224) he still wants her to be his wife. Owing to her mother’s mercenary motives. Nancy Armstrong has made a good case that for Austen “status seems to matter as much as the essential qualities of a person” (1987:141). should be the most important consideration when choosing a partner for life. and not money. She suggests that in Persuasion Austen demonstrates how wrong a ‘right’ marriage could be since this enables her “to make some of her sharpest and most derogatory comments on the hollowness of rank and position” (1987:45). and may therefore be implying that love.Chapter Three: Women and Marriage a loveless marriage. Similarly. In Northanger Abbey Catherine assures Isabella that “the difference of fortune can be nothing to signify” (108). Money also leads to unhappiness in Sense and Sensibility. Though Elizabeth feels sorry for Charlotte.
“the wickedest thing in existence” (Northanger Abbey. as Mrs Jennings says. and that she really does not know. like his sister is. 113). By having them marry men of superior rank Austen could be suggesting that difference of fortune should not keep any two people from getting married. Austen still manages to unite two people from different social backgrounds when she has her marry Edmund. Austen is at least creating an awareness of some of the class constraints affecting her heroines’ choices in marriage partners. Austen is suggesting that a marriage based on financial consideration only more often than not leads to unhappiness. It would appear that. 2.Chapter Three: Women and Marriage he proposes to Fanny. 295). 251). Though the implication that women need to marry into financial security cannot be overlooked. In Pride and Prejudice Charlotte Lucas believes “[h]appiness in marriage is entirely a matter of chance” (69) and that “it is better to know as little as possible of the defects of the person with 103 . while women need to marry in order to secure their financial future. in Catherine Morland’s words. why people make “such a to-do about money and greatness” (Sense and Sensibility. Austen’s work seems to imply that marriage should not necessarily make financial sense and that marrying for money is. that he will be “marrying a little beneath him” (Mansfield Park.2 Unfulfilled wives In most of Austen’s novels the narrator and even some of the characters seem to display a cynical attitude towards the notion that marriage for women means ultimate fulfillment. Henry Crawford must be aware. It could be argued that. Although Fanny refuses Henry. by showing how marrying for money ruins relationships. this should not be the only consideration when choosing a partner for life.
In Mansfield Park Mary Crawford pities her sister for having to endure a fastidious husband (113-4). She could not come. but must go and keep house together” (65). Because she in all probability feels unfulfilled she deserts her husband and runs 104 . 30). Grant. professing an indisposition. and doing as you were bid” (Emma. as becomes evident when she is kept from coming to see the young people’s rehearsal of Lovers’ Vows: They did not wait long for the Crawfords.Chapter Three: Women and Marriage whom you are to pass your life” (70). but there was no Mrs. for which he had little credit with his fair sister-in-law. Dr. His explanation seems to account for the “strange unsuitabilities which often [exist] between husband and wife” (Sense and Sensibility. 365). 114) and which Austen illustrates with relish. To her it is a “manoeuvring business” (45) which invariably leaves one of the partners disillusioned. Grant. while Edmund notes the “desperate dull life [Mrs Grant’s] must be with the doctor” (122). In Northanger Abbey Henry Tilney destroys all romantic illusions about marriage by asserting that married people have a duty to persevere and that they “can never part. Mary Crawford believes most married people to be unfulfilled when she claims to “look upon the Frasers to be about as unhappy as most other married people” (Mansfield Park. cynical view of marriage and only to have married Collins in order to secure her financial future (165). Being married to a selfish man has brought Mrs Grant no joy but a life of entrapment. While Mr Knightley describes matrimony as “submitting your own will. Charlotte appears to have a pragmatic. Maria Bertram cannot stand being unhappily married. could not spare his wife. Mary sees marriage as a business transaction in which either of the sexes is usually taken in. (174) While Mrs Grant manages to console herself by believing “[t]here will be little rubs and disappointments” (46) in most marriages.
following standard media representations of the patriarchal nuclear family as a perfect unit.Chapter Three: Women and Marriage away with Henry Crawford (444-446). owing to woman’s anatomy. It is possible that. her parish and her poultry” (Pride and Prejudice. (1999:892) It would seem indeed that contemporary feminist writers are concerned with reforming marriage and that they pay special attention to the reasons that many women believe being someone’s wife will make them happy. Austen is suggesting that being a wife does not necessarily mean being content. and if Austen is offering a critique of marriage as an institution. Patricia Waugh reveals how “myths of femininity” (1989:40) are reinforced by psychoanalysis which states that. The prevailing assumption that being a wife ensures happiness is challenged by Germaine Greer: Many of the women who will this year shed a husband who thinks that he has behaved as well as could be expected will do so because he is just too much trouble. If this is indeed the case. on the other hand. the ultimate goal for any 105 . (1999:163) Feminists have found that women are lured into marrying. by depicting wives who are unfulfilled. but marriage reform remains a major concern of second-wave feminism. then she could possibly be considered as one of the forerunners of nineteenth-century feminists who sought to reform this institution. it is only ‘natural’ that she should become a wife. Charlotte Lucas. Some gains were made. Helen Tierney writes that: [t]he condition of subordination in America and Europe in the nineteenth century was such that marriage reform was a priority of the feminist movement that began in mid-century. 244). Patricia Beer has suggested that Austen’s novels depict marriage as “ a state where women often struggle and endure” (1974:81). accepts her fate and handles being married to Collins by finding her solace in “her home and housekeeping.
Austen never challenges patriarchy so blatantly. Yet it would appear that she at times suggests marriage does not always leave women feeling fulfilled. be it consciously or subconsciously. In addition. 2000:451). (255) By showing that marriage can be disappointing. Even when women. Because society and language “construct our experiences in ways which we then reify as ‘natural’. women expect to find fulfillment in marriage. It signifies warmth. ‘universal’ and ‘the way things have to be’” (Code. and every year. despite their experience of the families in which they were children. Austen’s fiction examines what we can now refer to as ‘social constructedness’. and the much publicized evidence of the break-up of families in Britain today. In Austen’s novels we find many examples of husbands who regard and treat their wives as their property. she gently mocks the predicament of unfulfilled wives who pretend to be happy. Elinor comments that women are deceived if they think their happiness depends on their husbands: …and all that can be said of one’s happiness depending entirely on any particular person. realise the entrapping possibilities of matrimony. 106 . Chris Weedon explains: [The patriarchal family] is immensely seductive. In Sense and Sensibility we see how women lie to themselves when Mrs Palmer states that she is happily married and that her husband is just the kind of man she likes (114).Chapter Three: Women and Marriage woman to achieve. happiness and emotional and material security. thousands of women willingly set out to create conventional family life. it is not meant – it is not fit – it is not possible that it should be so. which seem to refute the socially-constructed expectation that being married means being content. (1987:16) Obviously. they still enter it in an attempt to find fulfillment.
In Mansfield Park Sir Thomas subscribes to the view that the man is the head of the family. Emma highlights the arrogance of men like Frank Churchill who believe finding a wife is simply a matter of choosing one you like (282). When Collins proposes to Elizabeth. Emma says that “it is not every man’s fate to marry the woman who loves him best” (204). A good wife. just as they always are” (281). In other novels Austen is possibly subverting the idea that husbands ‘own’ their wives by the way she uses language. and could therefore be displaying a dissident attitude towards patriarchal convention. among their own set. Sarah Gamble writes that feminist 107 . 1988:6). is one like his own who will never challenge her husband’s authority. In Pride and Prejudice a single man in possession of a large fortune is considered as “the rightful property” (51) of a single woman. Frank Churchill suggests that they see “women in their own homes. In order for prospective husbands to make an informed choice. for example. to Sir Thomas. When pondering on Mr Elton’s marriage to Augusta Hawkins. while in Emma a man is seen to be “the prize of a girl who would seek him” (313). given that there are other more important things to consider when selecting a wife.Chapter Three: Women and Marriage In the late eighteenth/early nineteenth century the man was seen as the undisputed head of the household and therefore as master over his wife (Nye. For this reason he means “to recommend [Fanny] as a wife by shewing her persuadableness” (285). 147-148). his presumptuousness in thinking such an offer to be irresistible and a great honour is met with amusement and derision by Elizabeth (Pride and Prejudice. Nancy Armstrong mentions in “Captivity and Cultural Capital in the English Novel” (1998) that English law was so one-sided that it “generally considered violence a man’s prerogative” (37). It could be argued that Austen is reversing what has become known as ‘sexist language’. Austen seems to relish portraying men who believe women are subordinate as arrogant and stupid.
Toril Moi believes that although sexism dominates the English language. empower men while they keep women in submission: ‘master’ implies dominance and control. according to Lorraine Code (2000:499). Traditionally. She mentions that with industrialization. Other feminist scholars such as Helen Crowley and Susan Himmelweit have commented on the power of language. Over the course of the century. Society in other words attributes certain connotations to certain words.Chapter Three: Women and Marriage critique is pitched at “the semantic system of English and its usage [for example] the pseudogeneric usage of man [which] enshrines the male-as-norm” (1999:142). Andrea Nye points out that even pairs of words. women have played the role of being subordinate to their husbands. (1988:174) It would seem that gender and language work together to shape opportunities and determine certain roles for men and women. supposedly similar in meaning but denoting a difference in gender. it has no inherent sexist essence (1985:158). Yet they continue to be responsible for 108 . some groups of women began to work for pay outside the home. instead of dominance and control. Janet Chafetz writes that “the division of labor in early industrial societies was such that married women often performed uncompensated work in or around the home” (1999:321). It would seem that there are no neutral words in which one could even attempt to indicate a male/female relation in which the woman was dominant. suggests a kept women or sexual object…‘spinster’ has none of the sophisticated. or even equal. more and more women started to participate in paid work. but indicates unattractiveness and failure. This included doing the housework without any compensation. Today. women make up almost half of the labour force in the industrial world. satisfied air of ‘bachelor’. and have shown that feminists found “within language an underlying bias against women” (1992:183). but ‘mistress’.
whether he says so or not. One might wonder then why all her novels end with the hero and heroine Despite the fact that women increasingly became part of the world’s workforce during the twentieth century. Many a woman is harassed by her husband’s expectations of order. we can infer that Austen may not have been an advocate of matrimony. the woman still does the large majority of housework” (1997:443). Germaine Greer points out that contemporary husbands often treat their wives as their servants: A man who marries expects his house to be kept clean. (1999:171) Given that Austen wrote her novels two centuries ago. coupled with the fact that her fiction at times appears to be openly cynical about the institution of marriage. Margaret McFadden states that “marriage appears… to be more advantageous for men…[since] wives are expected to perform more housework without compensation. Sarah Gamble writes that “[e]ven in an era in which feminism has won many more social and professional opportunities for women. 30 109 . her novels do appear to imply that becoming a wife does not necessarily ensure happiness.Chapter Three: Women and Marriage most of the household chores30. However. women in the United States. according to Margaret McFadden still “had to cope with cultural assumptions about their ‘place’ and with men who failed to do their share at home” (1997:268). often performing these duties as well as maintaining full-time employment” (1997:545). From this. Stevi Jackson suggests the reason that many women get married and “spend much of their adult lives performing housework for men” (1993:190) is that they believe marriage will provide financial security. one cannot expect her to write as openly about the realities of married life as feminist scholars do today.31. Feminist studies reveal that most men expect their wives to do the majority of the housework and take care of the children. 31 Schmittroth and Reilly McCall mention that “[o]ne 1994 study found that women employed full-time outside the home do 70 percent of the housework while full-time homemakers do 83 percent of the housework. marriage remains an enduring institution” (1999:269). This study suggests that while both partners may have full-time jobs.
When Lydia succeeds in ‘catching’ Wickham she and her mother are equally thrilled that she has been able to secure a husband at such a young age (320. The narrator in Pride and Prejudice seems to be critical of Mrs Bennet for hunting down husbands. “we are never allowed to feel that [economic] base as a determining force in [women’s] experience” (1981:130). 32 110 . In Sense and Sensibility Mrs Jennings feels proud that she has managed to marry off both her daughters and now wants “to marry all the rest of the world” (34). Women who chase after men. She also makes it known to the world that a match between Bingley and Jane would be most advantageous (140-141). in desperate pursuit of a husband. This apparent inconsistency will be 2. the narrator appears to be critical of women like Mrs Jennings who chase after eligible husbands for pretty girls: [Mrs Jennings] was remarkably quick in the discovery of attachments…and this kind of discernment enabled her soon Judith Lowder Newton points out that husband hunting had an economic base.on their minds (75-76). She feels that although a novel such as Pride and Prejudice emphasizes this idea. Mrs Bennet insists that they get married (151-152). When Collins proposes to Elizabeth. investigated towards the end of the chapter.and especially officers . could therefore be considered as naive. While Marianne abhors notions such as ‘setting one’s cap at a man’ and ‘making a conquest’ (43). Like their mother. We are told “[t]he business of her life was to get her daughters married” (53) and shown to what lengths she would go to see that they were settled in life. Lydia and Kitty have men only .Chapter Three: Women and Marriage entering nuptials and living happily ever after.3 Husband-hunting Though a married life might ensure one being financially secure32 it certainly has its disadvantages (as I show in the preceding section). 329).
111 . The irony is. It could be argued that Austen illustrates the sad reality that many women. Louisa and Henrietta Musgrove (Persuasion) fall in and out of love effortlessly. for it supplied her with endless jokes against them both. In the space of one year she falls in love with Mr Martin. a woman “not likely to be very. Both Maria and Julia fall in love with Henry Crawford. In Mansfield Park the Bertram sisters display their accomplishments while “looking about for their future husbands” (33). who seems to show some interest in Louisa. But. very determined against any young man who told her he loved her” (358). according to Knightley. In Northanger Abbey Eleanor Tilney does not seem to be a husband-hunter and attends balls “without wanting to fix the attention of every man near her” (43). decisively to pronounce that Colonel Brandon was very much in love with Marianne Dashwood…The immediate advantage to herself was by no means inconsiderable. Harriet Smith (Emma) is shown to be equally fickle and content with any man who would marry her.Chapter Three: Women and Marriage after her arrival at Barton. Mr Elton and Mr Knightley. chances are they will end up feeling unfulfilled. Wentworth. While Henrietta imagines herself to love Charles Hayter. When Robert Martin proposes for the second time she accepts because she is. like Isabella. because he will not have them. while they dream of happiness. Maria settles for Rushworth while Julia runs off with Yates. he is soon forgotten when Wentworth arrives at Uppercross (67). is quickly put out of the sisters’ minds when Louisa gets together with Benwick and Henrietta (once again) with Hayter. so desperately want to be married that they are prepared to forfeit their dignity and self-respect. (34-35) As is the case with the two youngest Bennet sisters. while Isabella Thorpe literally runs after good-looking young men (29-30).
Furthermore. she [had to] be on her best behaviour.Chapter Three: Women and Marriage 3. the woman novelist had to be extremely careful what she wrote: Precisely because [the woman writer’s] foothold upon literary respectability [was] so precarious. especially in novels featuring a woman protagonist. Simone Murray explains in “‘Deeds and Words’: The Woman’s Press and the Politics of Print” (2000) that since the literary world was composed (up until World War One) of male publishers only. It may be argued that Austen submits to patriarchy and endorses marriage as a patriarchal institution in order to continue living and writing in her society. At the same time she is possibly showing that her heroines. Another argument is that Austen uses the façade of happy endings in order to hide some dissident views on matrimony. all Austen’s novels end as the hero and heroine are united in matrimonial bliss. no matter how individualistic they are. Fairytale endings Despite illustrating the reality and dangers of marriage. (198) Judith Lowder Newton has argued in “Power and Ideology of ‘Woman’s Sphere’” (1981) that since Austen lived in a male-dominated society. There are critics 112 . Nancy Armstrong mentions that by the late eighteenth century “it had been established that novels were supposed to rewrite political history as personal histories that elaborated on the courtship procedures ensuring a happy domestic life” (1987:38). She adds that. “a successful conclusion could be none other than a life free of physical labor and secured by the patronage of a benevolent man” (42). walking warily so she [would] ‘not too much displease [the male publishers]’. she must have “felt the pressure of ideologies which required circumscription of power as rigorously as they required marriage (and more loss of power) as a ‘happy’ ending” (1981:884-885). also need to succumb to patriarchy in order to survive in a malefavouring world.
as far as women are concerned. Although the narrator invariably assures the reader at the end that the protagonists live happily ever after. At the very least one has to bear in mind that from very early in the novel marriage is viewed. mentions that in Austen’s work there is “the existence of another system of meanings behind the façade [but that] because of distortions of the surface these hidden meanings are invariably misread” (1998:115). Other newly formed attachments 113 . Sandra Gilbert and Susan Gubar believe that Austen’s ‘happy endings’ are all tongue-in-cheek: Many critics have already noticed duplicity in the “happy endings” of Austen’s novels in which she brings her couples to the brink of bliss in such haste. Mrs Bennet has to endure her husband’s condescension and constant teasing (51-52. (1979:169) The way in which Austen portrays married life in her novels would seem to concur with the view that she did not necessarily believe in matrimonial bliss herself. 262). André Brink shows how this is the case in Emma: It may be argued that. as no more than domestic service… (1998:121) Although we are told that Darcy and Elizabeth are happily married (Pride and Prejudice. we are shown Mr and Mrs Bennet’s stressful married life. referring specifically to Emma.Chapter Three: Women and Marriage who believe that Austen deliberately ends her novels in the conventional way in order to conceal her unconventional views on marriage. André Brink. While Mr Bennet soon has “all his views of domestic happiness…overthrown” (262). or with such unlikely coincidences. a very different picture of marriage is depicted in the marital relations enacted throughout the novels. towards the end. however paradoxically. marriage offers Emma a prospect of liberation…but this appears to be contradicted by all the preceding evidence from other marriages. or with such sarcasm that the entire message seems undercut. 393-396).
(1999:226) Given the unhappy marriages of the Tilneys and the Allens in Northanger Abbey. and not a week earlier. in time. as Barbara Seeber points out: Austen presents [Marianne’s] conversion as unlikely and anything but voluntary. the narrator may be implying the ending should not be taken seriously: I purposely abstain from dates on this occasion. Of the almost five hundred pages written.Chapter Three: Women and Marriage that seem doomed to fail include the marriages of Lydia to Wickam and Charlotte to Collins. Moreover. that every one may be at liberty to fix their own. I only entreat everybody to believe that exactly at the time when it was quite natural that it should be so.that of Sir Thomas and Lady Bertram. Maria and Rushworth .the happy ending reached at the end of the novel seems highly doubtful. Austen uses only the last four to unite Edmund and Fanny in matrimonial bliss. and became as anxious to marry Fanny as Fanny herself could desire. it is possible that the narrator is being ironic when she comments that for Henry and Catherine 114 . It is hard to believe that Lucy Steele would leave Edmund for his brother (which would allow him to court Elinor) and even more unlikely that Marianne would find happiness being married to Brandon. by focusing our attention on the fictionality of the ending and even letting us decide on our own dates. aware that the cure of unconquerable passions. That Marianne’s ‘whole heart became. In light of the array of unhappy marriages we find in Mansfield Park . (475-476) In Sense and Sensibility both Elinor and Marianne find happiness under very unlikely circumstances. Edmund did cease to care about Miss Crawford. as much devoted to her husband as it had once been to Willoughby’…is something we never see. Dr and Mrs Grant. must vary much as to time in different people. What we do witness is the rather violent process which brings about the endings. and the transfer of unchanging attachments.
It seems plausible that the endings are deliberately over-hasty and improbable and that we are expected to question their probability. Critics seem to have different views on Jane Austen’s endings.Chapter Three: Women and Marriage “[t]o begin perfect happiness at the respective ages of twenty-six and eighteen is to do pretty well” (236). Barbara Seeber feels that “Austen’s closures are full of gaps that speak of the inadequacy of the endings which fail to fulfill everyone’s desire” (1998:233). While John Halperin believes Austen’s abrupt endings to be her “one overriding fault as a writer” (1984:78). Her remark that “we are all hastening together to perfect felicity” (234) could signal that we are not supposed to take the ending seriously. Sarah Gamble remarks that the so-called ‘romance novels’ – which typically see the hero and heroine united in heterosexual bliss - 115 . While Nancy Armstrong believes that by marrying off the eligible members within the fictional world of the novel Austen manages “to fix them to a role within a household among households. thereby stabilizing the community” (1988:135). A standard response to Austen is to be found in the work of Patricia Beer who maintains that Austen endorses marriage in a patriarchal society (1974:46). (208) A possible reason that Austen’s endings find appeal among women today is that many women yearn for happy endings in their own lives. More recently. the conclusion reached by Edward Said would seem to concur that Austen’s endings (like most of the novels produced in the late eighteenth century) “confirm and highlight an underlying hierarchy of family” (1993:79). Austen’s parodic conclusions measure the distance between novelistic conventions with their culturally coded sentiments and the social realities of patriarchal power. Karen Newman writes in “Can this Marriage be Saved: Jane Austen makes Sense of an Ending” (1983) that: [f]ar from acquiescing to women’s traditional role in culture.
but because this is what is expected of her. Isobel Armstrong argues that: “[w]here Mrs Inchbald speaks out. not because she wants to conceal her views on matrimony. When one takes into account the numerous unhappy couples Austen creates (by showing rather than by telling). but because she needs to continue living and operating in patriarchal society. Because her novels create an ironic awareness of 116 . Comparing Austen’s Mansfield Park to Mrs Inchbald’s Lovers’ Vows. Since she lived and wrote in the late eighteenth/early nineteenth century. Their intense reliance on these books suggests strongly that they help to fulfill deeply felt psychological needs. But that does not mean that she was less concerned with questions which were profoundly important to her culture. she was not at liberty to be as openly defiant of convention as women writers today. In a paper entitled The Readers and their Romances (1984) Janice Radway explains why so many women want to see the hero and heroine get together at the end of a story: When current reading habits are examined…it becomes clear that the women think that it is the romances that are especially necessary to their daily routine. and not in the early twenty-first. Jane Austen does not. (1988:7) It is also possible that Austen writes according to tradition and succumbs to patriarchy. It could then be that she ends her novels with marriage. a very real possibility is that she neither believes in uncomplicated matrimonial bliss nor in fairytale endings. not necessarily because she endorses it herself.Chapter Three: Women and Marriage “retain an undeniable appeal” and condition women to accept patriarchal authority (1999:307). and when one considers that Austen may be implying that we should not take the endings seriously. (584) Jane Austen ends her novels in the tradition of the romance novel.
117 . Since we may never know the answer.to concentrate on issues that are of importance to women. It could therefore be argued that Austen’s subject matter contains more than what Karl Kroeber refers to in “Pride and Prejudice: Fiction’s Lasting Novelty” (1975) as “middle-class girls getting married” (144). At the least. her novels create an awareness that patriarchy renders women economically and socially dependent on men. regardless of what Austen’s personal views were. and that it thereby enforces marriage. What seems to be important is that. as I shall show in the next chapter. and since we cannot be sure whether her happy endings are intentionally traditional. In addition. it becomes increasingly difficult to decide if she in facts submits to patriarchy in order to survive or whether she opposes patriarchy and hides her dissent behind a decorous façade. they seem to create an awareness of the identity that women inherit in patriarchal society.Chapter Three: Women and Marriage the necessity for women to get married.when reading Austen from a feminist perspective . Austen’s novels make us re-think the reasons that women get married. it would seem useful .
Sniffer. newspapers celebrated my arrival. And I couldn’t even wipe my nose at the time. “men have always told [women] what [they] are” (Crowley and Himmelweit. later variously called Snotnose. there’s no getting away from the date: I was born in Doctor Narlikar’s Nursing Home on August 15th.Chapter Four: Women and Identity Chapter Four – Women and Identity Introduction I was born in the city of Bombay…once upon a time. No. it’s important to be more…On the stroke of midnight as a matter of fact. No. too. 1992:33). Well then: at night. Clock-hands joined palms in respectful greeting as I came. that won’t do. Like his character Saleem. Paula Nicholson comments in “Motherhood and Women’s Lives” (1993) that dominant male discourses have traditionally determined how women see themselves and have defined their social role for them (207-208). I tumbled forth into the world…thanks to the occult tyrannies of those blandly saluting clocks I had been mysteriously handcuffed to history. Buddha and even Piece-of-the-Moon. I was left entirely without a say in the matter. Nancy Armstrong has shown that in the past “language…was dismantled to form the masculine and feminine 118 . had become heavily embroiled in Fate – at the best of times a dangerous sort of involvement. For the next three decades. my destinies indissolubly chained to those of my country. 1947. (Salman Rushdie. spell it out. politicos ratified my authenticity. Stainface. I. Because patriarchy places men in such a powerful position. Soothsayers had prophesied me. Oh. there was to be no escape. Saleem Sinai. And the time? The time matters. Baldy. women have been “mysteriously handcuffed to history” and have had their identity determined by the society they have been born into. Midnight’s Children) The above passage by Salman Rushdie illustrates how our sense of ourselves is often determined by external factors over which we have no control. spell it out: at the precise instant of India’s arrival at independence.
1992:135). a legacy of having their identity prescribed. Contemporary women have inherited a legacy of being told who they are.“the place where our sense of ourselves. 34 Elsewhere I mention that Nancy Armstrong believes the conduct book to be alive and well. men were able to mould women’s identity as domestic overseer of the activities of the house (women’s interiority). used language . 33 119 .. Women were. but the woman character may only provide the domestic world of feeling in which he may…recognize his own inner life” (1989:28).to formulate an identity for women that would suit them and their own needs (Kanneh. our subjectivity. and that it appears as magazines. passive existence. Edward Said believes that today more than ever we “live. while at the same time as not working (women’s dependency). However. Men have. Nineteenth-century male novelists.Chapter Four: Women and Identity spheres that characterize modern culture” (1987:14).. is constructed” (Weedon. in short. 1987:21) . in other words. for example. women in the Western world are no longer explicitly told how to behave. denied women their subjectivity altogether by defining them in terms of interiority and dependency. books and advice columns telling women how to catch and keep a man (1987:62). Today. while constantly being encouraged to a life of submissiveness (2000:335-336). of course. there are feminist writers who believe that women’s identity is strongly influenced by the way in which women are portrayed by the media. The conduct book in turn has ceased to exist34 and women are more liberated to uncover their own identities. By the mere act of writing.in a world Patricia Waugh notes that “it has been argued that the identification of women with ‘interiority’ or ‘sensibility’ in the realist novel tradition precludes ‘their becoming autonomous’…The male hero may act in the world to assert his subjectivity and autonomy. expected to lead an asexual.33 Barbara Darby explains that in the late eighteenth/early nineteenth century the conduct books along with the so-called ‘novel of manners’ constructed a very specific image of femininity – one which suited the male half of the population.
magazines. (1999:167) Though women might have realised for some time that they had been portrayed in a certain way. Feminist scholarship aims at forging a new identity for women. that suffragists first reacted against women’s representation in the media by “seizing control of their own image-making in the press and in the booming popular print culture of the day” (2000:198). as Simone Murray reports. in Chris Weedon’s words. how our femininity and our sexuality are defined for us and 120 . Barbara Darby comments that “[t]elevision advertisements package and sell versions of femininity at the same time as they feature consumer goods” (2000:333). 1987:14). feminists have aimed at making women aware of the “dominant image of the family which confronts us in adverts. The Women’s Liberation Movement explored women’s identity by asking.Chapter Four: Women and Identity not only of commodities but also of representation” (1993:56). from the royals to our own photo albums” (Weedon. In an attempt to eradicate women’s identity as constructed by the media. Dafna Lemish reports that even today women in Israel are represented by the media as “marginal to society…[and] often associated with their traditional roles as caregivers or dependency roles as the ‘wife’ or the ‘daughter of’” (338). the cinema. television and family portraits. Germaine Greer has noted that the media plays a key role in shaping women’s identity: In commercial after commercial the performer of mindless routine tasks is an inanely smiling woman. In an interesting article entitled “The Whore and the Other: Israeli Images of Female Immigrants from the former USSR” (2000). it was not until the early twentieth century. “the very question what it is to be a woman. unless some inanely smiling man pops up to demonstrate a new and better way of using even more of the product by dint of making her look a complete fool.
is not a story. a story that. and how they see themselves (33). but must become a story. Shoshana Felman asks how women should “come…in possession of [the] female mind as distinct from the male mind into which [women] have been coerced” (5). Women and Writing: Virginia Woolf as flâneuse” (1992) that in order to define themselves. in other words. Trained to see ourselves as objects and to be positioned as the Other. subjectivity should be “central to women’s writing” 121 . as Nancy Armstrong points out. as women. women first need to distinguish between the male way of representing them. an autobiography. There is therefore.Chapter Four: Women and Identity how we might begin to redefine them ourselves” (1989:1). 1997:780). More recent writers continue to point out the “wide discrepancy between how women see themselves…and how they think they ought to be” (McFadden. has as yet. estranged to ourselves. (1993:14) Laura Marcus states in “Feminist Aesthetics and the New Realism” (1992) that in order to re-think and re-define women’s identity. precisely. While Judith Fetterley maintains in “Introduction: On the Politics of Literature” (1978) that feminist writing needs to “exorcise the male mind that has been implanted in [women]” (570). Lorraine Code emphasises the importance of “uncovering fundamental processes of patriarchal power in shaping [women’s] sense of [themselves]” (2000:451). She argues that women as yet have not found their own identities. but need still need to write them: …none of us. we have a story that by definition cannot be self-present to us. The view that women’s image is defined for them was thoroughly examined during the 1970s by feminist writers such as Sandra Gilbert and Susan Gubar who stated that for the woman artist the “essential process of self-definition is complicated by all those patriarchal definitions [of what it is to be a woman]” (1979:17). a distinction to be drawn between “essential human nature and the aspects of individual identity that have been imposed upon us by culture” (1987:12). Rachel Bowlby writes in “Walking.
creates an awareness of the way in which women’s identity has been constructed in male literature. 1977:14). She was encouraged to remain fragile and told that her dependence was “a tribute to the man’s strength and competence” (Miles. 1987:149). In this chapter I shall be looking at the ways in which women are represented in Austen’s texts. In addition her work. and a consciousness that women have artificially been endowed with qualities such as emotionality and natural mothering. 1987:39). questions women’s inherited identity and creates women protagonists who display rounded characters. if read from a feminist perspective. In the nineteenth century some women novelists used their writing to redefine what it is to be a woman (Gilbert and Gubar. 1979:44). All of Charlotte Brontë’s novels. 1. and how this portrayal of women differs from women’s representation in male texts. Woman’s image as so-called “Angel in the House” (Showalter. the educational curriculum introduced by the (male-dominated) government in the eighteenth century aimed at producing a specific view of what it meant to be a desirable woman (1987:21). it would seem. for example. she would find fulfillment (Gilbert and Gubar. and as a sweet and subservient being made her believe that her purpose on earth was to please men and that by surrendering the self. as “custodian of the moral values” (Miles. 1987:11). deal to some extent with “a woman in search of her identity” (Miles.1 Male texts In Austen’s day the image of women was created and maintained by men.Chapter Four: Women and Identity (19). Nancy Armstrong has argued that in the nineteenth 122 . Women’s Representation 1. According to Nancy Armstrong. Jane Austen. 1979:25).
(343) Sarah Gamble mentions that canonical texts present women as part of a crude sexual binary. suggest alternative images of women. angel or demon. and also its most satisfying symbol. Mary or Magdalen. The difference is that today feminist writers make women aware of how they are stereotyped and. virgin or whore. passive. woman is the stage on which the age enacts its own enduring morality play. they labelled all those who failed as ‘monsters’. Thus. in addition. Angela Leighton explains the sexual binary according to which women have often been judged in “‘Because Men Made the Laws’: The Fallen Woman and the Woman Poet” (1992): …woman…is the chief upholder of morality.Chapter Four: Women and Identity century “the dynamics of the sexual exchange [were] apparently such that the female [gained] authority only by redeeming the male. asexual existence was a view of women’s moral superiority and their importance as mothers…and guardians of domestic happiness” (2000:336). restricted to canonical texts but can also be seen in modern fiction.35 Toril Moi believes that because patriarchy sees women as representing “the necessary frontier between man and chaos…male culture [has sometimes been able] to vilify women as representing darkness and chaos. however. Patricia Waugh points out that “[t]he ‘splitting’ of women characters into idealized and asexual or highly sexualized objects is the norm in much modern fiction” Barbara Darby writes that the conduct books “constructed a Proper Lady who oversaw the activities of the house…ensured that her husband had a retreat from his work…and reared children…The compensation for this domestic. Stereotyping women by means of the written word is not. 35 123 . to view them as Lilith or the Whore of Babylon” (1985:167). The struggle between good and evil…takes up its old story on the scene of woman’s sexual body. not by pursuing her own desires” (1987:55). While the conduct books advocated that women should behave as ‘angels’. namely as virgin or whore (1999:130).
of the ‘Other’ and that of the ‘Exceptionally Successful’. This type of stereotyping has also been investigated by other feminists. as Gill Frith points out: Feminist critics dissected the sexual stereotyping pervasive in male-authored texts in the literary ‘canon’. 1. Dafna Lemish was able to identify three major images. Investigating the role of newspapers in constructing images of Russian immigrant women in Israel. positive images of women… (1993:153-154) In the following section I shall be looking at the way in which women are portrayed in Austen’s texts. magazines and popular fiction. in children’s literature. self-sacrificing virgin and predatory whore – feminists sought to identify and encourage alternative. It is clear that the narrator is unhappy with Catherine who is prepared to accept all the blame just in order to win back Henry’s favour: 124 .2 Austen’s texts The women in Austen’s fiction challenge the stereotypes associated with ‘femininity’. Austen identifies alternative images of women. In Northanger Abbey Catherine Morland seems to be a mixture of naivety and perceptiveness. In contrast to the dominant. One could therefore argue that. namely that of ‘Whore’. in her own way. negative images – such as passive woman and active man.Chapter Four: Women and Identity (1989:68). Interestingly. the image of whore was by far the most dominant of the three (2000:339). 137) and because she holds herself accountable for failing to keep her appointment with the Tilneys. It would seem that against certain stereotypes of women Austen depicts complex women characters. Although Austen does not explicitly challenge women’s portrayal in male texts. She is naïve because she believes men always to be in the right (36. particularly in exhibiting contradictory traits. her fiction promotes the idea that women are not one-dimensional and predictable.
Chapter Four: Women and Identity
Instead of considering her own dignity injured by this ready condemnation; instead of proudly resolving…to shew her resentment towards him…and to enlighten him on the past only by avoiding his sight, or flirting with somebody else, she took to herself all the shame of misconduct… (81) Yet Catherine is also perceptive. Despite the fact that she enjoys Henry Tilney’s company, for instance, she quickly notices an imperfection in his character. When Henry and Mrs Allen are discussing the qualities of muslin gowns, we are told that “Catherine feared…that
[Henry] indulged himself a little too much with the foibles of others” (16). Catherine also notices John Thorpe’s vanity. The narrator informs us that “the extreme weariness of
[Thorpe’s] company…induced [Catherine] in some small degree…to distrust his powers of giving universal pleasure” (55). In addition, Catherine realises that Isabella is not a true friend. In order to make Catherine call off her engagement with Eleanor Tilney so that she may accompany the Thorpes to Clifton, Isabella resorts to accusing Catherine of having more affection for Eleanor than for herself. That Isabella would reproach her in this manner makes Catherine realise that she is not a true friend but, instead, appears to her “ungenerous and selfish, regardless of everything but her own gratification” (86). In Mansfield Park Fanny Price’s character appears to develop as the novel progresses. Edward Said believes that “[f]rom frightened and often victimized poor relation [Fanny] is gradually transformed into a directly participating member of the Bertram household at Mansfield Park” (1993:87). In the beginning, Fanny herself believes that she can never be important to anyone because of her “situation, [her] foolishness and awkwardness” (Mansfield Park, 25). She is frightened of Sir Thomas (12; 14) and, according to the narrator, “quite overcome by Mrs. Norris’s admonitions” (13).
125
Chapter Four: Women and Identity
Fanny always seems to do as is expected of her. She tries to convince Maria that it is improper to climb over the gate with Henry’s help (101-102) and is firmly set against performing the play (156-158). As time moves on, however, Fanny seems to become more outspoken. Whereas, in the beginning, Fanny hardly manages to speak for herself (11; 72), she later remains firm in her refusal of Henry. Neither Edmund’s aversion to her being “so very determined and positive” (351), nor her fear of her uncle, can make her change her mind. Her concern that she might not always “be able to appear properly submissive and indifferent” (220) is warranted when she is “forced by the anxiety of the moment even to tell her uncle that he [is] wrong” (317). At first Sir Thomas feels Fanny is “[s]elf-willed, obstinate, selfish, and ungrateful” (322) because she will not heed him and marry Henry. When both his daughters elope, however, Sir Thomas begins to realise and to value Fanny’s good nature. What is more, he welcomes the news that she and Edmund are to marry for she is “indeed the daughter that he wanted” (477). Sir Thomas realises how much his opinion of Fanny has changed: [Sir Thomas] had pondered with genuine satisfaction on the more than possibility of the two young friends finding their mutual consolation in each other…and the joyful consent which met Edmund’s application, the high sense of having realized a great acquisition in the promise of Fanny for a daughter, formed just such a contrast with his early opinion on the subject when the poor little girl’s coming had first been agitated… (477) Not only is Fanny valued by Sir Thomas towards the end of the novel, but she herself believes she could be useful and “of service to every creature in the house” (437) when she hears about Maria eloping with Henry Crawford. Fanny proves to be very useful indeed as she helps Edmund to forget Mary Crawford (467) and consoles Lady Bertram (454). Though
126
Chapter Four: Women and Identity
her ‘usefulness’ is questionable in relation to gender (and class) politics, that she asserts herself in this way is commendable. In Sense and Sensibility Elinor Dashwood features a rounded character. While she at times seems to be critical of the society she is living in, she values propriety. For this reason she expresses her unhappiness with Marianne’s indecorous behaviour (51-56) and differs from her mother when she believes there is a proper way of being engaged (77-78). Elinor always behaves as she knows she ought to behave. Even when she is deeply hurt by Edward’s indifference she remains civil and treats him “as she thought he ought to be treated from the family connection” (86-87). Though Elinor values decorum, she notices the silliness of certain social conventions and does not have her judgement clouded. When Marianne asks whether “our judgments were given us merely to be subservient to those of our neighbours” (91), Elinor answers that one should never subject the understanding to the opinion of other people, and that all she has ever attempted to influence has been the behaviour (91). Because Elinor applies good judgement, she notices the absurdity of women like Mrs Ferrars who want their sons to marry someone with connections (289). Her ability to think and judge for herself also makes her realise how empty and monotonous women-talk often is (137). We see another of Austen’s complex women characters in Emma. From the outset we are told that she does what she likes (5) and that she always has her own way (30). Once she has made up her mind, there is no persuading her otherwise (11; 20). She stubbornly persists in her convictions (51) and is not afraid to challenge Knightley (49; 76; 115). She clearly enjoys arguing with men (11) and bravely ascertains that they are only really needed for their money (66-67). Emma’s confidence is reflected in her strong handwriting (224) and straightforward way of speaking (300). To pass the time, Emma enjoys playing games and solving riddles
127
In Elizabeth. headstrong (151. Austen thus succeeds in creating an unforgettable woman character who displays a mixture of strength and compassion. she loves meddling in other people’s affairs and playing matchmaker (10. for instance. Georgina Darcy’s idol. Being the heroine of the novel in most cases means that the reader identifies strongly with the character. 120). 79-81). Furthermore. and Darcy’s beloved. she does not seem to believe in the superiority of men but joins in their discussions (93-95) and argues with them (90). 27. Furthermore. a more serious. She also admits that she has acted inconsiderately and improperly towards Harriet (308). impressive female characters” (1985:47).Chapter Four: Women and Identity (54-59). Moreover. physically strong (78-82). Elizabeth however also displays an unselfish and loving nature . Elizabeth is also loved by characters within the fictional world of the novel: she is the apple of her father’s eye. She realises that Knightley is very dear to her and that she does not want to lose him. Anne Elliot in Persuasion is described as having “elegance of mind and sweetness of character” (7). instead of fragile and weak. While she is “nobody with either [her] father or sister” (7). as when she devotedly nurses Jane back to health (Pride and Prejudice. her sister Jane’s confidante. She. Elizabeth displays love and compassion herself.she is shown to have a great capacity for loving and for being loved in return. 159. and as such a multi-faceted identity. but strives to identify with strong. Toril Moi mentions that the ‘feminist’ reader of the realist period “not only wants to see her own experiences mirrored in fiction. In Pride and Prejudice Elizabeth Bennet is proud (72). There is. Emma gets to know her own heart towards the end of the novel. 208) and snubs decorum by being. displays a selfless nature when she takes care of the poor (65) and when she shows concern for her father’s well-being (7. In addition. unselfish side to Emma. she is “a most dear 128 . however. 314).
when he more seriously described the woman he should wish to meet with [as having a] strong mind. mind. Nancy Armstrong rightly notes that: …one can observe the shift in Austen’s emphasis away from natural virtue as the quality a woman exemplifies to a more complex understanding of subjectivity. I believe that because Austen’s fiction features women with complex. in her temper. (1987:154) If indeed it was Austen’s intention to explore and even suggest a multifaceted identity for women. a model of female excellence” (142). Anne. We are told that. Anne shows courage when she is slighted by her father and her sister. it identifies alternative images of women. She is respected by Mary’s children (39). The narrator mentions that “Anne Elliot was not out of [Frederick Wentworth’s] thoughts. We see that she has a strong mind when she does not hesitate to argue with men about issues such as women’s loyalty (205-207). and valued by Captain Benwick for her gentle nature (90). the narrator tells us that “Anne herself was become hardened to such affronts” (31). When Sir Walter engages Mrs Clay to accompany him and Elizabeth to Bath. favourite and friend” (7) to Lady Russell. Anne attended to her “with all the strength and zeal and thought which instinct supplied” (99). then surely she was not being prescriptive. rounded characters. and that they therefore cannot be stereotyped. Toril Moi’s criticism of feminist theorists such as Luce Irigaray who come to “analyse ‘woman’ in idealist categories” (1985:148) is 129 . when Henrietta fainted. apparently because she would be of more use to them than Anne. manners. with sweetness of manner” (55).Chapter Four: Women and Identity and highly valued god-daughter. It would appear that women like Anne Elliot and Elizabeth Bennet display natures that incorporate a variety of character traits. Anne also shows strength of character when Louisa falls and is seriously hurt. In addition. Mr Elliot thinks she is “a most extraordinary young woman. is not weak. despite her seemingly docile character.
a more complete reformation. for instance. Lorraine Code points out that “Western culture has historically tended to…associate both mind and reason with men and masculinity. While her father bases his decision on emotion and needs to be persuaded to move (13-14). instead of rational creatures” (63). and prone to emotional outbursts” (1997:831). women have been considered illogical. Nancy Armstrong writes that in nineteenth-century fiction “the difference between male and female was understood in terms of their respective qualities of mind…[which] made men political and women domestic” (1987:4). Rationality and Emotion In addition to having classified women as either angels or monsters. Margaret McFadden notes that not only in the eighteenth and nineteenth centuries but also “[i]n many other historical periods. 1992:72).Chapter Four: Women and Identity illuminating in relation to Austen whose work resists essentialist definitions of what women should be. On occasion Austen’s novels appear to subvert the master narrative of her time that all men are rational and all women emotional. 2. Because she has the ability to remain objective Anne makes wise decisions. a quicker release from debt” (13) seems much more rational. Anne realises they have no alternative but to quit Kellynch-hall. while Anne Elliot’s depiction illustrates that women are often more sensible than men. In Persuasion Mrs Croft vehemently objects when Frederick Wentworth talks “as if women were all fine ladies. and to devalue body and emotion while associating both with women and femininity” (2000:160). irrational. 130 . and offers alternative possibilities of what they might also be. When Sir Walter experiences financial difficulties. men have portrayed them as emotional creatures in speech and in writing (Moore. Anne’s favouring of “more vigorous measures. less intelligent than men.
Elizabeth Bennet is able to recognise his true character and knows to reject his marriage proposal (Pride and Prejudice. as any rational creature would have done. Austen seems to be saying something interesting here about the limits of rationality and the limits of an emotional response. 121). 148-149). Elizabeth’s pride is hurt. You talked of expected horrors in London. Henry’s irritation with women who rely solely on their fancy possibly reflects the attitude of the narrator: And you. For the same reason. and instead of instantly conceiving. In contrast to Elizabeth. that such words could relate only to a circulating library. and she loses her objectivity and misjudges Darcy’s character (59. When Darcy rejects her as a dancing partner. In Northanger Abbey Catherine Morland often seems to act on emotion only. Though Edmund thinks it is unlike her “rational self” (351) to reject Henry’s marriage proposal. when Charlotte marries Collins. Jane advises Elizabeth not to judge her friend so 131 . Maria ostensibly bases her decision to go away with Henry purely on emotion and later has to endure shame and scorn (470). Jane is able to regard Darcy rationally and make a more accurate judgment (128). Miss Morland – my stupid sister has mistaken all your clearest expressions. Because she becomes emotionally involved and loses objectivity. she immediately pictured a mob of three thousand men… (101) Possibly because she is not emotionally involved with Collins. however.Chapter Four: Women and Identity In Mansfield Park we see that if emotion only is one’s guide one can easily be led astray. she is convinced that General Tilney murdered his wife (181-182). Because Fanny applies reason she is not persuaded by her cousin to change her mind about Henry Crawford. and under what circumstances these manifest themselves. she turns out to have been the only one ‘rational’ enough to recognise Henry’s intentions (444). On the other hand.
37. When Willoughby betrays her love. Marianne’s actions are based on emotion only. her appearance of 132 . While women like Fanny Dashwood fall into “violent hysterics” (250) and others like Lucy are driven into “a fainting fit” (250).Chapter Four: Women and Identity harshly and sensibly argues that a match between them is not as bad as Elizabeth would make it out to be (174). that her firmness was as unshaken. and ascertains that Marianne “was without any power. Elinor remains calm and in control. whose “person and air were equal to what her fancy had ever drawn for the hero of a favourite story” (41). and coolness of judgment” (4). Elinor admits that she herself enjoys Brandon’s company for he is “a sensible man. In contrast to Marianne. While Elinor applies both. 35. She is shown to esteem passion (16. The narrator comments that Elinor did not need her family’s support for she “was stronger alone. and her own good sense so well supported her. because she was without any desire of command over herself” (80). Elinor never lets her feelings cloud her better judgment. It is partly Marianne’s unrestrained emotionality which induces her to fall hopelessly in love with Willoughby. and sense will always have attractions for [her]” (49). it becomes clear that responding from the heart only can have disastrous effects. rational (19) and discreet (24). 44) and to display an “indulgence of feeling” (81). Sense and Sensibility illustrates the benefits of applying reason as well as emotion by contrasting the Dashwood sisters. Elinor possesses “a strength of understanding. Even though she is emotionally involved she retains the utmost self-command when Edward seems cold and reserved (86-87) and when she learns about his engagement to Lucy Steele (126). and reprimands Marianne for judging Brandon solely “on the strength of [her] own imagination” (50). The narrator comments that “the imaginations of…people will carry them away to form wrong judgments” (241). She is prudent (12).
(1987:35) 133 . the subject (woman) does not notice how she is constantly shaped and subjugated: If knowledge is to become power. and not only by emotion. as…it was possible for them to be” (135). then. Because patriarchal discourse is camouflaged. that it is natural and rewarding for all women to be mothers. Though Elinor suffers as great an emotional loss as Marianne she is able to bear it “with less self-provocation. as Nancy Armstrong points out. Austen’s fiction features women who remain objective under difficult circumstances. Above all. In addition. thus empowers her. Since Austen’s writing contradicts the popular belief that women are born emotional creatures. Her ability to remain rational and objective. it could be argued that she challenges the identity which patriarchy has created for women. it cannot appear to operate in the interests of a political group. These discourses reinforce specific perceptions of women’s identity and “appear natural to the subjected individual” (121). Natural Mothers Much feminist writing has shown that women generally accept the identity society defines for them. Chris Weedon argues that the way “we live our lives as conscious thinking subjects…depends on the range and social power of existing discourses” (1987:26). In the following section I shall show that her novels reveal another myth of women’s identity. even where matters of the heart are concerned. 3. and greater fortitude” (349). In this way I believe it shows that rationality is not solely a man’s faculty. it seems to suggest that if a woman is governed by reason. she will be able to judge better and will remain strong when faced with life’s adversities.Chapter Four: Women and Identity cheerfulness as invariable. it cannot appear to be so.
Rosemary Gillespie reveals how this discourse has established women’s identity in an essay entitled “When No Means No: Disbelief. She states that. many women see it as a way of escaping their dreary employment. We expect to fall irrevocably in love with our babies. but it doesn’t always happen quite like 134 . In the 25 April 2001 edition Deborah Hutton asks in an article what happens when “mothers lose that loving feeling” (64).Chapter Four: Women and Identity A popular belief is that. In part she blames society for constructing the expectation that motherhood is bliss. society treats women who are not mothers as failures and as unfeminine (201-202). She writes that despite the “glossy images of lovey-dovey new-baby bliss” mothers sometimes feel an aversion to their babies. they are only fulfilled once they have borne children. and Deviance as Discourses of Voluntary Childlessness” (2000): Constructions of femininity and women’s social role have historically and traditionally been contextualised around the practices and symbolism surrounding motherhood. because of women’s anatomy. Popular women’s magazine Fair Lady contributes to the debate. It can therefore be said that “women are socialised into wanting children” (209). Motherhood has predominantly been perceived as natural for women. Disregard. and hence for leaving women disillusioned when they realise they do not love their children unconditionally: The bonding principle looms large in every new mother’s consciousness as the emotional superglue that will weld her and her infant together. despite motherhood being “the key means of women’s oppression in patriarchal societies” (1993:201). What is more. the desire for it inevitable… (223) Paula Nicholson investigates in her study on motherhood why many women in contemporary society believe they need to become mothers in order to be fulfilled.
as Nancy Armstrong (1987:59-69) reports. and states that the feminist struggle is one “toward a new feminine awareness fighting sex discrimination and redefining male and female sex roles” (69). we see a number of women who apparently find motherhood fulfilling. and always innocently busy.Chapter Four: Women and Identity that…women feeling less than total love for their children are depicted as. In fact. Armstrong writes that up until the seventeenth century. Although at times the narrator ostensibly praises her for her womanly ‘worth’. In order to understand the origins of the legacy that motherhood is natural. the great majority of conduct books represented the male of the dominant class. she does not appear to be sincere in her commendation. might have been a model of right feminine happiness. it is useful to have a look at what late eighteenth-century writers such as Jane Austen have to say (explicitly or implicitly) about women as mothers. maternal monsters. passing her life with those she doated on. (64) Shoshana Felman similarly exposes the myth that in patriarchal society women want nothing more than to be a mother. a daughter and a wife (1993:73). It was only by the second half of the eighteenth century that the conduct books prescribed the ideal of womanhood (61). it would seem that she is critical of Isabella who is oblivious to the social role she is playing: …poor Isabella. blind to their faults. full of their merits. If we look at the way in which Austen depicts women as mothers. In Emma Isabella Woodhouse plays the role of self-sacrificing mother (72-73). and feel they are. (107) 135 . Armstrong maintains that the conduct books “rewrote the female subject for an eighteenth century audience” (94) and that “it is reasonable to claim that the modern individual is first and foremost a female” (66). The eighteenth century is significant since it signals the rise of the domestic woman.
but she will swallow anything… (117) Austen depicts motherhood as unfulfilling when she. the most rapacious of human beings. because Mrs Morland was pregnant so regularly. Mansfield Park possibly suggests that mothering is not natural to all women and that bearing children does not mean 136 . as anybody might expect. (1) In addition the narrator mentions that. focuses on mothers “who fail in their nurturing of daughters” (1979:125). is likewise the most credulous. Mary Musgrove in Persuasion does not seem to earn the respect of her children (39). her demands are exorbitant. however. and critical of Lady Middleton for being blind to their faults: …a fond mother. While Mrs Bennet in Pride and Prejudice fails to love her daughters equally (145) and is a constant source of embarrassment for Elizabeth (143) and Jane (354-355).Chapter Four: Women and Identity Mrs Morland in Northanger Abbey purportedly finds happiness in motherhood. and to enjoy excellent health herself. as Sandra Gilbert and Susan Gubar have shown. While Mrs Dashwood is a good mother and wants what is best for her children. seems to ridicule the social discourse that childbirth is rewarding when she incredulously comments that Mrs Morland enjoyed health and prosperity after giving birth to ten children: [Mrs Morland] had three sons before Catherine was born. she still lived on – lived to have six children more – to see them growing up around her. Lady Middleton is similarly incapable of seeing her children’s mistakes. in pursuit of praise for her children. she inevitably neglected her children (3). she is blind to their shortcomings (51-52). though. The narrator. and. instead of dying in bringing the latter into the world. The narrator appears to be irritated with the children for being rowdy and mischievous. In Sense and Sensibility we see that motherhood dulls one’s perception.
While we do encounter women who accept their patriarchally-engendered social role. her work at times seems to contradict the discourse that motherhood is fulfilling. In addition. and the charge was made over to her sister… (33) Despite her being childless. Austen is possibly commenting on the enormity of the task of raising children as well as on the consequences of having so many children. some mothers are depicted as failures and as women who have not found fulfillment in motherhood. The narrator comments that: Lady Bertram did not go into public with her daughters. Edmund believes that his aunt is “much better fitted” (25) than his own mother for having the charge of Fanny. Mrs Norris is the one who takes responsibility for displaying their accomplishments and the one who helps them find their future husbands (33). She was too indolent even to accept a mother’s gratification in witnessing their success and enjoyment at the expense of any personal trouble. (Here it needs to be mentioned that since Edmund makes this claim while trying to persuade Fanny that going to stay with Mrs Norris will not be that bad. the narrator’s approval of them at times seems doubtful.Chapter Four: Women and Identity one knows how to take care of them. has so many children that she cannot provide for them all (3). in turn. despondent and worn-out (2-3). Although Austen’s work features wives and mothers. I do not believe it can therefore be said that she endorses women’s social role as defined by patriarchy. Fanny’s own mother. Instead. By portraying her as impoverished. Although Lady Bertram is Maria’s and Julia’s biological mother. it is not clear whether he genuinely believes his aunt is more capable of taking care of his cousin or whether he merely says this in order to reassure Fanny). When the narrator comments that being a 137 .
economic and social system. However.. (1999:151) 138 . and for their having instantly all the liberty and attendance. nineteenthcentury feminists wanted to obtain power for women by seeking equality within the existing social structure. and her intellect not for invention or creation” (Gilbert and Gubar. and to display a weak and fragile nature.. a consciousness of the constructedness of ‘natural’ motherhood. Women empowered Because late eighteenth/early nineteenth-century men believed woman’s power to be “not for rule.which they could possibly wish for” (Emma. many women characters are shown to be without real power. we are not only made aware of the fact that patriarchy renders women powerless but are presented with signs of women’s empowerment. equal rights under the law – they would attain equality with men. 72) it is not clear whether she is commending or exposing motherhood. not for battle.Chapter Four: Women and Identity mother like Isabella Knightley includes having “maternal solicitude for the immediate enjoyment of her little ones. 4. In contrast to the subtle ways in which Austen’s heroines are empowered. employment rights – in other words. Austen’s fiction seems to reflect the powerless state of women in her time. to refuse and to write. To this end I shall argue that women are shown to have the power to judge. the right to vote. Possibly owing to the male-favouring educational. amongst feminist scholars at least. What is clear is that Austen’s work raises questions regarding women’s identity and that it in this way creates. the right to own property. 1974:24) women in Austen’s day mostly remained powerless. as Janet Chafetz reports: Nineteenth century feminists believed that if they obtained the right to an education.
leading to competitiveness with other women. and Patricia Waugh sees: …women’s second-class position in patriarchy [as] reflected in their psychology: lack of confidence.Chapter Four: Women and Identity Chafetz explains that contemporary feminists. as Judith Lowder Newton has suggested. self-condemnation. believe women lack power because they are not allowed to compete with men in male-dominated economic and political spheres. She believes women as a group are not only marginalised culturally but also politically. institutions such as education and marriage rendered women weak. powerlessness. This includes making women good judges 139 . but are relegated to staying at home and raising children (151). does not openly criticise patriarchal society for keeping women powerless. insecurity. if we apply a feminist perspective when reading her novels. 4. Paula Wilcox suggests that the very structure of our society is conducive to the oppression of women (2000:36). (1989:86) In “Exiles From Power: Marginality and the Female Self in Postcommunist and Postcolonial Spaces” (2000) Maria-Sabina Draga-Alexandru metaphorically refers to women as “exiles from power” (356). “by quietly giving emphasis to female capability” (1981:883). on the other hand. However.1 The power to judge Austen empowers her women characters. Helen Tierney argues that “[a]uthority in patriarchal societies…resides ultimately in the male” (1999:892). Austen herself is aware of women’s powerlessness and of the dire need for self-empowerment when she creates strong women protagonists who exercise the power to judge and to refuse. and an inability to feel whole. overdependence. Austen. in contrast to contemporary feminist scholars. we are made aware of the fact that in the late eighteenth century.
who observes with “wonder and censure” (118) the game Henry is playing with her cousins. She is. more or less disguised. When Mrs Musgrove suddenly mourns the death of her “troublesome. Anne can hardly suppress a smile (58).Chapter Four: Women and Identity of character. When she rejects Henry. she is not fooled by her seemingly sweet exterior. The ability to judge thus protects Fanny from being hurt by people like the Crawfords. Despite his being “rational. Anne Elliot is similarly not deceived by people but quickly recognises their intentions. Although Fanny Price is modest and introverted. is consequently not taken in by him. Anne’s power of discernment enables her to recognise Elliot’s true intentions. and finally she is not hurt. Fanny. she has the ability to judge people and assess situations. She is amused by their childish behaviour when they decide to put on a play (134-140). 134). simply in order to impress Wentworth. polished” (143) she does not trust him. Her ability to study characters further proves to be useful when it 140 . for example. Although at times she enjoys Mary’s company she realises that it is “often at the expense of her judgment” (209). Fanny also notices a sort of fault in Mary right from the start (66). discreet. seemed to govern them all” (Mansfield Park. immediately recognises him to be a flirt and is probably not surprised that he never intended to marry Maria. the only one to condemn the young people’s “selfishness which. and even refuses to condone Edmund’s decision to partake (162). On another occasion. 45). She is also sensitive enough to realise that Henrietta and Louisa do not like Mary and really do not want her to join them on a long walk (75). Because she ascertains that Mary “loves nobody but herself and her brother” (429). Mary suggests that Fanny enjoyed “having it in [her] power to pay off the debts of [her] sex” (367). hopeless son” (Persuasion. She knows her uncle better than his own children do (198) and firmly believes that he would not approve (158). She resists his charms because although she “was quiet [she was] not blind” (367).
She boldly contradicts what James and Isabella have told her about him and finds his company tedious. although Emma regards Elton as a suitable match for Harriet. to form a “most unfavourable opinion” (290) of Robert Ferrars. I have mentioned that Catherine Morland. Also. scarcely four weeks after professing he loved Emma. This enables her to detect in Willoughby “a want of caution” (47) and to distrust him when he suddenly takes leave of Marianne (74). she cannot help but recognise and laugh at his superfluous gallantry (Emma. 91). Elinor Dashwood believes it is important to give oneself “time to deliberate and judge” (Sense and Sensibility. 54). Elinor similarly notices a “thorough want of delicacy. Similarly. This. and not a true friend at all. 65). and integrity of mind” (124) in Lucy Steele. she does not fail to see that Isabella is selfish. In addition. She recognises the vanity and superciliousness of Bingley’s sisters and is restored “to the enjoyment of all her original dislike” (81) when they act ungraciously towards Jane. In Pride and Prejudice Elizabeth Bennet’s “quickness of observation…[and] judgment” (63) enables her to see through people. she is not blind to the faults of her own family but wonders at their false sense of pride and at their foolishness (124). although Catherine can at times be extremely naïve. after a single encounter. notices how vain John Thorpe really is. in turn. Elizabeth’s ability to assess situations not only makes it 141 . Her power of discernment also induces her. “[l]ittle as [she] was in the habit of judging for herself” (Northanger Abbey. gives her new hope that he might still love her. She realises that she had been right in assuming he only wanted to marry her for her money when she learns the “amusing and…very welcome piece of news” (133) that he has married Miss Hawkins.Chapter Four: Women and Identity makes her realise that Frederick Wentworth is not in love with either of the Musgrove sisters (74). of rectitude.
Instead of being left disabled by society they find amusement in its follies. narrow-minded. however. feels “all the impertinence of her questions” (198) and recognises her for the bully she is. 142 . Armstrong stresses that “we must see Austen’s novels striving to empower a new class of people . also judges her own family.Chapter Four: Women and Identity possible for her to recognise silliness but also provides a means of self-protection when the sisters refuse to share Darcy’s company with her and she is able to laugh it off (97). to empower themselves. silly man” (174) and feels sorry for Charlotte for being his wife. Elizabeth judges him to be a “conceited. pompous. albeit in a compromised way. Though Austen’s heroines may exhibit ‘authority of a strictly female kind’. Elizabeth is not swayed by Collins’s reverence for Lady Catherine de Bourgh but. my emphasis). instead. She argues that the novel “maintains the continuity of traditional political authority while appearing to broaden its social base by granting Elizabeth authority of a strictly female kind” (1987:53. and in so doing manage. they represent the possibilities of the power of discernment which enables them to defend themselves in an unfair world of ‘normalising practices’. Nancy Armstrong argues that Pride and Prejudice demonstrates the truth of the sexual contract. which aims at providing women with security in exchange for their submission to a traditional role. Elizabeth. she feels she has “never been blind to the impropriety of her father’s behaviour as a husband” (262). Despite being young. While she condemns Lydia’s “unguarded and imprudent manner” (257). Because she is a good student of character she immediately notices Collins’s obsequiousness.not powerful people but normal people” (136).
she remains steadfastly unwilling to marry him. In Northanger Abbey Henry Tilney states that “man has the advantage of choice. In Persuasion Anne Elliott is portrayed as being silently determined when she refuses marriage on two occasions. Here I would agree with Patricia Beer who argues that although these women recognise the need for marriage. When she later realises that she loves Darcy. 173) appears to be subverted in many of Austen’s novels.2 The power to refuse The belief universally accepted “that every man is refused – till he offers” (Persuasion. Even the fear of her uncle is not enough to make her change her mind (317).Chapter Four: Women and Identity 4. In Mansfield Park Fanny stubbornly refuses Henry Crawford. She not only vehemently refuses Collins (Pride and Prejudice. albeit in a manner requiring some compromises and concessions. Austen’s heroines would rather “live unmarried than enter into marriage solely in response to the assumption of society that for women this is the only viable existence” (1987:45). We see how her heroines time and again exercise their right to refuse some proposals and to accept others. woman only the power of refusal” (65). to empower themselves whilst retaining their integrity. she assumes she has the right to change her mind and agrees to marry him (375). Fanny answers that a woman should not be obliged to accept any man who may 143 . Elizabeth Bennet is also shown to reject two suitors. She first breaks off her engagement to Frederick Wentworth and then declines Charles Musgrove (25-26). 148-149) but also Darcy (222). When questioned about her stubbornness. Although she is told that it would be a wonderful match for her. they “do not allow themselves to be utterly trapped by it” (1974:60). We see Catherine exercising her right to refuse when she rejects Thorpe (129-130). Mary Evans has suggested that even though refusing a proposal means risking their financial security.
In the late eighteenth/early nineteenth century “a strengthening discourse of femininity” (Darby. Though Fanny refuses Henry Crawford her new-found independence. according to Armstrong. is not equal to the power of her uncle (1988:52). When Emma (and therefore possibly Austen) suggests staying single as an alternative to marriage. Isobel Armstrong points out that Fanny’s power of refusal is limited. A number of critics. Edward Said feels that although Fanny acquires status during the course of the novel. 373-375). she remains “in her assumption of authority…relatively passive” (1993:85). however. Because Sir Thomas wants Fanny to realise the value of a good income (such as she would be assured of by marrying Mr Crawford) he sends her home to Portsmouth. 2000:336) propagated the idea that women should marry and take care of their husband and home. argue that Fanny displays only marginal power. Patricia Beer believes Fanny is not one of Austen’s spirited heroines but one of the “supine ones…who employ[s] the technique of lying down and going limp” (1974:46). Fanny has no choice but to do as her uncle says (Mansfield Park. Emma also makes a case for women to remain single by maintaining that because married women are only nominal mistresses in their homes and have no real power.Chapter Four: Women and Identity happen to like her (357). it would be better for single women of large fortune never to marry (66-67). 42). Since he is master at Mansfield Park. Nancy Armstrong 144 . she implies that men are dispensable and thus seems to defy the convention of her time. She exercises this right herself when she jilts Elton (101-102) and when she flirts with Frank Churchill while not ever intending to marry him (188). Emma Woodhouse strongly feels a “woman is not to marry a man merely because she is asked” (Emma. She expresses her abhorrence of men who imagine “a woman to be ready for anybody who asks her” (47) and believes that it is the “female right” (51) to reject suitors such as Robert Martin. or even no power at all.
Knightley’s standard of conduct” (1987:153). Women’s power seems limited. realising she needs to live and survive in a patriarchal world. Judith Fetterley notes that because women have been kept from telling their story. and it is in relation to the marriage choice that their autonomy is most emphatically subverted” (1981:126). It could be argued that Austen challenges patriarchy. To be excluded from a literature 145 . as it is in the politics of anything else. Once again. “subjects herself to Mr.3 The power to write I have shown in previous chapters that women were prevented from writing and in this way from producing knowledge. 4. Although some of Austen’s women characters snub male authority by rejecting certain men. which gives man the power to choose. At the same time she shows that women need not say yes to the first marriage proposal that comes along but have the right to reject and to accept whomever they wish. however. Judith Lowder Newton argues that in Austen’s novels “[i]t is in relation to the marriage choice that men’s potential autonomy is brought into most conscious focus. towards the end of the novel. by allowing her women characters to reject certain suitors and to accept others. they remained powerless in a male-dominated society. It could be that Emma. they have been rendered powerless: Power is the issue in the politics of literature. it may be that Austen is illustrating that women often enter the patriarchal institution of marriage in order to survive. all of them end up marrying the male protagonist. As a result. accepts her husband’s authority and thereby relinquishes some of her own.Chapter Four: Women and Identity however suggests that despite Emma’s bravado she.
fortunately. (1993:126) 146 . Shoshana Felman comments on the need for women to write their own story: The need to speak to women without the intermediary of a man. and that each woman’s story can become a story only through women’s collective perception of themselves. Chris Weedon believes reverse discourses to be “the first stage in the production of alternative forms of knowledge” (1987:111). my emphasis) Writing new discourses means challenging existing ones. to listen more attentively to women. is also true. only through a female sharing and exchange of stories.Chapter Four: Women and Identity that claims to define one’s identity is to experience a peculiar form of powerlessness… (1978:565) The reverse. Feminist scholars argue that they can empower women by what they write. and to address more urgently the community of women. only through the bond of reading. has imposed itself as a corollary of my growing sense that the feminine predicament of “the absence of a story”…can be truly grasped. Judith Lowder Newton states that “[t]o write subversively…is a form of struggle – and a form of power” (1981:892). it is also a way for the oppressed to “assert their own identity and the existence of their own history” (1993:xii). the knowledge of women’s contribution could make a significant difference to the judgments and practices of the whole society…male dominance means women’s silence and…society can no longer afford to neither hear nor heed the voice of half of humanity. Edward Said warns that while writing is a way for the oppressor to keep a minority group in subjection. that only women can empower women’s story to become a story. (32. and perhaps remedied. Dale Spender comments in “Women and Literary History” (1989) that by writing women are able to change existing power relations: This is the argument of many women: that in the broadest possible sense.
“a form of power in its own right” (1987:156). Writing for Austen is.4 Domestic Power(lessness) Austen seems to be equating (paradoxically at first glance) domestic power with powerlessness by depicting women characters who appear to be formidable as having no real power. and in this way were “a form of social control” (91). She notes that the conduct books. 147 . By allowing women to tell their story she defies the male authority manifest in literary texts of her era and opens up new possibilities for women. Mrs Ferrars. in Nancy Armstrong’s words. Mrs Churchill. Lady Russell and Mrs Norris might believe that they wield domestic power. she shows that women can claim specific forms of power such as the power to judge and to refuse. which “were attuned to the economic interests that they designated as the domain of the male” (1987:94). The issue of domestic power in Austen’s time has been addressed by current feminist scholars.Chapter Four: Women and Identity When early nineteenth-century women writers such as Jane Austen took up the pen they took up. as Sandra Gilbert and Susan Gubar have suggested. or none at all. 4. Austen’s novels illustrate that manipulating one’s family and friends brings women no real power when women who exercise this type of power have their authority undercut. propagated the idea of ‘domestic power’ in order to ensure that women would effectively manage the home. they are shown to have little power really. a “quest for [their] own story” (1979:76). In addition. Though women such as Lady Catherine de Bourgh. Nancy Armstrong argues that the domestic power of women in this time was ironically symbolic of their powerlessness.
Austen merely hints at its existence. power is money36. in contemporary society. Greer illustrates the destructive effect girlpower can have (399). Sir William (196) and Maria Lucas (196) make her a figure to be reckoned with. young girls at school are invited to partake in excessive drinking and casual sex (399-402). Her “dictatorial and insolent” (Pride and Prejudice. and showed that. who is shown to be overbearing and manipulative. it appears to leave them vulnerable and helpless. Germaine Greer recently investigated a current phenomenon called ‘girlpower’. both being products of the distribution of power” (842). Instead of empowering women. states that “if an individual has high status. wealth [will] follow. 148 . Pointing out the consequences of such behaviour (unwanted pregnancy and venereal disease to mention but two). and shows an awareness that domestic power is a sham. although they usually overlap. Advocated and exploited by the media. 127) nature coupled with the awe she inspires from people like Collins (111). despite what especially younger women may believe. Lady Catherine de Bourgh. women (for the most part) are no longer under the illusion that domestic power is real power. She shows that this 36 The Social Science Encyclopedia (1996). edited by Adam Kuper and Jessica Kuper. While the issue of real power in the twenty-first century is overtly addressed by feminist writers.Chapter Four: Women and Identity The idea of what constitutes real power has changed considerably since the early nineteenth century. A feminist reading of Austen reveals a concern with what constitutes real power in her time. this type of power is not real power (1999:410411). Judith Lowder Newton believes that some of the women characters in Pride and Prejudice aspire to a kind of power which is “manipulative and indirect and [which] is further diminished by the fact that obsession makes them ineffective and unreflecting” (1981:130). and encouraged to match men in any lewd behaviour (409). Austen however illustrates that dictating people’s lives provides a false sense of power. Today. Mostly. provides a good example of a woman seeking such power.
For fear of how she might react Edward. 1984:85). The narrator seems critical of this type of ‘power’. Elinor describes her as “a very headstrong. her meanness. 149 . 273). is shown to ‘wear the breeches’ when she cleverly manipulates her husband into giving his stepmother and sisters. Austen once again seems to be critical of such manipulative ‘power’ when she portrays Mrs Ferrars as a “piece of nastiness” (Halperin. She manipulates Frank’s life by often feigning illness (195) and by expecting him to capitulate to her every whim (231. Fanny Dashwood. and she is shown to control her family with an iron fist. who plays the part of the wicked stepdaughter-in-law. 231). nothing at all (3-11). however. Austen indicates that Mrs Ferrars has no real power when she marries off both her sons to women with neither money nor connections (352-354). Because they realise their fortune depends “on the will of [their] mother” (13) their decisions are influenced by her approval. keeps his engagement to Lucy Steele a secret (129). for example. and when she has Elinor condemn “her pride. In Sense and Sensibility we encounter a seemingly powerful mother-and-daughter pair. Mrs Ferrars is the undisputed head of her family. Like her daughter. Mrs Churchill always gets her own way. She presides not only over her husband but also over her sons. We are told that she “was a capricious woman who governed her husband entirely” (14) and that Frank’s coming to Highbury always depended “entirely upon his aunt’s spirits and pleasure…upon her being willing to spare him” (94).Chapter Four: Women and Identity type of power can easily be destroyed in showing Lady Catherine helplessly standing by and watching as Darcy and Elizabeth are married (395). when Fanny is admonished for her narrow-mindedness and selfishness (3). In Emma. and her determined prejudice” (Sense and Sensibility. instead of three thousand pounds. proud woman” (142).
quieted. It could be argued that by showing how manipulation leads to powerlessness. Of all the inhabitants at Mansfield Park she is the only one who is not afraid of Sir Thomas (Mansfield Park. She is criticized for “her love of money…[and] her love of directing” (6). Manipulation is. Austen is implying that so-called ‘domestic power’ is not real power.Chapter Four: Women and Identity In the same way that Lady Catherine. the wit. 181). and the critical attitudes of Jane Austen. She is so skilled in twisting words and manipulating people that the Bertrams end up taking full responsibility for Fanny even though it was her idea in the first place (27-29). shown to contain no real power when Anne and Wentworth marry and the narrator concludes that Lady Russell. then. 25). indifferent to everything that passed” (452). Manipulating one’s family. her favourite niece. seems to bring less power. This suggests that Austen is interested in women’s true empowerment. and Elizabeth Bennet…is essentially an Austen fantasy. 169). a fantasy of power” (1981:133). Mrs Norris belongs to the same category of women as Lady Russell and Lady Catherine. She is shown to be formidable and is known “as a woman of the greatest influence with every body…able to persuade a person to any thing” (93). stupefied. 80. She is portrayed as cruel and scheming. Lady Russell controls Anne Elliot’s choice in marriage when she is young (Persuasion. To this end she appears to 150 . and especially enjoys making Fanny’s life miserable (74. runs away with Henry Crawford and leaves her “an altered creature. 108. while “suffering some pain…must learn to feel that she had been mistaken…and to take up a new set of opinions and of hopes” (219). and by contrasting this to real power such as Elizabeth’s. Judith Lowder Newton argues that “[r]eal power in Pride and Prejudice…involves having the intelligence. Mrs Norris seems to get her due reward when Maria. instead of more. however. Mrs Ferrars and Mrs Churchill run people’s lives.
The power to write thus enables Austen to contribute to women’s empowerment. 151 . In addition. not only because she suggests ways in which women may empower themselves but also because she identifies alternative identities for women.Chapter Four: Women and Identity encourage women to re-think and re-evaluate their inherited identity. Austen presents the reader with complex women characters who are given the power to judge and the power to refuse. including the notions of women as emotional creatures and as natural mothers.
Which of these views.Conclusion Conclusion Reaching the end of this thesis and looking back at what I have written. from where it is done” (1993:93). He points out that Austen’s novels have no one singular meaning but are open to a myriad of interpretations. does she address the issue of achieving equality with men?37 I am. the understanding of Austen’s fiction “depends on who does the interpreting. as a self-effacing good aunt. or as a nasty old maid. 37 152 . I ask myself to what extent we can categorise Austen as an early nineteenth-century feminist writer. I would like to refer to Edward Said’s understanding of interpreting texts. as Claudia Johnson shows: Austen has appeared to us in a number of contradictory guises – as a cameoist oblivious to her times. not the first to ask this question. in other words. indicates the ‘real’ Austen? In an attempt to answer this question. Shoshana Felman believes “reading has historically been a tool of revolutions and of liberation…a rather risky business whose outcome and full consequences can never be known in advance” (1993:5). Over the years there have been many conflicting interpretations of Austen. (1988:xiii-xiv) Sandra Gilbert and Susan Gubar write that when Austen was “not rejected as artificial and convention-bound. then. it is clear that I followed a Janet Chafetz states that “[t]he first wave of women’s movement in the nineteenth century was…a liberal feminist reform movement [which] sought equality within the existing social structure” (1999:151). of course. and no less important. as a subtly discriminating stylist. when it is done. To him. or a stern propagandist on behalf of a beleaguered ruling class. she was condemned as natural and therefore a writer almost in spite of herself” (1979:110). To what extent. or a homely songbird. unconscious of her art. Evaluating my own reading of Austen.
Alternatively. 153 . The fact that Austen does not overtly challenge patriarchy does not mean that we can discard her input in achieving an overall awareness of women’s subordinate position in patriarchal society. When we. much like Austen herself. while endeavouring to emphasise her feminist awareness. see that all Austen’s heroines get married. there are indications that the endings should not be taken seriously. for instance. to deal with as much of the evidence as possible…to read what is there or not there” (Said. If we merely reduce Austen’s work to tales about marriage without even considering that she had a socially critical agenda. 1988:xx) enables us to understand that Austen had to end her novels in the conventional way. For this reason literary critics have suggested that she might have hidden her social criticism behind the façade of endorsing marriage in patriarchal society. Austen’s novels reveal a consciousness of women’s powerlessness. I believe it to be the duty of literary and cultural critics and theorists to uncover and amplify this awareness. My argument takes into account the premise that we cannot separate a writer and the social system in which she/he lives. we should keep in mind that these women protagonists. ‘lived’ in an emphatically patriarchal society and that they realised the need to adhere at least to some of its conventions if they wanted to survive. and a sensitivity to the problems women writers encounter living and writing in a maledominated culture” (Johnson. 1993:96). I believe we fail to take “seriously our intellectual and interpretative vocation to make connections. No matter how compromised her politics may have been. or if we do not at least acknowledge that her novels create an awareness of women’s subordinate position in the late eighteenth/early nineteenth century.Conclusion gynocritical approach. The “consciousness of how the private is political.
and to men such as Erasmus Darwin who. As a result.Conclusion By looking at some of the issues which Austen’s fiction addresses. Possibly as a consequence of this legacy. and therefore not nearly as dependent 154 . then. These women. 1987:79). In Austen’s time. by considering what Austen’s novels reveal about women’s position in society in the early nineteenth century. Another part of women’s inheritance is the old and mistaken notion that women need men in order to survive. for example. one is made aware of the significant developments in gender politics between Austen’s time and our own. we are given insight into the legacy modern women have inherited. The idea. When Anne Elliot states the pen has always been in male hands she exposes history. Though contemporary women are often permanently employed. in his conduct books. can be traced back to the conduct books. that women should (often in addition to managing a full-time job) take responsibility for their home and for raising the children. realised the need to marry in order to survive financially. Austen’s novels show that women were deprived of an equal education to men and reveal that writing and producing knowledge was a male prerogative. women for many years believed that certain areas of expertise belonged to men exclusively. they often felt compelled to cultivate their ‘talents’ in the hope that they might find a husband. which “elaborate[d] all of the tasks that can be called domestic duty” (Armstrong. language and literature to have traditionally been male domains. “tried to think of a way of instilling in women the idea that their work was its own reward” (92). women were rendered financially and socially dependent on men by a biased economic and social system. Moreover. and by comparing them with the concerns of contemporary feminist scholars.
These discourses. which were made two centuries ago. a need for the type of labour women could provide. Her novels reveal male power to be enshrined in patriarchal institutions such as education and marriage.Conclusion on men’s financial support as they used to be38. Austen’s novels make us aware of the fact that women in her time had their identity prescribed for them. In order to appreciate the extent to which the feminist ideal has progressed. This differs vastly from contemporary feminists who demand that women take action. men were able to keep them submissive and powerless. These findings. and indicate that by enforcing marriage on women. 38 155 . I have mentioned that the conduct books afforded men the opportunity to keep women subjugated by creating an identity for women which would suit their (male) needs. increased control over fertility and heightened social expectations about women’s roles” (2000:499). they do not seem to suggest that any drastic measures should be taken. women’s work opportunities were increased after the Second World War as a result of higher educational achievement. Feminist writers have held social discourses responsible for coaxing women into marriage and motherhood. they often opt to marry. While Austen’s novels create an awareness of women’s pre-determined identity and subordination. In industrialised countries. Austen’s exploration of the effects of masculine power and authority suggests an inequality inherent in the society she was living in. in many ways foreshadow the work of French Marxist Louis Althusser who identifies in Ideology and Ideological State Apparatuses (1971) Lorraine Code reports that by 2000 “about 41 per cent of the world’s women aged fifteen and over [were] economically active. seem to have had their origins in the late eighteenth century. and then to explore some of current feminist theory’s suggestions for transformation. it would seem useful to take Austen’s feminist awareness as a starting point. which declare unmarried women to be failures. To begin with.
by continuing consolidation within education. has given rise to feminist literature: The assertion that women’s history has ignored the exercise of power is the precise opposite of reality. and…[were manifested] by the authority of recognizable cultural formations. “[o]ne of the significant roles of feminist theory has been to try to account for women’s subordination in society” (1993:52). women’s history might not have evolved. the church. Similarly. Sandi Cooper writes in an article entitled “Women and the World Order” (1999) that male power. indeed. largely male. I shall call this reality by its concept: the ideological State apparatuses” (1488-1489). this needs to be inferred from her novels. literature. the ways in which elites. In the past half dozen years. albeit destructive. but must not be confused with it. trade unionism. While she does not openly express any discontent with the fact that authority in patriarchal society resides ultimately in male persons. were it not for the way power has been exercised.Conclusion that ideological State apparatuses such as schools. (98) According to Jackie Stacey. bell hooks believes 39 Althusser states that “it is indispensable to take into account not only the distinction between State power and State apparatus. feminists today call for an explicit examination of the domination of women by men. the political system.39 Edward Said attributes the consolidation of an oppressive system like imperialism in part to the authority of such cultural institutions: …the processes of imperialism occurred beyond the level of economic laws and political decisions. the media and culture support existing (oppressive) social relations. and the visual and musical arts… (1993:12) Although Sandra Gilbert and Susan Gubar believe that Austen is aware “that male superiority is far more than a fiction” (1979:154). 156 . the family. the law. have controlled power and the discourse of rights and wrongs…have shaped a cottage industry of literature. but also another reality which is clearly on the side of the (repressive) State apparatus.
sexism and patriarchy.Conclusion feminists are “compelled to examine systems of domination and [women’s] role in their maintenance and perpetuation” (2000:27). male power. have to be transcended too in any full history of women or feminism. my emphasis) In addition to exposing patriarchal institutions for keeping women submissive in society. Sally Alexander argues emphatically that contemporary women need to do more than merely show that men have kept them subordinated: Since the seventeenth century feminists have railed against the tyranny of men. but those categories. One of the characteristics of feminist literature is. as Laura Marcus has stressed. while retaining a polemical conviction. male domination and in the idiom of the 1970s. Austen’s work seems to suggest some of the ways in which women can be empowered. “a critical awareness of women’s subordinate position …however this is expressed” (1992:11). (2000:26. 1992:37) and if patriarchy is to be understood as “a fundamental organisation of power on the basis of biological sex” (Weedon. Rosalind Miles writes that “the novel has been the only literary form in which 157 . as bell hooks notes: Feminism is a struggle to end sexist oppression. (1994:101) If power relations in society can be defined in terms of gender (Crowley and Himmelweit. I believe. as well as a commitment to reorganizing society so that the self-development of people can take precedence over imperialism. it becomes imperative for feminists to eliminate all forms of power. and material desires. 1987:127). economic expansion. Therefore. it is necessarily a struggle to eradicate the ideology of domination that permeates Western culture on various levels. The novel (the power of the pen) has provided women writers with a means of expressing desire for change.
my emphasis). Others such as Shoshana Felman argue that “feminism [should be] an enabling inspiration [and] not…a theoretical orthodoxy or…an authorizing new institutionalization” (1993:8). contemporary feminists expose the ways in which patriarchal practice encourages women to apply their power within man-made limits. bell hooks commented that the efforts of a group of white bourgeois women. who set out to obtain power. and only then can feminism hope to achieve an overall transformation of existing power relations. “had tremendous appeal for ruling groups of white males who were not threatened by women in feminist movement validating the status quo” (2000:86. my emphasis). Austen. In order to transform power relations in society. though it is necessarily a form of power to be used within patriarchal parameters. Judith Lowder Newton remarks that patriarchal society requires women “to lay aside any desire for the power to achieve. Only once women realise the ways in which they are kept from self-empowerment can they be liberated and empowered. Although Lowder Newton and hooks may have different political agendas. She is of the opinion that writers are able to inspire women by 158 . feminists encourage women to compete with men in male-dominated economic and political arenas. Recently. some feminists regard the abolition of marriage as necessary in achieving equal power relations in society. it would seem. and urge women to transcend patriarchal parameters. Heroines such as Fanny Price and Elinor Dashwood are given power. makes good use of the act of writing and of the novel as a genre when she empowers some of her women characters.Conclusion women have participated in numbers large enough to make their presence felt” (1987:2). Since motherhood and domestic responsibilities often keep women from competing with men and gaining economic equality. especially outside the domestic sphere” (1981:882. In contrast. both contribute to making women aware of how they unwittingly play into men’s hands.
if they want to attain self-empowerment. Austen seems to question women’s man-made identity by featuring. as when she shows that being a wife more often than not is tedious. she manages to suggest an alternative identity for women.Conclusion addressing them and that this in itself is an act of empowerment (127). as story” (Brink. instead of stereotyped women. Given that “we perceive ourselves. Judging by Austen’s novels. which is sometimes the case. bell hooks argues that “women need to know that they can reject the powerful’s definition of reality” (2000:92) so that they might be liberated from the debilitating social role in which men have entrapped them in. or indicates that motherhood does not necessarily provide a sense of fulfillment. heroines with complex identities. 159 . who display a variety of character traits. Another way of empowering women is to eradicate gender roles. and can develop alternative senses of themselves as women. it is imperative that women share their stories with other women. While Austen only hints at women discovering their own identity. our lives. as narrative. or the threat of it. By creating women protagonists such as Elizabeth Bennet and Emma Woodhouse. Austen seems to question certain assumptions about her own sex. many feminists typically provide one of two replies: either women are forced into it by violence. Jackie Stacey points out that feminist theory investigates the reasons for women’s acceptance of their man-made role in society: In answer to the question of why…women ‘accept’ their subordinate opposition in society. 1998:14). In addition. feminist writers today overtly challenge women’s socially-constructed identity in an attempt to empower them. women in the late eighteenth century had their identity prescribed (mostly by the notorious conduct book) as emotional creatures who could only find fulfillment as wives and mothers. At other times they were stereotyped by canonical texts as either angels or monsters.
In particular. for that matter. is Austen lacking? The answer is quite simple. and continue to do so. Irene Gedalof discusses how feminist theory can challenge the positioning of women in male discourses. Does Jane Austen qualify as a feminist? It would seem that she was aware of women’s position in society and that her novels expose masculine domination. Where. or whether they are going to question them and attempt to discover other ways of being and responding to one another. the readers who continue to read Austen and relate to her work.Conclusion but often is not. Two final questions need to be posed. This. she focuses on that feminist theory which offers positive redefinitions of models of women’s identity. then. for it is not Austen who is lacking in commitment. What I am suggesting is that the onus does not rest upon any particular writer to determine women’s future or fate. nor are contemporary feminist writers. however. 160 . is not enough to transform society. or women learn to accept their position through social conditioning and role models. It is now up to every woman to offer her contribution so that gender roles may be challenged and self-development may start. sociologists or theorists. It is ourselves. and asks how effective they have been in dealing with women’s dislocation and with questions of women’s embodiment (2000:339-340). (1993:65) Chris Weedon mentions that feminism rejects stereotyping of women and “questions the assumptions about women which social theories posit as true” (1987:6). They need to decide whether they are going to accept their sociallydictated gender roles. but upon women themselves. Jane Austen and others have done their part.
Feminisms: An Anthology of Literary Theory and Criticism. 161 . 1971. 1985. Louis. Jane. “Constructing the Subject: Deconstructing the Text”. Michielsens and M. C. London: Penguin. Pride and Prejudice. 1818. Deliyanni. Allen. M. London: Routledge. Jane Austen: Mansfield Park. London: Penguin. 1994. London: Penguin. M. 1988. 1972. 1992. Arnot. “Walking. Charlotte Brontë. Armstrong. I. 2000.. “Captivity and Cultural Capital in the English Novel. 1972. London: Virago. 1813. 1988. Desire and Domestic Fiction: A Political History of the Novel. Norton & Company. Rinehart and Winston. Reader. Belsey. M.Bibliography Bibliography Abrams. Ed. 1996. Changing Concepts of Citizenship in Public and Private Spheres”. A Glossary of Literary Terms. G. Sense and Sensibility. Orlando: Holt. 1994. Bowlby. London: Penguin. R. 1818. New York: Oxford University Press. 7. 1987. Araújo. Leitch. 1990. “Ideology and Ideological State Apparatuses”. 1814. Althusser. Northanger Abbey. 1997. The Norton Anthology of Theory and Criticism. Basingstoke: Macmillan.E. 2001.R. 1994.. The European Journal of Women’s Studies Vol. Persuasion. Armstrong. 1816. 1811. Women and Writing: Virginia Woolf as flâneuse. 1998. Evans. “Changing Femininity. The Concise Oxford Dictionary of Current English.H. London: Sage Publication. Ed. Penguin Critical Studies. Price-Herndl. Mansfield Park. and Ivinson. Armstrong.” New Feminist Discourses. K. I Married Him: A Study of the Women Characters of Jane Austen. Eds. Beer. 1974. V. Elizabeth Gaskell and George Eliot. H. New York: W. London: Penguin. 1994. P. S.W. Eds. London: Penguin. Austen. London: Macmillan. London: Penguin. Emma. R. Warhol and D. Becoming a Woman and Other Essays in 19th and 20th Century Feminist History. Alexander. Ed. R. N.B.” Novel: A Forum On Fiction Vol. 31. I. New York: Oxford University Press.
I. 1967. 1978. 1999. Cecil.. Ed. Ed. S. Winship. E.M. London: Harrap. London: Hutchinson. J. London: Cambridge University Press. Mort. New York: Kluwer Chow. A Portrait of Jane Austen. 1988. Ed. Handbook of the Sociology of Gender. Milton Keynes: Open University. S. 2000. J. Wilkinson. M. “Sex Roles and the Socialization Process”. F. “ ‘The Pen of the Contriver’: The Four Fictions of Northanger Abbey”. Hélène. B. and Himmelweit. Ed. Culverwell. W. Dahlström. J. New York: The Feminist Press at the City University of New York. Mort. S. Sellers. The Changing Roles of Men and Women. Smith. Jane Austen: Bicentenary Essays. and Weedon. Ed. Women’s Studies: An Interdisciplinary Journal Vol. M. T.Bibliography Brink. Brundson. and Baca Zinn. Calvino. 1999. 1992. D. R. C. Eds. The Novel: Language and Narrative from Cervantes to Calvino.. D. Burlin. Oxford: Clarendon Press. If on a Winter’s Night a Traveller. 1987. A. “Women and the World Order”. “Extreme Fidelity”. 1975. Encyclopedia of Feminist Theories. Class & Gender. Butler. M. Knowing Women. Eds. Bland. Academic/Plenum Publishers. “Psychoanalysis and the Cultural Acquisition of Sexuality and Subjectivity”. 1978. 1998. Writing Differences: Readings from the Seminar of Hélène Cixous. Crowley. Ed. Cixous. O. Burniston. “The More Things Change: The Rules and Late Eighteenth-Century Conduct Books for Women”. L. S. O’Rourke. Women’s Studies Quarterly Vol. 1930. R. Harrison. Brun-Gulbrandsen. 1993. London: Mandarin. Martin. California: SAGE Publications. Chafetz.R. London: Gerald Duckworth. J. McCabe. L. D. Halperin. 1984. Weedon and.E. A. Cooper. Newark: Harwood Academic Publishers. 29. C. Race. C. Women Take Issue: Aspects of Women’s Subordination. The Englishman and His Books in the Early Nineteenth Century. Ed. E. London: Penguin. S. xxvii. Cambridge: Polity Press. 2000. Zandy. 1996. Cape Town: University of Cape Town Press. 162 . Hobson. Cruse. Code. K. Darby. Jane Austen and the War of Ideas.S. London: Routledge. F. H.
S.com/films/sensible. Eds.” Introducing Women’s Studies: Feminist Theory and Practice. Cambridge: Blackwell. B. 1978.7. Language. Warhol and D. G. Richardson and V. Bouchard. M. The Routledge Critical Dictionary of Feminism and Postfeminism. Working with Feminist Criticism. 11. 1996. “Identity in Transit: Nomads. 163 .html De Lapp. R. Writing and Language: Making the Silences Speak. Ed. Michielsens and M. Marcus and A. Fair Lady 26 April 2000: 141.cnn. “Hollywood Popularizes Jane Austen”. New York: Cornell University. H. 1969. 1993.sten/index. 2000. Michel. Felman. Eagleton. London: Macmillan. Jane Austen’s Novels: The Art of Clarity. [online]. [online]. 1996. Feminisms: An Anthology of Literary Theory and Criticism.html Draga-Alexandru. M. R.R. I. M. Practice: Selected Essays and Interviews. 2000. What Does a Woman Want? London: The Johns Hopkins University Press. Gedalof. “Women. London: Macmillan. 1993. Robinson. Eds. 1999. D. Women: A Cultural Review Vol. The French Lieutenant’s Woman. Jane Austen and the State. Available from Internet URL htpp://newtimes. “Introduction: On the Politics of Literature”. Du Plessis. 7. New Haven: Yale University Press. London: Routledge. K. L. Eds. Mark. The European Journal of Women’s Studies Vol. Cyborgs and Women”. London: Sage Publications. Gard. Michielsens and M. S. Counter-Memory. 1996. M. J.rway.. S. Eds. D. London: Tavistock Publications. Fetterley. J. R. or Sex and Class as Culture”.Bibliography Dean. “Sweet Jane”.com/SHOWBIZ/Movies96. 1997. I Armstrong. 1987. The European Journal of Women’s Studies Vol. Evans.. Available from Internet URL http//www-cgi. “Quality Time”. Evans. Carr. 2000. 1992. 1977. Gagnier. London: Sage Publications. Evans. New York: Routledge. Eds. “The Functions of Class at the Present Time: Including Taste. Ed. M. Price Herndl. Gamble. Fowles. “Exiles From Power: Marginality and the Female Self in Postcommunist and Postcolonial Spaces”. Frith. Basingstoke: Macmillan.F. Foucault.
1988. 1980. and Deviance as Discourses of Voluntary Childlessness”. 23.” New Feminist Discourses. Irigaray.M. Class. Horwitz. The Life of Jane Austen. Ed. M. Richardson and V. L. 1994. Chicago: University of Chicago Press. [Online]. G. 2000. Eds. Cambridge: South End Press. “Pride and Prejudice”. “When No Means No: Disbelief. F. “From The Woman Question in Technology to the Technology Question in Feminism: Rethinking Gender Equality in IT Education”. Speculum of the Other Woman. Fair Lady 25 April 2001: 64-66. 1992. 1979. Luce.best. Jane Austen: Women Politics and the Novel. B. and Gubar. Harlow. Sussex: The Harvester Press. D. The Madwoman in the Attic: The Woman Writer and the 19th Century Literary Imagination. Kaplan. “When mothers lose that loving feeling”. Evans. Halperin.R. Basingstoke: Macmillan.nzoj/pride. London: Anchor. S. Available from Internet URL.. S. C. London: Routledge. 1999. D. Eds.” Introducing Women’s Studies: Feminist Theory and Practice. The Whole Woman.. Multiculturalism and Media Culture”. Greer. New York: Cornell University. I. “Women and the Family. J. Women’s Studies International Forum Vol.html Henwood. Gillespie. Warhol and D. London: Sage Publications. “Love. California: SAGE Publications. Feminist Theory: From Margin to Center. 2000. C. Kanneh. Zmroczek. R. 1993. Michielsens and M. hooks.16. New York: Pergamon. D.” Persuasions No. Robinson.Bibliography Gilbert. “Pandora’s Box: Subjectivity. Narcissistic Narrative: The Metafictional Paradox. D. 1984. b. Jackson. Johnson. London: Macmillan. C. Eds. S. Hutton. The European Journal of Women’s Studies Vol. Disregard. Ed. 1997. 164 . “Cultural Studies. New Haven: Yale UP. K. Armstrong. 1985. 2000. Eds. Humez. 7. Dines and J.L. London: Methuen.M. Gender. and Sexuality in Socialist Feminist Criticism. 1995. “Women’s Education During the Regency: Jane Austen’s Quiet Rebellion. Hutcheon. Price Herndl. Kellner. Mourning and Metaphor: Terms of Identity. G. R. 1974.com/~donh/Esperanto/Lite.” Feminisms: An Anthology of Literary Theory and Criticism. Race and Class in Media.
“Women. Eds. Feminisms: An Anthology of Literary Theory and Criticism. D. 165 . McFadden.” Critical Reconstructions: The Relationship of Fiction and Life. “Balancing Gender in Higher Education: A Study of the Experience of Senior Women in a ‘New’ UK University”. C. Stanford: Stanford University Press. Eds. 1939.B. 1992. 1997. and Spender. 1981. Halperin. London: Routledge. 2000. “‘Because Men Made the Laws’: The Fallen Woman and the Woman Poet”. 7. Victorian Feminism: 1850-1900. Tallahassee: The Florida State Lowder Newton. I. Second Edition. J. Kuper. Kroeber. P. Eds. and Kuper.M. Polhemus and R. 1966. Thousand Oaks: Sage Periodical Press. 1981. Henkle. Gender & Society Vol. Price Herndl. and Manfredi. Jane Austen: Bicentenary Essays. Paris: Editions du Seuil. R. New York: Routledge. “Power and Ideology of ‘Woman’s Sphere’”. Lacan. Eds. A. Ledwith. 1997. Jane Austen and her Art. S. L.14. Jacques. London: Oxford UP. Bose. A. Clark. Ed.” New Feminist Discourses. The Social Science Encyclopedia. Marcus. Ed. University. Lascelles. S. 1996. D. C. K.Bibliography Kramarae. M. J. M. New Case Books: Sense and Sensibility and Pride and Prejudice. J. Routledge International Encyclopedia of Women: Global Women’s Issues and Knowledge. “The Whore and the Other: Israeli Images of Female Immigrants from the former USSR”. Michielsens and M.R. Evans. R. R. I. Ed. 1975. McMaster. 1994. New Feminist Discourses. Levine.E. Power and Subversion”. 2000. Ed. 1992. Armstrong. London: Routledge. Ed. Warhol and D. 2000. New York: St Martin’s. London: Routledge. Basingstoke: Macmillan. Leighton. J. 1987. London: Cambridge University Press. London: Sage Publications. 1994. Ready Reference: Women’s Issues. M. “Pride and Prejudice: Fiction’s Lasting Novelty”. Ecrits. Pasadena: Salem Press. “Emma Watson: Jane Austen’s Uncompleted Heroine. Lemish. Ed. The European Journal of Women’s Studies Vol. Armstrong. Eds. “Feminist Aesthetics and the New Realism.
Nicholson. “Why Have There Been No Great Women Artists?” Theorizing Feminism: Parallel Trends in the Humanities and Social Sciences.J. Schmittroth. London: Croom Helm. Sexual/Textual Politics: Feminist Literary Theory. 1988. Clark. R. Moi. Nochlin. 1993. Robinson. New York: Vintage Books. 1992. Eds. Feminist Theories and the Philosophies of Man. L. Culture and Imperialism. Moore. I. “‘Drim Dros’: Marginalised Women both Inside and Outside of the Academia”. Eds. Rutherford. D. 1981.S. Eds. Encyclopedia of the Novel. D.Bibliography Meyer. Zmroczek. 1997. J. London: Routledge. Stewart. 1983. 1998. Nye. Sense and Sensibility and Pride and Prejudice. Ed. Murray. Mark. 1994. Herrmann and A. L. London: Routledge. E. 23. Swets & Zweitlinger. Beggar on a Beach of Gold. Carr. C. The Female Form: Women Writers and the Conquest of the Novel. S. Miles. Said. Marcus and A. R. Produced by Christopher Neil. 2000. 1987. “Motherhood and Women’s Lives”. 1995. 2000. 1985. and Reilly McCall. 1993. A. “Another Cup of Coffee”. Newman. “An Other Space: A Future for Feminism?” New Feminist Discourses. Rushdie. London: Routledge. Chicago: Fitzroy Dearborn Publishers. L. P. 1998. I. Schellinger. Ed. R. English Studies: A Journal of English Language and Literature 79:3. Introducing Women’s Studies: Feminist Theory and Practice. New York: Pergamon. Armstrong. 166 . Martin’s Press. London: Routledge. Eds. London: Vintage. Women’s Studies International Forum Vol. P. M. Ed. Mike. Blom. S. 11. Ed. London: Macmillan. Boulder: Westview Press. H. 2000. “‘Deeds and Words’: The Woman’s Press and the Politics of Print”. “Mr Knightley’s Education: Parallels in Emma”. Midnight’s Children. Richardson and V. A. Ed. Armstrong. Reay. J. “Can this Marriage be Saved: Jane Austen makes Sense of an Ending”. T. 1994. Women’s Almanac. Gale: UXL. Women: A Cultural Review Vol. K. New York: St.
Westport: Greenwood Press. Women’s Studies Encyclopedia. Richardson and V. T. R. The Victorian Novel: Modern Essays in Criticism. Eds. 1989. “The Unsettling Subject of Violence in Women’s Lives: Encouraging Notes from the Classroom Front”. Belsey and J. G. London: Macmillan. New York: The Feminist Press at The City University of New York. Mark. 1989. Oxford: Blackwell Publishers. H. Basingstoke: Macmillan. Feminist Practice and Poststructuralist Theory. Stacey. 1985. Weedon. R. PriceHerndl. Moore.” Eighteenth Century Fiction Vol. The Feminist Reader: Essays in Gender and the Politics of Literary Criticism. C. G. “Sweeping Changes”. Watt. Tanner. Carr. 1997. A Literature of Their Own: British Women Novelists from Brontë to Lessing. Marcus and A. 167 . 1999. Thorp. Eds. Feminine Fictions: Revisiting the Postmodern. Eds. 1993. J. I. University Press. “‘I See Every Thing As You Desire Me to Do’: The Scolding and Schooling of Marianne Dashwood. Seeber. New York: John Wiley & Sons. London: Macmillan. London: Methuen. “Laughing Medusa: Feminist Intellectuals at the Millennium”.Bibliography Schulman. B. Ed. Robinson. Tierney. Armstrong. Eds.R. London: Macmillan. 1971. Ed. Unger. Zandy. London: Routledge. 2001. Metafiction: The Theory and Practice of Self-Conscious Fiction. Women’s Studies Quarterly Vol. Princeton: Princeton University. Warhol and D. Ed. 11.K. J. Handbook of the Psychology of Women and Gender. 1986. Feminisms: An Anthology of Literary Theory and Criticism. 2000. Jane Austen. 1984. 1999. C. “Three Women’s Texts and a Critique of Imperialism”. 1987. Spender. “Women and Literary History”. Women: A Cultural Review Vol.” Introducing Women’s Studies: Feminist Theory and Practice. 11. Showalter. 1999. C. London: Oxford Waugh. I. 2001. Spivak. London: Routledge. P. xxvii. D. B.K. “Untangling Feminist Theory. H. E. L. Fair Lady 25 April 2001:58-59. 1977. D.
Tomaselli.K. 2000. Ed.E. M. S. “The Lived Body Experience of Domestic Violence Survivors: An Interrogation of Female Identity”.1797. “‘Me Mother’s Bank and Me Nanan’s. P.. You Know. Women’s Studies International Forum Vol.T. Ed. Cambridge: Cambridge University Press. Alison. 23. Support!’: Women who Left Domestic Violence in England and Issues of Informal Support”. Ed. 2001. Encyclopedia of Women and Gender: Sex Similarities and Differences and the Impact of Society on Gender. New York: Pergamon. Zmroczek. Zmroczek. 168 . Wollstonecraft. J. 1995.Bibliography Wesely. 23. J. A Vindication of the Rights of Men and a Vindication of the Rights of Woman. New York: Pergamon. 1759 . I. and Schneider. 2000. Women’s Studies International Forum Vol. Wilcox. San Diego: Academic Press. C. C. Mary. Ed. Worell.
|
https://www.scribd.com/document/190295904/Kollmann-e
|
CC-MAIN-2017-47
|
refinedweb
| 55,708
| 57.77
|
view raw
I have a Trie in Java, and I want search if cointains a word.
For example: Trie: [casa-perro-animal], hogar = false; casa = true;
public boolean search (String word){
/**Method to complete**/
}
public class Trie {
/**
* Clase auxiliar para guardar caracteres que forman parte de una palabra
* @author zenon
*/
protected class Info {
char c; // Caracter actual
Info alt; // Caracter alternativo para la misma posición
Info next; // Caracter que es la primera opción en la siguiente posición
public Info(char c, Info alt, Info next) {
this.c = c;
this.alt = alt;
this.next = next;
}
}
protected Info root; // Referencia al punto de inicio de la estructura
You are looking at doubly chained tree implementation of Trie:
image and description from wikipedia's entry on Trie
Vertical arrows are child pointers, dashed horizontal arrows are next pointers. The set of strings stored in this trie is
{baby, bad, bank, box, dad, dance}. The lists are sorted to allow traversal in lexicographic order
Your search has to consume the characters one by one of the searched
word and navigate the trie.
Take the first character and check whether your root contains it. If yes, you can move to next character in the
word and down along the solid arrow to the next node of the current list - in your implementation it's the
next node of type
Info. This way you are traversing within the same list downwards (according to the diagram above).
If the current node does not contain the character you are searching for, you move horizontally across to the next alternative list (along the dotted lines). In your case this is represented by the
alt
Info node. And you repeat the test for the same letter there. If no luck, move to the next alternative list again.
If you have checked all alternative lists at a given level without any match, and are facing a dead end (where
alt == null), you can conclude that the
word is not contained within your trie.
Conversely if you have consumed all characters from the
word and are at the last node within a list (i.e.
next == null), then you can conclude that the
word is stored within the trie.
|
https://codedump.io/share/N4kO1LQeJZw/1/search-word-in-trie
|
CC-MAIN-2017-22
|
refinedweb
| 367
| 66.98
|
TL;DR
I get a build error when I try debugging my program. I press debug and Visual Studio 2010 asks me "Would you like to build it?" I press "Yes." Then it says "There were build errors, would you like to run the last successful build?" I click "Yes" again. Then it says "Unable to start program C:Users\admin\documents\visual studio 2010\Projects\HelloWorld\Debug\HelloWorld.exe The system cannot find the file specified"
The code is:
#include <FL/Fl.H> #include <FL/Fl_Box.H> #include <FL/Fl_window.H> int main() { Fl_Window window(200, 200,"Window title"); Fl_Box box(0,0,200,200,"Hey, I mean, Hello, World!"); window.show(); return Fl::run(); }
I keep getting that error. Is there a way to fix it? I can't seem to compile anything. My specs are: iMac 27'' Core i7 3.4 gHz 6970M 4GB DDR3 RAM 1TBHDD. Windows 7 Ultimate running in bootcamp using Visual Studio 2010 Ultimate SP1 as my IDE.
|
http://www.dreamincode.net/forums/topic/236537-c-fltk-bjarne-stroustrup-book/
|
CC-MAIN-2016-50
|
refinedweb
| 165
| 79.67
|
Flutter Canvas API: Getting Started
Learn how to use the Flutter Canvas API to draw shapes and create custom widgets.
Version
- Dart 2.12, Flutter 2.2, Android Studio 4.2
Flutter offers a cross-platform UI toolkit that’s both “expressive and flexible”. But even with this rich and flexible toolkit, there isn’t always an out-of-the-box widget for every nifty design your UI/UX team might dream up. So the Flutter team came up with a solution; they created a canvas and said: “Draw anything you like.” This article will be an entry-level answer to the question: “What is a Flutter canvas, and how can I draw with it?”
In summary, you’ll learn how to:
- Draw basic shapes like polygons, ovals, circles, arcs and curves.
- Compose the basic shapes to draw more complex shapes.
- Animate the complex shapes.
Drawing 2-D Images on the Screen
Like an artist’s canvas is a physical surface to draw on, a
Canvas in Flutter is a virtual surface for drawing. But unlike a regular art canvas, you can’t paint on the Flutter canvas with physical brushes.
Flutter
Canvas uses a two-point (x and y) coordinate system to determine the position of a point on the screen. This coordinate system is a Cartesian coordinate system in two-dimensional space. Although the x-axis starts from the left of the canvas and increases horizontally to the right, the y-axis begins at the top and increases as you move down the canvas. The first pixel at the top-left of the canvas is (0, 0). This position is the origin of both the x-axis and y-axis. Positive numbers move the virtual “brush” right on the x-axis and down on the y-axis. The opposite happens for negative numbers.
To draw, say, a triangle, you pass instructions to the
Canvas API to start from the coordinate of A, move to C, then move again to B and finally close the gap at A.
Getting Started
Download the starter project by clicking Download Materials at the top or bottom of this tutorial.
Open the starter folder with the latest version of Android Studio or Visual Studio Code. Next, either run
flutter pub get in the terminal or open pubspec.yaml and click the Pub get tab that appears in your IDE. Once complete, open lib/main.dart and run the project to see this on your target emulator or device:
Now that you’ve got the project running, it’s time to dive into the canvas API.
Overview of the CustomPaint and Canvas API
Flutter’s UI rendering stack comprises the Dart and C++ layers. The Material and Cupertino widgets comply with the Google Material and iOS design languages at the Dart layer. This high-level set of widgets depends on the Widgets layer, which depends on the Dart rendering engine. This rendering engine is built from the Animation, Gestures and Painting API, which all lie on the Foundation layer. These layers are written in Dart and powered by a much-lower-level rendering engine written in C++ that uses the high-performance C++ 2D rendering engine, Skia. This lower-level rendering layer exists at the same level as other layers as Platform Channel, Text Layout, System Calls, etc. For more information, see Flutter’s Architectural layers documentation.
CustomPainter is an abstract class in the Dart rendering layer. It provides you with a
Canvas. This
Canvas and most of the other APIs you’ll use to draw come from the Dart painting layer.
You’ll extend this class to draw your custom shape. A minimal implementation looks something like this:
class MyFancyPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { } @override bool shouldRepaint(covariant CustomPainter oldDelegate) => false; }
In
paint, The
size parameter contains the width and height of the
Canvas in logical pixels. You’ll use this to determine the size of the shapes to draw. If you draw outside this
size, the shapes will cut off or, worse still, won’t be visible on the screen.
shouldRepaint() is called when a new instance of the custom painter is created. This helps the Flutter engine decide whether to call
paint() again.
To display the shapes drawn in a
CustomPainter, you need a
CustomPaint widget.
CustomPaint is just like a normal widget. It accepts an instance of a subclassed
CustomPainter in its
painter and
foregroundPainter parameters. Next, is accepts a
child parameter which can be any widget. In some ways,
CustomPaint behaves like a
Stack widget. The value of
painter renders first, then
child, and
foregroundPainter renders on top. All three parameters are optional.
Drawing Basic Shapes
You’ll continue exploring the
Canvas API by writing instructions to draw basic shapes like polygons, ovals, circles, arcs and curves.
Drawing Polygons
Before drawing on the canvas, you need to decide the color and size of the drawing pen. An instance of
Paint defines the pen. Add the following lines of code to
PolygonPainter‘s
paint() in the file lib/polygon_painter.dart.
final paint = Paint() ..strokeWidth = 5 ..color = Colors.indigoAccent ..style = PaintingStyle.stroke;
Here’s a breakdown of the fields you just set:
- strokeWidth: The width, in pixels, of the drawing pen.
- color: The color of the drawing pen.
- style: Whether the shape should be filled in or just drawn as an outline.
There are other properties for
Paint, but those are the ones you’ll need for this tutorial.
Next, you’ll learn how to draw a triangle.
Drawing a Triangle
Now, you’ll draw a triangle on the canvas. Run the project and tap the Polygons button to see this:
The screen has a grid as a visual aid. The grid divides the area into boxes like graph paper. Each box is 50px by 50px.
GridPainterand
GridWidgetin lib/grid to see how to draw the grid.
You’ll need to place your pen somewhere on the
Canvas to start drawing. Then, you’ll declare a
Path object. Afterward, you’ll move the drawing pen to three boxes from the left and zero boxes from the top. And because each box is 50px by 50px, that’s 150px from the left and 0px from the top. Add the following code below the
paint declaration in the
paint() of the
PolygonPainter.
final triangle = Path(); triangle.moveTo(150, 0);
Hot-reload the app, and you’ll notice nothing changed. This is because you have to tell the
Canvas object to draw the
triangle path. Add the following below the triangle
path you just declared:
canvas.drawPath(triangle, paint);
Notice that you also passed
paint
into
drawPath. The Flutter engine will use the
paint object to draw the actual triangle.
Hot-reload the app again, and you'll still notice nothing changed.
What's the reason this time? Technically, you haven't drawn anything yet. You only moved your pen to a point on the
Canvas.
Now, you need three lines to draw a triangle. To draw the first line, you'll need to move your pen from the current point to another. Add this piece of code below the call to
moveTo():
triangle.relativeLineTo(100, 100);
This instruction draws a line from where you placed your pen earlier to two boxes to the right and two boxes below.
Hot-reload the app to see this:
To draw the second line of the triangle, add this method call after the previous
relativeLineTo statement:
triangle.relativeLineTo(-150, 0);
This instruction draws a line from where you stopped earlier to three boxes to the left while remaining at the same vertical position. Notice how left move commands use negative values?
Hot-reload the app again, and you'll see this:
You need another line to complete the triangle. You could either draw this line manually like you've been doing earlier or use
Path
close(). The latter automatically draws a line from the current position of the pen to where you initially moved your pen.
Now, write this below the other triangle path method calls:
triangle.close();
Your PolygonPainter paint method should now look like this:
void paint(Canvas canvas, Size size) { final paint = Paint() ..strokeWidth = 5 ..color = Colors.indigoAccent ..style = PaintingStyle.stroke; final triangle = Path(); triangle.moveTo(150, 0); triangle.relativeLineTo(100, 100); triangle.relativeLineTo(-150, 0); triangle.close(); canvas.drawPath(triangle, paint); }
Hot-reload the app and you'll get this:
Now you'll learn how to draw a square.
Drawing a Square
Like drawing with a physical canvas and brushes, there are several ways to draw a shape. A good example is a four-sided polygon like a square or rectangle. You could draw the individual lines from one point to another until you complete the shape or use the
Rect object.
- The
PathObject Method:
final square1 = Path(); // 1 square1.moveTo(50, 150); // 2 square1.relativeLineTo(100, 0); // 3 square1.relativeLineTo(0, 100); // 4 square1.relativeLineTo(-100, 0); // 5 square1.close();
Here's a breakdown of that code:
- Start at one box from the left and three boxes from the top.
- From there, draw a line to two boxes to the right while remaining at the same y point (i.e., a horizontal line).
- From there, draw a line to two boxes downwards while remaining at the same x point (i.e., a vertical line).
- From there, draw a horizontal line to two boxes to the left.
- Join the current position to the starting position.
- The
RectObject Method:
const square2 = Rect.fromLTWH(200, 150, 100, 100);
This draws a 100px by 100px shape from four boxes from the left and three boxes from the top.
Both methods will draw the same shape but at different positions. Add the code from both the rectangle draw methods above inside the
paint() of
PolygonPainter after the
canvas.drawPath(triangle, paint) statement. Then, add the following two statements to draw each of the rectangles:
canvas.drawPath(square1, paint); canvas.drawRect(square2, paint);
Hot-reload the project to see this:
Can you guess which method drew which square?
Now that you've mastered squares, you can move on to hexagons.
Drawing a Hexagon
To draw a hexagon — a polygon with six sides — use the
Path object like you did in the first method above to draw a square. Add the following statements below the other drawing instructions in the
paint() of
PolygonPainter:
final hexagon = Path() // 1 ..moveTo(175, 300) // 2 ..relativeLineTo(75, 50) // 3 ..relativeLineTo(0, 75) // 4 ..relativeLineTo(-75, 50) // 5 ..relativeLineTo(-75, -50) // 6 ..relativeLineTo(0, -75) // 7 ..close(); canvas.drawPath(hexagon, paint);
Here's what that code is doing:
- Start at 175px from the left and 300px from the top.
- From there, draw a line to a point at 75px on the x-axis and 50px on the y-axis.
- From there, draw a 75px vertical line to downwards.
- From there, draw a line to a point -75px on the x-axis and 50px on the y-axis.
- From there, draw a line to a point -75px on the x-axis and -50px on the y-axis. Negative values move up on the y-axis.
- From there, draw a 75px vertical line upward.
- Join the current position to the starting position.
Hot-reload, and you'll see this:
Hexagons are great, but wouldn't it be cool if you could draw more complex objects? Good news! You'll learn how to draw more complex objects next.
Drawing a Cross - a More Complex Polygon
You can also draw even more complex shapes like a Greek Cross with many joints by moving from one point to another. Add the statements below inside
paint() of
PolygonPainter:
final cross = Path() ..moveTo(150, 500) ..relativeLineTo(50, 0) ..relativeLineTo(0, 50) ..relativeLineTo(50, 0) ..relativeLineTo(0, 50) ..relativeLineTo(-50, 0) ..relativeLineTo(0, 50) ..relativeLineTo(-50, 0) ..relativeLineTo(0, -50) ..relativeLineTo(-50, 0) ..relativeLineTo(0, -50) ..relativeLineTo(50, 0) ..close(); canvas.drawPath(cross, paint);
Hot-reload to see this:
That's just the basics of drawing custom shapes: You draw lines from one position to another. But what if you want solid shapes and not just lines? That, too, is simple! Change the
style property of the
paint instance from
PaintingStyle.stroke to
PaintingStyle.fill. Hot-reload to see solid shapes like these:
Next up, you'll learn about drawing circles.
Drawing Circles
Start off by opening the lib/ovals_painter.dart file. To draw your oval you'll need another instance of
paint, so add the following below in
paint():
final paint = Paint() ..strokeWidth = 4 ..color = Colors.blueAccent ..style = PaintingStyle.stroke;
Unlike the straight lines that make up polygons, drawing circles and ovals doesn't require moving from point to point on the
Canvas. One of the easiest ways of drawing a perfect circle is to define the center point of the circle and give it a radius. Add the following below the
paint declaration:
const circleRadius = 75.0; const circleCenter = Offset(200, 150); canvas.drawCircle(circleCenter, circleRadius, paint);
The center of the circle is at 200px from the left and 150px from the top. The radius of the circle is 75px.
Run the app and tap the Ovals and Circles button to see this displayed in the app:
Now onto ovals!
Drawing Ovals
Ovals are just circles but with unequal width and height.
Add the following oval drawing statements below the code for drawing the circle in
OvalPainter:
const ovalCenter = Offset(200, 275); final oval = Rect.fromCenter(center: ovalCenter, width: 250, height: 100); canvas.drawOval(oval, paint);
The center of the oval will be at 200px from the left and 275px from the top. It'll be 250px wide and 100px tall.
Run the project to see this:
You have drawn an avatar by combining a circle and an oval! You can also combine circles to draw concentric circles. To achieve this, you can iteratively reduce the radius of the circle.
Add the following concentric circle code below the instructions for drawing the oval:
var concentricCircleRadius = 100.0; const center = Offset(200, 500); while (concentricCircleRadius > 0) { canvas.drawCircle(center, concentricCircleRadius, paint); concentricCircleRadius -= 10; }
Hot-reload and you'll see this:
You'll do more shape composition in later sections.
Drawing Arcs and Curves
The
Canvas API supports four types of curves: arc, quadratic Bézier, cubic Bézier and conic Bézier. In this section, you'll learn about arcs and quadratic and cubic Bézier curves.
Arc
An arc is a section of a circle. Imagine a circular pizza. After you've eaten a slice from it, what's left is an arc. The slice you ate is also an arc. The angle made by the slice of pizza when the slice is equal to the radius of the whole pizza is called the radian.
In the diagram above, the angle of θ is defined as one radian if the arc length made by BC equals the circle's radius.
You need a bounding box, a start angle and a sweep angle to draw an arc. Both start and sweep angles are in radians. Because many people like to think of angles in units of degrees, the utility function
degreesToRadians() has been provided in the
ArcsCurvesPainter class to convert degrees to radians.
The start angle begins at the x-axis on the circle, as shown by the red line shown below. You draw positive angles in the clockwise direction. The end position of the arc is the sum of start and sweep angles.
Add the following lines of code to the
paint() of
ArcsCurvesPainter in arcs_curves_painter.dart:
const arcCenter = Offset(200, 80); final arcRect = Rect.fromCircle(center: arcCenter, radius: 75); final startAngle = degreesToRadians(10); final sweepAngle = degreesToRadians(90); canvas.drawArc(arcRect, startAngle, sweepAngle, true, curvesPaint);
Run the project and tap the Arc and Curves button. You'll see an arc drawn in the clockwise direction:
To draw the arc counterclockwise, change the sweep angle to a negative number:
final sweepAngle = degreesToRadians(-90);
Hot-reload, and you'll see this:
The third parameter of
canvas.drawArc() determines how to close the arc. Passing
true, as you did, draws the arc like a slice of pizza. Otherwise, it draws just the curved line segment.
Change the drawing instruction of the arc to this:
canvas.drawArc(arcRect, startAngle, sweepAngle, false, curvesPaint);
Hot-reload to see this:
Play around with the parameters to better grasp how
canvas.drawArc() behaves.
Onwards to Bézier curves!
Quadratic Bézier Curves
Quadratic Bézier curves are sub-path segments that curve from the current point to an endpoint using a control point. The control point defines the slope at the beginning and the end of the curve.
Here's an example. The curve starts at point A (50, 300) and ends at B (350, 300). Point C is the control point at (150, 200). The plotted Bézier curve is the brown line.
And here's the Dart code for this curve:
final qCurve1 = Path() ..moveTo(50, 300) ..relativeQuadraticBezierTo(100, -100, 300, 0); canvas.drawPath(qCurve1, curvesPaint);
Look at another example:
The curve starts at (50, 50) and ends at (350, 150), and the control point is at (200, 350). As illustrated by the image below, A is the starting point, C is the control point and B is the end of the line. The plotted Bézier curve is the brown line.
final qCurve2 = Path() ..moveTo(50, 50) ..relativeQuadraticBezierTo(150, 300, 300, 100); canvas.drawPath(qCurve2, curvesPaint);
Cubic Bézier Curves
Although Quadratic Bézier uses one control point, Cubic Bézier uses two control points, giving more control over the beginning and end slope of the curve. Here's a simple example:
The curve starts at (50, 150) and ends at (350, 150). The curve begins with a slope defined by the line AC and ends with the slope defined by the line DB.
final cCurve1 = Path() ..moveTo(50, 150) ..relativeCubicTo(50, -100, 250, -100, 300, 0); canvas.drawPath(cCurve1, curvesPaint);
Here's another example. The curve starts at (350, 50) and ends at (200, 300). Like the previous example, the curve begins with a slope defined by the line AC and ends with the slope defined by the line DB.
final cCurve2 = Path() ..moveTo(350, 50) ..relativeCubicTo(0, 450, -300, 300, -150, 250); canvas.drawPath(cCurve2, curvesPaint);
To run the Bézier curve examples, add the following lines of code to
paint() in
ArcsCurvesPainter.
// Quadratic Bézier final qCurve1 = Path() ..moveTo(50, 150) ..relativeQuadraticBezierTo(100, -100, 300, 0); canvas.drawPath(qCurve1, curvesPaint..color = Colors.deepPurpleAccent); final qCurve2 = Path() ..moveTo(0, 150) ..relativeQuadraticBezierTo(150, 300, 300, 100); canvas.drawPath(qCurve2, curvesPaint..color = Colors.blue); // Cubic Bézier final cCurve1 = Path() ..moveTo(0, 450) ..relativeCubicTo(50, -100, 250, -100, 300, 0); canvas.drawPath(cCurve1, curvesPaint..color = Colors.black); final cCurve2 = Path() ..moveTo(380, 300) ..relativeCubicTo(0, 450, -300, 300, -150, 250); canvas.drawPath(cCurve2, curvesPaint..color = Colors.pink);
Hot-reload to see this:
Animating Custom Shapes
Combined with the simplicity of the animation API, you can implement fancy animations with custom shapes. To see how this works, you'll build an animated charging/discharging battery widget in this section.
Animating a Charging Battery
In this section, you'll draw a charging and discharging battery and drive the charge progress with the animation controller.
Here's what the unanimated state looks like:
The battery consists of the following shapes:
- A border with rounded corners drawn using
RRect. An
RRectis the same as
Rect, except it supports defining rounded corners.
- A filled semi-circle drawn with an arc representing the battery pin.
- The amount of charge drawn with a
RRect.
Start by opening animated_battery.dart in the battery folder.
AnimatedBattery has an animation controller configured to animate forever in an endless loop, calling
setState() when the controller value updates. Inside
build() is a
CustomPaint widget. The animation value passed to
BatteryPainter is used to draw the amount of battery charge.
Run the app and select the Animated Battery button, and you'll see a blank screen.
Open battery_painter.dart in the battery folder.
BatteryPainter is where you'll draw the battery widget. To move things along, some fields are already declared.
Start by drawing the battery border. Add the following code below
paint().
RRect _borderRRect(Size size) { // 1 final symmetricalMargin = margin * 2; // 2 final width = size.width - symmetricalMargin - padding - pinWidth; // 3 final height = width / 2; // 4 final top = (size.height / 2) - (height / 2); // 5 final radius = Radius.circular(height * 0.2); // 6 final bounds = Rect.fromLTWH(margin, top, width, height); // 7 return RRect.fromRectAndRadius(bounds, radius); }
Here's a breakdown of that code:
- The total of the margin on each axis. You're giving the shape a margin of the value
marginon the top, right and bottom.
- The width of the border. This is the
Canvaswidth minus the horizontal margins, the pin width and the space between the pin and the border.
- The height of the border. The height is half the width.
- The top of the border. This value is the y-coordinate of the top edge of the battery that will center the battery on the canvas.
- The radius of the border. The corner radius is 20 percent of the height.
- Instantiate the bounds of the border with all the above values. The left offset of the border is the value of the margin. That'll give a space (the value of margin) before drawing the border.
- Instantiate and return the RRect from the bounds and radius.
Now, add this code inside
paint():
// Battery border final bdr = _borderRRect(size); canvas.drawRRect(bdr, borderPaint);
Run the code to see this:
Next, you'll draw the battery pin. Add the following code below the declaration of
_borderRRect():
Rect _pinRect(RRect bdr) { // 1 final center = Offset(bdr.right + padding, bdr.top + (bdr.height / 2.0)); // 2 final height = bdr.height * 0.38; // 3 final width = pinWidth * 2; // 4 return Rect.fromCenter(center: center, width: width, height: height); }
Here's what this is doing:
- The center of the pin. Position the center with the center of the height of the battery border. Add some padding to position the pin away from the right edge of the battery border.
- The height of the pin, which is 38 percent of the height of the border of the battery.
- The pin bounding box width. This width is twice the pinWidth. The arc will only occupy half this.
- Instantiate and return the pin bounds.
Add the following import for the math package.
import 'dart:math' as math;
Now, add the drawing instructions for the battery pin to
paint() after the battery border:
// Battery pin final pinRect = _pinRect(bdr); canvas.drawArc(pinRect, math.pi / 2, -math.pi, true, pinPaint);
This draws a filled arc from 90° to -180°.
Hot-reload, and you'll see this:
The next step is to draw the charge of the battery. In this first iteration, you won't animate the charge. Add this below the declaration of
_pinRect():
RRect _chargeRRect(RRect bdr) { final left = bdr.left + padding; final top = bdr.top + padding; final right = bdr.right - padding; final bottom = bdr.bottom - padding; final height = bottom - top; final width = right - left; final radius = Radius.circular(height * 0.15); final rect = Rect.fromLTWH(left, top, width, height); return RRect.fromRectAndRadius(rect, radius); }
The statements above compute the bounds of the charge shape using the bounds of the battery border while providing for the padding.
Now, add this below the drawing instructions for the pin in
paint():
// Battery charge progress final chargeRRect = _chargeRRect(bdr); canvas.drawRRect(chargeRRect, chargePaint);
Run the code to see this:
The next step is to animate the charge progress, and you won't believe how ridiculously — wait for it! (in the voice of Barney Stinson) — easy this is!
In
_chargeRRect(), simply replace the width parameter passed to
Rect.fromLTWH() from
width to
width * charge. The line becomes:
final rect = Rect.fromLTWH(left, top, width * charge, height);
Run the project, and you'll see this:
In reality, this is not how a battery charges. To fix this, you'll make the animation progress in increments of
minCharge.
Write the statement below inside
_chargeRRect(), just at the top:
final percent = minCharge * ((charge / minCharge).round());
Also, change the width value you just changed from
width * charge to
width * percent, so
_chargeRRect() becomes:
RRect _chargeRRect(RRect bdr) { final percent = minCharge * ((charge / minCharge).round()); final left = bdr.left + padding; final top = bdr.top + padding; final right = bdr.right - padding; final bottom = bdr.bottom - padding; final height = bottom - top; final width = right - left; final radius = Radius.circular(height * 0.15); final rect = Rect.fromLTWH(left, top, width * percent, height); return RRect.fromRectAndRadius(rect, radius); }
Run the code to see this:
That's it! You did such a fantastic job!
Where to Go From Here?
The completed project contains all the code used in this tutorial. You can find this inside the completed folder in the file you downloaded earlier or by clicking Download Materials at the top or bottom of this tutorial.
This tutorial taught you to draw basic and composite custom shapes with the Flutter
Canvas API. Additionally, you learned how to tap into the power of the animation API to animate these custom shapes.
To learn more about the Flutter architectural layers, head over to this detailed official documentation by the Flutter team. This Stackoverflow answer by Flutter's former Product Manager Sett Ladd highlights the difference between logical and physical pixels in relationship to Flutter.
I hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!
|
https://koenig-assets.raywenderlich.com/26483389-flutter-canvas-api-getting-started
|
CC-MAIN-2021-49
|
refinedweb
| 4,242
| 67.45
|
Re: "Mastering C Pointers"....
From: Sheldon Simms (sheldonsimms_at_yahoo.com)
Date: 11/04/03
- ]
Date: Mon, 03 Nov 2003 23:33:58 -0500
On Tue, 04 Nov 2003 00:59:03 +0000, Alan Connor wrote:
> On Mon, 03 Nov 2003 18:50:09 -0500, Sheldon Simms <sheldonsimms@yahoo.com> wrote:
>>
>>
>> On Mon, 03 Nov 2003 21:29:12 +0000, Alan Connor wrote:
>>
>>> Got really fed up with the Richard fellow. Killfiled his arrogant ass for
>>> a while.
>>
>> You are of course welcome to killfile anyone you want, however you
>> should be aware that Richard is telling you the truth and Roose is
>> not. At least, he is not telling you the whole truth.
>
> And all the people that ARE, are doing nothing but confuse me.
Ok, let me try to tell you something about pointers that is (hopefully)
precisely correct, but won't confuse you.
A pointer is a kind of variable that can "point to" some object.
But what does "point to" mean in this case? It means that it is
possible to access the object by using the pointer to see where
it is.
Let me try to show how it works with an example. For example, let me
declare an integer variable:
int x; /* an integer named x */
Becase of the declaration there is an object named x that has a value
that is an integer. We can change the value of the object named x and
we can retrieve the value of the object named x:
x = 3; /* change the value of the integer named x to 3 */
printf("x == %d\n", x); /* print the value of the integer named x */
You might wonder why I'm being verbose and talking about changing "the
value of the object named x" instead of "changing x". I'm doing that
because it is possible to manipulate the object without calling it x.
The integer in memory can have many names, only one of which is "x",
although "x" could be considered the "main" or "canonical" name of
the object. For example I can also refer to the object with a pointer:
int * p; /* a pointer named p to int */
p = &x; /* make p "point to" the object named x */
Now px refers to the same object as x and I can manipulate the value
of that object by using the name "p".
*p = 5;
printf("x == %d\n", x);
printf("*p == %d\n", *p);
This will produce the output:
x == 5
*p == 5
And you can see that the value of the object named x has been altered
by using p. the object that p points to is the same object that is
named x. This can be said more succinctly "p points to x". However,
p is not the same as x. p is also the name of an object. That object
has a type (pointer to int), and a value of some kind. The value of
p "refers to" the object named x, but how it does that is of no
concern to us, all that is important is that we can manipulate that
value in certain ways which I will get to in a minute.
To try to make this clear before I talk more about the value of p,
here's a diagram that attempts to show the objects named p and x
in memory
+------------+
| (value)---|------+
+------------+ | +--------------+
+----->| 5 |
p: pointer to int +--------------+
x: int
There is an object named p, and an object named x. The object named x
has the value 5 and the object named p has a value that points to x.
Now roose said "pointers are integers". This is wrong, but it's close
to the truth. It's close to the truth because pointers act like integers
in some ways. For example, we can add an integer to them. If we add an
integer to a pointer, we get a pointer that points to the "next thing",
where thing is whatever pointer points to. To illustrate this I'll
make another diagram.
p p+1 p+2 p+3
| | | |
V V V V
+------------+------------+------------+------------+
| | | | |
+------------+------------+------------+------------+
x: int
If the pointer p points to the integer x, then p+1 points to the integer
after x, and p+2 points to the integer after that, and so on. C allows
the programmer to view memory this way. If you have a pointer to some
object, then the value of that pointer plus one is a pointer to another
object of the same type that comes right after the first one.
However, if you try this:
int x;
int * p;
p = &x;
p = p + 1;
printf("the integer after x is %d\n", *p);
Your program will probably crash. This is because there actually isn't an
object after x. We know where the object after x would be if it existed,
but since it doesn't exist, we can't access it. This is an example of
undefined behavior. The C language does not guarantee any particular
behavior and, in fact, allows pretty much anything to happen as a
result. This problem can be solved by declaring an array of int:
int x[8];
Now we know that there are 8 integers all lined up right after each other.
You may know that you can access these integers by using array notation
like this:
int i;
int x[8];
for (i = 0; i < 8; ++i)
printf("x[%d] == %d", i, x[i]);
But you can also use pointers to do the same thing, like this:
int * p;
int x[8];
p = &x[0];
printf("x[0] == %d\n", *p);
printf("x[1] == %d\n", *(p+1));
...
printf("x[7] == %d\n", *(p+7));
And, as you may expect, you can do this more easily with a for-loop:
int * p;
int x[8];
p = &x[0];
for (i = 0; i < 8; ++i)
printf("x[%d] == %d", i, *(p+i));
Now we come to a somewhat tricky subject, which is the conversion of
arrays to pointers. This isn't really that hard to understand, but it
seems to get talked about a lot in comp.lang.c.
In most cases, if you use the name of an array like a pointer, it acts
like a pointer. There are sometimes when this is not true, so you have
to be quite careful about using this fact until you know when it is true
and when it isn't.
To get back to our example, we can change the code like this:
int * p;
int x[8];
p = x; /* same as p = &x[0] */
We have used x as a pointer and it acts like a pointer. This does *not*
copy the entire array anywhere. All it does is make p point at the first
element of x. From this point we can continue as before:
for (i = 0; i < 8; ++i)
printf("x[%d] == %d", i, *(p+i));
and everything will work the same way.
You might wonder however, if the name of an array sometimes acts like a
pointer, can we use it to replace the variable p altogether in this code?
The answer is yes:
int x[8];
for (i = 0; i < 8; ++i)
printf("x[%d] == %d", i, *(x+i)); /* using x as a pointer */
In fact, not only can you do this to access the elements of the array,
this is THE ONLY WAY to do so. This is a very important fact about C.
You are probably thinking, hey, we just used x[i] to access elements of
the array named x, that's another way! But actually it's not another
way. That's because:
Definition:
the meaning of x[i] is *(x+i)
Because this is true, not only does x[0] access the first element of
the array named x, 0[x] does too! This may seem strange, but look at
the definition above and then consider:
0[x] means *(0+x) equals *(x+0) means x[0]
In mathematics a+b equals b+a when one is adding integers, and the same
is true in C when you add a pointer and an integer together. In fact we
can rewrite the example loop as follows:
int x[8];
for (i = 0; i < 8; ++i)
printf("x[%d] == %d", i, i[x]); /* perverse, but valid */
Now I will tell you one last thing about pointers today: you can subtract
one pointer from another, as long as they have the same type and are
pointing to different elements of the same array. The result of doing this
tells you how many elements ahead of one pointer the other one is.
Consider the following:
int x[4];
int * p = x; /* using x like a pointer */
int * q = x+2; /* x+2 points at the thing "2 after" the first */
These declarations set up the following situation:
p q
| |
V V
+------------+------------+------------+------------+
| | | | |
+------------+------------+------------+------------+
x: 4-element array of int
You can see that p is zero "elements ahead" of itself, and q is two
"elements ahead" of p. You can find this out in a C program like
this:
int difference = q - p;
printf("q is %d elements ahead of p\n", difference);
which will print
q is 2 elements ahead of p
Now I want to remind you, that this only works when both p and q
are pointing to elements of the same array. If the code looked like
this:
int x, y;
int * p = &x;
int * q = &y;
int difference = q - p;
printf("q is %d elements ahead of p\n", difference);
Then there's no guaranteeing what will happen. p and q both point to
objects of type int, but they are not elements of a common array.
The behavior of this program is undefined. We may find out how many
integer objects can fit in the space between wherever the compiler puts
the object named x and wherever the compiler puts the object named y, but
the C compiler is not required to do this, it could format our hard disk
instead. -- harsh, to be sure, but allowed by the C standard.
To finish up, I will present a function using some of these concepts.
The function will take one argument, a string, and will return the length
of the string. A string in C is an array of char containing values
representing characters. The array has at least as many elements as
characters in the string, plus one. The element of the array after the
last character in the string has the value 0, to mark the end of the
string. A character with the value 0 is called a NUL. In C, you can
just write it like a normal zero (i.e, 0), but many people choose to
show that it is a character by writing it inside ' quotes like this:
'\0'. The backslash is necessary to make this a character with value
zero, as opposed to the character which is used to print a zero on
your screen, which is written '0'.
A string is usually manipulated in C by using a pointer to the
first element of the array. A diagram should make this clear.
+------------+
| (value)---|------+
+------------+ | +----+----+----+----+----+---+
+----->| 72 | 69 | 76 | 76 | 79 | 0 |
p: pointer to char +----+----+----+----+----+---+
72=H 69=E 76=L 76=L 79=O
Here is a string containing the text "HELLO". Each object of type
char in the array has a numeric value. Each number corresponds to
some character. The mapping from number to character can be done in many
different ways, and that fact can be very important when writing programs
for international audiences. The mapping used above is a very common
mapping though, used in the US and Europe most of the time these days.
In any case, we use a pointer to char to access our string, which is
an array of elements of type char. The function to be presented will not
declare the array itself, it will assume that the array has already been
declared, but that does not change the fact that the array *must* be
declared somewhere. We can only use a pointer that points to some object
that really exists in memory, as I said way up above.
The function to be presented doesn't care what the values in the elements
of the array are, it will just look for the value 0, which is the last
element of the string. So here's the function, at first, line-by-line.
unsigned int
/* the length of a string can't be negative, so return unsigned char. */
string_length (const char * string)
/* we will not change the values in the string, so declare the pointer
as a pointer to const(ant) char. when this function is called,
string will point at the first element of a char array that contains
a string */
{
const char * index;
/* we will use this pointer to find the zero */
index = string;
/* string points at the first element, now index does too */
while (*index != '\0')
/* while index isn't pointing at the terminating NUL */
{
index = index + 1;
/* make index point at the next character */
}
/* when execution reaches this point, index points at the
character with value zero, that is, at the NUL. That
means that index is pointing at the end of the string. */
return index - string;
/* compute how many characters ahead of string index is, and
return that value as the length of the string. */
}
The way the length of the string is computed means that "the length of the
string" means "the number of non-zero characters in the string". You
should be able to follow the code, now. To convince you that it is correct,
the last diagrams...
At the beginning:
string index
| |
V V
+----+----+----+----+----+---+
| 72 | 69 | 76 | 76 | 79 | 0 |
+----+----+----+----+----+---+
72=H 69=E 76=L 76=L 79=O
*index is 72, not 0, so add one to index:
string index
| |
V V
+----+----+----+----+----+---+
| 72 | 69 | 76 | 76 | 79 | 0 |
+----+----+----+----+----+---+
72=H 69=E 76=L 76=L 79=O
Keep going like that until *index == 0:
string index
| |
V V
+----+----+----+----+----+---+
| 72 | 69 | 76 | 76 | 79 | 0 |
+----+----+----+----+----+---+
72=H 69=E 76=L 76=L 79=O
Now return the number of elements that index is ahead of string:
string index
| |
V 5 4 3 2 1 V
+----+----+----+----+----+---+
| 72 | 69 | 76 | 76 | 79 | 0 |
+----+----+----+----+----+---+
72=H 69=E 76=L 76=L 79=O
index - string == 5, which is the number of letters in the string
"HELLO".
Here the code again, without comments, along with a main function that
uses it:
#include <stdio.h>
unsigned int string_length (const char * string)
{
const char * index;
index = string;
while (*index != '\0')
{
index = index + 1;
}
return index - string;
}
int main (void)
{
unsigned int length;
length = string_length("hello");
printf("the length is %u\n", length);
return 0;
}
-Sheldon
- ]
|
http://coding.derkeiler.com/Archive/C_CPP/comp.lang.c/2003-11/0587.html
|
crawl-002
|
refinedweb
| 2,468
| 73.41
|
Hi, so I am making a program that hinges on a function that takes a total amount of seconds as input and is supposed to output using printf the number of days, hours, minutes, and seconds. The program is now able to compile, but I am not getting the output that I expected. Any advice?
Thanks.Thanks.Code:
#include <stdio.h>
#include <math.h>
#include "checkit.h"
/* function declarations */
/* time conversion function */
void convertTime(int seconds);
#define Sec_per_day 86400
#define Sec_per_hr 3600
#define Sec_per_min 60
/* function definitions */
void convertTime(int seconds){
int Days;
int Hrs;
int Mins;
int Secs;
Days = seconds/Sec_per_day; /* int division returns # of days */
Hrs = (seconds%Sec_per_day)/Sec_per_hr; /* left over seconds returns hrs */
Mins = ((seconds%Sec_per_day)%Sec_per_hr)/Sec_per_min; /* left over seconds
returns mins */
Secs = ((seconds%Sec_per_day)%Sec_per_hr)%Sec_per_min; /* left over seconds */
printf("Elapsed time: %d days, %d hours, %d minutes, %d seconds\n",
Days, Hrs, Mins, Secs);
}
|
https://cboard.cprogramming.com/c-programming/145292-converting-time-program-printable-thread.html
|
CC-MAIN-2017-17
|
refinedweb
| 150
| 57.61
|
Kanban Board
- 6 minutes to read
This document shows how to implement a Kanban board in a Tile View, and provides information on the main Kanban customization options.
Demo
Limitations
TileView does not support Infinite Scrolling in Kanban mode.
What is a Kanban Board
Kanban (‘signboard’ in Japanese) is a method of managing business processes, and the Kanban board provides a visual workflow.
A typical Kanban board consists of cards (tiles) combined into groups (columns or rows). Groups identify workflow stages (statuses), and cards represent workflow items. A user can drag-and-drop cards within a group and between groups to change their status and order.
Note
In this topic, the term “tile” will be used to refer to Kanban board items (cards).
Prepare Data and Bind It to Data Grid
Create a data source for your Kanban board. When the Tile View is bound to a data source, each data source record is rendered as a tile. Ensure the data source contains a status field (tiles are combined in groups according to their status field).
Use the GridControl.DataSource property to bind the data source to the Data Grid.
The following code snippet shows a Data Grid bound to data in the Tile View Kanban Board demo:
void InitData() { tasksData = KanbanHelper.LoadTasks(); //... gridControl.DataSource = tasksData; } public static BindingList<TaskRecord> LoadTasks() { var _tasks = new BindingList<TaskRecord>(); //... return _tasks; } public enum TaskStatus { ToDo, Planned, Doing, Testing, Done } public class TaskRecord { public string Caption { get; set; } public string Description { get; set; } public Image AttachedImage { get; set; } public TaskStatus Status { get; set; } //... }
Enable Kanban Layout Mode and Tile Grouping
Set the TileView.OptionsTiles.LayoutMode property to Kanban to enable Kanban layout mode.
To combine tiles into groups, specify a group column via the TileView.ColumnSet.GroupColumn property.
Specify the Tile Template
The Tile View renders all tiles based on a tile template. To create a template, use the Tile Template page of the Data Grid’s Designer or the TileView.TileTemplate property in code.
See the Tile View topic for information about how to create tile templates.
Automatic and Manual Group Generation
Automatic groups
The TileView automatically generates groups for all unique values in the group column (TileView.ColumnSet.GroupColumn). When a group becomes empty (for instance, when you remove all tiles from a group), the TileView deletes this group.
Manual groups
You can use the TileView.OptionsKanban.Groups collection to create Kanban groups (KanbanGroup objects) and use them to perform the following tasks:
- Maintain the group’s lifetime. Created groups are not automatically removed.
- Show only specific groups.
- Customize settings of individual groups.
The following animation shows three created groups:
See the TileView.OptionsKanban.Groups topic for more information.
Enable Tile Drag-and-drop
The built-in tile drag-and-drop feature is disabled initially. You can use the TileView.OptionsDragDrop.AllowDrag property to allow users to drag tiles within and between groups.
Drag-and-drop operations in data-aware controls, including the Data Grid’s Tile View, are performed on the data source level. Whenever a tile is dragged-and-dropped in a new position, the Tile View moves the underlying record to the corresponding position in the data source. If a tile is moved to a different group, the record’s group column value is changed accordingly.
The following properties and events allow you to customize drag-and-drop operations:
- TileView.BeforeItemDrag event - Fires when a tile drag operation is about to be started. Allows you to provide a drag image, or to cancel the operation. This event does not fire when you enable drag-and-drop using Drag And Drop Behavior.
- TileView.BeforeItemDrop event - Fires when a tile drop operation is initiated. This event does not fire when you enable drag-and-drop using Drag And Drop Behavior.
- TileView.ItemDrag - Fires repeatedly when a user drags a tile. Allows you to prevent a tile from being dropped at a specific position. This event does not fire when you enable drag-and-drop using Drag And Drop Behavior.
- TileView.ItemDrop event - Fires after a tile drop operation has been completed. This event does not fire when you enable drag-and-drop using Drag And Drop Behavior.
- KanbanGroup.AllowItemDrag property - Gets or sets whether to disable tile drag-and-drop operations within and from the current group.
- KanbanGroup.DropTargetGroups property - The collection of groups that can accept tiles from the current group during drag-and-drop operations.
Enable Tile Editing Feature
See Tile Editing for instructions on how to allow users to edit tiles.
Additional Customizations
This section covers additional tile customization options.
Dynamic Tile Customization
Use the TileView.ItemCustomize event to dynamically modify tile elements according to your logic. This event fires for each tile when it is about to be displayed.
Tile Auto-Height
When you create a tile template, you can enable auto-height mode for a specific template row. This allows tiles to have different heights depending on their contents.
See the TableRowDefinition.AutoHeight topic for more information.
Group Header Text
The text displayed in group headers is specified by the Caption property of the group column (TileView.ColumnSet.GroupColumn). To provide custom display text, handle the ColumnView.CustomColumnDisplayText event.
The following code snippet from the Tile View Kanban Board demo displays the number of child tiles in group headers:
void TileView_CustomColumnDisplayText(object sender, Views.Base.CustomColumnDisplayTextEventArgs e) { if(e.IsForGroupRow) { var kanbanGroup = tileView.GetKanbanGroupByValue(e.Value); int count = tileView.GetChildRowCount(kanbanGroup); string cards = count == 1 ? " card" : " cards"; e.DisplayText += "<br><size=-2><r>" + count.ToString() + cards; } }
Buttons in Group Headers
Group headers can display additional buttons. These buttons can be always visible or visible only when you hover the mouse pointer over the group header.
Use the TileView.OptionsKanban.GroupHeaderContextButtons collection to add buttons. To perform actions when a button is clicked, handle the TileView.GroupHeaderContextButtonClick event.
Group Footer Buttons
Use the TileView.OptionsKanban.GroupFooterButton property to add footer buttons to all groups.
The KanbanGroup.FooterButton property allows you to show/hide footer buttons in individual Kanban groups.
Group Appearance Settings
The TileView.OptionsKanban.ShowGroupBackground property allows you to enable a background layer for groups.
The current skin specifies the default background color. You can use the TileView.Appearance.Group and KanbanGroup.Appearance properties to set a custom background color and group text color.
Horizontal or Vertical Alignment
Use the TileView.OptionsTiles.Orientation property to align Kanban groups horizontally or vertically. Tiles are arranged in columns in horizontal mode, and in rows in vertical mode.
Context Buttons in Tiles
You can add additional actions (for example, buttons) to tiles via the TileView.ContextButtons collection.
|
https://docs.devexpress.com/WindowsForms/117616/controls-and-libraries/data-grid/views/tile-view/kanban-board
|
CC-MAIN-2021-49
|
refinedweb
| 1,098
| 51.14
|
Before C# 5, trying to write asynchronous code was difficult. It was hard to read and tricky to debug. Thankfully Microsoft have added the Async and Await keywords to make asynchronous programming far more manageable, but there is still a lot of uncertainty in the .NET development community on how this works so let’s have a look at some coded examples.
Async Await is all about Tasks
When programming asynchronously it’s important to understand that its all about Tasks. When creating an async method the return type is a of Task or Task<T>. The difference between these two types is simple. If your async method is void with no return type, then you would set this to return Task. If your async method is non-void and returns any type of value then you would return Task<T> where T is the type you want to return.
Now you may be thinking, what's the difference between Asynchronous Programming and Multithreaded Programming?
So, like I said before Async is about Tasks. Multireading is all about Workers
Understanding the differences between Async and MultiThreaded
Asynchronous Programming (Multithreaded)
you hire 2 employees, 1 to fill your car with fuel and the other to wash your car. However, as they are running asynchronously you will need to direct them so they can work without interfering with each other and manage any shared resources.
Synchronous Programming (Single Thread)
you fill up the car and then wash the car.
Asynchronous Programming (Single Thread)
you set the fuel pump to begin filling the car and while that is in progress you start to wash the car. When the fuel tank is full the pump will notify its complete. You take out the pump and then finish washing the car.
Synchronous Programming (Multithreaded)
you hire 2 employees, 1 to fill your car with fuel and the other to wash your car. They are working completely independent of each other and will complete when they are done.
So now you understand the principles let’s explore in more detail the two new keywords Async and Await.
Async Keyword.
Assigned to a method signature, this tells the compiler that it’s an async method and Visual studio will allow you to add the await keyword within the method. Without making a method as async, you cannot add the await keyword as your code will not compile. You can also call await on any method marked as async.
public async void BeginLongOperation()
Await Keyword.
The await keyword will stop operation until the current line of code competes. It does this by executing the current line and then at the same time transferring operation back to the calling method so it can continue its execution. This is the key aspect of using Async Await in C#.
Let’s have a look at some code. The example is a console app that will call an async method and while that is executing it will continue to loop outputting Asterisks to the console until the async method completes.
public async void BeginLongOperation() { _IsOperationComplete = false; Console.WriteLine("Begin Start LongOperation() - Please Wait " + Environment.NewLine); int RandomNumber = await LongOperation(); Console.WriteLine(Environment.NewLine + "Finish End LongOperation() Async Return Int = " + RandomNumber); _IsOperationComplete = true; }
This is our async method, we are calling await on LongOperation() this means that it will execute this method while at the same time passing back to the original call for that to continue. Let’s have a look at the method LongOperation() in more detail.
private Task<int> LongOperation() { return Task.Run(() => { Console.WriteLine($"Executing LongOperation - Sleep Duration = {_SleepDurationSeconds}"); Thread.Sleep(_SleepDurationSeconds); return new Random().Next(); }); }
This is the method we call await on. You can see that it has a return type of Task<int> this means that we are returning a task object that will itself will return an int. Interestingly you can see that we have 2 return statements in a single method. For the example I am simply returning a random number for the int, but in a real application this could be any type of object. Task is generic with the signature Task<T>.
Let’s have a look at the full code.
using System; using System.Threading; using System.Threading.Tasks; namespace AsyncProgrammingExample { public class Program { public static void Main(string[] args) { Console.WriteLine("Program start " + Environment.NewLine); AsyncTask worker = new AsyncTask(1); worker.BeginLongOperation(); while(worker._IsOperationComplete == false) { Thread.Sleep(50); Console.Write("*"); Thread.Sleep(50); } Console.WriteLine("Program complete"); Console.ReadKey(); } } public class AsyncTask { public bool _IsOperationComplete { get; private set; } public int _SleepDurationSeconds { get; private set; } public AsyncTask(int DurationSeconds) { _SleepDurationSeconds = (DurationSeconds * 1000); } public async void BeginLongOperation() { _IsOperationComplete = false; Console.WriteLine("Begin Start LongOperation() - Please Wait " + Environment.NewLine); // - as we have called await - this method cannot continue until LongOperation() // has completed. the call is passed back to the calling method - the while loop int RandomNumber = await LongOperation(); Console.WriteLine(Environment.NewLine + "Finish End LongOperation() Async Return Int = " + RandomNumber); _IsOperationComplete = true; } private Task<int> LongOperation() { return Task.Run(() => { Console.WriteLine($"Executing LongOperation - Sleep Duration = {_SleepDurationSeconds}"); Thread.Sleep(_SleepDurationSeconds); return new Random().Next(); }); } } }
Following through the code it’s important to know that this is a console app and the starting method is Main. To begin the application starts by outputting “Program Start” to the console and then creates an instance of the class AsyncTask passing a value of 1 for 1 second into the constructor. Next it calls the method BeginLongOperation() this executes until it reaches the await keyword, execution is passed back to the main method where it now enters the while loop. The boolean prioperty _IsOperationComplete is set a false and will remain false until LongOperation() completes. Asterisks are logged during iteration of the loop. As soon as LongOperation() completes the property is set to true and the while loop breaks which then completes the program.
So there we have it, a simple example of how to code asynchronously in C# using Async Await. Please have a play with the code above and try using Async Await on your C# project. Please leave your thoughts in the comments.
|
https://www.intermittentbug.com/article/articlepage/asynchronous-programming-using-async-await-in-c-sharp/2301
|
CC-MAIN-2019-13
|
refinedweb
| 1,018
| 56.76
|
Release date: 6/9/2010
System Requirements
Note: AIR 2 does not support Windows 2000 and Mac PowerPC. Additionally, Mac OS 10.4 is not a supported development environment when using the AIR 2 SDK.
Additional Requirements for Linux Systems
A list of libraries required to run AIR 2 on Linux are listed in the following Adobe Knowledge Base (KB) article:
Adobe AIR 2 installation and runtime user experience supports the following languages:
ADL provides a new feature to support screen size simulation when the movileDevice profile is specified. Please read details in the section below, "ADL screen size simulation in the mobileDevice profile."
URLRequest.idleTimeout and URLRequestDefaults.idleTimeout let you specify the amount of time (in milliseconds) that a connection will for the server response after a request is sent.
You can now use the DNSResolver class to look up the following types of resource records:
Using the new FilePromise APIs, it is now possible to drag and drop files that exist on a remote server or that haven't been generated yet. You can copy such files by dragging them out of the AIR application and onto the desktop. This enables new user interaction possibilities for applications like content management systems, online stores, or FTP clients.
New socket properties allow you to access the local address, local port, remote address and remote port.
New printing support allows finer control of the way content is printed from an AIR application, including the choice of printer, paper size, and number of copies. New APIs allow a developer to retrieve additional printing information, such as printable area, whether the printer will print in color, and whether the print job is currently active. It is also possible to print without displaying the print dialog.
There are several new features added in this release to support better text input handling with IME software. The new API enhancements are designed to use with the new Flash Text Engine (FTE).
Large screen displays now can display windows that are 4,096 pixels horizontal x 4,096 pixels wide. It used be 2880 x 2880 in previous version.
Record audio locally on your device without the need of a server.
Detect when mass storage devices such as cameras and USB flash memory drives are available to synchronize files such as photos, videos, mp3 files or other files.
Open popular document types like .pdf, .psd, .doc, .ppt, and .mp3 using the native application associated with that file. For example, opening an .mp3 file will launch iTunes on systems where iTunes is the default application for mp3 files.
Developers can now launch and communicate with native processes using the standard input, output, and error streams. Using the Native Process API, it is now possible to communicate with native libraries built using Java and .NET and also native applications such as "grep" for file searching. You can also create operating system specific installers (native installers). Applications that use the native process API must be deployed using a native installer.
You can package an AIR application in a native install program instead of an AIR file. Applications packaged and installed using a native installer have access to platform-specific features such as the Native Process API. See Packaging an AIR application in a native installer.
The local SQLite database now provides support for nested transactions.
The new NetworkInfo object lets you enumerate the network interfaces on a computer and access the properties of an interface such as whether it is active, the IP address, and the display name.
New capabilities such as CSS transforms, animations, and canvas support are now available. See section "Adobe AIR and AJAX" for additional details.
Build peer-to-peer applications or local servers that make it easier to communicate with other local applications or remote applications over the network.
You can now connect to a server that requires TLSv1 or SSLv3 for socket communications.
Runtime support for user datagram protocol (UDP) allows developer to build time-sensitive, real-time networking applications such as multi-player games.
JavaScript code runs 50% faster without any code changes to the application using the new SquirrelFish Extreme JavaScript engine.
Build entirely new types of applications using multitouch (Windows 7 only) and Gestures (Windows 7 and Mac OS 10.6). Multitouch is not supported in Windows 7 Starter and Home Basic.
Applications run faster and use system resources more efficiently. The CPU usage of idle applications has been reduced, as has overall memory usage. The runtime itself is also smaller.
Vector printing, already available on Windows, is now available on the MAC.
NOTE: Vector printing is not supported on Linux.
When an unexpected error happens within an application, developers can now capture that event as an exception and present useful information back to the user such as instructions on how to report the issue or restart the application.
Support for next generation secure internet protocol.
AIR 2 can be installed using Debian and rpm package installers in addition to the binary installer.
TLS sockets (encrypted sockets) and access to the MAC address are supported. The new File.downloaded property lets you indicate that a file was downloaded from the network and the OS should prompt the user with a confirmation dialog before opening it.
Enable applications built using Flash or Flex work with a screen-reader application.
Users with these operating systems will continue to be able to install and run AIR 1.5 applications, but will not be able to install or update to the AIR 2 runtime. These operating systems are not supported when developing AIR applications with the AIR 2 SDK.
You must update your application descriptor file to the 2.0 namespace in order to access the new AIR 2 APIs and behavior. If your application does not require the new AIR 2 APIs and behavior, you are not required to update the namespace from 1.x based namespace. To update the namespace, change the xmlns attribute in your application descriptor to:
There is a new AIRCore framework, which includes the existing service monitoring classes, as well as a couple of additions :
air.net.ServiceMonitor
air.net.URLMonitor
air.net.SocketMonitor
air.net.SecureSocketMonitor
air.desktop.URLFilePromise
The SecureSocketMonitor class is a new addition that takes advantage of the new SecureSocket class available in AIR 2. The URLFilePromise class implements the IFilePromise interface using an HTTP data source. The entire service monitoring framework, plus the new additions, are now packaged in a new library file, aircore.swc and aircore.swf. The original library files, servicemonitoring.swc and servicemonitoring.swf, are still included in the AIR 2 SDK, but use of these files is deprecated. We recommend switching to using aircore.swc in your Flex- and Flash-based applications, and switching to aircore.swf for HTML-based applications.
In an AIR application that uses the AIR 2.0 namespace, the value property of an HTML <input type = "file"> element differs depending on the sandbox of the HTML content. If the document containing the input element is in the application sandbox, the value property is set to the full path of the file chosen by the user (for example, "C:\air\file.txt"). If the document containing the input element is in a non-application sandbox, the value property is set to the file name only (for example, "file.txt").
In an AIR application that uses a namespace of 1.5 or earlier, the value property of an HTML <input type = "file"> element always returns the full path to the file. This is true whether the HTML content is in the application sandbox or in a non-application sandbox.
Please refer to the End User release note for information about Installing and Uninstalling Adobe AIR and about Installing AIR applications.
The AIR API versioning scheme is not currently enforced by the ActionScript compiler made available in Flash Professional, Flash Builder, Flash Catalyst, and the Flex SDK. An application using an older AIR namespace (e.g. 1.5) but developed with a tool supporting a newer version of AIR (e.g. 2.0) will be able to successfully reference and compile when using newer APIs. However, when that application is run, attempting to use one of the newer APIs will result in a runtime error or incorrect behavior. To avoid this issue, we recommend updating your application to the latest namespace supported by the authoring tool in use.
The AIR 2 SDK can be used on its own to develop HTML-based AIR applications or with the Flex SDK to develop ActionScript or Flex-based AIR applications. The Flex SDK is free, open source, and is available for download from.
* Windows Flex Builder 3: c:\Program Files\Adobe\Flex Builder 3\sdks\3.2.0 * Windows Flash Builder 4:\Program Files\Adobe\Adobe Flash Builder 4\sdks\4.0.0 * Mac Flex Builder 3: /Applications/Adobe Flex Builder 3/sdks/3.2.0 * Mac Flash Builder 4: /Applications/Adobe Flash Builder 4\sdks\4.0.0
tar jxvf AdobeAIRSDK.tbz2
If you have trouble overwriting files due to file permissions, try this command:
sudo tar jxvf AdobeAIRSDK.tbz2
If you use Flash Professional CS4 to build Adobe AIR applications, please follow the instructions below to manually update to the AIR 2 SDK.
Flash CS4 is now configured to use the AIR 2 SDK.
In order to take advantage of the new AIR 2 features, you must update your application descriptor file to use the AIR 2.0 namespace. See the section "Updating Your Application Descriptor Namespace" for additional details on how to update it.
You must manually change the application descriptor generated by Flash Professional CS4 for every new AIR 2 project.
If you have an existing AIR project, navigate to the folder that contains your SWF file and open the application descriptor file. By default, the name of the application descriptor file will be the name of your .swf plus include "-app" in the name. For example, if the .swf file is named mygame.swf, the application's descriptor file will be "mygame-app.xml".
For a new project, you will need to do the following steps to create and update the application descriptor file:
Note: Moving these folders may require administrator authentication depending on your account privileges.
Adobe Community Help is Adobe's next generation help experience. It's an AIR application that provides the following features:
Community Help is installed by default in Creative Suite CS5 and Flash Builder 4. If you're using the AIR SDK separate from those tools, you can install Community Help yourself here: Install Adobe Community Help.
You can find links to all of the AIR documentation on the Adobe Developer Connection.
The AIR Help and Support page is a search portal for AIR information from Adobe and the AIR developer community. You'll also find great new articles and tutorials and links to current support issues.
In AIR 2, installation logs for the runtime and for individual applications are created by default. The file is named "Install.log" on Linux and Windows. The file is named "system.log" on Mac OS. This log file is cumulative, meaning that a new log is appended at the end of the existing log file whenever an attempt, successful or unsuccessful, is made to install or update the AIR runtime or an AIR application. The size of the log file is limited to 0.5MB and the file is truncated when it becomes too large.
The location of this file differs from platform to platform:
*On Windows XP: C:\Documents and Settings\<username>\Local Settings\Application Data\Adobe\AIR\logs\Install.log *On Windows Vista/ Windows 7: C:\Users\<username>Appdata\Local\Adobe\AIR\logs\Install.log *On Mac OS X: /private/var/log/system.log (console application) *On Linux: /home/<username>/.appdata/Adobe/AIR/Logs/Install.log
If an URL contains non-ASCII characters, the application might fail to work properly on Windows if the libraries that the runtime depends on to parse such URLs are not present. If IE 7 is installed, then the necessary libraries are installed and the application should work fine. The problem does not reproduce on Windows Vista and Windows 7. (2477685)
If Firefox is configured as the default browser and a Firefox window is already open in the background, calling navigateToURL doesn't bring the Firefox window to the front on Windows. (1609175)
Java versions 1.5 and above do not accept high-ASCII characters in passwords used to protect PKCS12 certificate files. Java is used by the AIR development tools to create the signed AIR packages. When you export the certificate as a .p12 or .pfx file, use only regular ASCII characters in the password.(1908199)
Mac 10.6 only. When replacing the NativeApplication menu property, the first menu's label always shows mac's logo. The menu functions correctly in other respects. (2442577)
The cursor can move to the wrong position when typing certain Thai characters in HTML content. Text input for languages other than those listed in the supported languages section above is currently not supported. (2486968)
Mac only. Native application installer packaging may fail if the AIR SDK or the files you are packaging are in a path with Unicode-encoded Chinese characters or the <filename> descriptor tag has Unicode-encoded Chinese characters. This is due to an underlying issue Java has with Unicode filenames. (2539439)
Mac 10.6 only. The application menu bar isn't visible when the application is run from command line with adl. The workaround is to switch focus to another application and then return to your app. (2530559)
Some applications on Windows 7 can not be opened using a .lnk file when using file.openWithDefaultApplication. Examples include C:[ProgramData]]\Microsoft\Windows\Start Menu\Programs\Accessories\Sticky Notes.lnk and C:[ProgramData]\Microsoft\Windows\Start Menu\Programs\Administrative Tools\System Configuration.lnk. (2573727)
<IMG> tags won't displaying ICO files on Mac OS 10.4/10.5. This limitation does not exist on Mac OS 10.6. (2563698)
The EXITING event does not fire properly when Introspector is open in an HTML-based AIR application. (2559508)
Users cannot install an 2.0 application over a 2.0beta2 application. Users are shown an error message stating that the AIR file is damaged and to contact the application vendor. A more descriptive error message should be provided in this circumstance. (2559067)
Only a single instance of an AIR application can be running. A workaround is to change the value of the <id> element in your application descriptor file prior to debugging. (2516616)
Using Flex 4 Spark text components is only supported when using the released version of Flex 4 and AIR 2. Known issues exist in older (beta) versions of Flex 4. The AIR 1.5.x does not support the Spark text components. (2559578)
On certain hardware configurations running Windows XP, the AIR app "theGood Uploader" application can cause CPU usage to reach 100%. (2540843)
Using both the SecureSocektMonitor and other monitors in the air.net package simultaneously may cause a crash on Mac OS 10.5.8 or later when using a low polling interval, such as 1 ms. The workaround is to use a higher polling interval. (2555669)
On Mac systems, the NativeWindowDisplayStateEvent may get dispatched twice when calling NativeWindow.maximize(). (2564809)
When using the File APIs to copy large amounts of files and data from a DVD, the copying step may experience a sharp slowdown on Mac OS 10.5. The issue is caused by an underlying issue in the OS, which has been fixed in Mac OS 10.6. (2414772)
If you are printing a page containing Flash Text Engine (FTE) text which is transparent and which uses a non-embedded font, the page will not print correctly using the bitmap, vector, or auto print job options. To work around the problem, please embed the font. (2629777)
ADT currently cannot turn off timestamping for native application installers built on Windows. The '-tsa none' argument will not work when attempting to sign the .exe installer. Typically, developers turn off timestamping while they build and test their applications and they don't have access to the network. The workaround is to not sign the.exe installer in this case. (2628232)
A native application package created on a computer running OpenSuse 11.2 cannot be installed on older RPM Linux distributions. (2495682)
After installing the runtime.
Mailto links do not work if Google Chrome is set as default browser. (2565050)
Application name is reported as "anonymous" in the kwallet password dialog which this displayed when an AIR application accesses data in the encrypted local store. (1862087)
With certain applications like iPlotz, SocialVisor, UVLayer, and Time100, flickering can be observed in the application stage when using these applications. (2487242)
When installing AIR using the binary installer, the installation dialog at times appears clipped. (2461190)
When accessing certain secure sites, a "SSL Certificate Alert" is displayed.
|
http://www.adobe.com/support/documentation/en/air/2/releasenotes_developers.html
|
CC-MAIN-2013-20
|
refinedweb
| 2,825
| 56.86
|
Coding conventions: 9 areas where developers actually agree
When it comes to writing code, programmers can often differ over what conventions should rule. Based on GitHub data, here are a number of conventions where there seems to be some consensus
Programmers usually adhere to certain conventions when writing code, such as using spaces instead of tabs (or vice versa) when indenting code. These conventions can differ across programming languages and organizations and even from developer to developer. But which conventions are most commonly followed? A new tool that grew out of a recent GitHub data challenge now helps to identify the most popular coding conventions. By looking at millions of recent GitHub commits, Popular Convention by JeongHoon Byun identifies the rates at which programmers are following common conventions for a number of popular programming languages. Using this tool, here are 9 coding conventions that developers seem to (almost) agree on.
Whether to use spaces or tabs when indenting code is an age old debate. However, based on over 7 million GitHub commits for 7 different languages (JavaScript, Java, Python, Scala, Ruby, C#, and PHP), spaces are clearly chosen far more often than tabs. The language using spaces instead tabs the most was Scala (96%), followed by Ruby (95%), Python (95%), C# (82%), JavaScript (81%), Java (74%), and PHP (70%).
A maximum line length of 80 characters has a long history in computers and programming, dating back to IBM punch cards and early monitors. Nowadays, though, with bigger and higher resolution monitors, longer line lengths are easily possible. However, the convention of keeping lines of code to no more than 80 characters clearly persists, as these data show. 92% of the over 5 million GitHub commits for six different languages (Java, Python, Scala, Ruby, C# and PHP) adhered to this convention, with 6% using a 120 character limit, and just 2% using a 150 character limit.
Normally when defining or calling functions or methods, arguments are wrapped in parentheses. However, some programming languages make the use of parentheses optional. While some programmers will prefer to still include them for readability, for Ruby developers there is a clear consensus that, when there are no arguments (hence the parentheses would be empty) parentheses should omitted. 98% of the 239k commits in the GitHub data omit parentheses in this case. So
def some_method
# do something...
end
is clearly preferred over
def some_method()
# do something...
end
Some developers feel that putting an extra space around the arguments in a function declaration improves code readability. For example:
function fn( arg1, arg2 ) {
// ...
}
However, 94% of the almost 1.5 million GitHub commits for JavaScript, Java, C#, and PHP code did not put a space around the arguments, like so:
function fn(arg1, arg2) {
// ...
}
Clearly, no spaces is the preferred convention.
When defining a series of values over multiple lines, such as in an array, some people advocate putting the comma between values at the beginning of each line to improve readability, debugging, and maintainability.
var obj = {
foo: 1
, bar: 2
, baz: 3
};
However, the convention, at least within the JavaScript world, seems to be to put commas at the end of lines, since 92% of the 1 million JavaScript commits in GitHub went with comma last over comma first.
var obj = {
foo: 1,
bar: 2,
baz: 3
};
Programmers agree that one of the hardest things they have to do is name things, like variables, classes, and methods. However, what they often don’t agree on is the type of casing to use when naming things. For example, should they use camelCase, snake_case or PascalCase? When it comes to naming functions in PHP or methods in Scala, however, there does seem to be a consensus: 87% of the 237k commits in the GitHub data followed the camelCase convention, with snake_case (11%) and PascalCase (2%) lagging far behind. ALL_CAPS_SNAKE_CASE and Snake_Pascal_Case were also used, but in under 1% of these commits, so they are not shown in this chart.
When writing blocks of code, such as classes, methods, or control structures, programmers have to decide whether to put curly braces on their own lines, or, for opening braces, on the same lines as the declarations. That is
class Foo
{
// ...
}
or
class Foo {
// ...
}
Some find putting braces on their own lines is cleaner and clearer, while others find it excessive. Based on 1.5 million GitHub commits for Java, C# and PHP, curly braces were put on a new line only 30% of the time, so the clear convention is to not put each curly brace on a new line.
When using strings in JavaScript, you can wrap them in either single or double quotes. For example
var foo = 'bar';
versus
var foo = "bar";
The choice of which to use essentially comes down to personal preference. Some prefer double quotes since with single quotes you have to escape any other single quotes within the string, such as in contractions ('That\'s it!'). Based on 1.6 million commits of JavaScript code in GitHub, while the choice between the two is close, there is a clearpreference for single quotes, which were used 57% of the time.
Traditionally, many programmers have put the names of constants in all caps as a way to make their special nature more obvious to anyone reading the code. However, some find that to be a bit of a coding anachronism. Based on over 350,000 GitHub commits of Java, C# and PHP code, all caps is still the convention -- but not by much (53% used all caps).
- Video/Webcast
Sponsored
- Video/Webcast
Sponsored
- White Paper
- White Paper
- White Paper
- Video/Webcast
Sponsored
- Save on electronics from Dell’s deals of the week!
- See the Infographic: The Critical Path to an Agile Data Center
- Top 10 Reasons Enterprises Choose Veeam
|
http://www.infoworld.com/article/2606694/application-development/140018-Coding-consensus-9-popular-programming-conventions.html
|
CC-MAIN-2015-11
|
refinedweb
| 963
| 59.84
|
Let’s start with a picture of a bench, as we’re going to do some benchmarking.
One of my take home message from useR was that we are going to have to do things in parallel. JJ set the motion with the RcppParallel package.
The inceptive example for RcppParallel was about calculating the sum from a numeric vector.
The article shows some nice global benchmark results.
As I’m going to be doing a lot of that kind of work, I’ve spent some time developping a few tools for finer grained benchmarking, hence the title of this post, the idea is that I want to know which thread is doing what and when.
Let’s start with the serial version. In these graphs below, the height of rectangles is proportional to the mount of data a thread is dealing with. In the serial version obviously there is only one thread doing all the work, so we have a big old blue rectangle. The x axis is time in milliseconds.
Then, some version using
parallelReduce from
RcppParallel. This was run on a machine that has 4 cores, so 8 threads with hyper threading. The first thing to notice is that it is faster, mission accomplished. We can also see the work of tbb scheduler, which has used many more than 8 threads, also within each thread (a line of variable height) we can see many rectangles. That is because tbb does not just split the data in chunks and hand them directly to the threads, it uses a advanced algorithm to schedule threads and hand small chunks to them.
The previous example use the default grain size (1) which might not be a good idea because we might end up with tasks running on very small chunks of data. Here’s another shot using a grain size of
1,000,000. Does not change much in that case in terms of total time, but we can see that there are less chunks. Finding the best grain size for a problem is not an exact science, but it is not that critical for such an obvious problem anyway.
Last example is about doing the splitting manually in 8 chunks and have one thread handling the whole chunk.
I’m working on another representation that might make it easier to compare the versions. the idea is to represent how much of the data has been processed at a given point in time. All the information is in the data, I just have to tidy it a bit as now the data is more or less organised to facilitate the previous graphs.
The code for these various versions is below. It uses current development version of
RcppParallel and my little
TimerPlot package that does the graphs.
#include
#include #include // [[Rcpp::depends(RcppParallel)]] using namespace Rcpp ; using namespace RcppParallel; // [[Rcpp::export]] List sum_serial( NumericVector x){ SingleTimer timer ; timer.step("start") ; double res = std::accumulate( x.begin(), x.end(), 0.0 ) ; timer.step( "work" ) ; return List::create( (SEXP)timer, res ) ; } class Summer : public Worker { public: Summer( const NumericVector& x ) : data(x.begin()), res(0.0) {} Summer( const Summer& other, Split ) : data(other.data), res(0.0) {} void operator()( std::size_t begin, std::size_t end){ res += std::accumulate( data + begin, data + end, 0.0 ) ; } void join(Summer& rhs ){ res += rhs.res ; } double get() const { return res ; } private: const double* data ; double res ; } ; typedef TimersList Timers ; typedef TimedReducer TimedSummer ; // [[Rcpp::export]] List sum_parallelReduce( NumericVector x, int grain_size = 1){ int n = x.size() ; Timers timers(n) ; Summer summer(x) ; TimedSummer worker( summer, timers ) ; parallelReduce(0, n, worker, grain_size) ; return worker.get() ; } template inline void process_thread( void* data ){ Work* work = reinterpret_cast (data) ; work->process() ; } struct SummerThread { public: IndexRange range ; double& res ; const double* data ; tbb::mutex& m ; ProportionTimer & timer ; SummerThread( IndexRange range_, double& res_, const NumericVector& data_, tbb::mutex& m_, ProportionTimer & timer_ ) : range(range_), res(res_), data(data_.begin()), m(m_), timer(timer_) {} void process(){ timer.step("start") ; double d = std::accumulate( data + range.begin(), data + range.end(), 0.0 ); timer.step("work") ; { tbb::mutex::scoped_lock lock(m) ; res += d ; } timer.step("join" ) ; } }; // [[Rcpp::export]] List summer_manual_threads(NumericVector x){ using namespace tthread; int n = x.size() ; IndexRange inputRange(0, n); std::vector ranges = splitInputRange(inputRange, 1); int nthreads = ranges.size() ; FixedSizeTimers timers(nthreads+1, n) ; timers[0].n = n ; std::vector workers ; std::vector threads ; double result = 0.0 ; tbb::mutex m ; for( int i=0; i , w )) ; } for( int i=0; i join() ; delete threads[i] ; delete workers[i] ; } return List::create( (SEXP)timers, result ) ; } /*** R library("TimerPlot") x <- rnorm(1e8) data_serial <- sum_serial(x)[[1]] data_parallel_1 <- sum_parallelReduce(x, 1L)[[1]] data_parallel_1000000 <- sum_parallelReduce(x, 1000000L )[[1]] data_threads <- summer_manual_threads(x)[[1]] xmax <- max( unlist(list(data_serial, data_parallel_1, data_parallel_1000000, data_threads ))) / 1e6 png( "serial.png", width = 800, height = 400 ) plot(data_serial, xmax = xmax) dev.off() png( "parallel_1.png", width = 800, height = 400 ) plot(data_parallel_1, xmax = xmax) dev.off() png( "parallel_1000000.png", width = 800, height = 400 ) plot(data_parallel_1000000, xmax = xmax) dev.off() png( "manual_threads.png", width = 800, height = 400 ) plot(data_threads, xmax = xmax)...
|
https://www.r-bloggers.com/yocto-benchmarking/
|
CC-MAIN-2018-13
|
refinedweb
| 841
| 56.55
|
1110 Feature Creation in WAS application server profile Replies2013-06-27T10:30:27.801ZIBM Connections - Discussion Forumurn:lsid:ibm.com:forum:36b87fab-0668-4da9-95d9-e4e3aa351e5fRe: User Feature Creation in WAS application server profile2013-06-27T09:15:56.600ZMarkN110000BE39active2013-06-27T09:15:56.600Z <p dir="ltr"> Hi Ravi, </p> <p dir="ltr"> Thank you for your question. You're quite right in that WAS Full Profile does not include support for custom namespace handlers. If this is something that you need, do please consider telling us more formally, by voting for Request For Enhancement (RFE) 35642, <a href="">here</a>. </p> <p dir="ltr"> In the absence of RFE 35642, if you need to use Full Profile in production, then you'll need to modify your application so as not to require custom namespace support. However the Liberty profile is a fully supported production runtime, as well as being a great tool for developers. Your other alternative would be to use custom namespace handlers and run your application on the Liberty Profile. </p> <p dir="ltr"> Regards, </p> <p dir="ltr"> Mark </p> none, view_forum, view_category
|
https://www.ibm.com/developerworks/community/forums/atom/replies?topicUuid=abbf76fd-0929-4f47-a31f-93bbbd41baef
|
CC-MAIN-2018-09
|
refinedweb
| 187
| 55.84
|
The service was great, the food was tasty and the price was reasonable. My fries could have been a bit hotter but the spicy flavor was super
My wife and I walked past and saw this amazing place so unlike our restaurants in Norway. We decided there and than to ask for a table on one of the balconies.
Great place to sit. Fantastic view. The food? Had chicken, fried salmon and the burger. Fiished with plain coffee. Very tasty.
Absolute a place to recommend to others.
I'm a jersey girl (with an inability to eat gluten) and grits are one of the most underutilized starch up here, in my opinion! Whenever I see shrimp and grits on a menu I gravitate toward it. Riverboat Landing absolutely nailed it! We went as a party of three and had a nice window seat. If you're going as a...
More
Fantastic view and a real food discovery for us European : seafood, typical Southern dishes... We loved it ! Good service as well.
We stopped here after the trolley tour and a broef walk on the riverwalk. From the outside, it ressembles a home in New Orleans. I was hesitant to enter for lunch, thinking it would be pricey, but, was pleasantly surprised. My daughter and ai each had a dandwich and a side. The total, with tax and tip, was just under...
More
I recently took a group of 30 people here for dinner in their upstairs dining room where they had also set up a bar for us. The food and service was superb. I'd definility return (again).
Walked by here yesterday and admired small 2 seat bistro tables on balcony, but we were 4... Got rid of the kids (!) and came back for nice lunch with million dollar view. Panko breaded salmon cake BLT and house chicken salad both satisfied, especially with tossed greens in white house vinaigrette side. Excellent server. Might have to stop back...
More
Great meal.....spinach ravioli and spicy shrimp linguine was delicious. Our waiter, Kevin, was awesome. Prices were good as well. Highly recommend.
The restaurant is right on the river so you have a great view of the river from some tables. The food was delicious. I had the chicken bacon sandwich and a salad. The citrus vinegarette was awesome. We also shared the potato skins. They were delicious! Great portions of food and very friendly staff. Service was quick and the prices...
More
Our last minute day trip to Wilmington culminated in our hungry family walking from a parking garage straight to the waterfront for dinner. It had gotten chilly, we were ready for a good meal -- no one felt like walking around or taking the time to check TripAdvisor for somewhere to eat so we winged it (usually not a good...
More
Register now for free — and start getting automatic notification of new reviews, responding to traveler feedback, adding new photos to your listing and much more.
|
http://www.tripadvisor.com/Restaurant_Review-g49673-d515815-Reviews-The_Riverboat_Landing-Wilmington_North_Carolina.html
|
CC-MAIN-2015-22
|
refinedweb
| 497
| 76.72
|
Chaos Journey
Introduction
This year “2020”, we have seen some real chaos. Though we are coming out from this pandemic, one thing strikes me, have we thought about this Chaos? If So, then how to build resiliency for day to day things we are dealing, today? This thought process brings aspects and focuses more on being ready for Chaos on software, products, and platforms. Chaos in the human environment is beyond imaginable, though we could do things we have control. We can put extra effort into making things reliable. How can we achieve this? Chaos Engineering is the discipline of experimenting on a system to build confidence in its capability to withstand turbulent conditions. Chaos Engineering will happen in a Control environment, where you should inject Chaos and ensure the system state remains stable. I am sharing my learning on this journey, from Application, cloud to the platform ( Kubernetes with Keiko). As I mentioned, it is a journey, so there is a lot more to learn and achieve.
Starting on Chaos
I started on Chaos engineering a couple of years back when we used to have chaos monkey and Symbian Army solutions from Netflix executed on AWS. The main focus was application resiliency and implementing a Hystrix pattern. Later, we explored more Tools to identify the Hystrix pattern’s opportunity for Application (Mentioned below). We were later reproducing those chaos scenarios for Application and kept ourselves engaged in chaos work. It is essential for chaos engineering that resiliency should be built-in to Application. They were stand-alone solutions, and bringing under one solution was tough. We did many POC on Chaos and tried various open-source and commercial tools in chaos-engineering. We looked at our chaos use cases as well as implementation with security and compliance. We found the customization for our need with a security compliance commercial solution is not viable. We were looking for a robust solution to leverage core functionality, contribute our requirements, and customize our needs.
Chaos Game Day
We had hosted a Chaos engineering meetup. This meetup brings chaostoolkit Tool in attention, which is an open-source solution as well as highly customizable. ChaosToolKit follows the Principles of Chaos Engineering. We did the initial POC and found it useful, and it was open for our needs with highly customizable. We were working on a small scale with various Teams to adopt this solution. we did a GAME Day on Kafka reliability during this phase ( See Below Image). It was just an Idea Phase.
Chaos Framework
As we started working on this framework, we started using many of their plugins. Though we realized that we need to customize some plugins, we also needed to write our customize extensions as they were not there. However, we were incrementally making progress on our work, framework changes, and new plugin support. We had started and were using 7–8 plugins , we have added 4–5 new plugin, and we enhanced Kubernetes and AWS plugin for our needs. AWS and Kubernetes plugins we made changes, and we are exploring options for its contribution. That was the time we needed to understand customer requirements, as it was beyond POC.
Chaos Tipping Point
The first turning point was during Innovation days 2018. We presented the chaos engineering mindset and got second place; The second turning point came in 2019; Intuit was building the NextGen Kubernetes platform; as part of that, We had onBoarded many teams on Kubernetes clusters. Our Customers faced a few incidents related to resiliency during that time, which pointed to further investment in reliability work, especially on our platform. As this is a core platform, its reliability is most important. We spent close to 2 weeks in the war room, built all the possible use cases, and validated our platform ( Kubernetes with Keiko),. We partnered with a few teams during this time and shared our idea for consuming chaos Solutions. Chaos is getting essential and vital; we were going on a mainstream project from a pilot project.
Chaos as a Service
During the war room, when we validated chaos use cases for kubernetes, how can we automate these chaos use cases and then how we will execute it as part of platform certification, was open questions? As we are using Kubernetes, we did POC and built a python based deployment service, which runs this chaos framework in a container along with Application. This Chaos Service interacts with Rest API and uses a cluster role to execute the chaotic operation. Later we improvised it and created a node-js based UI so that the Team can adapt quickly. We want to eat our dog food; we want to roll out with few teams and validate chaos adoption. Some customers opted and like this solution in their pre-prod environment and are using it to date. We were building a product for broader adoption.
Chaos on Kubernetes/Cloud
Chaos as a Service, Solution was working well; PM brings another dimension for rolling out this solution across clusters as teams want to get reliability for their Application and services. Reviewing existing solutions with the security team, we found compliance and rollout challenges. Setting up access and permission via service mode has feasibility, security, and compliance issues. On top of that question came this is not a Kubernetes Native solution, how we roll out across 100s of the cluster. So we started searching for a solution in kubernetes space. Initially, we built two solutions via the controller ( AWS and kubernetes), but then the question came, how we will port our framework and use cases. Effort and work would be more for porting. Hence we explored open source again and did many POC before choosing Litmus. We pivoted and reconsidered the solution for current needs.
Chaos Architecture for Kubernetes
Before picking Litmus, we did technical as well as Use case feasibility Analysis. We decided Litmus as it has a plugin architecture, community-backed, and Kubernetes native support. More importantly, it is open-source, which now becomes a sandbox project in CNCF. Our first POC was looking to port our current work, which has more than 50+ use cases. We want to minimize effort hence build this project to interact with kubernetes and chaostoolkit. We look plugin infrastructure as part of Litmus and the CRD based approach, which creates custom resources; in a couple of weeks, we were ready to execute our first kubernetes use case on Litmus. We presented in Litmus community and sharing our progress every month. I am a maintainer for SIG-Integration under Litmus. We are incorporating more use cases and building on core solutions for cluster and service owner.
Chaos using CRD’s / CR
When we started looking at Litmus, we wanted Chaos use-cases to execute via kubernetes native way. We have to build a container-native solution to run the container with our code, leveraging the custom resource and CRDs. The integration of the framework requires us to orchestrate and break our service layer to python wrapper. We build resources that match and invoke our framework, using a litmus runner and operator to execute this container. During this integration, we found many challenges, which, with their community’s help, were resolved. Custom Annotation, overriding custom resource permission, passing IAM roles for AWS are few contributions at the Litmus level we did, to support our custom use case. Now with these changes, we can execute the Kubernetes experiment as well as AWS experiments. Please refer to the pod custom resource for the engine and experiment.
Chaos use cases
We divided our customer persona in, cluster-admin, and service owner. Cluster admin has more permission for cluster-level Chaos, where service owner has limited permission only on their namespace to interact with his Application. This persona will do Chaos on the platform, Application, and Cloud, using our orchestrate code called the chaos tool kit framework. We are executing Kubernetes, Application, and Cloud base chaos with platform health and service uptime. We had three buckets of use cases that cater to Application, platform ( Kubernetes with Keiko), and cloud (AWS). In these categories, we divided Tier 1,2,3 test cases based on their feasibility and execution frequency. Please refer to the git, doc for more information. We have contributed kubernetes pod, microservice, and AWS ec2 chaos use cases till now
Chaos workflow
We are using the Argo workflow for test infrastructure execution. Chaos on Argo-Workflow is a solution we build in house and share on the Argo community. This solution helps us to automate and provide a way to maintain infra as a code. Similar work we extended and added as part of chaos workflow and contributed back to open-source. Later we have shared how we are using declarative pipeline and executing via Jenkins pipeline. Please refer to the git, doc, and video for more information. We are expanding the solution to the next level, with our expertise in Argo space.
Chaos and Performance Engineering
We take customer Failed interaction very seriously, which means we don’t want our service to be down. When we started doing chaos experiments, most of the chaos are stateful via our solution, Then we go and validate the uptime and availability of service. There was no stateless way to keep checking the service uptime when the pod or Application was down; though we are using HPA, we want to validate uptime during pod downtime. Hence we have introduced the Performance test along with Chaos. We leverage our existing performance infra solution using Argo workflow enhanced and included with chaos workflow. Now we can run Chaos as well as performance leveraging Argo workflow on performance infra. This solution is being built on open source and shared in the Argo workflow community. We now have resiliency, measured in terms of end-customer experience or service uptime. Chaos workflow with Performance test is part of the end to end via Argo-workflow automation. Please refer to the git, and video for more information.
Chaos Report
If you can’t measure, you won’t see the progress and improve. Though every team/company has its way of reporting, the same is true for us. Chaostoolkit gives us a report, as well as Litmus, will give chaos results and kubernetes events; though they are useful, we have specific reporting requirements. However, we had our reporting requirements build in the framework from the first day; with some small changes, we pushed all the data to Kafka-based Data Lake. This report matches and helps us derive results with other operations like code, performance tests. Today we move all our chaos results to a centralized data Lake and, through Kibana, build a custom dashboard, which provides information on chaos execution.
Chaos GitOps
The latest feature in this journey is Chaos GitOps; there is a lot more information available on GitOps. We are following the GitOps for our application deployment using ArgoCD. Now, we started doing GitOps for Chaos too. We are working on a solution leveraging Litmus/Argo-CD, where Chaos is available on the cluster. Gitops will execute on namespace for experiments and roles. Namespace GitOps we leverager kustomize, which is sync via Argo cd. Application GitOps we use via annotating the Application using custom annotation support via Litmus chaos operator. Please refer to the video for more information; code will be coming soon; stay tuned
Chaos Team and Support
Here are engineers (Vijay, Navin, Anu, Phani, Gunjan, May, Ravi, Veena) working with me on this project. Special mention of Russ and Sylvain from chaostoolkit, Karthik and Uma from Litmus, who guided me in this journey.
Chaos References
-
-
-
-
-
-
-
-
Sumit Nagal , Principal Engineer , Intuit Inc.
|
https://sumitnagal.medium.com/chaos-journey-279924051d57?source=rss------kubernetes-5
|
CC-MAIN-2020-50
|
refinedweb
| 1,947
| 54.42
|
#include <BCP_var.hpp>
Inheritance diagram for BCP_var_indexed:
This index is a unique user specified ID which enables the user to expand the variable into a column that can be added to the LP formulation.
Definition at line 263 of file BCP_var.hpp.
The default constructor is declared but not defined to disable it.
The copy constructor is declared but not defined to disable it.
This constructor just sets the data members to the given values.
See also the constructor of BCP_var.
Definition at line 287 of file BCP_var.hpp.
The destructor deletes the object.
Definition at line 291 of file BCP_var.hpp.
The assignment operator is declared but not defined to disable it.
Return the user index of the variable.
Definition at line 297 of file BCP_var.hpp.
Return BCP_IndexedObj indicating that the object is an indexed variable.
Definition at line 300 of file BCP_var.hpp.
References BCP_IndexedObj.
The only (not inherited) data member is the user given index of the variable.
Definition at line 269 of file BCP_var.hpp.
|
http://www.coin-or.org/Doxygen/CoinAll/class_b_c_p__var__indexed.html
|
crawl-003
|
refinedweb
| 170
| 52.66
|
#include <TestDecider.h>
#include <TestDecider.h>
Inherits BasicDecider.
Inheritance diagram for TestDecider:
THis decider does not contain functionality and is only to test core functionality
[protected, virtual]
In this function the decision whether a frame is received correctly or not is made.
Redefine this function if you want to process messages from the channel before they are forwarded to upper layers
In this function it has to be decided whether this message got lost or not. This can be done with a simple SNR threshold or with transformations of SNR into bit error probabilities...
Afterwrads the message has to be decapsulated (decapsMsg) and send to the MAC layer (sendUp)
just an example how to handle the snrList...:
bool correct = true; //check the entries in the snrList if a level greater than the //acceptable minimum occured: double min = 0.0000000000000001; // just a senseless example
for (SnrList::iterator iter = snrList.begin(); iter != snrList.end(); iter++){ if (iter->snr < min) correct = false; }
if (correct){ sendUp(frame); } else{ delete frame; }
Implements BasicDecider.
Handle self messages such as timer...
Define this function if you want to timer or other kinds of self messages
|
http://mobility-fw.sourceforge.net/api/classTestDecider.html
|
CC-MAIN-2018-05
|
refinedweb
| 188
| 54.83
|
I am able to have c# (client) and python (server) talk to each other by using a simple request-reply. However, I want my web application built on c# asp.net to be stable and need more clients and servers, so I tried connecting c# and python using the Router-Dealer Proxy with python.
I tried running the proxy python script first, then running c# (client), then python (server). However, when I run the python (server), it gives me an "Address in use" error message.
Am I running them in a wrong order OR is there something wrong with the proxy python script (shown below)?
5602 = c# client
5603 = python server
def main():
context = zmq.Context()
# Socket facing clients
frontend = context.socket(zmq.ROUTER)
frontend.bind("tcp://*:5602")
# Socket facing services
backend = context.socket(zmq.DEALER)
backend.bind("tcp://*:5603")
zmq.proxy(frontend, backend)
# We never get here…
frontend.close()
backend.close()
context.term()
if __name__ == "__main__":
main()
I'm assuming your servers use bind, so the proxy should
connect to them rather than also using
bind.
Note: in zeromq the order of application startup doesn't matter so you can tell your proxy to
connect to a server that doesn't yet exist, when the server is started the connection will be made.
|
https://codedump.io/share/KG7rPtgFQ80v/1/sending-message-with-router-dealer-proxy-using-c-and-python
|
CC-MAIN-2017-30
|
refinedweb
| 214
| 63.9
|
[laravel-echo] can't get laravel-echo to work properly with Quasar
please help on configuring Laravel-echo with quasar
what i have done so far:
yarn add laravel-echo
quasar new plugin laravel-echo
add laravel echo on my /quasar.conf.js
- then i configured laravel-echo.js as in the bellow image
- then i try to listen like this
- but i always get this error
i have tried many configuration but it still has not worked.
please what am i doing wrong and if anyone has a better procedure , i can do with some help here.
thank you
- metalsadman last edited by
have you tried declaring a Vue.prototype for $echo? maybe try to put it after Vue.use(echo) in your plugin ie.
Vue.prototype.$echo = echo.
laravel-echo.js:
import Echo from 'laravel-echo' window.io = require('socket.io-client') const echo = new Echo ({ broadcaster: 'socket-io', host: window.locatin.hostname + ':6001' }) export default ({Vue}) => { Vue.prototype.$echo = echo
Note: I have never used Laravel Echo with Vue., so I am not sure if the instantiation of Echo is correct, I am just going off of your code.
Now, you can use the above in your code with
this.$echo
Wow guys. Thank you very much. I will try and send feedback
@metalsadman @Hawkeye64 yes it works. i will give more info soon
thank you
@metalsadman @Hawkeye64 yes it works. i will give more info soon
thank you
can you show me settings from socket.io-client.js and vue-socket.io.js plugins? I have error
this.$echo.channel is undefined
|
https://forum.quasar-framework.org/topic/2879/laravel-echo-can-t-get-laravel-echo-to-work-properly-with-quasar/7
|
CC-MAIN-2019-13
|
refinedweb
| 266
| 69.28
|
Fiori Overview Pages are a great way to show a snapshot of the business data. Many a time you have Global filters to limit what do you want to see in those cards. Most of the times you will have a date range filter which will report data for current financial year, or last month so on.
I had such a date range filter on my OVP, and the requirement is to default the date range to last 90 days, so that user does not have to set it manually after opening it.
The first solution I tried was with a Global Variant. I created a Global variant, so that all users have it available. However there are couple of issues.
- You cannot set a Global variant as ‘default’ for all your users. (even if you are a power/key user). Hope SAP provides this functionality.
- For filters like Date range, you cannot maintain a static value there. It has to be dynamic, for example “last 90 days”. There is no way to do that with Date Range control. However there is a ‘DynamicDate’ UI5 control, which provides you to specify “Last X Days” kind of values. But currently OVP pages do not respect the annotations for rendering a DynamicDate control, rather renders a Date Range control. (SmartFilterBar when used alone, respects those annotations though).
So I was exploring a programmatic solution and it turned out to be a simple solution. Here is how.
Step 1. Setup Extension Controller. In the manifest.json file of your OVP project, under “sap.ui5” node, maintain below extension.
"extends": { "extensions": { "sap.ui.controllerExtensions": { "sap.ovp.app.Main": {"controllerName":"my.namespace.controller.customMain" } } } }
Step 2. Create the controller extension file. Create a controller folder, and then create a Controller file like below with name customMain.controller.js.
sap.ui.define([], function() { "use strict"; return sap.ui.controller("my.nameSpace.controller.customMain", { onBeforeRendering: function() { //Get reference of Global FIlter var oGlobalFilter = this.getView().byId("ovpGlobalFilter"); //Create JSON data to be defaulted var oToday = new Date(); var o90DayesEarlier = new Date(); o90DayesEarlier.setDate(o90DayesEarlier.getDate() - 90); var oDefaultFilter = { InspectionDate: { low: o90DayesEarlier, high: oToday } }; //Default the Goabl filter values oGlobalFilter.setFilterData(oDefaultFilter); } }); });
Step 3. Ensure there is no conflict with Variant Management
If you have enabled Variant Management, and if user has selected a default variant within OVP, then above code will overwrite that default variant. So you need to check if there is a default variant, only otherwise you have to set your defaults. Here is the updated code.
sap.ui.define([], function() { "use strict"; return sap.ui.controller("my.nameSpace.controller.customMain", { onBeforeRendering: function() { //Get reference of Global FIlter var oGlobalFilter = this.getView().byId("ovpGlobalFilter"); //Ensure that there is no default Variant set by the user. //In such a case, do not set default values to the Gloabl Filter. var sDefaultVariantKey = oGlobalFilter.getVariantManagement().getDefaultVariantKey(); //If No variant is set, default variant is "standard" if (sDefaultVariantKey !== "*standard*"){ return; } //Create JSON data to be defaulted var oToday = new Date(); var o90DayesEarlier = new Date(); o90DayesEarlier.setDate(o90DayesEarlier.getDate() - 90); var oDefaultFilter = { InspectionDate: { low: oToday, high: o90DayesEarlier } }; //Default the Goabl filter values oGlobalFilter.setFilterData(oDefaultFilter); } }); });
Note: Instead of using setFilterData, you can set a Global Variant using oGlobalFIlter.getVariantManagement().setCurrentVariantId(<variant_id>) as well.
If you want the Project structure with the custom controller, here it is.
That’s it. Hope it was useful!!
Important note: Like many of my blogs, this is a hack. Which means this is not an SAP documented supported scenario. So SAP does not guarantee that these APIs will work seamlessly across upgrades. Thanks Prasita Prabhakaran for pointing that.
If you are on S/4HANA
and if you want to set up static default values on Fiori Elements applications, there is a solution needing no coding. You can choose default values at the Fiori Launchpad level and this gets updated to all the Fiori Elements applications. Blog here explains how to get this done. Thanks to Jocelyn Dart for the context.
Ashish Anand has mentioned a new way to achieve this in the comment section below. Standard S/4 Fiori elements can be extended using the extension method modifyStartupExtension to set the default variant. Read more here. Please blog if you achieve this.
Hello Krishna,
the post is really cool!
Could you please provide the folders structure of your project? I would like to check the route to custom controller to fix my case.
Thanks
Updated it. Let me know where did you get it wrong. I too had issues before I got it right.
Thanks so much for this blog Krishna, made me finally activate my SAP profile again to post here 🙂
I'd been struggling with how to get a default to be applied and was messing around with extensions but couldn't figure this one out.
In my case i'm using a dynamic default by calling a function import on my OData service in the onBeforeRendering method in the extended controller and works great, defaulting in user specific values obtained from backend.
Cheers
Chris
Hi Chris, Glad it helped. And congrats for getting back to the community. ?
Hi Krishna
Thanks - I've added this to the Fiori elements wiki.
Can you please add a small comment re S/4HANA - in S/4HANA you can also pass User Defaults from the Fiori launchpad target mapping as per
Rgds
Jocelyn
Thanks Krishna ! This is exactly what I was looking for.
One more thing I was trying to do is hide/show 'shared' variants for various users based on some conditions.
Can we show/hide variants to users using Variant Management API ? or any other way would you recommend ?
Thanks,
Tanveer
Hi Tanveer, It can be done, but you need to find the backend services which are supplying these variants to the UI and filter them using ABAP implicit enhancement points.
Hi Krishna Kishor Kammaje
From SAP Version 1.58, OVP support new break out named “modifyStartupExtension”, which can be used to set the default value of global filter dynamically. Please refer to the example below:
Official documentation for the same:
Hope this helps
Thanks and Regards
Ashish
How to set a value which gets from config parameter in launchpad instead of hardcoding it here
|
https://blogs.sap.com/2018/08/23/fiori-ovp-defaulting-values-into-global-filters/
|
CC-MAIN-2021-10
|
refinedweb
| 1,040
| 58.79
|
Problems with TDD
If you have not yet read it, please read Maria Siniaalto's 15 page "Test-Driven Development: empirical body of evidence." It summarizes the few empirical studies done to evaluate the effectiveness of TDD. In the conclusion you'll find:
Based on the findings of the existing studies, it can be concluded that TDD seems to improve software quality, especially when employed in an industrial context. The findings were not so obvious in the semi-industrial or academic context, but none of those studies reported on decreased quality either. The productivity effects of TDD were not very obvious, and the results vary regardless of the context of the study. However, there were indications that TDD does not necessarily decrease the developer productivity or extend the project lead-times: In some cases, significant productivity improvements were achieved with TDD while only two out of thirteen studies reported on decreased productivity. However, in both of those studies the quality was improved.
The empirical evidence on the practical use of TDD and its impacts on software development are still quite limited.
I mention this first because I've concluded that not only is TDD not useful for me but I don't think it's a generally useful technique. The important requirements are to have good, complete automated unit tests, to develop code for testing, and to do interative improvement through refectoring and rewriting. TDD promotes those, but my experience is that TDD pins down the code too early and my observation is that TDD by itself ignores certain classes of essential unit tests.
My position against TDD will be contentious to some, like those who believe that TDD is a required component in modern best-practices development. I quoted Siniaalto to show that there is no strong evidence to back that belief. I fully expect someone to tell me that TDD drastically improved their development style. My response will be they learned good practices, but those practices don't require TDD and can as easily be learned without TDD.
By the way, while my conclusion is in opposition to Siniaalto's, it's because the most successful TDD paper in her report comes from Maximilien and Williams about their experience at IBM. They went from ad hoc unit testing to good development practices based on TDD. I think good testing practices without using TDD would have given the same results.
Before going further I'll also quote from Kent Beck's "Test-driven development: by example":
One of the ironies of TDD is that it isn't a testing technique (the Cunningham Koan). It's an analysis technique, a design technique, really a technique for structuring all the activities of development.This entire essay will describe why TDD is a weak testing technique and an incomplete development technique. I'll bring up other techniques which are not part of TDD but end up leading to better unit tests that should help make you more confident that your code works.
Test first vs. test last vs. good testing
By TDD I mean Test Driven Development, and specifically its test first approach. Wikipedia describes TDD as:
First the developer writes a failing automated test case that defines a desired improvement or new function, then produces code to pass that test and finally refactors the new code to acceptable standards.By contrast, people also talk about "test last". Test last is the extreme opposite of "test first". One good definition of test last is:
testing should be done before the code goes into production; it does not imply that the tests are automated.
When I say that people shouldn't do TDD I do not mean they should do test last development instead. That is false dichotomy, and it annoys me when I read descriptions which present those two styles as the only possibilities.
My own practice is to have good, automated tests, but these don't get put into place until the cost/benefit ratio makes the tests worthwhile; which is rarely at the start of the code development and always by the end. The test themselves are guided by the code, and the knowledge of where the failure cases might be in the code. In addition, I'll add tests which check the expected input range, and after the code is done I'll add tests which check my belief that the code is done, as well in some cases tests driven by code coverage or other reasons.
I expect people to point out that TDD does not preclude other testing strategies, to fill in those gaps. I completely agree. I agree so much that I mostly use those other good strategies, and not TDD. TDD seems to add little to the result.
Worked out TDD examples
I want to base my response in at least the spirit of empirical research. I can't, because I don't (and neither likely do you) have the resources to do those tests. What I can do is find some descriptions of TDD used to implement a problem and make comments about them to highlight limitations in TDD.
I give full props to those who have described the steps they go through to work on a problem. Even in the simplest of cases it's a lot of work.
I found number of basic TDD tutorials, based around addition and subtraction, either with basic add() and sub() functions or through depositing and withdrawing money from a bank account [1] and [2].
Those were too simple to have problems. I wanted something more complex. The most complete examples I found were Robert Martin's Prime Factors Kata, which he also works through in a video, and implementing the Fibonacci sequence in Gary Bernhardt's blog post How I started TDD and Kent Beck's "Test-driven development: by example". I don't know if Bernhardt's example is derived from Beck's, but it's the one I came across first.
Prime Factors
The Prime Factor Kata asks for a function which takes a number and returns its prime factors in an ordered list, including duplicates. For example, 12 would return 2, 2, 3. The test cases were 1, 2, 3, 4, 6, 8, and 9 and the kernel of the solution was:
public static List<Integer> generate(int n) { List<Integer> primes = new ArrayList<Integer>(); for (int candidate = 2; n > 1; candidate++) for (; n%candidate == 0; n/=candidate) primes.add(candidate); return primes;
Fibonacci
The Fibonacci sequence examples checked that the first few outputs were correct, giving fib(i=0, 1, ...) = 0, 1, 1, 2, 3, 5 . Both people ended with variations of the classic recursive solution, here from Bernhardt:
def fib(n): if n <= 1: return n else: return fib(n - 1) + fib(n - 2)
Problem: TDD doesn't emphasize good test cases
When I looked at Martin's Prime Number Sieve, I first thought the code was wrong. It tests to see if 2 is a divisor, then 3, then 4, then 5, and so on. 4 can never be a prime divisor of the candidate because 4 isn't prime. Why does his code check for that possibility? Was there a bug?
Code should be readable, so that others can understand it and verify that it works. In the same vein, tests should serve as a way for others to check that the code is working. I looked at the tests, and noticed that the only prime factors tested were 2 and 3. Perhaps if 5 was a prime factor then there would be a problem when the code got to 4?
I couldn't tell from the tests, so I had to look more closely at the code. It then became obvious. All factors of 2 were removed, so there was no way that 4 could be a divisor. By construction, no non-prime candidate could ever work, so will never be added to the list.
The tests were not good enough to minimize doubt that the code contained bugs. I can think of a couple of simple variations of the code which would contain bugs and which would pass the tests. Yes, the tests were enough to help Martin get to a solution, but they shouldn't have been enough to convince him, much less others, that the code was right.
Some good tests might have included the primes 17 and 97 as well as 91 (=7*13). I can't think of simple bugs to put in Martin's code which would also cause those test cases to fail, excepting a hard-coded upper limit to the search space which would easily show up on code review.
Fibonacci Sequence
Bernhardt's Fibonacci Sequence did test enough numbers that I was pretty sure that algorithm would come up with the correct answers, although I would have preferred some larger numbers, like fib(12) = 144. (I picked that one because it's cute that 144=12*12.)
Problem: When do you add tests that should pass?
TDD says to add a failing test then fix the code. What do you do with tests which are expected to pass? For example, suppose I finished the prime factors code but upon review of the tests I have a niggling uncertainty that it handles prime factors greater than 3. I want to add a test case to find the factors of 91.
I asked this of Bernhardt, and he kindly addressed that in his followup essay "The Limits of TDD."
After the tests drove the first fully-functional design out, I'd add exactly the types of tests you describe. These wouldn't fail at first, but that's fine; TDD doesn't preclude such things, they're just outside its scope. What I would do, to make sure the tests were honest, is to intentionally break the code, watch them fail (probably along with several other tests), then unbreak the code. This gives me at least some of the confidence that TDD does - I know that something is actually being tested.This is a bit different than what I would do. If the code is supposed to work then I don't want to touch the code at all. Instead, I add the test but make sure the test is supposed to fail, perhaps by saying the factors of 91 are 5 and 13. Seeing the failure is a check that I didn't make a stupid mistake in writing the test. Then I fix the test and see that it passes.
Mine is not his more TDD approach, although close. But I want to highlight his comment that "TDD doesn't preclude such things, they're just outside its scope."
That's exactly my point, and notably in disagreement with Beck's statement that TDD is "really a technique for structuring all the activities of development."
Other tests and other development approaches besides TDD are needed for good software development, including approaches which are conceptually quite close to TDD but not part of it. I say that the skills that are needed to detect and add good passing tests can equally be applied to developing good unit tests in the first place.
Only, without extra requirement of coming up with all of the tests first.
Problem: TDD does not consider worst-case scenarios
In "good test cases" I said that TDD doesn't stress the tests needed to convince yourself or others that the code was right, only tests to implement the code you think is right. Here I'll talk about a different sort of unit test that TDD doesn't help with - worst-case scenarios.
Prime Factors Kata
I implemented the Prime Factors Kata on my own. It took me a while too. I implemented the Sieve of Eratosthenes to generate prime factors, and only searched for factors up to sqrt(n). This has been my general approach for this sort of problem since college. I ended up with 29 lines of code, and I couldn't understand how Martin was able to write:
The final algorithm is three lines of code. Interestingly enough there are 40 lines of test code.(BTW, I counted 15 total LOC in the program and 43 LOC in the test module, or 3 vs. 12 if you only talk about "real" code, vs. import statements, function definitions, lines with only a closing brace, and so on. In either way of counting, it's still less than my 29 lines of code.)
If you listen closely in Martin's video you'll see that he considers his three line solution to be "more elegant" than the Sieve solution. I really didn't understand assertion. His solution is going to be slow for almost all cases. I timed Python implementations of our two algorithms for numbers around 200,000. His was 150* slower than my sieve-based solution, and it gets much worse after that.
If you listen even more closely, I think you'll hear the reason. He introduced the problem by saying his kid was learning about prime factors at school, and Martin wanted a program which could solve the same sort of problem. In that case, the prime factors are small. Few teachers would be so mean as to require their students to find the prime factors of 524,287 by hand.
If the possible input range was only, say 1 to 150, then I could see how Martin's code is elegant. But if the input range is 1 to 2**32 (which is more like I expected), then it's clearly not elegant because finding that 2**31-1 is prime will take about 2**31 modulo tests. Computers are fast, but that's excessive. (BTW, it's also cute that 2**31-1 is both max signed integer and a Mersenne prime.)
In either case, there should be tests for values which represent a worst-case scenario. In this case that would be a prime at the high end of the expected range. His largest test was 9. Mine was 2**31-1.
Fibonacci
There are three problems with the Fibonacci implementations. One is that the classic recursive solution (without memoization) takes exponential time. I implemented the solution iteratively and compared the results. Bernhardt's solution for fib(32) takes about as long as my iterative soluton for fib(100000), and after a minute I gave up computing fib(40) recursively.
Another is that Python's default stack size is 1000 function calls. Doing fib(1500) quickly gives a "RuntimeError: maximum recursion depth exceeded" exception.
The last is in Beck's code. Assuming the recursive solution could compute it in time, fib(48) is larger than 2**32. He uses a Java 32 bit integer, so his code would silently overflow.
Discussion
TDD creates unit tests which are used to develop and refactor code. These tests are only a subset, and not even an essential subset, of the tests needed to check that the code implements the requested feature. You may think you are finished with the code and you pass all the TDD tests, but you still aren't finished with the development process. You still have to do other important unit tests.
I'm certain that Beck and Bernhardt know the limitations of their Fibbonacci implementations. I'm really surprised they didn't mention the problems in their solution. It would have been the perfect place to show that other types of unit tests can't be ignored, and discuss how to fit them into the TDD development process.
I also wish that Martin has been less dismissive of the sieve solution. It's obvious that others have mentioned it to him. He should have responded by pointing out that the solution was overkill for the problem range. I also wish he had included tests for the high end of that range. (I have the idea based on other writings that he's not an algorithms person, so he also might not have been aware of the performance problems in his solution.)
Problem: TDD doesn't give you confidence that the code works
Many TDD advocates bring up confidence as a reason for doing TDD. In his book Beck writes:
Psychological - Having a green bar feels completely different from having a red bar. When the bar is green, you know where you stand. You can refactor from there with confidence.and others write similiar things.
If your goal is to be confident in your code, then TDD is a weak method for developing those tests of confidence. I've now shown a couple of TDD examples, which were done with TDD principles foremost in mind, but which failed to consider worst-case solutions. You should not be confident that your code works just because your TDD tests pass.
When I write my code, I'm not confident that it works. I'm not even confident that a refactoring works despite passing all of the unit tests. I worry about edge cases I didn't think of, I worry about implementation flaws, I worry about worst-case scenarios.
If I write the tests first, I also worry that I've overfit my code to the tests. This is a problem that happens in statistical modelling. Given any set of data points, I can fit them to a model. The next question is, is the model valid and useful? The way to check is to use them to make predictions, and see how well it matches reality. This in turn means testing the model with data which wasn't used to make the model.
I feel the same way about my code. I start with doubt that my program works, but with confidence that I can develop new tests which should pass if the code is correct. To reduce doubt, I'll write new tests and see if they pass or fail. Passing tests reduces my doubt, failing tests means I need to figure out what happened, and I'm back to more code development.
TDD by itself cannot give you that confidence because it excludes the idea of adding tests which are expected to pass. On the other hand, developing unit tests even if just after the code is written (but long before it's deployed as is done with test-last), guided by knowledge of how the software is implemented and experience in how the code can fail, can give you all the benefits of TDD, plus be able to handle the cases that TDD doesn't handle. TDD is one technique for learning those skills, but it is not an essential technique.
Incorrect claim: TDD leads to 100% coverage
Beck and others write that TDD naturally leads to nearly 100% test coverage. In his book he writes "TDD followed religiously should result in 100% statement coverage." Elsewhere I've seen people write similar things.
That's not true. Yes, under TDD new code should have 100% statement coverage, but what about refactored code? This is especially true if the refactor is more like a rewrite, perhaps to replace an algorithm with a faster version.
If I start with Martin's Prime Factors code and change it to my prime sieve based code, I can think of several ways where part of the refactored code wouldn't be tested. You can easily come up with plenty of other refactorings where part of the new code are not tested.
Yes, people will respond that TDD doesn't mean you can't stop being smart, and you must remember to include those tests, or even to add those tests while refactoring the new code. That's very true. I only point out that refactoring doesn't have the goal of maintaining full statement coverage, and therefore TDD doesn't either.
If you feel that code coverage is needed, above and beyond code inspection and manual methods, then there are tools to help automate coverage tests. The best covered tool I know of is SQLite. Its "veryquick" tests run about 42 thousand tests to get 97.23% coverage of about 66,000 SLOC, with additional tests which get 99.50% statement coverage of the entire code, and 100% coverage of the core. This was an intense and dedicated effort which does not and cannot fall out as a simple consequence of TDD.
Complaint: TDD freezes the API too early
This is my personal complaint. It is not derived from those worked out examples.
My own development style is a mixture of many techniques. When I've tried doing TDD I feel like it locks me down too early. My code in the early stage is very fluid. I'm mostly trying to get a feel for what it's going to look like. At that stage the code isn't meant to even compile, and the only machine it runs on is the model in my head.
This is especially true for cases where I'm trying to come up with a good API to implement the new functionality. My test cases are short programs which would use the API, and I try out different example programs to get a feel for usefulness, ease-of-use, ease-of-implementation and other factors.
If I use TDD here, I don't know what the API is going to look like, so how do I write the tests? I won't know what the API is going to look like until I've had a feel for implementing it but even then the API changes often. If I have tests for the API and the API changes, then there's the extra mental barrier of having to change all the tests for the new API.
Especially bad are the cases when I realized that some function isn't needed and should be deleted. With TDD that would also mean deleting the tests which went along with the function, and it would likely mean I've already spent time debugging the function, now all thrown away.
I've seen that in the code katas we do in the GothPy meetings (the local Gothenburg Python Users Group). Once we have working code with unit tests, I don't want to remove the function, and I start thinking about ways to adapt it, rather than thinking about ways to simplify the overall code base.
XP allows something this as a spike solution, but says that you should expect to throw the implementation away and start anew. I don't.
Once I have a good sketch of how the code is going to be, I often continue by filling in the details. At this point unit tests starts to be useful, but if I'm developing an API I'll write a simple functional test which uses the API, and make it work. It really might be a command-line program or even a __main__ for the current module. This helps give me get more concrete solution and once that's solidified enough code I start developing my automated unit tests.
Since I'm not using TDD, I used code coverage (either manually or through coverage tools) to improve statement coverage, and I use my knowledge of the problem to come up good test cases. The result seems to be no less effective than TDD, plus as a methodology it includes development tests which TDD does not.
Conclusion
Good testing practices help make good code. Automated unit tests, written by the developer and run often during the development stage, is a good testing practice. TDD uses those sorts of tests, but its focus on test-first, with failing test cases that reflect missing code, exclude important tests in the development process.
TDD can easily be modified to handle these other cases, but the result is simply "good unit testing", without the test-first aspect that makes TDD what it is.
Questions or Comments?
This is a contentious topic with a long history and plenty said about it. I think I've contributed something new to it with my commentaries on what should be exemplar TDD-based solutions. I hope you found it interesting if not enlightening or useful. With three nearly complete rewrites, it was by far the hardest essay I've ever written for my site.
If you have any comments or feedback, please do let me know.
Andrew Dalke is an independent consultant focusing on software development for computational chemistry and biology. Need contract programming, help, or training? Contact me
|
http://www.dalkescientific.com/writings/diary/archive/2009/12/29/problems_with_tdd.html
|
CC-MAIN-2016-44
|
refinedweb
| 4,097
| 70.33
|
ESP8266 Read ADC Values Micropython
ADC stands for “Analog to Digital Convertor”. As the name suggests, it takes an analog signal as input and gives it’s digital equivalent value as output. In embedded systems ADCs are used all the time whenever something is to be measured; be it the temprature, pressure, weight, voltage, current; anything like that.
Usually the sensors that give analog values as an output are connected to the ADC of the microcontroller.
With micropython it becomes very easy to read adc values from ESP8266. It is literally three lines of code.
To initiate ADC on ESP8266
>>> import machine >>> adc = machine.ADC(0) # this is the pin A0 on NodeMcu ESp8266 module.
To read the Adc values:
>>> adc.read()
Following is the code that connects to the wifi, connects to the mqtt server and publishes ADC values on a perticular topic after a regular interval.
from umqtt.simple import MQTTClient import time import network import machine config = {"wifiSSID": "<Your-SSID>", "wifiPass": "<Your-Password>", "ip": "<IP-Of-your-server>", "nodeId": "Node3"} # Connect to Wifi sta = network.WLAN(network.STA_IF) sta.active(True) sta.connect(config['wifiSSID'], config['wifiPass']) # initialize the the ADC adc = machine.ADC(0) # this is the delay after which the adc input will be read. interval = 5 def sub_cb(topic, msg): print(msg, topic) # change the interval interval = int(msg) def main(server=config['ip']): time.sleep(5) # connect to the Mqtt Broker (Mosquitto) c = MQTTClient('umqtt_client', server) c.set_callback(sub_cb) try: c.connect() print(b'{}/input'.format(config['nodeId'])) c.subscribe(b'{}/input'.format(config['nodeId'])) except OSError: main() while True: c.check_msg() val = adc.read() # read the adc value print(str(val)) c.publish("Node3/output", str(val)) # publish the adc value time.sleep(interval) c.disconnect() main()
|
http://girishjoshi.io/post/esp8266-read-adc-values-micropython/
|
CC-MAIN-2018-47
|
refinedweb
| 295
| 50.84
|
Important: Please read the Qt Code of Conduct -
C++ object assignment between two context property in QML through Q_Invokable
Hi,
I'm trying to implement a simple edit dialog in QML with (almost) pure C++ backend. The class to be edited has some displayable members and also others i.e. pointers, vectors, etc. Because of this and to keep (almost) all the logic on the C++ side, I want to have a temp instance while editing the properties in the QML window, so that I can either discard them or save them to my class instance represented there.
One way would be to use simple properties on the QML side and assign to them the first the original values on open and the new values upon save or do nothing on discard, but that way I would have to check everything on the QML side probably in javascript and part of the logic would be transfared to the QML side, and If I have many members I would also have that my QML property and two times the assigments.
My solution to avoid the above mentioned things is that I not just expose the two object to QML but also register their class as a QML type and then I can call a C++ clone function, as I was unable to call the overloaded assignment operator (use a single AInstance = BInstance in QML) while it would be convenient and cool.
I also have to bind these members to their TextField.text one-by-one.
Below you can find my MCP example. Is there a better, more sophisticated way to implement this?
C++
A.h
Class A; typedef struct { QString prefix; QString firstname; QString lastname; std::vector<A*> As; } StructVar; class A : public QObject { Q_OBJECT Q_PROPERTY( QString a1 READ geta1 WRITE seta1 NOTIFY a3Changed ) Q_PROPERTY( QString a2 READ geta2 WRITE seta2 NOTIFY a2Changed ) Q_PROPERTY( QString a3 READ geta3 WRITE seta3 NOTIFY a3Changed ) Q_PROPERTY( QString var1 READ getvar1 WRITE setvar1 NOTIFY var1Changed ) signals: void a1Changed(); void a2Changed(); void a3Changed(); void var1Changed(); public: A( QObject *parent = 0 ); ~A(); A( const A& a ); A& operator=( const A& a ); Q_INVOKABLE void copy( QObject* a ); ... setters, getters, other functions ... private: QSrtring a1; QSrtring a2; QSrtring a3; StructVar sv1; SomeOtherClass B*; } /* not copying here almost empty/trivial/not relevant A.cpp content */
main.cpp
#include <QApplication> #include <QQmlApplicationEngine> #include <QtQml> #include <QQmlContext> #include "a.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); A currentA; currentA.seta1( "Text a1" ); currentA.seta2( "Text a2" ); A editA = currentA; qmlRegisterType<A>("My", 1, 0, "A"); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty( "currentA", ¤tA ); engine.rootContext()->setContextProperty( "editA", &editA ); engine.load(QUrl(QStringLiteral("qrc:///main.qml"))); return app.exec(); }
QML
import QtQuick 2.2 import QtQuick.Controls 1.2 ApplicationWindow { id: appWindow visible: true height: 640 width: 1140 visibility: "Maximized" Rectangle { id: menuContainer x: 100 y: 100 width: 200 height: 200 Rectangle { id: saveButton x: 10 y: 10 width: 40 height: 40 color: "blue" MouseArea { anchors.fill: parent onClicked: { currentA.copy( editA ) } } } Rectangle { id: cancelButton x: 60 y: 10 width: 40 height: 40 color: "red" MouseArea { anchors.fill: parent onClicked: { // do nothing in the example } } } Item { id: textInputContainer width: 200 height: 100 anchors.horizontalCenter: parent.horizontalCenter anchors.bottom: parent.bottom anchors.bottomMargin: 20 Binding { target: editA property: "a1" value: a1Text.text } TextField { id: a1Text text: editA.name placeholderText: "type..." height: 50 width: 150 } } } }
Thanks for looking it through ; )
|
https://forum.qt.io/topic/52732/c-object-assignment-between-two-context-property-in-qml-through-q_invokable
|
CC-MAIN-2020-34
|
refinedweb
| 568
| 53.71
|
abstract class defined API for attribute data More...
#include <vtkGenericAttribute.h>
abstract class defined API for attribute data
vtkGenericAttribute is an abstract class that defines an API for attribute data. Attribute data is data associated with the topology or geometry of a dataset (i.e., points, cells, etc.). vtkGenericAttribute is part of the adaptor framework (see GenericFiltering/README.html).
vtkGenericAttribute provides a more general interface to attribute data than its counterpart vtkDataArray (which assumes a linear, contiguous array). It adopts an iterator interface, and allows attributes to be associated with points, edges, faces, or edges.
Definition at line 50 of file vtkGenericAttribute.h.
Definition at line 53 of file vtkGenericAttribute.h.
Return 1 if this class is the same type of (or a subclass of) the named class.
Returns 0 otherwise. This method works in combination with vtkTypeMacro found in vtkSetGet.h.
Reimplemented from vtkObjectBase.
Name of the attribute.
(e.g. "velocity")
Is the attribute centered either on points, cells or boundaries?
Type of the attribute: scalar, vector, normal, texture coordinate, tensor.
Type of the components of the attribute: int, float, double.
Number of tuples.
Size in kibibytes (1024 bytes) taken by the attribute.
Range of the attribute component ‘component’.
If ‘component’==-1, it returns the range of the magnitude (euclidean norm). It returns double, even if GetType()==VTK_INT. NOT THREAD SAFE
Range of the attribute component ‘component’.
If ‘component’==-1, it returns the range of the magnitude (euclidean norm). THREAD SAFE
Return the maximum euclidean norm for the tuples.
Attribute at all points of cell ‘c’.
Put attribute at all points of cell ‘c’ in ‘tuple’.
Attribute at all points of cell ‘c’.
Put attribute at all points of cell ‘c’ in ‘tuple’.
Value of the attribute at position ‘p’.
Put the value of the attribute at position ‘p’ into ‘tuple’.
Put component ‘i’ of the attribute at all points of cell ‘c’ in ‘values’.
Value of the component ‘i’ of the attribute at position ‘p’.
Recursive duplication of ‘other’ in ‘this’.
Update ‘this’ using fields of ‘other’.
|
https://vtk.org/doc/nightly/html/classvtkGenericAttribute.html
|
CC-MAIN-2019-47
|
refinedweb
| 339
| 61.93
|
- Start Date: 2018-10-07
- Relevant Team(s): Ember.js
- RFC PR:
- Tracking:
Remove jQuery by default
Summary
This RFC proposes deprecating those public APIs that are coupled to jQuery, and to finally remove them (with an optional backport), so Ember apps will be built by default without bundling jQuery.
While RFC294, which is already implemented, provides a way to opt out of jQuery, the intention of this RFC is to push this a step further and essentially move from the current "included by default, allow opt out" strategy to "excluded by default, allow opt in".
In that way it is not meant as a replacement of the previous RFC, but rather as a continuation and the logical next step.
Motivation
Lean by default
This follows the philosophy of making Ember leaner (or higher octane if you want), by deprecating unused or non-essential APIs. New apps will be smaller and faster by default, while allowing to opt-in into using jQuery when needed.
Why the current opt-out strategy is not sufficient
The biggest problem in the current opt-out strategy is that many addons still require jQuery. Many of these usages seem to be rather "accidental", in that the full power of jQuery is not really needed for the given task, and could be rather easily refactored to use only native DOM APIs. But as it is available anyway by default, and it is very convenient, authors probably tend to use it without being fully aware of the consequences, that it prohibits jQuery-less builds for all its consumers.
In that way the general availability of jQuery by default and Ember APIs around it like
this.$() tend to manifest the
status quo, the coupling of Ember to jQuery. In fact I could observe an actual increase of jQuery usage numbers
(see below), rather than a decrease, which was an intention of the previous RFC. So it is not only a concern of the core
Ember library to enable jQuery-less builds, but the whole addon ecosystem has to go through that transition.
In that regard early deprecations will help prevent this accidental use of jQuery on the one side, and on the other side for addons that depend on jQuery already they will provide an incentive and a long enough transition period to refactor their jQuery usage to use standard DOM APIs.
jQuery might still be needed
This RFC does not propose to discourage the use of jQuery. There are legitimate cases where you still want to have it.
And this is also true for addons, especially those that basically wrap other jQuery-based libraries like jQuery plugins
in an Ember friendly way. For those cases, there should be an opt-in path to continue bundling jQuery and to preserve
the existing APIs around it. This is what the
@ember/jquery package is meant for.
Transition path
Add deprecations
All current public APIs that are coupled to jQuery should be deprecated via the usual deprecation process. This specifically involves:
- adding a (universal, non-silenceable) deprecation warning to
Ember.$()
- adding a deprecation warning to
this.$()in an
Ember.Component
- adding a deprecation warning to
this.$()in component integration tests, based on
setupRenderingTest()
this.$() in old style tests
this.$() in tests based on the old
moduleForComponent() based testing APIs will not be specifically deprecated,
as these legacy testing APIs will eventually be deprecated altogether, as already envisaged in RFC232.
Extend
@ember/jquery package
For apps and addons that have to or choose to still require jQuery, they can add this package to its dependencies. This will provide a way to retain the deprecated and later removed APIs. So by adding this to your dependencies this would effectively be the way to opt-in to require jQuery.
RFC294 already introduced this package, being responsible to include jQuery into the JavaScript bundle. As part of this
RFC the scope of this addon will be extended to also reintroduce the deprecated APIs, but without triggering any
deprecation warnings for
this.$() in a component.
As the default
EventDispatcher, which currently dispatches jQuery events when jQuery is enabled, will eventually
support native events only (see the Timeline below), the addon also needs to replace it with one that again dispatches
jQuery events for compatibility with existing jQuery-based code. This can happen in a similar way as
ember-native-dom-event-dispatcher did it, just the other
way around.
This effectively makes the integration of jQuery a feature of this addon, rather than Ember itself, which is freed from the burden to care about this.
So effectively, for the Ember 3.x release cycle, adding this package will not change the behavior in any significant way, other than removing the mentioned deprecation warnings, as Ember will still have these APIs available. However starting with Ember 4.0, which will have these APIs removed and not include jQuery integration features anymore, this package will make sure jQuery remains included and it will add the now removed APIs back again, so any jQuery depending code will continue to work just as before. Also see the timeline below.
As
ember-cli-babel will currently transform
import $ from 'jquery'; to use
Ember.$ again, it must be made aware of
the
@ember/jquery package so it tells
babel-plugin-ember-modules-api-polyfill not to convert those imports to the
global
Ember.$. Instead the package itself should provide the necessary shim to make
import $ from 'jquery'; work.
Addons that continue to depend on jQuery would have to list this package as a dependency in their
package.json,
to make their consuming app automatically include jQuery and the related APIs in its bundle as mentioned above.
Thereby they make their dependency on jQuery explicit, which in turn helps users to make an educated choice if they
deem this to be acceptable.
Extend ember-fetch
The
ember-fetch addon integrates the newer
Fetch API
nicely into an Ember app, with an (optional) polyfill for older browsers. This can be used as a replacement for the
jQuery-based
ember-ajax.
One piece that is missing so far when switching is a convenient way to customize all outgoing requests, e.g. to add
HTTP headers for authentication tokens. When using jQuery's AJAX implementation, this could be easily done using its
prefilter function. To facilitate something similar when using
ember-fetch, the addon should be extended with an appropriate API, e.g. by adding a simple service through which
fetch requests are issued, which provides similar features for customization. The exact API of such a service is however
out of scope for this RFC.
Make ember-data use ember-fetch
It must be ensured that all parts of the core Ember experience work flawlessly without jQuery. Currently
ember-data
is still relying on jQuery for its XHR requests. By the time this RFC is implemented (i.e. the deprecation messages are
added), it must work out of the box without jQuery.
Fortunately migration efforts are well advanced to support the
fetch API
through
ember-fetch, so we can expect that to land soon enough that it does not block the transition.
Update app blueprint
The blueprint to create a new app with
ember new should be updated to not use jQuery by default. This involves to
- disable jQuery integration by default (in
config/optional-features.json)
- remove the
@ember/jquerypackage
- replace
ember-ajaxwith
ember-fetch
- add the
no-jqueryrule to the default ESLint config
Timeline
During Ember 3.x:
- migrate the jQuery integration features to the
@ember/jquerypackage
- update the blueprints as stated above
- add deprecation warnings as stated above
Upon Ember 4.0
- remove deprecated functions
- remove the jQuery specific code paths in the
EventDispatcher
How we teach this
As part of the efforts to make jQuery optional, the guides have already been updated to have all examples teach native DOM APIs instead of jQuery, and the new testing APIs. The jQuery migration guide already mentions the APIs that are not available anymore without jQuery and how to opt-out now.
Activating the
no-jquery ESLint rule will warn developers about any usages of the jQuery-based APIs being deprecated
here.
The newly added deprecation messages should link to a deprecation guide, which will provide details on how to silence
these deprecations, either by using native DOM APIs only or by installing
@ember/jquery to explicitly opt-in into
jQuery.
For apps the tone of it should be neutral regarding jQuery itself, in the sense that using jQuery is neither bad nor good by itself. It depends on the context of the app if using jQuery makes sense or not. It is just that Ember does no need it anymore, so it is not part of the default Ember experience anymore.
For addons the story is a bit different, in that they are not aware of their app's context, so they should abstain from using jQuery if possible. See the Motivation chapter above.
Drawbacks
Churn
A vast amount of addons still depend on jQuery, so adding the deprecations will add some considerable churn for the addon ecosystem. As of writing this, there are:
- 407 addons using
Ember.$
- 546 addons using
this.$in components
- 994 addons using
this.$in tests
A good amount of that churn can be mitigated by
- existing codemods that migrate tests
- having an easy way, given by the
@ember/jquerypackage, to opt-in to continue bundling jQuery, and to restore the deprecated APIs, so no further refactorings are required
Alternatives
Stick to the current opt-out process.
|
https://emberjs.github.io/rfcs/0386-remove-jquery.html
|
CC-MAIN-2019-43
|
refinedweb
| 1,588
| 60.14
|
Design of Main Memory Database System/Database Management
Table of Contents — Previous: Storage Engine Overview — Next: Allocator
Chapter 5 Database Management
Database is a collection of objects that hold and manipulate data. Every database management system will have a limit on the total number of databases supported. Most of the databases support up to 10K databases per instance. Because of the virtual address space limitation, MMDB may not be able to support 100 databases per instance. Lets assume that database size is set to 100MB, then instance shall support 4 GB/ 100 MB= 40 databases maximum.
Database is a collection of many relational objects such as tables, views, and constraints. A user owns a database; the owners shall give special access to other users.
Contents
- 1 Functions of Database Management
- 2 Validation Techniques for stray pointer writes
- 3 Database VS Schema
- 4 Schema VS User
- 5 Default Database, Schema and User
- 6 Database Security
- 7 Database Administrator
- 8 Access protection , user accounts and database
- 9 Database Audits
- 10 Role based Access control
- 11 Types of Databases
- 12 Memory Pages
Functions of Database Management[edit]
- Create and delete databases
- Grant/Revoke privileges to users to access
- Grow/Shrink database based on its size
- Persistency of data
- Recovery of database in case of system crash
- Archive/Restore
Validation Techniques for stray pointer writes[edit]
This is one of the major concerns in MMDBs during the application development cycle. MMDB expose the actual pointer to data, which may lead the application to do stray pointer write. This will corrupt the data. MMDB should provide a mechanism to detect this and recover the database in the event of corruption.
Database VS Schema[edit]
In the ANSI SQL-92 standard, a schema is defined as a collection of database objects that are owned by single user and form a single namespace. A namespace is a set of objects that cannot have duplicate names. For example, two tables can have same name if and only if they both belong to two different schemas.
Schema VS User[edit]
There is an implicit relationship between schemas and users. This relationship is so close that, many of the database users are unaware about this. If you create a user, DBMS creates a user and a schema and grants all privileges to the user on the created schema. Some DBMS expect the user to do the above in three different steps.
Default Database, Schema and User[edit]
Every DBMS will have at least one default database, schema and user with preset password. This is done to ensure that DBMS is ready to soon after the installation.
Database Security[edit]
In a multi-user database management system, DBMS should provide techniques to enable certain users to access selected portions of a database without gaining access to the rest of the database. This is very important, when a large integrated database is to be used by many different users within the same organization. For example sensitive information such as salary should be kept confidential from most of the other database system users. DBMS accomplishes this by having authorization subsystem that is responsible for ensuring security of portions of database against unauthorized access.
Another security issue with databases that work across network shall be handled though data encryption. Encryption can also be used to provide additional protection for sensitive portions of database as well. The data is encoded using some coding algorithm. An unauthorized user who accesses encoded data will have difficulty in decoding the data. Authorized users will be given the decryption algorithms using which they shall access the data.
Database Administrator[edit]
Database Administrator is the central authority for managing a database system. The DBA’s responsibility include creating, deleting users, changing user passwords, granting privileges to user on database objects and revoking the privileges in accordance with the policy of the organization. DBA is responsible for the overall security of the database system.
Access protection , user accounts and database[edit]
1. Whenever a person or group of person s need to access a database system, the individual or group must first apply for a user account. The DBA will then create a new account number and password for the user if there is a legitimate need to access the database. 2.The user must log in to the DBMS by entering account number and password whenever database access is needed.
3.The DBMS checks that the account number and password are valid; if they are, the user is permitted to use the DBMS and to access the database. Application programs can also be considered as users and can be required to supply passwords.
4. It is straightforward to keep track of database users and their accounts and passwords by creating an encrypted table or file with the two fields account number and password. This table can easily be maintained by the DBMS. Whenever a new account is created, a new record is inserted into the table. When an account is canceled, the corresponding record must be deleted from the table. 5. The database system must also keep track of all operations on the database that are applied by a certain user throughout each login session, which consists of the sequence of the database interactions that a user performs from the time of logging in to the time of logging off. When a user logs in, the DBMS can record the user's account number and associate it with the terminal are attributed to the user's account until the user logs off. It is particularly important to keep track of update operations that are applied to the database so that, if the database is tampered with, the DBA can find out which user did the tampering. 6.To keep a record of all updates applied to the database and of the particular user who applied each update, we can modify system log, which includes an entry for each operation applied to the database that may be required for recovery from a transaction failure or system crash. We can expand the log entries so that they also include the account number of the user and the on line terminal ID that applied each operation recorded in the log..
Database Audits[edit].
Role based Access control[edit]
Types of Databases[edit]
Control Database - one
Catalog Database - one
User database - many
Memory Pages[edit]
Usually 8 KB. should be same as OS page size.
Table of Contents — Previous: Storage Engine Overview — Next: Allocator
|
http://en.wikibooks.org/wiki/Design_of_Main_Memory_Database_System/Database_Management
|
CC-MAIN-2014-10
|
refinedweb
| 1,080
| 50.06
|
I have two objects, Customer and Store. I would like a user (from a user table) to be able to specify a customer or store as "preferred". I would then be able to see a list of users who prefer different stores or customers. Is this possible with a hibernate mapping?
What would the table structure look if a status of preferred could be set on either customer of store per user?
So, a User has many preferred Stores, and a Store is the preferred store of many users. This is thus a ManyToMany association between User and Store.
Just map it as explained in the documentation:
public class User { @ManyToMany private Set<Store> preferredStores = new HashSet<Store>(0); } public class Store { // necessary only if you want the association to be bidirectional: @ManyToMany(mappedBy = "preferredStores") private Set<User> preferringUsers = new HashSet<User>(0); }
|
http://m.dlxedu.com/m/askdetail/3/4f421751863ef515c02ef47ebed5136a.html
|
CC-MAIN-2019-30
|
refinedweb
| 143
| 62.68
|
Library tutorials & articles
How to NNTP in C#
Introduction..
public class NntpException : System.ApplicationException
{
public NntpException(string str)
:base(str)
{
}
};
I'm still unsure how best to implement exception classes in .NET and as such I've remained faithful to my C++ roots. I'm investigating otherwise and might consider writing a brief article on just this subject. We'll see. Next step is the class declaration. I'm deriving the
Nntp class from the
TcpClient class in the
System.Net.Sockets namespace of the .NET framework.
public class Nntp : System.Net.Sockets.TcpClient
We'll inherit a lot of basic functionality from the
TcpClient class.
Great article - thanks.
However I'd like to post HTML to an NNTP server. I'm assuming that I need to specify this in the Header info somehow but can't find any documentation on NNTP message headers.
Could you shed some light here.
Thanks again
The only problem I found with this article, was the missing "Supporting Functions" you included in your other programs. Other than that, this is an awesome article! Keep up the good work!
This saved me days of work ! Thanks, really excellent.
This thread is for discussions of How to NNTP in C#.
|
http://www.developerfusion.com/article/4472/how-to-nntp-in-c/
|
crawl-002
|
refinedweb
| 204
| 61.93
|
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How can I add VAT (TIN) field from partner in customer Invoice tree view? Odoo v7
I need to make the VAT (TIN) field from res.partner available in account.invoice, so I can add it to the Invoice Tree View. How can I achieve this?
Hi,
You can inherit account.invoice object and add a functional field.
Try like this:
in .py file:
from openerp.osv import fields, osv
class account_invoice(osv.osv):
_inherit = "account.invoice"
def _get_vat_num(self, cr, uid, ids,field_name, args, context=None):
partner_pool = self.pool.get('res.partner')
invoice_pool = self.pool.get('account.invoice')
res = {}
for inv_id in self.browse(cr, uid, ids, context=context):
invoice = invoice_pool.browse(cr,uid, inv_id.id, context=None)
partner = partner_pool.browse(cr, uid, invoice.partner_id.id, context=None)
res[inv_id.id] = partner.vat
return res
_columns = {
'inv_vat': fields.function(_get_vat_num, string="VAT", type='char', method=True)
}
in .xml file:
<openerp>
<data>
<record id="invoice_form_inherit" model="ir.ui.view">
<field name="name">invoice.form.inherit</field>
<field name="model">account.invoice</field>
<field name="inherit_id" ref="account.invoice_form"/>
<field name="arch" type="xml">
<field name="partner_id" position="after">
<field name="inv_vat"/>
</field>
</field>
</record>
</data>
< have to customize one small module to make it visible to invoice, for more info contact@tidyway.in
I know how to create a module, I just need to know what to inherit exactly...in order to pass the field data from one model to another
|
https://www.odoo.com/forum/help-1/question/how-can-i-add-vat-tin-field-from-partner-in-customer-invoice-tree-view-odoo-v7-83897
|
CC-MAIN-2017-09
|
refinedweb
| 270
| 55.91
|
...one of the most highly
regarded and expertly designed C++ library projects in the
world. — Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
#include <boost/spirit/home/phoenix/container.hpp>
The container module predefines a set of lazy functions that work on STL containers. These functions provide a mechanism for the lazy evaluation of the public member functions of the STL containers. The lazy functions are thin wrappers that simply forward to their respective counterparts in the STL library.
Lazy functions are provided for all of the member functions of the following containers:
Indeed, should your class have member functions with the same names and signatures as those listed below, then it will automatically be supported. To summarize, lazy functions are provided for member functions:
The lazy functions' names are the same as the corresponding member function. The difference is that the lazy functions are free functions and therefore does not use the member "dot" syntax.
Notice that member functions with names that clash with stl algorithms are absent. This will be provided in Phoenix's algorithm module.
No support is provided here for lazy versions of
operator+=,
operator[] etc. Such operators are not specific to STL
containers and lazy versions can therefore be found in operators.
The following table describes the container functions and their semantics.
|
http://www.boost.org/doc/libs/1_47_0/libs/spirit/phoenix/doc/html/phoenix/container.html
|
CC-MAIN-2015-32
|
refinedweb
| 217
| 55.03
|
.
Advent of Code puzzles are designed to be approachable by anyone with an interest in problem-solving. You don’t need a heavy computer science background to participate. Instead, Advent of Code is a great arena for learning new skills and testing out new features of Python..
To get a feeling for how an Advent of Code puzzle works, consider the Day 1 puzzle of 2020:
Before you leave, the Elves in accounting just need you to fix your expense report (your puzzle input); apparently, something isn’t quite adding up.
Specifically, they need you to find the two entries that sum to
2020and then multiply those two numbers together.
Each year, there’s a wonderfully silly backstory that binds the puzzles together. The 2020 story describes your attempts at leaving for a well-deserved vacation, now that you’ve saved Christmas several years in a row. The story usually has no effect on the puzzles, but it’s still fun to follow along.
In between the plot elements of the story, you’ll find the puzzles themselves. In this example, you’re looking for two entries in your puzzle input that sum to 2,020. After the explanation that describes the problem, you’ll usually find an example showing the calculations you’re expected to do:.
The example shows you the answer for this particular list of numbers. If you were about to jump in and start solving this puzzle, you would now start thinking about how you can find the two entries in any valid list of numbers. Before getting deeper into this puzzle, however, you’ll explore how to use the Advent of Code site.
How to Participate in Advent of Code
You’ve seen an example of an Advent of Code puzzle. Next, you’ll learn how you can submit your answer for it. You never submit any code to solve the puzzles. You just submit the answer, which is usually a number or a text string.
In general, you’ll follow a series of steps to solve a puzzle on the site:
Log in on the Advent of Code website. You do this by using your credentials from another service like GitHub, Google, Twitter, or Reddit.
Read the puzzle text and pay special attention to the given example. You should make sure you understand the solution for the example data.
Download your personalized input for the puzzle. You’ll need this input in order to find your unique answer to the problem.
Code up your solution. This is the fun part, which you’ll get a lot of practice for in the rest of this tutorial.
Enter your answer to the puzzle on the puzzle page. If your answer is correct, then you earn a golden star and part two of the puzzle is opened up.
Repeat steps 2 to 4 for part two of the puzzle. This second part is similar to the first, but it usually adds some twist requiring you to adapt your code.
Enter your second answer on the puzzle page in order to earn your second star and finish the puzzle.
Remember, you don’t submit any code—only your puzzle answers. This means that Advent of Code puzzles can be solved in any programming language. Many people use Advent of Code to practice and learn a new programming language. Eric Wastl, the creator of Advent of Code, gave a talk in 2019 where he talked about the diverse background and motivation of the people participating, among other things.
Note: There is a leaderboard for Advent of Code. In general, you should ignore this leaderboard! It only shows who submitted the first 100 solutions after a puzzle opened up. To have a shot at joining the leaderboard, you need a lot of preparation, dedication, and experience with competitive programming.
Instead, you should look at the private leaderboards. These become available after you’ve logged in, and they give you a chance to invite your friends and colleagues to a more relaxed community. You can choose to score your private leaderboard either based on when puzzles were solved or simply based on the number of puzzles people have solved.
You can also link your name in the private leaderboards to your GitHub account, which allows you to share your solutions with your friends. You set this up by clicking Settings in the menu on the Advent of Code site after you’ve logged in.
Advent of Code is completely free to use, but there are still a few different ways you can support the project:
- You can share information about Advent of Code on your social media to get the word out.
- You can help others by taking part in the r/adventofcode subreddit or other forums.
- You can invite your friends to take part in Advent of Code, sharing your results on a private leaderboard.
- You can donate to Advent of Code. If you do, then you’ll get an AoC++ badge next to your name on the site.
In the next sections, you’ll see some suggestions on how you can prepare for solving Advent of Code with Python. There’s also an awesome list you can check out that links to many different resources related to Advent of Code, including many other people’s solutions.
Solving Advent of Code With Python
The Advent of Code has become an annual highlight for many coders around the world. In 2020, more than 170,000 people submitted their solutions. Since Advent of Code was started in 2015, more than 380,000 programmers have participated. Many of them use Python to solve the puzzles.
Well, now it’s your turn! Head over to the Advent of Code website and have a look at the latest puzzles. Then, come back to this tutorial to get some tips and help to start solving Advent of Code puzzles with Python.
The Anatomy of a Puzzle
In this section, you’ll explore the typical anatomy of an Advent of Code puzzle. Additionally, you’ll learn about some tools you can use to interact with it.
Each Advent of Code puzzle is split into two parts. When you start working on a puzzle, you only see the first part. The second part unlocks once you’ve submitted the correct answer to the first part. This is often a twist on the problem you solved in the first part. Sometimes, you’ll find it necessary to refactor your solution from part one, while other times you can solve the second part quickly based on the work you’ve already done.
Both parts always use the same puzzle input. You can download your puzzle input from the puzzle page for that day. You’ll find a link after the puzzle description.
Note: As mentioned earlier, your puzzle input is personalized. This means that if you discuss solutions with other people, their final answers will likely be different from yours.
Everything you need to do in order to submit your puzzle solutions—except actually solving the puzzle—you can do from the Advent of Code website. You should use it to submit your first solutions so that you can get familiar with the flow.
Later, there are several tools you can use to organize your Advent of Code setup and work more efficiently. For example, you can use the
advent-of-code-data package to download data. It’s a Python package that you can install with pip:
$ python -m pip install advent-of-code-data
You can use
advent-of-code-data to download a particular puzzle input set on the command line with its
aocd tool. Another fun possibility is automatically downloading and caching your personalized puzzle input within your Python code:
>>> from aocd.models import Puzzle >>> puzzle = Puzzle(year=2020, day=1) >>> # Personal input data. Your data will be different. >>> puzzle.input_data[:20] '1753\n1858\n1860\n1978\n'
You need to set your session ID in either an environment variable or a file before you can download your personalized data with
advent-of-code-data. You’ll find an explanation for this in the documentation. If you’re interested, then you can also use
advent-of-code-data or
aocd to submit your solutions and review your earlier answers.
As part of the puzzle text, you’ll also find one or several examples typically calculated based on smaller data than your personalized input data. You should read these examples carefully and make sure you understand what you’re asked to do before you start coding.
You can use the examples to set up tests for your code. One way is to manually run your solution on the example data and confirm that you’re getting the expected answer. Alternatively, you can use a tool like
pytest to automate the process.
Note: Test-driven development (TDD) is a process where you write tests before implementing your code. Because Advent of Code provides you with expected answers to small examples, it gives you a great opportunity to try out test-driven development on your own.
You’ll learn more about TDD later when you try to solve some puzzles by yourself.
You can solve all Advent of Code puzzles using just plain Python and the standard library. However, there are a few packages that can aid you as you’re putting together your solutions:
advent-of-code-datacan download your input data and submit your solutions.
pytestcan check your solution on the example data automatically.
parsecan parse strings with a simpler syntax than regular expressions.
numpycan effectively compute with arrays of numbers.
coloramacan animate your solutions in the terminal.
If you create a virtual environment and install those packages, then you’ll have a very solid toolbox for your Advent of Code adventures. Later, you’ll see examples of how you can use
parse,
numpy, and
colorama to solve puzzles.
The Structure of a Solution
In the last section, you got familiar with how to read and understand Advent of Code puzzles. In this section, you’ll learn how you can solve them. You don’t need to do a lot of setup before you solve the Advent of Code puzzles.
Have you thought about how you’d solve the puzzle that you saw earlier? Recall that you’re looking for the product of the two numbers in a list that sum to 2,020. Before moving on, think about—and maybe code up—how you’d find which two entries of the following list sum to 2,020:
numbers = [1721, 979, 366, 299, 675, 1456]
The following script shows one way to solve this first part of the Day 1, 2020 puzzle:
1for num1 in numbers: 2 for num2 in numbers: 3 if num1 < num2 and num1 + num2 == 2020: 4 print(num1 * num2)
The nested
for loop finds all combinations of two numbers from the list. The test on line 3 is actually slightly more complicated than it needs to be: you only need to test that the numbers sum to 2,020. However, by adding the condition that
num1 should be smaller than
num2, you avoid solutions being found twice.
In this example, one solution looks like
num1 = 1721 and
num2 = 299, but since you can add numbers in any order, that means that also
num1 = 299 and
num2 = 1721 form a solution. With the extra check, only the latter combination is reported.
Once you have this solution in place, you can copy your personalized input data into the
numbers list and calculate your answer to the puzzle.
Note: There are more efficient ways of calculating this answer than trying all possibilities. However, it’s usually a good idea to start with a basic approach. Joe Armstrong is quoted as saying:
Make it work, then make it beautiful, then if you really, really have to, make it fast. 90 percent of the time, if you make it beautiful, it will already be fast. So really, just make it beautiful! (Source)
— Joe Armstrong
Now that you’ve seen a working solution for this puzzle, can you make it beautiful?
As you’re working through more puzzles, you might start feeling that copying your data into your code and rewriting it into valid Python gets tiresome. Similarly, adding a few functions to your code gives you more flexibility later. You could use them to add tests to your code, for example.
Python has many powerful features for parsing strings. In the long run, you’ll be better off leaving the input data just as you downloaded them and let Python parse them into a usable data structure. In fact, dividing your code into two functions is often beneficial. One function will parse the string input and the other will solve the puzzle. Based on these principles, you can rewrite your code:
1# aoc202001.py 2 3import pathlib 4import sys 5 6def parse(puzzle_input): 7 """Parse input""" 8 return [int(line) for line in puzzle_input.split()] 9 10def part1(numbers): 11 """Solve part 1""" 12 for num1 in numbers: 13 for num2 in numbers: 14 if num1 < num2 and num1 + num2 == 2020: 15 return num1 * num2 16 17if __name__ == "__main__": 18 for path in sys.argv[1:]: 19 print(f"\n{path}:") 20 puzzle_input = pathlib.Path(path).read_text().strip() 21 22 numbers = parse(puzzle_input) 23 print(part1(numbers))
On lines 12 to 15, you’ll recognize your solution from earlier. First of all, you’ve wrapped it in a function. This makes it easier to add automatic tests to your code later. You’ve also added a
parse() function that can convert lines of strings into a list of numbers.
On line 20, you use
pathlib to read the contents of a file as text and strip off any blank lines at the end. Looping through
sys.argv gives you all the filenames entered at the command line.
These changes give you more flexibility as you’re working on your solution. Say that you’ve stored the example data in a file called
example.txt and your personalized input data in a file named
input.txt. You can then run your solution on any one of them, or even both, by supplying their names on the command line:
$ python aoc202001.py example.txt input.txt example.txt: 514579 input.txt: 744475
514579 is indeed the answer to the problem when using the example input data. Remember, the solution for your personalized input data will be different from the one shown above.
Now it’s time to give the Advent of Code website a spin! Go to the 2020 Advent of Code calendar and find the puzzle for Day 1. If you haven’t already, download your input data and calculate your solution to the puzzle. Then, enter your solution on the website and click Submit.
Congratulations! You’ve just earned your first star!
A Starting Template
As you’ve seen above, Advent of Code puzzles follow a set structure. Therefore, it makes sense to create a template for yourself that you can use as a starting point when you start to code up a solution. Exactly how much structure you want in such a template is a matter of personal taste. To get started, you’ll explore one example of a template that’s based on the principles you saw in the previous section:
1# aoc_template))
The template has separate functions for parsing the input as well as for solving both parts of a puzzle. You don’t need to touch lines 15 to 27 at all. They take care of reading text from an input file, calling
parse(),
part1(), and
part2(), and then report the solutions to the console.
You can create a similar template for testing your solutions.
Note: As mentioned earlier, the example data are useful for creating tests, as they represent known data with corresponding solutions.
The following template uses
pytest as a test runner. It’s prepared for three different tests, one each for the functions
parse(),
part1(), and
part2():
1# test_aoc_template.py 2 3import pathlib 4import pytest 5import aoc_template@pytest.mark.skip(reason="Not implemented") 20def test_parse_example1(example1): 21 """Test that input is parsed properly""" 22 assert example1 == ... 23 24@pytest.mark.skip(reason="Not implemented") 25def test_part1_example1(example1): 26 """Test part 1 on example input""" 27 assert aoc.part1(example1) == ... 28 29@pytest.mark.skip(reason="Not implemented") 30def test_part2_example2(example2): 31 """Test part 2 on example input""" 32 assert aoc.part2(example2) == ...
You’ll see an example of how you can use this template later. Until then, there are a few things you should note:
- As indicated on line 1, you should name your
pytestfiles with a
test_prefix.
- Similarly, each test is implemented in a function named with a
test_prefix. You can see examples of these on lines 20, 25, and 30.
- You should change the import on line 5 to import your solution code.
- The template assumes that the example data are stored in files named
example1.txtand
example2.txt.
- You should remove the skip marks on lines 19, 24, and 29 when you’re ready to start testing.
- You’ll need to fill in the ellipses (
...) on lines 22, 27, and 32 according to the example data and the corresponding solutions.
For example, if you were to adapt this template to the rewritten solution of the first part of the Day 1, 2020 puzzle from the previous section, then you’d need to create a file
example1.txt with the following contents:
1721 979 366 299 675 1456
Next, you’d remove the skip marks for the first two tests and implement them as follows:
def test_parse_example1(example1): """Test that input is parsed properly""" assert example1 == [1721, 979, 366, 299, 675, 1456] def test_part1_example1(example1): """Test part 1 on example input""" assert aoc.part1(example1) == 514579
Finally, you’d need to make sure that you’re importing your solution. If you used the filename
aoc202001.py, then you should change line 5 to import
aoc202001:
You would then run
pytest to check your solution. If you implemented your solution correctly, then you’d see something like this:
$ pytest ====================== test session starts ===================== collected 3 items test_aoc202001.py ..s [100%] ================= 2 passed, 1 skipped in 0.02s =================
Note the two dots (
..) in front of the
s. They represent two tests that passed. If the tests had failed, you’d see
F instead of each dot, along with a detailed explanation of what went wrong.
Tools like Cookiecutter and Copier make it easier to work with templates like these. If you install Copier, then you can use a template similar to the one you’ve seen here by running the following command:
$ copier gh:gahjelle/template-aoc-python advent_of_code
This will set up the template for one particular puzzle in a subdirectory of the
advent_of_code directory on your computer.
Solution Strategies
Advent of Code puzzles are very diverse. As you advance through the calendar, you’ll solve many different problems and discover many different strategies for approaching them.
Some of these strategies are quite general and can be applied to any puzzle. If you find that you’re stuck on a puzzle, here are some things you can try to get unstuck:
- Re-read the description. Advent of Code puzzles are typically very well specified, but some of them can be quite information heavy. Make sure you’re not missing a vital part of the puzzle.
- Use the example data actively. Make sure you understand how those results are achieved, and check that your code is able to reproduce those examples.
- Some puzzles may get a bit involved. Break the problem into smaller steps, and implement and test each step individually.
- If your code works for the example data but not for your personalized input data, then you can build additional test cases based on numbers you’re able to calculate by hand to see whether your code covers all corner cases.
- If you’re still stuck, then reach out to your friends and other puzzle solvers on some of the forums dedicated to Advent of Code and ask for hints about how they’ve solved the puzzle.
As you do more and more puzzles, you’ll start to recognize some general kinds of puzzles that come up again and again.
Some puzzles deal with text and passwords. Python has several powerful tools for manipulating text strings, including many string methods. To read and parse strings, it’s helpful to know the basics of regular expressions. However, you can often get very far with the third-party
parse library as well.
For example, say that you have the string
"shiny gold bags contain 2 dark red bags." and want to parse the relevant information from it. You can use
parse and its pattern syntax:
>>> import parse >>>>>>> match = parse.search(pattern, string) >>> match.named {'outer_color': 'shiny gold', 'num': 2, 'inner_color': 'dark red'}
In the background,
parse builds a regular expression, but you use a simpler syntax similar to the one that f-strings use.
In some of these text problems, you’re explicitly asked to work with code and parsers, often building a small custom assembly language. After parsing the code, you often need to run the given program. In practice, this means that you build a small state machine that can track its current state, including the contents of its memory.
You can use classes to keep state together with behavior. In Python, data classes are great for quickly setting up a state machine. The following example shows the implementation of a small state machine that can handle two different instructions:
1from dataclasses import dataclass 2 3@dataclass 4class StateMachine: 5 memory: dict[str, int] 6 program: list[str] 7 8 def run(self): 9 """Run the program""" 10 current_line = 0 11 while current_line < len(self.program): 12 instruction = self.program[current_line] 13 14 # Set a register to a value 15 if instruction.startswith("set "): 16 register, value = instruction[4], int(instruction[6:]) 17 self.memory[register] = value 18 19 # Increase the value in a register by 1 20 elif instruction.startswith("inc "): 21 register = instruction[4] 22 self.memory[register] += 1 23 24 # Move the line pointer 25 current_line += 1
The two instructions
set and
inc are parsed and handled within
.run(). Note that the type hints on lines 5 and 6 use a newer syntax that only works on Python 3.9 and later versions. If you’re using an older version of Python, then you can import
Dict and
List from
typing instead.
To run your state machine, you first initialize it with an initial memory and load the program into the machine. Next, you call
.run(). When the program is done, you can inspect
.memory to see the new state of your machine:
>>> state_machine = StateMachine( ... memory={"g": 0}, program=["set g 44", "inc g"] ... ) >>> state_machine.run() >>> state_machine.memory {'g': 45}
This program first set
g to the value of
44, then increased it, leaving it at its final value of
45.
Some fun puzzles involve grids and labyrinths. If your grid has a fixed size, then you can use NumPy to get an effective representation of it. Labyrinths are often useful to visualize. You can use Colorama to draw directly in your terminal:
import numpy as np from colorama import Cursor grid = np.array( [ [1, 1, 1, 1, 1], [1, 0, 0, 0, 1], [1, 1, 1, 0, 1], [1, 0, 0, 2, 1], [1, 1, 1, 1, 1], ] ) num_rows, num_cols = grid.shape for row in range(num_rows): for col in range(num_cols): symbol = " #o"[grid[row, col]] print(f"{Cursor.POS(col + 1, row + 2)}{symbol}")
This script shows an example of storing a grid using a NumPy array and then using
Cursor.POS from Colorama to position the cursor in the terminal to print out the grid. When you run this script, you’ll see an output like the following:
##### # # ### # # o# #####
Visualizing your code as it runs can be fun and also give you some good insights. It can also be an invaluable help when you’re debugging and don’t quite understand what’s happening.
So far in the tutorial, you’ve gotten some general tips on how you can work with Advent of Code puzzles. In the next sections, you’ll get more explicit and solve two puzzles from earlier years.
Practicing Advent of Code: Day 1, 2019
The first puzzle you’ll attempt to solve on your own is Day 1, 2019, called The Tyranny of the Rocket Equation. This is a typical Day 1 puzzle in that the solution isn’t very involved. It’s a great exercise to get used to how Advent of Code works and to check that your environment is properly set up.
Part 1: Puzzle Description
In the 2019 storyline, you’re rescuing Santa, who’s become stranded at the edge of the solar system. In the first puzzle, you’re getting your rocket ready for launch:.
The example data look like.
You need to calculate the total fuel requirements for your spacecraft:?
Now it’s time to try to solve the puzzle on your own! It’s probably the most fun to download your personalized input data and check your solution on Advent of Code so that you can earn your stars. However, feel free to solve the puzzle based on the example data provided above if you’re not ready to sign in to Advent of Code yet.
Part 1: Solution
Once you’re done with the puzzle and you’ve earned your star, you can expand the collapsed block to see a discussion of the puzzle solution:
This solution discussion is a bit more involved than what’s necessary for the puzzle. The goal is that you’ll explore some extra detail in this first solution so that you’ll be even better prepared for the next puzzles.
This section is split into two parts:
- A short discussion of integer division and how that can help.
- A straightforward solution to the puzzle.
Then, in the next section, you’ll see another solution that uses the templates for solutions and tests that you’ve seen earlier.
To return to the current puzzle, take a second look at the calculation you’re asked to perform:
[To] find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
You can carry out these steps one after another:
>>> mass = 14 >>> mass / 3 4.666666666666667 >>> int(mass / 3) 4 >>> int(mass / 3) - 2 2
For positive numbers, you can use
int() to round down. If your numbers may be negative, then you should use
math.floor() instead.
Python, and many other programming languages, have support for dividing and rounding down in one step. This is called integer division and is done with the integer division operator (
//). You can then rewrite your previous calculation:
>>> mass = 14 >>> mass // 3 4 >>> mass // 3 - 2 2
Using
mass // 3 divides by three and rounds down in one step. You can now calculate the fuel for each mass and add them together to solve the puzzle:
>>> masses = [12, 14, 1969, 100756] >>> total_fuel = 0 >>> for mass in masses: ... total_fuel += mass // 3 - 2 ... >>> total_fuel 34241
The four example modules need a total of
34241 fuel units. In the puzzle description, they’re listed as requiring
2,
2,
654, and
33583 fuel units, respectively. Adding these up, you get
34241, which confirms your calculations. You can replace the numbers in the
masses list with your personalized input data to get your own answer to the puzzle.
If you’re familiar with comprehensions and generator expressions, then you can use
sum() to shorten your code:
>>> masses = [12, 14, 1969, 100756] >>> sum(mass // 3 - 2 for mass in masses) 34241
With
sum(), you don’t need to manually add up each fuel requirement. Instead, you can solve the current puzzle in one line of code.
You’ve now solved the first part of the puzzle. However, before moving on to the second part of the puzzle, the next section shows how you can use the templates you saw earlier when solving this problem.
Part 1: Solution Using Templates
Expand the collapsed block below to see another solution to the first part of the Advent of Code puzzle for Day 1, 2019—this time using the templates you saw earlier to organize your code and simplify testing:
If you’re going to do several Advent of Code puzzles, then it’s a good idea to organize your solutions into folders. This allows you to keep all the files related to a puzzle together. One nice way of keeping things tidy is to have one folder for each year of Advent of Code and to have folders for each day within each year’s folder.
For this puzzle, you might set up something like this:
advent_of_code/ │ └── 2019/ └── 01_the_tyranny_of_the_rocket_equation/ ├── aoc201901.py ├── input.txt ├── example1.txt └── test_aoc201901.py
You store your personalized input data in
input.txt, while
example1.txt contains the example data from the puzzle description:
You can then use these data to set up your first tests. Start with the test template from earlier, and fill in tests for parsing input and for solving part one:
1# test_aoc201901.py 2 3import pathlib 4import pytest 5import aoc201901def test_parse_example1(example1): 20 """Test that input is parsed properly""" 21 assert example1 == [12, 14, 1969, 100756] 22 23def test_part1_example1(example1): 24 """Test part 1 on example input""" 25 assert aoc.part1(example1) == 2 + 2 + 654 + 33583 26 27@pytest.mark.skip(reason="Not implemented") 28def test_part2_example2(example2): 29 """Test part 2 on example input""" 30 assert aoc.part2(example2) == ...
You want the parser to read the text file and convert each line to a number in a list. You specify this on line 21 as the expected value in
test_parse_example1(). The expected value for
test_part1_example1() is the sum of the four fuel requirements mentioned in the text.
Finally, add
aoc201901.py based on the solution template:
1# aoc201901))
Before you start adding your solution to the template, take a minute to run
pytest to confirm that the tests are indeed failing. In between a lot of details, you should get something like this:
$ pytest test_aoc201901.py FFs [100%] ===================== short test summary info ===================== FAILED test_parse_example1 - assert None == [12, 14, 1969, 100756] FAILED test_part1_example1 - assert None == (((2 + 2) + 654) + 33583) ================== 2 failed, 1 skipped in 0.09s ===================
Note that you have two tests that are failing—just as expected. This way of working is known as test-driven development (TDD). You first write your tests and make sure they fail. Afterward, you implement the code necessary to make them pass. This may seem like overkill for this puzzle but can be a very useful habit for more challenging problems.
It’s time to add your solution to
aoc201901.py. First, parse the input data. They are delivered to
parse() as a text string of numbers separated by newlines (
\n) and should be converted into a list of integers:
def parse(puzzle_input): """Parse input""" return [int(line) for line in puzzle_input.split("\n")]
The list comprehension assembles each line into a list and converts them to integers. Run
pytest again and confirm that your first test,
test_parse_example1(), no longer fails.
Next, add your solution to the puzzle:
def part1(data): """Solve part 1""" return sum(mass // 3 - 2 for mass in data)
You’re solving part one by using
sum() as discussed in the previous section. Confirm that your solution is correct by running
pytest one more time:
$ pytest test_aoc201901.py ..s [100%] ================== 2 passed, 1 skipped in 0.01s ===================
With the tests passing, you can solve the puzzle for your personalized input data by running the program against
input.txt:
$ python aoc201901.py input.txt input.txt: 3550236 None
Your own answer will be different from what’s shown here,
3550236. The
None output at the bottom represents the solution to the second part, which you haven’t implemented yet. Now might be a good time to look at part two!
You can now move on to the second part of the puzzle. Are you ready for the twist?
Part 2: Puzzle Description
Every Advent of Code puzzle consists of two parts, where the second part is revealed only after you solve the first part. The second part is always related to the first and will use the same input data. However, you may often need to rethink your approach to the first half of the puzzle in order to account for the second half.
Expand the collapsed block below to have a look at the second part of the Advent of Code puzzle for Day 1, 2019:
Your quest to get the rocket off the ground continues:.
Of course, adding all that fuel to your spacecraft has made it heavier. You need to add more fuel to account for the added weight, but that fuel will also need to be accounted for. To see how this works in practice, have a look at the examples:
So, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative. For example:
- A module of mass
14requires
2fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is
0, which would call for a negative fuel), so the total fuel required is still just
2.
- At first, a module of mass
1969requires
654fuel. Then, this fuel requires
216more fuel (
654 / 3 - 2).
216then requires
70more fuel, which requires
21fuel, which requires
5fuel, which requires no further fuel. So, the total fuel required for a module of mass
1969is
654 + 216 + 70 + 21 + 5 = 966.
- The fuel required by a module of mass
100756and its fuel is:
33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.
The examples are still using the same numbers as for part one. The fuel needed for the module with mass
12 isn’t specified, but you can calculate that it will be
2 using the same calculation as for the module with mass
14. The question you need to answer remains the same:
What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel? (Calculate the fuel requirements for each module separately, then add them all up at the end.)
Have a go at solving this part as well. Can you earn your second star?
You’ll see a possible solution to part two in the next section. However, try to solve the puzzle for yourself first. If you need a hint to get started, then expand the box below:
Repeated calculations like the ones in this part of the puzzle often lend themselves well to recursion.
How did you do? Is your rocket ready for launch?
Part 2: Solution
This section shows how you can solve part two, continuing with the template you saw above:
Continuing with the test-driven development workflow, start with adding the new examples to your test file. The examples are using the same numbers as part one, so you can use the same
example1.txt file. You can therefore remove the
example2() fixture from your test code. Next, remove the skip mark and then rename and implement
test_part2_example1():
def test_part2_example1(example1): """Test part 2 on example input""" assert aoc.part2(example1) == 2 + 2 + 966 + 50346
As before, run
pytest to confirm that your test is failing.
Note:
pytest has a nice option,
-k, that you can use to only run a subset of your tests. With
-k you can filter on the test names. For example, to only run the tests related to part two, you can use
pytest -k part2. This is also a nice incentive to use consistent and descriptive test names.
Next, it’s time for the actual implementation. Repeated calculations of fuel like you’re asked for here can be handled well using recursion.
A recursive function is a function that calls itself. When implementing a recursive function, you should be conscious of including a stopping condition: When should the function stop calling itself? In this example, the stopping condition is mentioned quite explicitly in the puzzle description. You should stop when the fuel becomes zero or negative.
Add the following as a new function in your
aoc201901.py solution file:
1def all_fuel(mass): 2 """Calculate fuel while taking mass of the fuel into account""" 3 fuel = mass // 3 - 2 4 if fuel <= 0: 5 return 0 6 else: 7 return fuel + all_fuel(mass=fuel)
Line 4 implements the stopping condition, while line 7 does the recursive call. You can add a test to check that the calculation works as expected. Note that if you’d been doing pure test-driven development, then you’d have added the test first. Add this function to your test file:
def test_all_fuel(): """Test that fuel can be calculated recursively""" assert aoc.all_fuel(1969) == 966
In this test, you don’t use the input files. Instead, you check directly one of the examples given above. Before moving on to solve the whole puzzle, note that you can use the walrus operator to write the function more concisely:
def all_fuel(mass): """Calculate fuel while taking mass of the fuel into account""" return 0 if (fuel := mass // 3 - 2) < 0 else fuel + all_fuel(fuel)
While the code is shorter, it’s also denser. Whether you find that the end result is more readable or not is a matter of taste and experience.
To finish off the puzzle, you also need to implement
part2(). Your
all_fuel() function calculates the fuel needed for each module, so what’s left is adding the fuel for all modules together:
def part2(data): """Solve part 2""" return sum(all_fuel(mass) for mass in data)
The implementation of
part2() ends up being quite similar to
part1(). You only need to change the fuel calculation for each mass.
To finish up, run
pytest to confirm that everything works. Then run your program on your input to get your final puzzle answer:
$ python aoc201901.py input.txt input.txt: 3550236 5322455
Back at the Advent of Code website, enter your own answer, which will be different from the one above. Your second star is waiting!
Before leaving this puzzle completely, note that it’s possible to solve the second part without using recursion. You could do the same calculations using loops instead. Here’s one possible implementation:
def part2(data): """Solve part 2""" total_fuel = 0 for mass in data: while (mass := mass // 3 - 2) > 0: total_fuel += mass return total_fuel
For each mass, the
while loop calculates all the fuel needed and adds it to the running total fuel count.
One of the fun things about challenging yourself with programming puzzles is that they give you a great opportunity to try out different solutions to problems and compare them.
Congratulations! You’ve now solved an entire Advent of Code puzzle. Are you ready for a more challenging one?
Practicing Advent of Code: Day 5, 2020
The second puzzle you’ll attempt to solve is the one for Day 5, 2020, called Binary Boarding. This puzzle is a bit more challenging than the previous one, but the final solution won’t require a lot of code. Start by having a look at the puzzle description for part one.
Part 1: Puzzle Description
In 2020, you’re trying hard to get to your well-deserved vacation spot. On Day 5, you’re about to board your plane when trouble ensues:
You board your plane only to discover a new problem: you dropped your boarding pass! You aren’t sure which seat is yours, and all of the flight attendants are busy with the flood of people that suddenly made it through passport control.
You write a quick program to use your phone’s camera to scan all of the nearby boarding passes (your puzzle input); perhaps you can find your seat through process of elimination.
Instead of zones or groups, this airline uses binary space partitioning to seat people. A seat might be specified like
FBFBBFFRLR, where
Fmeans “front”,
Bmeans “back”,
Lmeans “left”, and
Rmeans “right”.
The first 7 characters will either be
For
B; these specify exactly one of the 128 rows on the plane (numbered
0through
127). Each letter tells you which half of a region the given seat is in.
Start with the whole list of rows; the first letter indicates whether the seat is in the front (
0through
63) or the back (
64through
127). The next letter indicates which half of that region the seat is in, and so on until you’re left with exactly one row.
For example, consider just the first seven characters of
FBFBBFFRLR:
- Start by considering the whole range, rows
0through
127.
-
Fmeans to take the lower half, keeping rows
0through
63.
-
Bmeans to take the upper half, keeping rows
32through
63.
-
Fmeans to take the lower half, keeping rows
32through
47.
-
Bmeans to take the upper half, keeping rows
40through
47.
-
Bkeeps rows
44through
47.
-
Fkeeps rows
44through
45.
- The final
Fkeeps the lower of the two, row
44.
The last three characters will be either
Lor
R; these specify exactly one of the 8 columns of seats on the plane (numbered
0through
7). The same process as above proceeds again, this time with only three steps.
Lmeans to keep the lower half, while
Rmeans to keep the upper half.
For example, consider just the last 3 characters of
FBFBBFFRLR:
- Start by considering the whole range, columns
0through
7.
-
Rmeans to take the upper half, keeping columns
4through
7.
-
Lmeans to take the lower half, keeping columns
4through
5.
- The final
Rkeeps the upper of the two, column
5.
So, decoding
FBFBBFFRLRreveals that it is the seat at row
44, column
5.
Every seat also has a unique seat ID: multiply the row by 8, then add the column. In this example, the seat has ID
44 * 8 + 5 =
357.
Here are some other boarding passes:
-
BFFFBBFRRR: row
70, column
7, seat ID
567.
-
FFFBBBFRRR: row
14, column
7, seat ID
119.
-
BBFFBBFRLL: row
102, column
4, seat ID
820.
As a sanity check, look through your list of boarding passes. What is the highest seat ID on a boarding pass?
There’s a lot of information in this puzzle description! However, most of it concerns how binary space partitioning works for this particular airline.
Now, try to solve the puzzle for yourself! Keep in mind that if you consider it from the right perspective, the conversion from a boarding pass specification to a seat ID isn’t as complicated as it might seem at first. If you find that you’re struggling with that part, then expand the box below to see a hint on how you can get started.
The boarding pass specifications are based on the binary system, just camouflaged with different characters. Can you translate the boarding passes into binary numbers?
When you’re done with your solution, have a look in the next section to see a discussion about the puzzle.
Part 1: Solution
Now that you’ve given it a shot yourself, you can go ahead and expand the following block to see one way the puzzle can be solved:
You can implement the calculation of the seat IDs based on the description in the text. The following function takes the same steps as the example:
def decode(string): """Decode a boarding pass string into a number""" start, end = 0, 2 ** len(string) for char in string: if char in {"F", "L"}: end -= (end - start) // 2 elif char in {"B", "R"}: start += (end - start) // 2 return start
You limit the range of possible rows or columns by
start and
end. While
start is included in the range,
end is not. This makes the math easier as it keeps the difference of
end - start divisible by two throughout the calculation. You lower the upper limit for each
F or
L, and you increase
start, the lower limit, for each
B or
R. You can check that the function gives the same results as the examples:
>>> decode("FBFBBFF") 44 >>> decode("RLR") 5 >>> decode("FBFBBFFRLR") 357
Using
decode(), you can calculate the row, the column, and the seat ID for a boarding pass. However, Python already has built-in tools to carry out the same calculation for you.
The name of the puzzle, Binary Boarding, and the mention of binary space partitioning are meant to start you thinking about (or reading about) the binary system. Binary is a number system composed of two digits,
0 and
1, instead of the traditional ten digits.
In the puzzle, the boarding pass specifications are really binary numbers. The difference is that they use
F or
L in place of
0, and
B and
R in place of
1. For example,
FBFBBFFRLR can be translated to the binary number 01011001012. You can use Python to convert this to a regular decimal number:
>>> int("0101100101", base=2) 357
Do you recognize that answer?
357 is indeed the seat ID of
FBFBBFFRLR. In other words, in order to calculate seat IDs, you need to translate
F,
L,
B,
R into their respective binary digits. There are several ways you can do this, but
str.translate() in Python’s standard library is probably the most convenient. Here’s how it works:
>>> mapping = str.maketrans({"F": "0", "L": "0", "B": "1", "R": "1"}) >>> "FBFBBFFRLR".translate(mapping) '0101100101'
The
.translate() method uses character codes like
70 instead of strings like
"F". You can set up the translation based on strings, though, with the convenience function
str.maketrans(). You can now use these tools to solve the puzzle in three steps:
- Convert boarding pass specifications to binary numbers.
- Calculate the decimal value of the binary numbers to get the seat IDs.
- Find the maximal seat ID.
Set up your templates for the new puzzle, with
input.txt containing your personalized puzzle input:
advent_of_code/ │ └── 2020/ └── 05_binary_boarding/ ├── aoc202005.py ├── input.txt ├── example1.txt └── test_aoc202005.py
You can add the worked examples to
example1.txt as usual:
FBFBBFFRLR BFFFBBFRRR FFFBBBFRRR BBFFBBFRLL
Next, you’re gonna prepare the tests for the first part. Before doing so, you should think about how you want to parse the puzzle input.
One option is to parse the input file into a list of strings. However, you can also think about the conversion from boarding pass specification to seat ID as part of the parsing process. One consideration to take into account is whether you think you’ll need the original boarding pass strings later—that is, in part two.
You decide to take the chance, and you parse the seat IDs immediately. If the boarding pass strings are needed in part two, then you can always go back and refactor your code. Add the following tests to your test file:
def test_parse_example1(example1): """Test that input is parsed properly""" assert example1 == [357, 567, 119, 820] def test_part1_example1(example1): """Test part 1 on example input""" assert aoc.part1(example1) == 820
As usual, run
pytest to confirm that your tests are failing. Then it’s time to start implementing your solution. Start with the parsing:
BP2BINARY = str.maketrans({"F": "0", "B": "1", "L": "0", "R": "1"}) def parse(puzzle_input): """Parse input""" return [ int(bp.translate(BP2BINARY), base=2) for bp in puzzle_input.split("\n") ]
You set up the translation table between boarding pass strings and binary numbers. Then you use
.translate() to translate each boarding pass in your input to a binary number and
int() to convert the binary number to a seat ID.
Finding the highest seat ID is now straightforward:
def part1(data): """Solve part 1""" return max(data)
Python’s built-in
max() finds the highest value in a list. You can now run your tests to confirm that your solution works and then run your code against your personalized input to get your answer to the puzzle.
Time to move on to the second part of the puzzle. Will you be able to board the plane?
Part 2: Puzzle Description
Expand the section below when you’re ready for the second part of the puzzle:
Compared to the first part, the description of part two is quite short and concise:
Ding! The “fasten seat belt” signs have turned on. Time to find.
What is the ID of your seat?
Can you find your seat?
Take your time and work on your solution to this second part.
Part 2: Solution
Open the box below when you’re ready to compare your solution to another one:
In this second part of the puzzle, you’re looking for one missing number in a list of numbers.
There are several ways you can approach this. You can, for example, sort all the numbers and compare consecutive items in your sorted list. Another option is to use Python’s powerful sets. You can first create the full set of valid seat IDs. Then you can calculate the set difference between this full set and the set of seat IDs on your list.
Before you start on the implementation, though, you should add a test for it. In this case, the example data are actually not good to use for a test. They have many seat IDs missing and not only one like the puzzle text specifies. You’re better off creating a small test manually. Here’s one way you can do it:
def test_part2(): """Test part 2 on example input""" data = [3, 9, 4, 8, 5, 10, 7, 11] assert aoc.part2(data) == 6
The list
[3, 9, 4, 8, 5, 10, 7, 11] contains all seat IDs from 3 and 11 with the exception of 6. This smaller example fulfills the conditions of the puzzle. Your solution should therefore be able to pick out the missing seat ID.
In this implementation, you’ll use the
set() approach:
1def part2(data): 2 """Solve part 2""" 3 all_ids = set(range(min(data), max(data) + 1)) 4 return (all_ids - set(data)).pop()
On line 3, you create all the valid seat IDs. These are the numbers between the smallest seat ID and highest seat ID in your dataset, inclusive. To find your seat ID, you convert your list of seat IDs to a set, compare it to the set of all IDs, and pop out the one remaining seat ID.
Congratulations! By now, you’ve solved at least two Advent of Code puzzles. Luckily, there are hundreds more waiting for you!
Conclusion
Advent of Code is a great resource of fun programming puzzles! You can use it to practice your problem-solving skills and challenge your friends to a fun competition and common learning experience. If you haven’t already done so, then head over to the Advent of Code website and try out some of the new puzzles.
In this tutorial, you learned:
- How solving puzzles can advance your programming skills
- How you can participate in Advent of Code
- How you can approach different kinds of puzzles
- How you can organize your code and tests when solving Advent of Code puzzles
- How test-driven development can be used when solving puzzles
Real Python hosts a private leaderboard and a community forum about Advent of Code. Become a Real Python member and join the
#advent-of-code Slack channel to access it.
|
https://statsidea.com/advent-of-code-solving-your-puzzles-with-python/
|
CC-MAIN-2022-40
|
refinedweb
| 8,598
| 71.44
|
. Sed Substitution Delimiter
As we discussed in our previous post, we can use the different delimiters such as @ % | ; : in sed substitute command.
Let us first create path.txt file that will be used in all the examples mentioned below.
$ cat
Example 1 – sed @ delimiter: Substitute /opt/omni/lbin to /opt/tools/bin
When you substitute a path name which has ‘/’, you can use @ as a delimiter instead of ‘/’. In the sed example below, in the last line of the input file, /opt/omni/lbin was changed to /opt/tools/bin.
$
Example 2 – sed / delimiter: Substitute /opt/omni/lbin to /opt/tools/bin
When you should use ‘/’ in path name related substitution, you have to escape ‘/’ in the substitution data as shown below. In this sed example, the delimiter ‘/’ was escaped in the REGEXP and REPLACEMENT part.
$
II. Sed ‘&’ Get Matched String
The precise part of an input line on which the Regular Expression matches is represented by &, which can then be used in the replacement part.
Example 1 – sed & Usage: Substitute /usr/bin/ to /usr/bin/local
$ sed 's@/usr/bin@&/local@g' path.txt /usr/kbos/bin:/usr/local/bin:/usr/jbin/:/usr/bin/local:/usr/sas/bin /usr/local/sbin:/sbin:/bin/:/usr/sbin:/usr/bin/local:/opt/omni/bin: /opt/omni/lbin:/opt/omni/sbin:/root/bin
In the above example ‘&’ in the replacement part will replace with /usr/bin which is matched pattern and add it with /local. So in the output all the occurrance of /usr/bin will be replaced with /usr/bin/local
Example 2 – sed & Usage: Match the whole line
& replaces whatever matches with the given REGEXP.
$ sed 's@^.*$@<<<&>>>@g'>>>
In the above example regexp has “^.*$” which matches the whole line. Replacement part <<<&>>> writes the whole line with <<< and >>> in the beginning and end of the line respectively.
III. Grouping and Back-references in Sed
Grouping can be used in sed like normal regular expression. A group is opened with “\(” and closed with “\)”.Grouping can be used in combination with back-referencing.
Back-reference is the re-use of a part of a Regular Expression selected by grouping. Back-references in sed can be used in both a Regular Expression and in the replacement part of the substitute command.
Example 1: Get only the first path in each line
$ sed 's/\(\/[^:]*\).*/\1/g' path.txt /usr/kbos/bin /usr/local/sbin /opt/omni/lbin
In the above example, \(\/[^:]*\) matches the path available before first : comes. \1 replaces the first matched group.
Example 2: Multigrouping
In the file path.txt change the order of field in the last line of the file.
$ sed '$s@\([^:]*\):\([^:]*\):\([^:]*\)@\3:\2:\1@g' path.txt /usr/kbos/bin:/usr/local/bin:/usr/jbin:/usr/bin:/usr/sas/bin /usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/omni/bin: /root/bin:/opt/omni/sbin:/opt/omni/lbin
In the above command $ specifies substitution to happen only for the last line.Output shows that the order of the path values in the last line has been reversed.
Example 3: Get the list of usernames in /etc/passwd file
This sed example displays only the first field from the /etc/passwd file.
$sed 's/\([^:]*\).*/\1/' /etc/passwd root bin daemon adm lp sync shutdown
Example 4: Parenthesize first character of each word
This sed example prints the first character of every word in paranthesis.
$ echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g' (W)elcome (T)o (T)he (G)eek (S)tuff
Example 5: Commify the simple number.
Let us create file called numbers which has list of numbers. The below sed command example is used to commify the numbers till thousands.
$ cat numbers 1234 12121 3434 123 $sed 's/\(^\|[^0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g' numbers 1,234 12,121 3,434 123
Get the Linux Sysadmin Course Now!
{ 33 comments… read them below or add one }
Dear author,
In the example 4, what is the meaning of \b escape character? and why the REGEXP can finish the task?
@Berry,
\b matches a word boundary.
If you omit \b from example 4, it just parenthesize all the Uppercase letters.
$ echo “Welcome To The Geek StuffPost” | sed ‘s/\([A-Z]\)/\(\1\)/g’
(W)elcome (T)o (T)he (G)eek (S)tuff(P)ost
@Sasikala,
Oh, I got it. Thank you very much. ^_^
Following your tips, I found that / can match the right. Thank you again!
@Sasikala,
Following your tips, I found that / plus “smaller than” can match the left boundary and / plus “larger than” can match the right. Thank you again!
Hi,
Regarding the example 4, when i try it in Red Hat linux, it works, but when i try in HP-UX or SunOS it does not. Any reason why so?
Also, same is the case with example 5 as well…please let me know why
Example 5 may only work on Linux (I don’t see how) but does not work for other systems. The following snippet does work on Sun OS and am sure will work on most systems out there; including Linux:
echo ’1234
12121
3434
123′ | sed ‘s/\([0-9]\{3\}\)$/,\1/g;s/^,//’
Thanks,
-Anjum.
Example 4 reworked and tested on Solaris 9:
echo “Welcome To The Geek Stuff” | sed ‘s/\<\([A-Z]\)/\(\1\)/g'
Thanks,
-Anjum.
A complete example of commify (add comma as thousands separator)
$ cat numbers.txt
1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
1234567890.1234
+1234567890.1234
-1234567890.1234
With the “-r” option, there is no need to escape the paraenthesis and curly brackets.
The simple code below doesn’t work for numeric strings larger that 6.
$ sed -r ‘s/(^|[^0-9.])([0-9]+)([0-9]{3})/\1\2,\3/g’ numbers.txt
1
12
123
1,234
12,345
123,456
1234,567
12345,678
123456,789
1234567,890
1234567,890.1234
+1234567,890.1234
-1234567,890.1234
This one works. (taken from question 4.14 of)
$ sed -r ‘:a;s/(^|[^0-9.])([0-9]+)([0-9]{3})/\1\2,\3/g;ta’ numbers.txt
1
12
123
1,234
12,345
123,456
1,234,567
12,345,678
123,456,789
1,234,567,890
1,234,567,890.1234
+1,234,567,890.1234
-1,234,567,890.1234
Can you please explain this Substitution.
sed -r ‘s/(^|[^0-9.])([0-9]+)([0-9]{3})/\1\2,\3/g’ numbers.txt
Thanks,
Rafi
I am not clear about .can you explain this Grouping and Back-references in Sed.
Thanks in advance.
HAI
Can u given one example for replacing current date with * or ** (single digit with * and double digit with **) in calender using sed command.
thanks
can you tell what is this “^” actually does ??
‘^’ serves two purposes. When inside of [] it means “not these”, but outside of that it means “the start of input”. So, for example
echo “why hello” | sed ‘s/hello/goodbye’
would replace ‘hello’ with ‘goodbye’, but
echo “why hello” | sed ‘s/^hello/goodbye’
would not replace the ‘hello’ with ‘goodbye’ because it is not at the beginning of input.
echo “why hello” | sed ‘s/[^z]ello/goodbye’
Would replace hello with goodbye (because ‘hello’ does not start with a ‘z’)
hi ,
Using Sed can we append/remove the new content in crontab file without disturbing old entries .
I am trying to parse a header file and the array size and paste later.
I want to change a line like the following :
bool SetValues(int array1[30], int array2[30, int size)
I want it to look like
SetValues(&array1[0], &array2[0], 30).
I have got most it, but i cannot figure out how to replace the string :”int size”
with the string “30″
I cannot figure out how to hold the pattern I want and use it to substitue later.
name marks grade
abc 50 CB
def 45 CC
ghhi 55 CA
jkl 85 A
mno 75 BA
pqr 77 BA
stu 89 A
my question is..
add .00 after every mark value in mark column…
how can I do with sed command??????
is there any another command???
$ cat file.txt
name marks grade
abc 50 CB
def 45 CC
ghhi 55 CA
jkl 85 A
mno 75 BA
pqr 77 BA
stu 89 A
$ cat file.txt|awk ‘{print $1, $2″.00″, $3}’
name marks.00 grade
abc 50.00 CB
def 45.00 CC
ghhi 55.00 CA
jkl 85.00 A
mno 75.00 BA
pqr 77.00 BA
stu 89.00 A
$
Hi,
I want to insert null character at particular position in every line of file.
How can i do that?
thanks in advance.
Hi..
How to change the second field of the /etc/shadow file to NP without touching other entries in a line
thank you thegeekstuff.com every time you give us interesting informations
I use the following sed command to add some additional aliases to .bashrc
sed -i -e ‘/ls –color=auto/a \
alias ll=”ls –color=auto -lh” \
alias la=”ls –color=auto -lAh” \
alias l=”ls –color=auto -CF”
‘ ~/.bashrc
I would like to use single quotes ‘ in the added lines for cosmetic reasons, but none of the combinations of escape codes will work for me. I’ve tried \’, ”, ”’, and even tried exchanging ‘ and “. Any idea how to include a single quote in the added lines?
Hi,
Could u pls explain the Example 5, how it works.
$sed ‘s/\(^\|[^0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g’ numbers
Boss, pls explain example 5.
ANYONE please do let me know , how to add the below information after 10th line in a file in linux using sed command
===================================================================
SSLEngine on
JkMountCopy On
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile “/opt/test/sys/Apache/conf/ssl.crt/server.crt”
SSLCertificateKeyFile “/opt/test/sys/Apache/conf/ssl.key/server.key”
SSLOptions +StdEnvVars
SSLOptions +StdEnvVars
CustomLog “/opt/test/sys/Apache/logs/ssl_request.log” “%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \”%r\” %b”
===================================================================
Here is you do it.
1.Save the contents you want to insert after the 10th line into a separate file.
2. Use read option (“r”) to read the above file into the original file.
The original file
$ cat myfile.txt
this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
this is line 6
this is line 7
this is line 8
this is line 9
this is line 10
this is line 11
this is line 12
Save the contents to be inserted into new_file.txt
$ cat new_file.txt
=======================
new line 1
new line 2
new line 3
new line 4
new line 5
=======================
Read the contents of the new_file into the original file, myfile.txt
$ sed ’10r new_file.txt’ myfile.txt
this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
this is line 6
this is line 7
this is line 8
this is line 9
this is line 10
=======================
new line 1
new line 2
new line 3
new line 4
new line 5
=======================
this is line 11
this is line 12
Thank you very much Logan Palanisamy ,,,, Thank you very much once again palanisamy…!! it is really working thank you very very much …!!
Logan Palanisamy , but in the text i had to pass variables like $HOSTNAME $PWD when i place in the text issue the command sed -i ’10r text’ httpd.conf , it is saving as it is , but it is not replacing the value of $HOSTNAME and $PWD , please help me in this regard logan palanisamy
# ServerAdmin webmaster@dummy-host.example.com
# DocumentRoot /www/docs/dummy-host.example.com
ServerName $HOSTNAME
# ErrorLog logs/dummy-host.example.com-error_log
# CustomLog logs/dummy-host.example.com-access_log common
SSLEngine on
JkMountCopy On
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
would anybody explain the meaning of every field of example 1
Hi author,
I have one comment regarding example 1 in section III. Grouping and Back-references in Sed).
You wrote, “\(\/[^:]*\) matches the path available before first : comes.”, which is not correct.
Explanation:
Let’s get rid of “\(” and “\)” in the expression, which are used for grouping.
For the remaining part, “\/[^:]*”, which means, match the strings that starting with “/”, and followed by any strings other than “:”, for zero or more times.
So, your explanation should be corrected to, “\(\/[^:]*\) matches any path that does not includes a colon.”
The first ocurrence of the path in the line is represented by “\1″, not “\(\/[^:]*\)”.
please help me
i have a one text file.
cat sample.txt
0
0
0
0
0
0
i want to replace 0 with name using sed command
please help me …for this also
i have a file with 500 telephone numbers..and i want to replace number with name=data.
using sed command .
@ sasikala
First, let me say your examples not just on sed are a fantastic starting point for those who are passionate to learn
My question is example 5
———————————————————————
$sed ‘s/\(^\|[^0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g’ numbers
———————————————————————
can you tell me what does the dot “.” after 9 in the pattern \(^\|[^0-9.]\) do?
The pattern should match all chars which are not digits anchored at the beginnng and defines the first group as that.
But it works even without the dot after 9 . Can you explain what does the dot after 9 do?
|
http://www.thegeekstuff.com/2009/10/unix-sed-tutorial-advanced-sed-substitution-examples/
|
CC-MAIN-2014-41
|
refinedweb
| 2,261
| 74.29
|
Microservices have been a popular topic recently. People argue over whether you should start with microservices or evolve there from a single ‘monolithic’ app. Maybe in a well designed app microservices are simply a deployment option?
It all seems rather academic when you have upward of 100,000 lines of (non-test) Ruby code glowering back at you. (And that’s before you start counting the gems!) You know you want to split it up, but how do you move on from there?
What follows is a case study from Yammer, in which we gradually moved our core messaging data store out of an ActiveRecord model into a microservice responsible solely for managing access to messages in Yammer. I’ll present some useful gems, point out some pitfalls that we encountered and how we tackled them, and hopefully show some techniques that may save you some time if you have to do the same. If nothing else it should give you the courage that you’re not stuck with your current architecture. If it’s important enough, you can escape!
Some background
Yammer has had a ‘service oriented architecture’ for many years. Today I can count nearly 200 services listed in our deployment tool. But back in the beginning there was one Ruby on Rails app, and even as most significant new functionality was created in new services, that Rails app has continued to grow.
Is that a problem? Not necessarily; some organisations make the monolith work, but here at Yammer it’s something we’re keen to move away from. It’s too special when compared with the other services we run.
- Deploys take too long, and deploy to too many servers.
- Too much function is ‘at risk’ with a single deploy — the surface area for testing is too great. Other services have a very tightly defined responsibility, which greatly limits the risk of a deploy.
- Coupling so much function leads to inefficiencies everywhere. Just loading all the gems (more than 200) makes unit tests slow. Why is my deploy held up for asset packaging when I only changed JSON API endpoints?
One piece we were particularly keen to extract from the monolith was the storage of message and thread objects. Yammer is a messaging platform. Yes, it’s a social network — how you find interesting conversations and contribute to the movement of information in your company is what makes Yammer messaging special — but it’s messages moving information around that make Yammer so valuable to our customers. With messages fiercely guarded by a highly complex ActiveRecord model backed by memcache and Postgres our hands were tied as we attempted to improve the scale, reliability and performance of our messaging systems. What we wanted was a service that provided a single source of truth for messages, that hid the complexities of sharding those across multiple data stores, that could be called directly from many services.
Our Rails app would still need free access to create, read, and modify messages, but we wanted a model that was backed by this new service. The Rails app would just be one of many equal consumers of the service. So how do we go from a model subclassing ActiveRecord to one that isn’t?
Hey! ActiveRecord! Let go of that!
Step 1: Acknowledge
ActiveRecord is an amazing tool and you’re probably using a lot more of its features than you realise. You’re going to have to write a lot of code now that you can’t lean on ActiveRecord. (We were really surprised how much time we ended up spending on this!)
Step 2: Reduce
Use less ActiveRecord. Anything we used we would have to re-implement, so we cut down on how much ActiveRecord we used.
- No Arel. ActiveRecord relations (built on top of Arel) expose the huge power of a relational database, but that’s not an interface we could provide in an HTTP web service with a future that doesn’t include a relational database. So we moved all model loading to explicit find_by_xxxx methods. For each of those finder methods we would create a matching HTTP endpoint in the messages service.
- No scopes. They’re just ActiveRecord Relations in disguise.
- Cut code that relies on transactions for rollback. The only way to roll back an HTTP request is to issue a request that reverses what you have done.
- Reduce use of callbacks. You can of course add callbacks to your model without using ActiveRecord. Just mix in ActiveModel::Callbacks. But many of the callbacks provided by ActiveRecord only really make sense when you’re thinking of a model that maps directly to a database table. For example before_commit no longer makes any sense when save and commit are done together with a single HTTP POST or PUT.
Step 3: Recreate
Start recreating the ActiveRecord features you do want to use.
Note that you don’t have to implement everything at once. Remember “favour composition over inheritance”? Do that refactoring! Our initial ActiveRecord-free Message model delegated a lot of function to an internal instance of MessageActiveRecord. Over time we gradually cut out all that delegation.
Attributes. ActiveRecord does a lot of work to map database columns to attributes on your model. You’ll need to replace that.
- Virtus is a popular option but doesn’t have change tracking (which we wanted).
- attr_accessor + ActiveModel::Dirty. The basic building blocks, but ActiveModel::Dirty leaves you with a fair bit of plumbing to do, and you don’t get any checking that what’s assigned to your attributes will make a sensible JSON payload to send to your service.
- When all else fails, make your own gem. We made ModelAttribute. So you don’t have to! It also handles efficient serialisation and deserialisation to/from JSON. Yammer loads a lot of messages, so performance here really mattered to us.
So our model started to look like this:
class Message
extend ModelAttribute
attribute :id, :integer
attribute :body, :string
attribute :message_type, :integer
attribute :references, :json
attribute :created_at, :time
# ...
def save
# ModelAttribute provides #changes and #changes_for_json
return if changes.empty?
Messages::MessageStore.save(self.changes_for_json)
changes.clear
end
end
Loading records from the database. We started with just delegating to ActiveRecord for that. But our new model was supposed to be loading JSON from a web service, so we rewrote the loading to request JSON over a direct database connection. The model loading logic was then the same for both backends, except for the source for that JSON.
Getting JSON directly from the database is really very easy using Postgres’ JSON functions:
sql = "SELECT row_to_json(t) FROM (
SELECT id,
...,
round(extract(epoch from created_at) * 1000) as created_at,
round(extract(epoch from updated_at) * 1000) as updated_at,
FROM messages
WHERE ...
) t;".gsub(/s+/, ' ')
json = connection.select_values(sql)
Callbacks. ActiveModel::Callbacks for when you just can’t live without them. (Usually because we still wanted to use a library that relied on a callback.)
class Message
extend ActiveModel::Callbacks
define_model_callbacks :save, :destroy, :commit
def save
return if changes.empty?
run_callback :commit do
run_callbacks :save do
Messages::MessageStore.save(self.changes_for_json)
end
# To match ActiveRecord behaviour, after_save callbacks expect
# to see a populated changes hash, after_commit callbacks don't.
changes.clear
end
end
# Similarly for destroy
end
Caching. Maybe this is not a problem for you, but it was a big problem for us. Yammer’s Ruby monolith uses a fork of the RecordCache gem to cache database reads (similar to the more recent IdentityCache gem from Shopify). Without the cache Postgres just can’t keep up, even running on a monster of a DB server, kitted out with FusionIO cards. But RecordCache is deeply entwined with ActiveRecord, so we had to re-implement that. (Sadly this gem is based on a Yammer special caching gem, so we haven’t open-sourced it as it’s not going to be much use to anyone.)
(Side note — as we move function from our Ruby monolith into services we also want to move responsibility for caching out of the monolith. So we store cache entries not in the Ruby-specific marshall format, but using a combination of JSON, MessagePack and ZLib compression, so that it can be read equally well from Java services.)
The rest. new_record? persisted? destroyed? primary_key to_param update_attribute… We wrote up a little module called ActiveRecordMimic that provided re-implementations of little helper methods that we still wanted without cluttering our model with methods that are nothing to do with its domain responsibilities.
module ActiveRecordMimic
def destroyed?
!!@destroyed
end
def new_record?
!id
end
def persisted?
!(new_record? || destroyed?)
end
# This allows us to use this object as a hash key, and for uniq'ing arrays
def hash
id.hash
end
# See more in
end
Step 4: Transition
Nearly there! We have a model now that doesn’t rely on ActiveRecord, but does still access Postgres directly from within a Rails monolith. Gradually we transitioned traffic to go via the new service instead, allowing us to tune performance, server provisioning, circuit breakers, network settings, etc. in a production environment.
(There are a myriad of ways of doing a gradual transition. We switched code based on user IDs (our own to start with!) before moving on to checking the last digit of the ID — allowing us to roll out 10% at a time. And we always had a kill-switch, so we could revert to the old code path at a moment’s notice.)
So long, and thanks for all the records
It’s easy to underestimate how much ActiveRecord gives you. It may encourage you towards designs that you regret later, but it does so much heavy lifting. It’s only when you try to quit that it become clear how much you’re reliant on it!
This is not a blog post on application architecture. There are already a lot of those! The end result still follows the Active Record pattern, just loading the data from a service instead of the database. It’s not the end state for Yammer either, just a step along the way to a messaging pipeline that is better decomposed into services. With message data exposed directly through a simple, extremely fast HTTP service we have already started to use that data in other services, pushing towards a faster, more resilient messaging infrastructure for our users.
It took a lot of effort, but it was possible, and a valuable move. I hope that this case study gives you some of the tools and confidence to break away from ActiveRecord when the time is right for you!
David Waller is a senior engineer in the Yammer London office.
|
http://engineeringjobs4u.co.uk/activerecord-stole-my-data-and-now-i-want-it-back-yammer-engineering-medium
|
CC-MAIN-2019-04
|
refinedweb
| 1,775
| 63.9
|
was just doing some more tests. I realized that the client with the current
version is way slower than i am use to, I'll let you know what i find.
- Brad
__________________________________________________
Do You Yahoo!?
Yahoo! Health - your guide to health and wellness
--- andrey <ahristov@...> wrote:
> Hello Brad,
> I am very thankful to you that you created the SOAP extension. I gived it a
> try but had only problems.
> I didn't succeeded to test even the HelloWord example which I got from the
> project's site.
> After receiving blank screens in the browser several times, I decided to
> debug.Here I spoke for Windows experience -CGI.
> I tried to var_dump() the SoapObject and one of the properties was setted -
> the fault. The fault was received from the hello_world_server.php so
> probably the client part is working well. The message reads that I've to
> turn always_populate_raw_post_data on.
My example section aren't up to par yet. You can do this on the client side to
help determine some faults.
$soap->some_call();
if($soap->__isFault())
var_dump($soap->__getFault());
But why it isn't saying that always_populate_raw_post_data is off i don't
know.
On the server side try
var_dump(ini_get("always_popuplate_raw_post_data"));
I added that test in there just before i made the release because i know
php-4.2.0 uses that and i wanted some kinda test in there.
Maybe the test can first test if HTTP_RAW_POST_DATA is available then if not
test the ini setting, finally returning a soap fault if it's not set.
I moved from 4.1.1 to 4.2.0 with no
> success even changing always_populate_raw_post_data to On. I debugged the
> server part to be sure that $HTTP_RAW_POST_DATA is populated and
> after several atempts do it, I done it. Several attempts because I realized
> that no code after $some->handle() in the main program is executed so I
> moved mu
> debugging code before this call. I wrote the contents of $HTTP_RAW_POST_DATA
> in a file using var_export()/ob_*. The var is ok but why the SoarServer
> claims that there is an error.
> I decided that maybe the problem is under windows and switched to Linux. I
> unpacked the zip with the sources and here the problems begun. First the
> config.m4 is not .m4 file but a .tar. I needed some time to realize that.
Hmm.. ill look into that.
> I've problems with compiling because libxml2 path was
> /usr/include/libxml2/libxml not /usr/include/libxml. I fixed that with a
oh.. my includes are
#include <libxml2/*.h>
ill can change them.
> soft link, and the code started to compile. It compiles well but on
> linking(not sure but i think that is the job of libtool) with libtool I got
> errors. The errors are about not existents calls to functions. These are
> functions from the libxml2 library.
it assumes that libxml2 is installed under /usr/local/
This is only because i don't know how to use libtool and config.m4 files. I am
hoping that someone can enlighten me on configure them.
> I'm lost. I was so happy that you released the SOAP extension because I
> started working on my bachelor thesis few days ago and I decided previously
> that I will use xmlrpc because there is such extension and not to use SOAP
> because Dietrich Ayala's SOAP4x, now called NuSOAP is too slow. I'll be glad
> if I can help you in any way.
Are you familure with the make config process. Currently it doesn't compile as
a .so ither because of the config/make process.
> May you give me some light what to do.
Just to let you know that this extension is very much an alpha release. There
are still some leaks/segfaults in there. I am hoping that people like you and
others can help me to get this at a stable release as soon as possible.
>
> Best regards,
> Andrey Hristov
>
__________________________________________________
|
https://sourceforge.net/p/phpsoaptoolkit/mailman/phpsoaptoolkit-development/?viewmonth=200205&viewday=1
|
CC-MAIN-2017-04
|
refinedweb
| 659
| 76.62
|
Prediction
Prediction is the notion of the client predicting the effects of the local player's actions without waiting for the server to confirm them. An entity's predicted state is tested against server commands as they arrive until either a match or a mis-match is detected.
In the vast majority of cases the client's prediction is confirmed by the server and it continues happily as if there was no latency. If there is a mis-match, which is rare if the prediction code is written correctly, then the client goes back and re-simulates all of the commands it ran with bad data. Depending on the severity of the error this can cause a noticeable hitch in the player's position and state, and possibly the state of the world too.
Prediction is closely linked to lag compensation, but is separate from interpolation. It only exists on the client.
Implementation
To predict an entity:
- It should be manipulable by the local player. Otherwise, what is the point in predicting it?
- The functions that are to be predicted must exist and be identical on both the client and server. This is achieved by making them shared code.
- The entity must make the call
SetPredictionEligible(true), preferably in its constructor.
- It must have a
bool ShouldPredict()function on the client. Check if the local player is holding this entity and so forth here.
Weapons must also implement
bool IsPredicted(), again on the client. It should return
trueall the time.
- Any variables that must be synchronised between the client and server must be both networked and present in the entity's prediction table.
Prediction tables
All client-side variables modified by predicted player input must be added to a prediction table. There are three behaviours you can choose between:
FTYPEDESC_INSENDTABLE
- This is a networked variable. The client's predicted value will be tested against received server values, and if the two go out of synch a prediction error will be created.
FTYPEDESC_NOERRORCHECK
- This is a predicted value that can go out of synch without generating a prediction error. It may or may not be networked.
FTYPEDESC_PRIVATE
- This isn't predicted or networked at all, but is still registered so that it can inspected with
cl_pdump.
This type of variable won't be saved/restored when the prediction system winds time back to test against a new server command. If a predicted function increments it, the increment will be applied over and over again on the client as each new command is tested.
These behaviours are implemented with the
DEFINE_PRED_FIELD() and
DEFINE_PRED_FIELD_TOL() macros. The latter allows you to specify a tolerance within which an int or float is allowed to differ without generating prediction errors. This is mainly intended for use when a value has been rounded prior to transmission: floats are often trimmed to 1ms resolution, for instance (the #define
TD_MSECTOLERANCE exists especially for this situation - otherwise, you should pass a numeric value).
Be cautious when extrapolating from a rounded figure in these circumstances. Small differences in the transmitted value can lead to large changes in the results of your calculations!
To do:
DEFINE_PRED_TYPEDESCRIPTION
Example
#ifdef CLIENT_DLL BEGIN_PREDICTION_DATA( CBaseCombatWeapon ) DEFINE_PRED_FIELD( m_nNextThinkTick, FIELD_INTEGER, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_hOwner, FIELD_EHANDLE, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD_TOL( m_flNextPrimaryAttack, FIELD_FLOAT, FTYPEDESC_INSENDTABLE, TD_MSECTOLERANCE ), END_PREDICTION_DATA() #endif
Predicting entity creation
The standard prediction system can maintain an existing entity's state, but it does not help with creating new entities.
CreatePredictedEntityByName() does. It creates a new entity on the client and swaps it for the real one when it arrives from the server. Needless to say, you should call it from shared code.
CBaseEntity::CreatePredictedEntityByName( char* classname, char* class_file, int line, bool persist = false )
modulein the actual code, and its line number (
persistcauses the entity to be tested during reprediction.
If the predicted entity contains data that was not sent to the server, you should copy it into the real entity in
C_BaseEntity::OnPredictedEntityRemove().
Tools and tricks
IsFirstTimePredicted()
Testing
prediction->IsFirstTimePredicted() ensures that code is only executed when the client first predicts an action, and not when it checks against subsequent server updates. You must
#include "prediction.h" to access it.
Use this function for random numbers. The seed it uses is based on the usercmd number, making the result identical on client and server.
CDisablePredictionFiltering
To do
Suppressing network data
Non-critical events like weapon effects can be done entirely on the client. Suppressing that data is a good idea as it results in reduced bandwidth usage.
IPredictionSystem::SuppressHostEvents() is meant for this. When it is called, all network data to the given player is halted. Sending NULL again will turn transmission back on. For example:
if ( pPlayer->IsPredictingWeapons() ) IPredictionSystem::SuppressHostEvents( pPlayer ); pWeapon->CreateEffects(); IPredictionSystem::SuppressHostEvents( NULL );
Note that after doing the above you will need to write code somewhere else that makes the suppressed player's client generate the effects itself.
Sample
Here is a simple weapon that prints prediction information to the console. Use its rapid secondary fire with net_fakelag 200 (or above) to see how the engine handles multiple predicted shots.
Troubleshooting
If you add functionality to weapons and forget to follow the steps above, then an entity may jerk around or animate strangely. You can use
cl_predictionlist and
cl_pdump to debug this. Changing
cl_pred_optimize can also help sometimes.
Now let's say you see a variable that turns red in the
cl_pdump panel from time to time. Now you know that somehow the client is producing a different value for this variable than the server is. This can usually be traced down to one of the following problems:
- The client is not running some code that the server is running. This would be the case if you had an
#ifdef GAME_DLLor an
#ifndef CLIENT_DLLaround a piece of code that could affect the value of the variable that's turning red.
- Another variable that can wind up affecting the value of the red variable is not being transmitted via the data table. In this case, the client's value for that variable would always be wrong (since the server never transmitted it).
- It's also possible that you just forgot to add in the appropriate tolerance using the
DEFINE_PRED_FIELD_TOLmacro. For example, if you're transmitting a floating point variable with a value range of 0.0 - 255.0, and you only give it 4 bits of precision, then you're going to need a tolerance of about 17.0, or else the prediction system will think the variable's value is wrong when it is actually just different because the variable was compressed into 4 bits before sending it to the client.
Tracking down prediction problems is usually a matter of walking through any code that can affect the values that are turning red, and noticing which other variables affect their values. It can be tedious at first, but once you get the hang of it, you can track down prediction problems quickly.
|
https://developer.valvesoftware.com/wiki/Prediction
|
CC-MAIN-2015-48
|
refinedweb
| 1,154
| 53.51
|
A few weeks ago, I posted a notebook presenting a new Optimize API. Today we're announcing that the Optimize API is available for use in algorithms, and we've added new features to make the API easier to use in the context of a running algorithm.
The basic idea of the Optimize API is that it relieves authors from the burden of having to manually size orders and positions. Instead of calculating individual share counts and placing orders directly, authors can now specify the desired state of their portfolio in terms of high-level objectives and constraints.
Since the original announcement, we've made a few tweaks to the built-in Objective and Constraint classes, but the biggest change to the API is the addition of a new top-level entrypoint,
order_optimal_portfolio, which is available only in algorithms. order_optimal_portfolio accepts three parameters, all of which are required:
objective, an Objective that the new portfolio should maximize or minimize.
constraints, a list of Constraints that the new portfolio should adhere to.
universe, an iterable of Equity objects to consider in the optimization. In idiomatic usage, this will usually be the index of a Pipeline result.
When called, order_optimal_portfolio calculates the set of portfolio weights that optimizes
objective while still respecting
constraints. It then subtracts the target portfolio weights from the current portfolio weights and places orders to move from the current portfolio state to the new optimal state.
Examples
Backtest
The backtest attached to this post provides a complete example of how the Optimize API can be used in a realistic trading algorithm. The outline of the algorithm is as follows:
- Once a month, choose a universe of 500 liquid assets.
- Every day, build an alpha vector for our 500 assets. The alpha model we use is very simple: we rank assets by z-score of free cash flow yield and earning yield, both of which are fundamental value measures.
- Once a week, calculate the portfolio that maximizes the alpha-weighted sum of our position sizes, subject to.
Notebook
In the first comment below this post I've included an updated version of my original optimization notebook. It provides a more theoretical introduction to the idea of portfolio optimization, and it includes a reference for the built-in objectives and constraints.
Next Steps
Now is a great time to try out the Optimize API and provide design feedback or ideas for improvements. The API is still marked as experimental, which means breaking changes are possible, but based on feedback from the previous announcement, I think it's unlikely that there will be major backwards-incompatible changes. Examples of ideas for improvements might include new objectives/constraints, a first-class notion of "penalties", or options for avoiding orders if the new portfolio isn't a significant improvement over the old one.
If you want to get a feel for the new API but don't know where to start, I'd recommend cloning the attached algorithm and tweaking some of the parameters. Many of the constants listed above can be easily changed by editing a line or two. How does increasing the leverage cap affect performance? How about the position size constraint? For a bit more of a challenge, try adding a new constraint. The algorithm currently places a few orders that don't fill by the end of the day. Would the algo improve if we constrained our position sizes to a fixed percentage of trailing volume?
If you're looking to dig deeper into the details of the Optimize API, I'd recommend opening up the notebook reading through the examples. If you have a specific idea you want to try, you can build your constraints and objectives interactively in research and copy them over to an algorithm when you're happy with them.
import pandas as pd import quantopian.algorithm as algo import quantopian.experimental_LEVERAGE = todays_universe = pipeline_data.index #GrossLeverage(MAX_GROSS_LEVERAGE) #PartitionEx, ], universe=todays_universe, )
|
https://www.quantopian.com/posts/optimize-api-now-available-in-algorithms
|
CC-MAIN-2019-18
|
refinedweb
| 655
| 52.7
|
Quote from: hilukasz on Oct 22, 2012, 02:01 pmI think its more of a format issue.If you don't want to fix the problems being pointed out then it seems pointless taking the effort to try to help you find them.
I think its more of a format issue.
You should be able to send and receive on the same serial port.In your code you only seem to be trying to read from the Serial port when the distance reading is in range. I don't know why you're doing that - is it deliberate? Do you know that the value actually is in range? You need to know what's going on inside your sketch, and to understand that you really need to know what it's outputting to the Serial port and what your Processing application is writing to it.For simplicity while testing, you could set the Processing application aside and use the Arduino serial monitor to send input to the Arduino and display whatever the Arduino outputs..).
sketch_oct22b.cpp: In function 'void loop()':sketch_oct22b:54: error: expected `}' at end of input
Code: [Select] float distance = analogRead(1);The analogRead() function returns an int. Why are you storing that in a float?Code: [Select] //map float to an int int x = (int) distance;There's no "mapping" going on here.Code: [Select] data[counter] = String(serialDataIn);The serialDataIn variable is already a String. There is no reason to make another String instance, and then invoke the copy constructor on that instance, and then delete that instance. That is just uselessly gambling with an already dodgy class.
float distance = analogRead(1);
//map float to an int int x = (int) distance;
data[counter] = String(serialDataIn);
Couple of remarks, hope they can help.First, the line ' //}' seems weird, with the comment marks it does NOT compile. Taking out the '//' compiles ok.Next, does it actually print the "length" string? If x is not inside your range, nothing is done, whatever you receive.Then, the line 'float distance = analogRead(1);', again hmm, analogRead returns a int, not a float. Not critical, but not clean.But, most critical, you are not looping yourself, but using the Arduino background code to repeatedly call loop(). This means you are not in full control over what the system is doing. Even in the Arduino the microcontroller 'rule' the main function never exits is still a good one to follow.Now, i am not sure, but it looks like the serial buffer is reset upon entering loop().If i place the main block in a while(true) { .. } loop, it seems to work; at least it sees the incoming data etc.Oh, and finally, the lines // say what you got: Serial.print("I received: "); Serial.println(incomingByte, DEC);make no sense, inComingByte is initialise to 0 and never set.HTH,Guido
int x = analogRead(IRpin);
if(inbyte >= '0' && inbyte <= '9')
//SERVO stuff#include <Servo.h> Servo myservo; // create servo object, max 8 servo objects//IR portionint IRpin = 1; //int IRpin2 = 2; // incoming serial data from processingString serialDataIn;String data[3];int counter, inbyte, newPosX;void setup() { Serial.begin(9600); myservo.attach(3); // server is on pin 3 counter = 0; int pos = 0; }void loop() { //float distance = analogRead(IRpin); int x = analogRead(IRpin); int y = 20; Serial.print("Data,"); Serial.print(x); Serial.print(","); Serial.print(y); Serial.print(",\n"); // SERVO stuffs //int incomingByte = 0; if( x > 0 && x < 180){ //Serial.write("passed"); if (Serial.available() > 0) { Serial.write("serial avail"); inbyte = Serial.read(); /* if(inbyte >= '0' && inbyte <= '9') serialDataIn += inbyte; if (inbyte == ','){ // Handle delimiter data[counter] = String(serialDataIn); serialDataIn = String(""); counter = counter + 1; } if(inbyte == '\r'){ // end of line //myservo.write(x); } */ // say what you got: newPosX = (int) inbyte; //Serial.print("I received: "); //Serial.println(incomingByte, DEC); myservo.write(inbyte); } delay(25); } }
data :[0] "Data"[1] "328"[2] "20"-65data :[0] "Data"[1] "328"[2] "20"-65data :[0] "Data"[1] "303"[2] "20"-65
import java.awt.AWTException;import java.awt.Robot;import processing.serial.*;import java.awt.MouseInfo;import java.awt.event.InputEvent; import java.awt.PointerInfo.*;Serial myPort; // Create object from Serial classint windowHeight = 500;int windowWidth = 500;int lastVal = 1000;int currentVal, posX, meetsThreshold;float posXf, mappedPosXf;void setup() { myPort = new Serial(this, Serial.list()[4], 9600); myPort.bufferUntil('\n'); size(windowWidth, windowHeight);}void draw(){}void serialEvent(Serial p) { String message = myPort.readStringUntil('\n'); // read serial data if(message != null) { String [] data = splitTokens(message,",\n"); // Split the comma-separated message if (data[0].equals("Data")){ posX = Integer.parseInt(data[1]); print("X:"); println(posX); if( data.length > 2){ posXf = float(posX); mappedPosXf = map(posXf, 150, 740, 0, 180); posX = int(mappedPosXf); println(posX); myPort.write(posX); } } } }int downSample(int handSensor) { if (handSensor % 3 == 0){ int meetsThreshold = 1; println("meets threshold"); } else if (handSensor % 3 != 0){ meetsThreshold = 0; println("doesnt meet threshold"); } return meetsThreshold;}
"Serial.available acting funny"Was it doing standup? -
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy
|
http://forum.arduino.cc/index.php?topic=128403.msg967250
|
CC-MAIN-2017-09
|
refinedweb
| 855
| 59.09
|
In this section, you will get to know about reading line by line a text file using java.util.Scanner class.
AdsTutorials
In this section, you will get to know about reading line by line a text file using java.util.Scanner class.
The java.util.Scanner class uses the regular expression to parse the primitive types and strings. Using delimiters, it breaks the input into tokens. The default delimiter is white space. In absence of external synchronization ,a Scanner class is not considered safe for the multithreaded environment.
Given below the list of constructors of the Scanner class, which produces the scanned value from a specific source :
In the below example, we are reading line by line using the Scanner class :
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFileLineByLine { public static void main(String[] args) { // Provide Source Location to read file File file = new File("data.txt"); try { Scanner scan = new Scanner(file); while (scan.hasNextLine()) { String scannedline = scan.nextLine(); System.out.println(scannedline); } scan.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
In the above code, Scanner class constructor is used to bring out the values scanned from the specified file. The first Scanner method used here is hasnextLine() which return true, if there exist a line to read. If next line doesn't exist, this method returns false. The second method used here is nextline(), which return the current line. If the file doesn't existed at location provided, it will throw exception of type FileNotFoundException and print it on the console. The above code will display content of the file , line by line, on the console.
Scanner class is also very useful in reading a text file line by line. The hasNextLine() method of the Scanner class is used to find if there more line available in file. The nextLine() method is used to read the next line from the file.
The java.util.Scanner class is very useful class in the java.util package. It works as a simple text scanner and can be used to parse primitive types and strings. It uses the regular expressions for parsing the data.
Posted on: January 5, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles
Advertisements
Ads
Ads
Discuss: Line by Line reading from a file using Scanner Class
Post your Comment
|
https://www.roseindia.net/java/javafileprogramming/read-file-line-by-line-with-the-help-of-scanner-class.shtml
|
CC-MAIN-2018-13
|
refinedweb
| 399
| 74.49
|
straightforward when we use the Database First approach in which we design our database first and then we want to create the controller and view.
We are going to walk through this scenario to see how we can achieve this with Scaffolding and the Entity Framework..
Open Visual Studio 2010 and create an MVC project with these options:
Now that we have our project created, we need to add the database entity model first. This is basically the concept of Database first development.
Add the entity model from the database by following these steps:; }
}
We are now ready to start creating our controller and view. Let’s start by installing the Scaffolding package to our project by following these steps:
That should install the T4 templates for code generation and the MVCScaffolding reference to our project. Let’s now create our vehicle make controller
and view by typing this command at the PM> prompt::
System.ComponentModel.DataAnnotation).
CommerceEntities
public class VehicleMakeRepository : IVehicleMakeRepository
{
CommerceEntities context = new CommerceEntities();
public IQueryable<VehicleMake> All
{
get { return context.VehicleMakes; }
}
The controller file should look as follows: (notice how the controller uses the repository interface as the parameter in the constructor).;
}
For the views, we have the index, edit, create, delete and details views which can be used for the CRUD operations. These views and controller can be enhanced to meet
your application requirements..
|
http://www.codeproject.com/Articles/482801/Database-First-Development-with-ASP-NET-MVC-Scaffo
|
CC-MAIN-2014-35
|
refinedweb
| 228
| 50.97
|
SSH API Framework
Project description
Korv is an API framework that uses TCP sockets over SSH to exchange JSON data with a REST-like protocol. It's built on top of the
asyncssh module, so it uses
asyncio to manage the sockets and its callbacks. This allows you to build rich APIs with the session security of SSH and without the TCP overhead of HTTP.
Communications over this framework requires SSH keys like logging into a normal SSH server:
- The server itself has a private key and a set of public keys for the authorized clients.
- The client has a private key and a set of public keys for the servers it can connect to.
Verbs
There are 4 main verbs that indicate the intent of your request:
GETfor retrieving information.
STOREfor creating new objects.
UPDATEfor changing existing objects.
DELETEfor removing objects.
Keys
As discussed previously, you establish an SSH session with the server, so it's possible to reuse existing keys or generate them through any standard mechanism like the one below:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Server
Getting a server up and running is very simple:
from korv import KorvServer def hello(request): """Callback for the /hello endpoint""" return 200, {'msg': 'Hello World!'} def echo(request): """Callback for the /echo endpoint""" return 200, {'msg': f'{request}'} # Create a server k = KorvServer(host_keys=['PATH_TO_YOUR_SERVER_PRIVATE_KEY'], authorized_client_keys='PATH_TO_YOUR_AUTHORIZED_PUBLIC_KEYS') # Register the callbacks k.add_callback('GET', '/hello', hello) k.add_callback('GET', '/echo', echo) # Start listening for requests k.start()
This will start a new SSH server with the specified private key that listens on port
8022 by default and will accept the clients listed in the authorized keys.
Client
Following is an example on how to communicate with this server.
>>> from korv import KorvClient >>> >>> # Create the client >>> k = KorvClient(client_keys=['PATH_TO_YOUR_CLIENTS_PRIVATE_KEY']) >>> >>> # Issue a GET request and print the output >>> k.get('/hello', callback=lambda response: print(response['body'])) >>> {'msg': 'Hello World!'}
Return Codes
We're using standard HTTP response codes:
200= Success.
400= Malformed request or missing parameters.
404= NotFound
500= Internal error.
Server exceptions map to a
500 return code ans will include a traceback in the response.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/korv/
|
CC-MAIN-2021-31
|
refinedweb
| 384
| 56.35
|
So far, we've been content to evaluate single expressions from the command line, printing the result and exiting afterwards. This is fine for a calculator, but isn't what most people think of as "programming". We'd like to be able to define new functions and variables, and refer to them later. But before we can do this, we need to build a system that can execute multiple statements without exiting the program.
Instead of executing a whole program at once, we're going to build a read-eval-print loop. This reads in expressions from the console one at a time and executes them interactively, printing the result after each expression. Later expressions can reference variables set by earlier ones (or will be able to, after the next section), letting you build up libraries of functions.
First, we need to import some additional IO functions. Add the following to the top of the program:
import System.IO
Next, we define a couple of helper functions to simplify some of our IO tasks. We'll want a function that prints out a string and immediately flushes the stream; otherwise, output might sit in output buffers and the user will never see prompts or results.
flushStr :: String -> IO () flushStr str = putStr str >> hFlush stdout
Then, we create a function that prints out a prompt and reads in a line of input:
readPrompt :: String -> IO String readPrompt prompt = flushStr prompt >> getLine
Pull the code to parse and evaluate a string and trap the errors out of main into its own function:
evalString :: String -> IO String evalString expr = return $ extractValue $ trapError (liftM show $ readExpr expr >>= eval)
And write a function that evaluates a string and prints the result:
evalAndPrint :: String -> IO () evalAndPrint expr = evalString expr >>= putStrLn
Now it's time to tie it all together. We want to read input, perform a function, and print the output, all in an infinite loop. The built-in function
interact almost does what we want, but doesn't loop. If we used the combination
sequence . repeat . interact, we'd get an infinite loop, but we wouldn't be able to break out of it. So we need to roll our own loop:
until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m () until_ pred prompt action = do result <- prompt if pred result then return () else action result >> until_ pred prompt action
The underscore after the name is a typical naming convention in Haskell for monadic functions that repeat but do not return a value.
until_ takes a predicate that signals when to stop, an action to perform before the test, and a function-returning-an-action to do to the input. Each of the latter two is generalized over any monad, not just
IO. That's why we write their types using the type variable
m, and include the type constraint
Monad m =>.
Note also that we can write recursive actions just as we write recursive functions.
Now that we have all the machinery in place, we can write our REPL easily:
runRepl :: IO () runRepl = until_ (== "quit") (readPrompt "Lisp>>> ") evalAndPrint
And change our main function so it either executes a single expression, or enters the REPL and continues evaluating expressions until we type
quit:
main :: IO () main = do args <- getArgs case length args of 0 -> runRepl 1 -> evalAndPrint $ args !! 0 otherwise -> putStrLn "Program takes only 0 or 1 argument"
Compile and run the program, and try it out:
$ ghc -package parsec -fglasgow-exts -o lisp [../code/listing7.hs listing7.hs] $ ./lisp Lisp>>> (+ 2 3) 5 Lisp>>> (cons this '()) Unrecognized special form: this Lisp>>> (cons 2 3) (2 . 3) Lisp>>> (cons 'this '()) (this) Lisp>>> quit $
|
http://en.m.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/Building_a_REPL
|
CC-MAIN-2014-49
|
refinedweb
| 609
| 56.08
|
C: Code to time execution with accuracy greater than a second
The following application computes the time needed for a process to finish using the method
clock().
The result of the application is the time in seconds as a floating number (where 1.0 = 1 second).
It provides greater accuracy than seconds as the estimation is done using processor time used by the program.
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <limits.h> int main() { /* clock_t clock(void) The clock() function returns an approximation of processor time used by the program. The value returned is the CPU time used so far as a clock_t, to get the number of seconds used, divide by CLOCKS_PER_SEC. On error it returns -1. */ const clock_t start = clock(); /* svoid srand(unsigned. */ /* time_t time(time_t *__timer) time() returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. If the __timer variable is not NULL, the return value is also stored there. */ srand(time(NULL)); unsigned long i; for (i = 0; i < 10000000; i++) { /* int rand(void) The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive. */ rand(); } const clock_t end = clock(); /* ISO/IEC 9899:1999 7.23.1: Components of time The macro `CLOCKS_PER_SEC' is an expression with type `clock_t' that is the number per second of the value returned by the `clock' function. */ /* CAE XSH, Issue 4, Version 2: <time.h> The value of CLOCKS_PER_SEC is required to be 1 million on all XSI-conformant systems. */ const float seconds = (float) (end - start) / CLOCKS_PER_SEC; printf("Seconds elapsed %f\n", seconds); return 0; }
|
https://bytefreaks.net/2017/03/20
|
CC-MAIN-2020-29
|
refinedweb
| 270
| 66.64
|
I am attempting to fix some XS code and have reached a point where I'm slightly confused with the output of B::PV. The XS code now does a sv_setsv(sv, 100) (it used to do a sv_setpvn) and the test code is:
use Devel::Peek;
use B qw( svref_2object SVf_IOK SVf_NOK SVf_POK );
sub is_iv {
my $sv = svref_2object(my $ref = \$_[0]);
my $flags = $sv->FLAGS;
my $x = $sv->PV;
if (wantarray) {
return ($flags & SVf_IOK, $x);
} else {
return $flags & SVf_IOK;
}
}
# code to connect to database here
$sth = $dbh->prepare(q/select a from PERL_DBD_drop_me/);
$sth->execute;
$sth->bind_col(1, \$r, {TYPE => SQL_INTEGER});
$sth->fetch; # this will do a sv_setiv($r, 100)
is($r, 100, "correct value returned SQL_INTEGER") or Dump($r);
my ($iv, $pv) = is_iv($r);
ok($iv, "ivok bind integer") or Dump($r);
ok($pv, "pv not null bind integer") or Dump($r);
[download]
The output is:
not ok 10 - pv not null bind integer
# Failed test 'pv not null bind integer'
# at t/sql_type_cast.t line 149.
SV = PVIV(0x9f81420) at 0xa1353f4
REFCNT = 2
FLAGS = (PADMY,IOK,pIOK)
IV = 100
PV = 0xa23fd88 "100"\0 # <--- should this be set?
CUR = 3
LEN = 4
[download]
I am unsure why B::PV returns undef. Could someone explain this? Thanks.
my $x = $sv->can('PVX') ? $sv->PVX : undef;
[download]
But why are you checking that?! It's equally correct for it to be present and absent.
use strict;
use warnings;
use Test::More tests => 3;
use Devel::Peek;
use B qw( svref_2object SVf_IOK SVf_NOK SVf_POK );
sub is_iv {
my $sv = svref_2object(my $ref = \$_[0]);
my $flags = $sv->FLAGS;
my $pv = $sv->can('PVX') ? $sv->PVX : undef;
if (wantarray) {
return ($flags & SVf_IOK, $pv);
} else {
return $flags & SVf_IOK;
}
}
my $r = "100";
$r = 100;
Dump($r);
my ($iv, $pv) = is_iv($r);
is($r, 100, "correct value returned SQL_INTEGER");
ok($iv, "ivok bind integer");
ok($pv, "pv not null bind integer");
[download]
Thank you for the explanation. The test is looking to see that the scalar does not look like a string because it wants to behave like a number because it was a number in the database. The test is simply ensuring the scalar was either created with sv_setiv or sql_type_cast_svpv was run on it.
Before sql_type_cast_svpv or DBDs like DBD::ODBC (here) set the scalar with sv_setiv the scalar looks like a string then you have to add 0 to all your numbers retrieved from the database before passing them to modules like JSON::XS or they will be turned into "NNN" instead of NNN. Another example was people doing select a_int, b_int from table then performing a_int & b_int which gives the wrong answer unless you add 0 to them first. See and various discussions on dbi-dev mailing list.
The test is looking to see that the scalar does not look like a string
You want SvPOK(sv) which is defined to be SvFLAGS(sv) & SVf_POK and is available as $sv->POK.
So you want $sv->PV() to return a true value while you also want PV to not be set in the Dump() output? I am going to assume that your "should this be set?" comment just gave me an incorrect impression.
DB<1> $x= 100
DB<2> Dump $x
SV = IV(0x2f10ee0) at 0x2f10ee4
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 100
DB<3> $y = "$x"
DB<4> Dump $x
SV = PVIV(0x424424) at 0x2f10ee4
REFCNT = 1
FLAGS = (IOK,POK,pIOK,pPOK)
IV = 100 # ^^^ ^^^^ These are important
PV = 0x2eeda6c "100"\0
CUR = 3
LEN = 4
DB<5>
[download]
$sv->PV() is not returning a value because your scalar isn't marked as having a valid PV value (no POK nor pPOK flags set). I don't know what $sv->PV() actually translates to in C code.
It appears that the scalar had previously been upgraded to type PVIV and Perl doesn't waste resources to downgrade it to type IV when sv_setiv() marks the IV as the only value currently in sync with the SV's value. Perl doesn't even waste time free()ing the PV's buffer or putting a '\0' character at the front of it.
You don't show enough code for me to be able to determine why the "100" string was already sitting cached (it appears) in that SV. You might want to Dump($r) in between each of your steps to gain better insights.
If you want a PV to be cached in the SV, then it looks like $sv->PV() doesn't do that work so you should use the scalar as a string before that.
- tye
Also, to explain why there was 100 already in the pv it was because a previous test (prior to the one I showed) did a sv_setpvn. Sorry, I tried to omit other stuff for brevity and in this case probably added to the confusion.
I think ikegami answered my question. I thought PV simply returned the string pointer which is really what PVX does. As such I was surprised PV was false but the scalar had a pv.
The should be set test comment was left over from the fact that another bug masked the fact that test should have failed. Now that is fixed I am expecting PV to return undef and don't care there is a pv pointer.
Lots
Some
Very few
None
Results (215 votes),
past polls
|
http://www.perlmonks.org/?node_id=971411
|
CC-MAIN-2016-07
|
refinedweb
| 895
| 73.21
|
“Diamonds are forever” — price prediction using Machine Learning regression models and neural networks..
We Buy Engagement Rings Because a Diamond Company Wanted Us To
That invention is surprisingly recent: Epstein traces its origins to the discovery of massive diamond mines in South…
The Engagement Ring Story: How De Beers Created a Multi-Billion Dollar Industry From the Ground Up
One of the biggest assets in a married couple's relationship, the diamond engagement ring, might be an emotional asset…
blog.hubspot.com
The actual value of a diamond however is determined by a gemologist after inspecting its various “features” (let’s start using the proper machine learning words now since this article is about predicting diamond price using machine learning) and applying a relative valuation principle of “compare and price”.
Learn to Calculate Diamond Prices So You Don't Get Ripped Off
The best way to ensure you get the most value for your money when buying a diamond is to educate yourself. Start by…
How to Buy Diamonds Online - The 4C's of Engagement Rings
Never commit the same mistakes that 90% of shoppers make when buying an engagement ring... to read our NO-BULLSHIT…
beyond4cs.com
But in recent years, perhaps last 2 decades, the valuation and pricing has become more or less quantitative i.e. calculations based on values of many properties not just limiting to 4Cs (carat, cut, colour, clarity). Properties like culet, pavilion, crown, girdle, girdle thickness polish, symmetry, fluorescence, table, depth and so on are the most easily identifiable and recordable features while the diamond is actually cut.
The following is a no-brainer, easy-to-follow, quickie article for newbie learners on machine learning for a Linear regression problem i.e. how to predict some number using minimal dataset at a fairly good accuracy.
Let’s begin with predicting diamond prices now.
A dataset of roughly 1500 rows is generally not a helpful one if there are tens of features. The algo would need lots of training for acceptable accuracy metrics
However, I will show very simple approaches to a complex problem which have yielded relatively good accuracy.
It’s holiday season and you can use this algorithm to predict the price of the diamond you really desire before purchasing it from the local retailer — best for a little help in negotiation.
Lets begin :
Import all basic libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inlinefrom sklearn import preprocessing
Getting the data
I will begin with training and predicting price based on dataset from Kaggle — it has basic data on more than 54000 diamonds.
Later we will train the same model and predict prices based on fresh data from pricescope.com. By fresh data, I mean the data I downloaded just few days back.
df = pd.read_csv(“diamonds.csv”)
df.drop(‘Unnamed: 0’, axis=1, inplace=True)
display(df.head(3))
The output is something like the following:
Data pre-processing
We now begin with basic data prepossessing. We first look if any null values or unexpected datatypes are present.
df.isnull().sum()
df.info()
Now we plot a Pair-plot of Price vs. 4 Cs (Carat, Cut, Color, Clarity) — the most popular and marketed properties of a diamond.
Read more about 4Cs at the following links:
4Cs of Diamond Quality by GIA | Learn about Diamond Buying | What are the Diamond 4Cs
Beautiful. Rare. Cherished. Each diamond is unique and is a miracle of time, place and change. And each has specific…
4cs.gia.edu
The 4 C's of Diamonds: Diamond Buying Guide | The Diamond Pro
Scared of getting ripped off? Don't want to waste your money? Confused by all the choices? Contact us. James Allen has…
# plot price vs. carat
sns.pairplot(df, x_vars=[’carat’], y_vars = [’price’])# plot carat vs other Cs
sns.pairplot(df, x_vars=[’cut’, 'clarity’, 'color’], y_vars = [’carat’])
plt.show()
The output is something like the following:
We can see that the properties charts reveal a lot about how and where bulk of diamonds fall under each property value e.g. most bigger diamonds (higher carat) fall in Fair cut, I1 clarity and H-I color. These are poor (commercial grade) diamonds generally sold by retail jewelry shops across the world to attract consumers with advertisements like ‘Diamonds at 50% off’
The price vs. carat chart also show that there are some outliers in the dataset i.e. few diamonds that are really over priced!
Now we need to see the distribution of the dataset. We will create a histogram plot for this. First we define the histplot function.
Now we list the continuous variables and leave out the categorical variable. A continuous variable e.g. carat is one which has numercial values whereas a categorical variable is the one with alphanumeric values as categories e.g. clarity
linear_vars = df.select_dtypes(include=[np.number]).columns
display(list(linear_vars))
Output is
[‘carat’, ‘depth’, ‘table’, ‘price’, ‘l’, ‘w’, ‘d’]
Now we plot the histogram
histplot(df,linear_vars)
This revels the distribution of each property. As expected, we see that the data is not normally distributed. After all, how can you expect a 1 carat diamond to be priced just at twice the price of a half-carat given all properties remain the same, while a 1 carat diamond looks much bigger to the eye when in a ring, or earrings for that matter, than a half carat one.
Diamond Database - Compare Diamond Shapes and Sizes
Explore diamond shapes and sizes How big is a 1 carat diamond? ... It's around 6.5mm... OK, but how big is 6.5mm…
Convert the features to log scale
- Check for any ZERO value amongst features namely table, depth, l, w, d. Check if any continuous variable has zero value. This would give a division by zero error when converting to log. Add a tiny number 0.01 to any zero value.
print(‘0 values →’, 0 in df.values)
df[linear_vars] = df[linear_vars] + 0.01
print(‘Filled all 0 values with 0.01. Now any 0 values? →’, 0 in df.values)
The output is:
0 values --> True
Filled all 0 values with 0.01. Now any 0 values? --> False
2. View and remove outliers using z-score
Since we could briefly sense some outliers in the pairplot charts, lets dwell deeper and see whether there genuinely are any outliers.
Lets first begin by printing top X values of each diamond property.
Output is like:
'sorted by carat --> [5.02, 4.51, 4.14, 4.02, 4.02]''sorted by depth --> [79.01, 79.01, 78.21000000000001, 73.61, 72.91000000000001]''sorted by table --> [95.01, 79.01, 76.01, 73.01, 73.01]''sorted by price --> [21646.459999999995, 21640.709999999995, 21626.909999999996, 21624.609999999997, 21623.459999999995]''sorted by l --> [10.75, 10.24, 10.15, 10.03, 10.02]''sorted by w --> [58.91, 31.810000000000002, 10.549999999999999, 10.17, 10.11]''sorted by d --> [31.810000000000002, 8.07, 6.99, 6.7299999999999995, 6.4399999999999995]'
From this list itself, we see that there are some outliers for w,d. Lets visualize those using boxplots.
Create a boxplot function:
Call dfboxplot to view outliers for all properties
dfboxplot(df, linear_vars)
We can now clearly visualize that there are outliers for table, w and d properties. Lets call
removeoutliers() function to remove the outliers based on z-score. There are several methods of removing outliers but I am going to follow the z-score process here since its the easiest to implement and delivers optimal results — after all, this is a no-brainer quickie article for newbie users.
For more on all other alogs to remove outliers, check these out:
Detect and exclude outliers in Pandas data frame
I have a pandas data frame with few columns. Now I know that certain rows are outliers based on a certain column value…
stackoverflow.com
Finding outliers in dataset using python
In this article, we will use z score and IQR -interquartile range to identify any outliers using python
medium.com
Now, after calling dfboxbplot again to view outliers for all properties, we see the output as:
3. Convert to log
Since we saw earlier that most features (or properties of a diamond) are not normally distributed, and one of the most favored approach, if not a prerequisite, is to use Gaussian distributed (another name for normally distributed) data.
What is the difference between Gaussian and normal distribution?
Answer (1 of 4): > What is the difference between Gaussian and normal distribution? The person who posed the above…
Gaussian distribution: Why is it important in data science and machine learning?
And how to transform your dataset to Gaussian?
medium.com
# this log converts dataframe's features inplace
def convertfeatures2log(df, listvars):
for var in listvars:
df[var] = np.log(df[var])convertfeatures2log(df, linear_vars)
histplot(df, linear_vars)
The output now is:
Convert categorical column to numerical column using labelencoder
We now have to convert all categorical columns to numerical columns using labelencoder. You may read more about labelencoder in the following webpage — quick and easy to understand description there.
First we define the
convert_catg() function to convert categorical columns to numerical columns
Next, we run the function and see the head of the dataframe.
convert_catg(df)
df.head(3)
Now is the time to start coding machine learning algorithms on this data
Divide the data into X and y
First we set X and y, where X is the matrix (or DataFrame) for all the properties (independent features) and y is the vector for output (dependent variables) i.e. diamond price.
X_df = df.drop([‘price’, ‘l’, ‘w’, ‘d’], axis=1)
y_df = df[[‘price’]] # two [[ to create a DF
Now, we determine correlations between price and all other attributes.
- I will be combining both X (already converted categorical to numerical) and y to form a new dataframe for correlation
df_le = X_df.copy()# add a new column in dataframe — join 2 dataframe columns-wise
df_le[‘price’] = y_df[‘price’].values
df_le.corr()
df_le = X_df → df_le will be like a pointer to X_df. Any change made to df_le will actually be a change to X_df. So, df_le = X_df.copy() is better
- It seems price is highly corr with carat and fairly with table, color and clarity, not much with cut
Note on Feature scaling — it seems its not needed here since we have already log the properties. Nevertheless, if I had feature scaled, then the code would have been as written below:
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()X_df = sc_X.fit_transform(X_df)
X_df[0:3]
Train Test Split
Data scientists generally split the data for machine learning into either two or three subsets: 2 subsets for training and testing, while 3 for training, validation and testing. I will talk about it in detail a bit later.
This data split prevents an algorithm from overfitting and underfitting.
I have explained overfitting and underfitting briefly in my other post here:
Machine learning interview notes (part 3 — short bullet-points)
This is a set of really concise notes with brief explanation, quick answers and python code with comments for a lot of…
medium.com
The code for train_test_split is as follows:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_df, y_df, test_size=0.3, random_state=42)
Now we will run different algorithms. Once you are really ready with your data, coding a simple Machine Learning algorithm is a cakewalk.
Let me demonstrate a few with code, output and charts.
What we will do here is:
- split the data into training set and test set.
- Train the algorithm on training set data
- Use the trained algorithm (or trained ML model) to predict prices from diamond properties in test data.
- Verify / visualize / measure the differences between predicted prices and actual prices using scatterplots, histograms, accuracy metrics etc.
Linear regression
Lets start with the simplest of all, the ubiquitous linear regression model.
- Import
LinearRegressionclass from Sci-kit learn
- Create an object of LinearRegression model
- Fit the model to X_train and y_train
- Make predictions
# Import the class from Sci-kit learn
from sklearn.linear_model import LinearRegression# Create an object of LinearRegression model
reg_all = LinearRegression()# Fit the model to X_train and y_train
reg_all.fit(X_train,y_train) # Make predictions
y_pred=reg_all.predict(X_test)
Now visualize the discrepancy of predictions vs. actual prices using scatterplot and histogram
import matplotlib.pyplot as plt
plt.scatter(y_test,y_pred)
import seaborn as sns
sns.distplot((y_test-y_pred),bins=50);
Note that this is a comparison between logarithm of prices and predictions → See the code again. It is written as
plt.scatter(y_test,y_pred) after all features were converted to logarithm using
convertfeatures2log()
This means to see actual discrepancies, we should un-logarithm it i.e. find the exponent of every price and prediction and then plot. The following code does this:
# convert prices and predictions back to exp
y_pred2 = np.exp(y_pred)
y_test2 = np.exp(y_test)
Now see the scatterplot and histogram again:
K-nearest neighbors (KNN)
Because so many API libraries exist for several machine learning algorithms, the code for all simple machine learning algorithms is straightforward.
On the lines of linear regression code, we use sklearn library for KNN algo as well.
from sklearn.neighbors import KNeighborsRegressorreg_all = KNeighborsRegressor(n_neighbors = 8, metric = ‘minkowski’, p = 2)
reg_all.fit(X_train,y_train)
y_pred=reg_all.predict(X_test)
The distplot and scatterplot for logarithmic features are as follows. You can confirm from values in x-axis and y-axis that y_test and y_pred are log here.
The distplot and scatterplot for absolute values of features are as follows. You can confirm from values in x-axis and y-axis that y_test and y_pred are NOT log here.
Support vector machines (SVM)
from sklearn.svm import SVRregressor = SVR(kernel=’rbf’)
regressor.fit(X_train,y_train)
y_pred = regressor.predict(X_test)
Below is a comparison of scatterplots of log values of features (left plot) and absolute values (right plot) of features.
As of now, we can deduce that SVM is a better option since it gives better metrics score and a better scatterplot than Linear Regression and KNN
Regression Evaluation Metrics
Here are three common evaluation metrics for regression problems:
Mean Absolute Error (MAE) is the mean of the absolute value of the errors. It is average error, the easiest to understand.
Mean Squared Error (MSE) is the mean of the squared errors. It “punishes” larger errors i.e. better in real world
Root Mean Squared Error (RMSE) is the root of the mean of the squared errors. It is popular because of its interpretability in “y” units.
from sklearn import metricsprint(‘MAE:’, metrics.mean_absolute_error(y_test, y_pred))
print(‘MSE:’, metrics.mean_squared_error(y_test, y_pred))
print(‘RMSE:’, np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
Output for SVM is :
MAE: 0.08815796872409032
MSE: 0.012811091991743056
RMSE: 0.11318609451581522
Random Forest
Random forest is one of the most popular algorithms in most use cases / projects across industries. Its fast, easier to implement, needs lesser data, doesnt require extensive training and produces almost equally good results.
Again, because so many API libraries exist for several machine learning algorithms, the code for all simple machine learning algorithms is straightforward.
from sklearn.ensemble import RandomForestRegressorrf = RandomForestRegressor(n_estimators = 10)
rf.fit(X_train,y_train)
y_pred = rf.predict(X_test)
Now the metrics and their outputs
MAE: 0.08413000449351056
MSE: 0.012880789432555585
RMSE: 0.1134935655997977
It turns out that Random Forest is similar to the far slower SVM.
The big daddy — Artificial neural networks
Generally neural networks or ANNs are more suited for classification problems requiring lots of complex logic / decision making and huge computations. They require larger datasets for their optimization to get the benefit of generalization and nonlinear mapping. But, if there’s not enough data, a plain regression model may be better suited despite a few nonlinearities.
However, just for sake of completeness, I will show you how to predict diamond price (a regression problem) using ANNs.
You can read more about whether Neural networks are really needed for regression problems or not in the following webpage.
Neural Networks for Regression (Part 1)-Overkill or Opportunity? - MissingLink.ai
Regression models have been around for many years and have proven very useful in modeling real world problems and…
missinglink.ai
And for ANN, the best, fastest and easiest to use and code library is Keras. Read more about Keras at their official website:
Home - Keras Documentation
Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or…
keras.io
The step-wise process for creating an ANN is:
- Construct, compile and return a Keras model, which will then be used to fit/predict.
- Predict diamond prices
- Evaluate the model using metrics between ypred vs. ytest
Firstly import the libraries for our project:
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import RMSpropfrom keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
Next, we construct a
baseline_model() function to create and return a Keras model
- Then, we run the
KerasRegressor()function, which returns a baseline ANN model built in Keras. It takes as input the model, epochs and batch-size. An epoch defines the number of times the learning algorithm will work through the entire training dataset to update the weights for a neural network. An epoch that has one batch is called the batch gradient descent learning algorithm. For batch training, all of the training samples pass through the learning algorithm simultaneously in one epoch before weights are updated. The batch size is a number of samples processed before the model is updated.
- More information on
KerasRegressorcan be found at Tensorflow website:
tf.keras.wrappers.scikit_learn.KerasRegressor | TensorFlow Core r2.0
Educational resources to learn the fundamentals of ML with TensorFlow
- Thereafter, we run the
KFold()function. K-Fold Cross Validation uses a given data set, splits it into a K number of folds where each fold is used as a testing set while other K-1 are used as training set. For example, for 10-Fold cross validation (K=10), the dataset is split into 10 folds. In the first iteration, the first fold is used for validation while the 9 remaining folds form the training set. In the second iteration, 2nd fold is used as the testing set while the rest serve as the training set. This process is repeated until each fold of the 10 folds have been used as testing sets.
- Subsequently, the cross_val_score function takes the model, X and y, and kfold’s result as inputs and outputs multiple results — a list of regression model metrics scores. The
cross_val_scorefunction splits the data, using
KFoldas described above, into K pieces, trains on each combination of K-1 folds and gives back the metrics of the model.
estimator = KerasRegressor(build_fn=baseline_model, epochs=10, batch_size=5)kf = KFold(n_splits=5)
results = cross_val_score(estimator, X_train, y_train, cv=kf)
print(“Results: %.2f (%.2f) MSE” % (results.mean(), results.std()))
Brief information and steps on
KFoldand
cross_val_scorecan be found in my other post; link below.
Machine learning interview notes (part 3 — short bullet-points)
This is a set of really concise notes with brief explanation, quick answers and python code with comments for a lot of…
medium.com
Finally, we fit the estimator to our training data to get predictions.
estimator.fit(X_train, y_train)
y_pred = estimator.predict(X_test)# Plot a scatter plot like above to see prediction perfection
plt.scatter(y_test,y_pred)
The scatterplot output for log(features) is as below. It turns out that it is not as bad as we expected when I said that ANNs are mostly used for classification, not regression.
Predictions on Pricescope data
Now we start the process of diamond price predictions using roughly 1500 rows of Pricescope diamonds data.
Assuming all the libraries are already imported, as shown in the beginning of this article.
Get Pricescope data
WELCOME TO PRICESCOPE | PriceScope
Pricescope is the premier diamond and jewelry community on the Internet. With over 79,000 registered users and over…
An excerpt from the website itself:
Pricescope is the premier diamond and jewelry community on the Internet. Visitors to Pricescope find clear and concise tutorials from industry experts and have their questions answered by knowledgeable forum members. The majority of consumers go online to learn about diamonds, while 90% buy diamonds from brick and mortar shops. Pricescope exists to help consumers get the best value online or in-store.
Take your time to digest all that’s mentioned above. Copy the code and run on your machine / cloud. The rest of the story specific to generating predictions using PriceScope and CaratLane data is shown in the following post.
Diamonds are forever” — Diamond price prediction on PriceScope and CaratLane diamond listings
Continuation story of Diamond Price Prediction using ML
medium.com
References
For this particular post, I have referred to several websites including Beyond4Cs, Machine Learning Mastery and others few posts and websites on internet.
About Me
I work in IT projects side of an Investment bank. I have 15 years of experience in building production ready applications in Front-office Trading and for the last 3 years in Machine Learning, NLP, NER, Anomaly detection etc.
Over the course of my career in Artificial Intelligence and Machine Learning, I studied various medium / hackernoon / kdnuggets posts; took various courses on Coursera, Udemy, edX; watched numerous YouTube videos.
I believe gaining all this knowledge gives you a real boost in confidence and gets you ready for the next challenge in life.
However, even years of study and experience (projects), one can hardly know even 1% about the area of AI ML.
It is possibly as vast as the universe, ever-evolving and explored by humans not even at the level of an iceberg tip.
Feel free to connect with me on LinkedIn or follow me on Medium
|
https://groverjatin.medium.com/diamonds-are-forever-price-prediction-using-machine-learning-regression-models-and-neural-f4f54b5fcf7f?source=post_page-----f4f54b5fcf7f--------------------------------
|
CC-MAIN-2021-31
|
refinedweb
| 3,641
| 55.95
|
import "go.chromium.org/luci/common/isolatedclient"
Package isolatedclient implements the API to communicate with the Isolated server and to process '.isolated' files.
doc.go flags.go isolatedclient.go
DefaultNamespace is the namespace that should be used with the New function.
Client is a client to an isolated server.
func New(anonClient, authClient *http.Client, host, namespace string, rFn retry.Factory, gcs CloudStorage) *Client
New returns a new IsolateServer client.
'authClient' must implement authentication sufficient to talk to Isolate server (OAuth tokens with 'email' scope).
'anonClient' must be a functional http.Client.
If either client is nil, it will use http.DefaultClient (which will not work on Classic AppEngine!).
If you're unsure which namespace to use, use the DefaultNamespace constant.
If gcs is nil, the defaultGCSHandler is used for fetching from and pushing to GCS.
The hashing algorithm used depends on the namespace.
func (i *Client) Contains(c context.Context, items []*isolateservice.HandlersEndpointsV1Digest) (out []*PushState, err error)
Contains looks up cache presence on the server of multiple items.
The returned list is in the same order as 'items', with entries nil for items that were present.
Fetch downloads an item from the server.
Hash returns the hashing algorithm used for this client.
Push pushed a missing item, as reported by Contains(), to the server.
func (i *Client) ServerCapabilities(c context.Context) (*isolateservice.HandlersEndpointsV1ServerDetails, error)
ServerCapabilities returns the server details.
type CloudStorage interface { // Fetch is a handler for retrieving specified content from GCS and storing // the response in the provided destination buffer. Fetch(context.Context, *Client, isolateservice.HandlersEndpointsV1RetrievedContent, io.Writer) error // Push is a handler for pushing content from provided buffer to GCS. Push(context.Context, *Client, isolateservice.HandlersEndpointsV1PreuploadStatus, Source) error }
CloudStorage is the interface for clients to fetch from and push to GCS storage.
Flags contains values parsed from command line arguments.
Init registers flags in a given flag set.
Parse applies changes specified by command line flags.
PushState is per-item state passed from IsolateServer.Contains() to IsolateServer.Push().
Its content is implementation specific.
type Source func() (io.ReadCloser, error)
Source is a generator method to return source data. A generated Source must be Closed before the generator is called again.
NewBytesSource returns a Source implementation that reads from the supplied byte slice.
Package isolatedclient imports 20 packages (graph) and is imported by 22 packages. Updated 2019-10-14. Refresh now. Tools for package owners.
|
https://godoc.org/go.chromium.org/luci/common/isolatedclient
|
CC-MAIN-2019-43
|
refinedweb
| 397
| 53.58
|
00001 /* challenge.h --- Generate a CRAM-MD5 challenge string. 00002 * Copyright (C) 2002 GNU SASL Library; if not, write to the Free 00018 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 00019 * Boston, MA 02110-1301, USA. 00020 * 00021 */ 00022 00023 #ifndef CHALLENGE_H 00024 #define CHALLENGE_H 00025 00026 #define CRAM_MD5_CHALLENGE_LEN 35 00027 00028 /* Store zero terminated CRAM-MD5 challenge in output buffer. The 00029 CHALLENGE buffer must be allocated by the caller, and must have 00030 room for CRAM_MD5_CHALLENGE_LEN characters. Returns 0 on success, 00031 and -1 on randomness problems. */ 00032 extern int cram_md5_challenge (char challenge[CRAM_MD5_CHALLENGE_LEN]); 00033 00034 #endif /* CHALLENGE_H */
|
http://www.gnu.org/software/gsasl/doxygen/challenge_8h_source.html
|
CC-MAIN-2015-22
|
refinedweb
| 102
| 65.83
|
Great! Will place it in the Demo directory. Now all I need is an
application for threads :-)
> BUG: The attached module worms around this, but the following self-
> contained little program usually freezes with most threads reporting
> [Example using "import" in a thread, followed by correct analysis of
> what goes wrong]
>
>>.
Can't we agree that the user is responsible for this? It would be
simple enough (and a more common programming style in any case) to
import the needed modules in the main thread. After all, ANYTHING
that modifies global variables and doesn't know about threads should
be serialized by the caller. Only the most basic operations are
guaranteed to be atomic -- to be exact: everything that is one
instruction of the Python Virtual Machine and does not call other
Python code.
--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
URL: <>
|
https://legacy.python.org/search/hypermail/python-1994q2/0614.html
|
CC-MAIN-2021-43
|
refinedweb
| 145
| 59.74
|
User Details
- User Since
- Oct 23 2018, 12:36 AM (37 w, 6 d)
Jan 16 2019
Any news on this?
Dec 18 2018
Right, that looks better indeed :)
Nov 28 2018.
Nov 27 2018
I have updated the patch according to the comment.
Nov 25 2018
I have added static and shared library tests
(there still needs to be work on the test part)
I'll update the diff according to the comments.
Nov 19 2018
Here is the test for realpath extension fixed.
Nov 18 2018
(I can't commit this myself)
I have added a few checks (the ld.so dynamic linker specification, the ../lib32 paths, and /usr/lib/i386-gnu)
Nov 17 2018
I believe this version handles all the comments.
I could run this with check-all on a linux-amd64 box.
In general when structuring your code, the performance penalty for other targets when the conditions that can be easily tested are not met should pretty much be close to nonexistent. I would suggest keeping that in mind when submitting revisions.
Nov 12 2018
Doesn't APPLE imply MACH anyway outside of targets that are way out of scope of libc++?
I have dropped the endif comment as requested.
Nov 11 2018
This includes version finding the gcc Hurd triplet (i[3456]-gnu) in the Gcc detector.
So we are back with this.
In this version, the Driver introduces the "-hurd-" part
(I can't commit this myself)
Nov 10 2018
i386-pc-hurd-gnu is fine as is, however, it seems that you want to be able to use i386-pc-gnu from Clang, if I understand correctly.
Or perhaps at least keep a Triplet::isOSHurd() which does the hurd-specific triplet parsing, instead of adding a function to clang to be used wherever we want to check for that?
I'm not sure to understand: do you mean to drop this patch entirely, so that llvm considers i386-pc-gnu as just a GNU-ish platform, and then Driver::getToolChain should special-case the Triple::UnknownOS and parse Triple::getTriple itself to call the Hurd code instead of the default toolchains::Generic_GCC case?
(as expected, I could run make check-all fine on an x86_64 linux host)
Perhaps we could go this way with additional code in cmake/config-ix.cmake, to get "hurd-gnu" as soon as possible just after detection and keep everything else inside llvm straight with llvm conventions?
Ah, right, sorry, done so now.
Well, that's what I did the in the latest version?
For sure I consider that not breaking anything on other archs is a must :)
I'm getting an immense amount of errors, did you run make check-all on this patch?
if people forget the OS part, for example, write "target-gnu" instead of "target-linux-gnu".
not supporting Hurd at all (which is not that big of a problem, I get it :).
I commented one of them, and will fix the rest.
I understand your concerns, but that's really not something that we can change at this point, there is far too much software which has written i386-pc-gnu in their source code for us to change all that.
The Hurd::Hurd constructor would actually need to do the same gcc inclusion path detection as on Linux, but let's leave this aside for now, this commit is enough for a build without libc++.
(I can not commit this myself)
The GNU/Hurd triple is target-gnu, simply.
So that'd be it? I don't know if libcxx supports more than free/net/open bsd and apple ?
Nov 9 2018
Nov 6 2018
(I cannot commit this myself)
Here it is
Nov 3 2018
Oct 23 2018
(I can not commit this myself).
|
https://reviews.llvm.org/p/sthibaul/
|
CC-MAIN-2019-30
|
refinedweb
| 634
| 78.38
|
Search the Community
Showing results for tags 'mac'.
Found 21
Hersir posted a topic in Questions & AnswersHi, does anyone have problems with new playground on mac safari browsers? Every time I click run scene just disappears.
Skeptron posted a topic in PhaserHi everyone, I'm having some weird issues with Safari on Mac : it seems like using the arrow keys in combination with A messes up the keyboard language. I have a french keyboard (azerty), and if I press A, no issue, A is triggered. If I press the right arrow + A, the A becomes a Q. Is that a known issue? Is anyone having the same issue? Is there something wrong with the way I handle the keys? Here is a JSFiddle to illustrate the issue (open the console to see the logs) : Thanks a log guys!
AlbertTJames posted a topic in BugsHey, I just upgraded to OSX Sierra and this bit of code does not work anymore on chrome : /* --- Skybox --- */ var skyboxObject = BABYLON.Mesh.CreateBox("skyBox", 10000.0, scene); var skyboxMaterial = new BABYLON.StandardMaterial("skyBox" + sceneKey, scene); skyboxMaterial.backFaceCulling = false; skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture(taskObject.ASSETS_FOLDER + "/textures/fantasy/Sky", scene, ["_px.png", "_py.png", "_pz.png", "_nx.png", "_ny.png", "_nz.png"]); skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE; skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0); skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0); skyboxObject.material = skyboxMaterial; skyboxObject.rotation.x = Math.PI; I get this : Only one side of the cube. No error in the console. I will try to get more information on this, I have been swamped these past few days... sorry. This bug is not present in safari.
Jacob Sam posted a topic in Coding and Game DesignWhat is the best tool for mac to handle sprite sheets ? I need one that i am able to replace sprites of a spritesheet easily... Does not matter if its paid or free...Thanks in advance.
PeapBoy posted a topic in BugsHi guys ! I just spotted what I think is a bug (or rather a compatibility issue). Here is a *very* simple PG : It only prints the depth map on a plane. Here is a screenshot of the PG with Chrome 52 on Windows 7 : Here is a screenshot of the PG with Safari on an Ipad (iOS 9.2.1) : As you can see, no depth map with Apple, the plane is totally black (or gray with the light here). Maybe are you aware of this issue ? (do I hope too much ? ) Is there a WebGL restriction I don't know with Apple ? I had the chance to run the PG on different Macs and iPhones (different versions also), and the issue appears on every Apple device. I don't own any Apple devices but I can make tests at work if you need them. I would be glad to help if I can. PS: I make some tests and it looks like a simple render target texture with a shader material which computes the depth could work. And it seems like the RTT of the depthRenderer has a lot of different properties than the basic RTT I made.
Gorpomon posted a topic in PhaserHi all, I'm making a game in phaser and it is making my mac run very hot. I'm looking to find out what might be the cause. I noticed the first time it happened was when I made a shooter game that did not cache bullet objects, but instead just created new ones. After maybe 20 refreshes the game was causing my mac to run very hot (so much that you wouldn't want it on your lap). I fixed that and it cooled down. The second time was when I was logging 'this' in an update function, which I don't think should result in that but it was. Outside of not reusing objects what else can be a really big memory/processor suck in your game?!
Kingmarc77 posted a topic in Questions & AnswersHere:
RichardN posted a topic in Questions & AnswersHi, I'm new to Babylon.js and to this forum, so perhaps I am missing something obvious. The documentation on PBR has an image of beautiful materials with different glossiness and reflectivity values. But when I run the demo Playground Demo Scene - PBR Materials in my browser (Safari or Chrome, on a Macbook Pro), the materials look much less impressive. For low glossiness and reflectivity values, the spheres don't look "rough" with a lot of light scattering. Instead I can clearly see the edges of the skybox. See attached screenshot, the spheres in the top right corner. Why is this happening? Is it my hardware? Did something change in the source code since the picture was taken? Thanks! [Edit] complete specs: Chrome Version 48.0.2564.116 (64-bit) and 49.0.2623.87 (64-bit) Safari Version 9.0.3 (10601.4.4) MacBook Pro (Retina, 13-inch, Early 2015) Intel Iris Graphics 6100 1536 MB 2,7 GHz Intel Core i5 8 GB 1867 MHz DDR3
shooter
hit2501 posted a topic in Questions & AnswersHi everybody! I did a configurator for prefabricated houses: It works fine on Chrome for Windows, Firefox and Safari but the drag and drop function its not working on Chrome for Mac. Here is a video where you can check how it works on other browsers: Here is a video with the errors: I had the same issue in Internet Explorer but I fix it (just for IE) changing: src = evt.dataTransfer.getData ("text / plain"); for: src = evt.dataTransfer.getData ("text"); but on Chrome for Mac this only let me put the first model of window and first model of door (other windows, doors, color function, roof function dont work). I asked a friend in other country to prove it because I dont have mac equipment (its hard to find in my country). How can I fix the drag and drop function for Chrome for mac? Thank you all in advance.
hit2501 posted a topic in Questions & AnswersHi everyone! I'm trying to make a house configurator, the problem that I have is not working properly on mac. You can see a preview version of the configurator in: And it works fine on Windows (Chrome & Firefox) as seen in this video: But as in my country it is not very easy to access Mac equipment I asked a friend (in other country) to try it in mac but the drag n drop function does not work, you can check the mistakes in this short videos: Can someone tell me what I should correct to make it work properly on any desktop? Thank you very much to all.]
Acid posted a topic in PhaserHi, I noticed today while developping that when you press mac's cmd + directional arrow keyboard shortcut on a game where the arrow keys are binded, the command will repeat itself for a while (probably due to the original cmd + arrow function of moving the cursor to the end of the line), i first noticed it on my project, but it also happened on the website's examples as well. I dont know if this applies to window's ctrl + arrow as well, i haven't tested it yet. I did some research here on the forums and found nothing (perhaps i searched wrong), is this behavior normal? Is it possible to avoid it? (Other that not binding events to the arrow keys)
Guedez posted a topic in PhaserI am making a typewritter game in portuguese using phaser, and some words have accents, like café or água. The problem is, whenever someone tries to type an accented letter, such as á, phaser only captures 'a', completelly ignoring the accent before, since accents are typed as ´a. Accents for some reason don't get captured, like ´ or ~ before an letter, so I can't even build an table like 'if there was a ~ before an a, then replace with ã'. I don't know how to know when an accented letter was typed on mac, I need help I am using this: game.input.keyboard.addCallbacks(game, undefined, undefined, function (key) { if (game.typer) { game.typer.typed(key); } console.log("phaser: " + key); game.data.toConsume.push(key); });and also attempted to use: window.addEventListener('keypress', function (event) { var key = event.keyCode || event.which; console.log("press: " + key + ", " + String.fromCharCode(key)); event.preventDefault();});window.addEventListener("keydown", function (e) { var key = event.keyCode || event.which; console.log("down: " + key + ", " + String.fromCharCode(key)); if (e.which === 8) { e.preventDefault(); }});keydown event sometimes would capture some crazy thing rather than an accent, however, if the accent were to be accessed via 'shift + 6' for instance, I would only know that 6 was pressed, but not what 'shift + 6' means
Sphearis posted a topic in Game ShowcaseHi everyone, I'm from Belgium and making games in my free time(with a full time job and 2 kids). This is one of the first official game I made. It's available on android/PC/Mac(links below). It's totally free and will be updated with new "servers". In short, you work for The Agency and they provided you with a hacking device, you must learn to use it (user manual included) and connect to servers to discover the truth behind the disappearance of scientists from a powerful organization. The game is easy to pick up but decoding all messages will take time. There are achievements and leaderboards on Google play games services. This game has been made mainly with construct 2 and cocoonjs. If you have any question about the development, I'm available. Please enjoy and send me your feedback. Fabrice from Studio Nonante. Welcome to the Agency, You have been chosen to be a part of one of our most important investigation. Several scientists at Venntech disappeared these past few weeks, they were working on top-secret experiments and we don't know what happened to them or what they were working on. For this purpose, we've sent you a brand new hacking device: the SD90. Use it to decode messages they were exchanging before they vanished. As this task is crucial for the Agency, you and other agents will be competiting for the position of worldwide best agent. Good luck! - Innovative MATH PUZZLE, very ADDICTIVE with a lot of replay value. - DECODE the messages and discover the MYSTERIES around the Venntech company and its borderline scientific experiments. - The SD90 is a brand new DEVICE in your hands, complete with his user's manual. Learn to use it and to master it! - Decode messages by using operators on DECIMAL and HEXADECIMAL numbers. Hexadecimal numbers is an exclusivity in the world of mathematical games on mobile, this game will allow you to think differently and to learn how to do calculations more easily in that numeric system. - Worldwide LEADERBOARDS and ACHIEVEMENTS with the Google Play Games service. - MORE servers will be available soon. The perfect game for brainiacs, easy to play but still a great challenge. Here are the links: Android: Linux 32: ... HHH_65GP-4 Linux 64: ... MbAqDWWBoQ MacOSX: ... eMrzY7jR0w Windows: ... Zatbn5fdE4
rcolinray posted a topic in PhaserHi all, I you use the Dash app for Mac OS X to download and read documentation, then you might be interested in the Phaser Docset that I just created. Information on how to download the Docset can be found here. The Docset is very basic in its current state. It has entries for each class in the Phaser namespace and nothing else. In the future, I plan on adding entries for constructors, properties, and methods.
MikeA posted a topic in 2DWebCode is a vector drawing app for Mac that generates JavaScript+Canvas, CSS+HTML or SVG code.
|
http://www.html5gamedevs.com/tags/mac/
|
CC-MAIN-2017-26
|
refinedweb
| 1,961
| 64.91
|
import "github.com/elves/elvish/pkg/diag"
Package diag contains building blocks for formatting and processing diagnostic information.
context.go doc.go error.go pprint_error.go range.go
Complain prints a message to stderr in bold and red, adding a trailing newline.
Complainf is like Complain, but accepts a format string and arguments.
PPrintError pretty-prints an error. It uses the PPrint method if the error implements PPrinter, and uses Complain to print the error message otherwise.
type Context struct { Name string Source string Ranging // contains filtered or unexported fields }
Context is a range of text in a source code. It is typically used for errors that can be associated with a part of the source code, like parse errors and a traceback entry.
NewContext creates a new Context.
PPrint pretty-prints a SourceContext.
PPrintCompact pretty-prints a SourceContext, with no line break between the source position range description and relevant source excerpt.
Error represents an error with context that can be pretty-printed.
Error returns a plain text representation of the error.
PPrint pretty-prints the error.
Range returns the range of the error.
Ranger wraps the Range method.
Ranging represents a range [From, To) within an indexable sequence. Structs can embed Ranging to satisfy the Ranger interface.
Range returns the Ranging itself.
Package diag imports 6 packages (graph) and is imported by 7 packages. Updated 2019-12-23. Refresh now. Tools for package owners.
|
https://godoc.org/github.com/elves/elvish/pkg/diag
|
CC-MAIN-2020-16
|
refinedweb
| 236
| 60.31
|
Functional Web Services Testing Made Easy with SoapUI - Part 3.
The project we will use is the famous PetStore from Sun’s BluePrints. We will use JPA (with Toplink) for the persistence tier and session beans for the business tier; by adding simple annotations we will publish these session beans as web services. This project has no front end. It will be deployed to the JEE reference app server GlassFish. This is a prototype written for this series in less than an hour using the NetBeans IDE. However, we will pass over the details of project creation in favor of keeping our eyes on the prize: using SoapUI and Ant, generating JUnit reports, integration with CI, and code coverage.
package com.stelligent.biz.ws;
import java.util.Collection;
import javax.ejb.Remote;
import com.stelligent.ent.jpa.Account;
/**
*
* @author msubbarao
*/
@Remote
public interface AccountManager
{
public Account create(Account info);
public Account update(Account info);
public void remove(Account info);
public Account[] findAllAccounts();
public Account findByUsername(String username);
}
Implementation Class for Account Manager with annotations for web services:
package com.stelligent.biz.ws;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.persistence.*;
import com.stelligent.ent.jpa.Account;
import java.util.*;
/**
*
* @author msubbarao
*/
@WebService(name="AccountManager", serviceName = "AccountManagerService", targetNamespace = "urn:AccountManagerService")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@Stateless(name="AccountManager")
public class AccountManagerBean implements AccountManager
{
@PersistenceContext
private EntityManager manager;
@WebMethod
public Account create(Account info)
{
this.manager.persist(info);
return info;
}
/**
* Updates the Account entity.
*
* @param info the Account object used to update.
* @return the info object.
*/
@WebMethod
public Account update(Account info)
{
return this.manager.merge(info);
}
/**
* Removes the Account entity.
*
* @param info the Account object used to update.
*/
@WebMethod
public void remove(Account info)
{
this.manager.remove(this.manager.getReference(Account.class, info.getUserid()));
}
/**
* Retrieves all the Account entities as an array.
*
* @return the objects as a Account array.
*/
@WebMethod
public Account[] findAllAccounts()
{
Query query = this.manager.createQuery("SELECT o FROM Account o");
java.util.List<Account> accounts = new java.util.ArrayList<Account>();
java.util.Iterator<Account> iter = query.getResultList().iterator();
while (iter.hasNext())
{
accounts.add(((Account) iter.next()));
}
return (Account[]) accounts.toArray(new Account[accounts.size()]);
}
/**
* This method retrieves the Account entity info using the primary key.
*
* @param username the String
* @return the object as a AccountInfo or null if not found.
*/
@WebMethod
public Account findByUsername(final String username)
{
try
{
return (Account) this.manager.find(Account.class, username);
}
catch (Exception e)
{
return null;
}
}
}
Let’s consider each of these in more detail.
1. SoapUI and Ant
SoapUI provides command line tools to run various tests. To run the functional tests, we need to use the com.eviware.soapui.tools.SoapUITestCaseRunner class, which takes the path to the SoapUI project file containing the tests and a number of options:
Since the runner runs from the command line, we will use the exec task in Ant. SoapUI comes with scripts based on the operating system you installed it on, testrunner.bat or testrunner.sh. (If you are using a Windows machine and your build machine is using a different operating system, for example UNIX, you will need to make changes to this script.)
Let’s begin by writing out what we need to add to the Ant build file to run these functional tests on a Windows machine. We need to define a target that will run the tests; for clarity, we will also specify properties that will clarify the meanings of the file locations specified:
a. Specify the properties for SoapUI location and the project file
<property name="soapui-location" location="C:\\Program Files\\eviware\\soapUI-1.7.6\\bin"/>
<property name="soapui-project-xml-location" location="Weather-soapui-project.xml"/>
b. Define a target to run the functional tests.
<target name="run-soapui-tests" description="runs all functional SoapUI tests">
<exec dir="${soapui-location}" executable="cmd.exe" failonerror=”true”>
<arg line="/c testrunner.bat -j -f${reports} -r -a ${soapui-project-xml-location}"/>
</exec>
</target>
At this point, we will open a command window and run the soapui-tests. The output is:
2. JUnit Reports
Adding the -j switch in the Ant task arg above produces XML reports. SoapUI maps TestSuites to report-packages and TestCases to report TestCases. The XML reports generated from the Ant task can be further transformed using the junitreport Ant task:
<target name="generate-report" description="creates JUnit-compatible xml reports">
<junitreport todir="${reports}">
<fileset dir="${reports}">
<include name="TEST-*.xml"/>
</fileset>
<report format="frames" todir="${reports}\\html"/>
</junitreport>
</target>
This produces output like this:
3. Integration with CI
Continuous integration is all about compiling, testing, inspecting, and deploying to your application server at each commit. The benefit of CI is simple: when you build software often, you will find code defects early. A lot of CI servers are available, both open source and commercial. Hudson is an open source CI server with a very simple set up, just three steps (yes you heard me right, just three steps):
a. Download the latest version of Hudson.
b. Open a command window and type java -jar hudson.war
c. Open up a browser and go to the url
That’s all you need to get the CI server up and running in less than two minutes. You can read more about configuring Hudson and downloading all the plugins and much more at the link here.
As we will now see, it’s very easy to run the functional tests we wrote in this series once we deploy our application to a server. If all the tests run, the build file will generate JUnit reports; these reports can be integrated within our CI dashboard. If any of the tests fail, we fail the build, using the failonerror attribute of the Ant task. Based on how CI has been set up, everyone in the team can receive an email or a text message should the build break.
Let’s take a look at how we run these functional tests and integrate them with CI:
Once you have Hudson installed and running, you must add your projects to Hudson as Jobs for it to monitor these projects. We are going to create a single job which runs at midnight.
1. Go to the Hudson main page, and click New Job. This will open a page as such:
2.Enter a descriptive name since this is the name which will be displayed on the Hudson dashboard. Select the "Build a free-style software project". Click the OK button and you’ll be presented with yet another screen
3. In this screen, select your source code management. You will be presented with a detailed screen based on your SCM. Fill in all the details. Hudson needs all this information to checkout all the source code assets to build the project.
4. Hudson can be configured to build your project on a scheduled basis, or periodically. In our case the job needs to run at midnight. So, here are the changes needed to run the job on a nightly basis.
5. Next step is to configure Hudson to properly build our project using Ant. As you can see from the image above, Hudson provides many ways for building your project. In the PetStore case, I am setting up some environment variables and therefore using a simple batch file.
6. In the Post-Build Actions section, we will select the Publish JUnit test result report option. We are generating the JUnit reports from SoapUI. Specify a location for where Hudson can find the XML files that JUnit produces when run through Ant.
7. Now, that we have Hudson setup. we will force the build. This will cause Hudson to checkout all the source code artifacts from SCM, and initiate a build. In my case the build failed; reason being SoapUI generates the JUnit reports with no package name, Hudson complains about the same and throws a NPE. A possible workaround to publishing the JUnit reports, is to use the Achive the artifacts option in Post-build Actions. Here are the Hudson screenshots and the output:
Hudson console output:
4. Code Coverage using Cobertura
There are many open source tools available to identify line and branch coverage. By using these, you can find areas in your test code that need more tests. In most cases, when a developer checks in something, the commit build runs, which in turn runs the unit tests and some integration tests. A secondary build, often run at night, can instrument your code for code coverage reporting, deploy to the application server, and run the available tests. This will create a detailed report that the team can see first thing in the morning.
Cobertura is a code coverage analysis tool for Java. You can use it to determine what percentage of your source code is exercised by your unit tests. Cobertura adds instrumentation directly to the bytecode and is easy to integrate with Apache Ant. It comes with its own Ant task definitions for you to use.
The steps to follow here are simple:
1. Change the build file to instrument the code. Here are the changes we need in the build file to instrument our source code:
<target name="instrument" depends="compile">
<cobertura-instrument
<fileset dir="${classes.dir}">
<include name="**/*.class" />
</fileset>
</cobertura-instrument>
</target>
2. Deploy the instrumented code to GlassFish. Once the code is instrumented, deploy it your application server. The ant task provided here is for GlassFish V2 application server.
<target name="gf2-deploy-ear" depends="instrument">
<echo message="Deploying webservices-samples"/>
<taskdef name="sun-appserv-deploy" classname="org.apache.tools.ant.taskdefs.optional.sun.appserv.DeployTask"
classpath="${GLASSFISH_HOME}/lib/sun-appserv-ant.jar" />
<sun-appserv-deploy
</target>
3. Generate a report. Cobertura stores coverage information to a file called cobertura.ser. Using the report task, Cobertura can generate coverage reports in either HTML or XML format.
<target name="coverage-report" depends="run-soapui-tests">
<cobertura-report
<cobertura-report
</target>
5. Integrate these reports with Hudson using the Cobertura plug-in.
Installing a Hudson plug-in is as simple as installing Hudson. Download the latest version of the plug-in from here,
click the Manage Hudson link from Hudson's homepage. Next, click the Manage Plugins link, where you can upload the plug-in archive file. Once the plug-in has been installed, you'll have to restart Hudson. If everything goes well, you should be able to see a screen like:
Once you have downloaded and installed the cobertura plug-in, you need to configure your Job to use the reports generated. Click configure on PetStore_Nightly Job, this will display the Job configuration. Choose Publish Cobertura Coverage Report, and provide the file name pattern that can be used to locate the cobertura xml report files.
6. Finally, lets force a build and see the results.
PetStore Dashboard:
Cobertura Coverage Report in Hudson:
Since we also generated the HTML reports for cobertura within the Ant task, we can take a look at these as well:
P.S: I should mention that when deploying instrumented code using cobertura to an application server, cobertura doesn't update the data file unless the application server is shutdown. So, I used the same workaround as mentioned in the cobertura web site, instead of stopping and starting the server each and every time. I placed the following code in one of the Session Beans, published this as a web service, added a test case for this method and this was the last test case called within SoapUI.) {
}
In this part, you learned about the Ant tasks for running tests written using SoapUI, generating JUnit reports, integrating with CI, and getting code coverage using Cobertura. I've used some popular open source tools like Ant, Hudson, Cobertura and showed you how easy it is to set up a CI environment using these tools and run functional tests for your web services written using SoapUI.
You can go ahead start building web services with great confidence! Enjoy.
|
https://dzone.com/articles/functional-web-services-testin-1?mz=62823-enterprise-integration
|
CC-MAIN-2015-35
|
refinedweb
| 2,006
| 57.77
|
, MS Exchange has been attacked so many times over the years that it would be stupid to let it just sit out on the internet. Same goes for Microsoft DNS server. I would try as hard as I could to never put a Microsoft Server out on the Internet, or even allow a Microsoft to directly service the Internet. It’s just too risky, and I don’t play dice in certain situations such as these. I would, however, make an exception for hosting an Internet Information Services (IIS) Web Server. There are easy ways to lock down IIS and the OS, perform secure code reviews on the website itself, put reverse proxies in front of the web server (Apache Mod_Security or DotDefender)… the list goes on.
But this isn’t a blog about web services. This blog is about setting up a secure Debian Server to host out a Bind9 DNS server and a Postfix reverse email Proxy. And this really could be split up into two different blogs, but I really think that they belong together because of how intertwined Email services are with DNS. Without DNS, mail would be significantly more difficult. But, DNS is also the problem with a LOT of SPAM. DNS configured improperly causes much of the SPAM that gets through to be seen by end users. Also, with DNS and Postfix running on the same box, the services are speedier and more responsive. We’ll do our best, but I really hope I can just refer people to this setup, because I truly believe that if more people would secure their mail servers and setup DNS properly, we could easily stop MOST SPAM that is out on the Internet from making it to Inbox’s around the world.
And this will be a nice, really long, blog… strap in, people, we’re in for a ride! 🙂
First things first, we need to start with a fresh install of Debian server. The main reason why I choose to go with Debian server is that:
- First, it’s exceedingly stable and secure right out of the box. Very little configuration is needed…
- Second, the creators of Debian don’t make tons of changes and they aren’t on the bleeding edge of new technologies.
- Third, Debian is super easy to use and the software we need is also super easy to install
- Lastly, especially for virtualized environments, a full install, using my method, takes a minimum of 512MB RAM and 1.5GB HDD space.
I want to let everyone know here, that whatever I post on my site is things that I truly believe in. The main reason why I believe this process to work so well is that I’ve seen it in action at past employers, I’ve seen the MASSIVE cost savings past on to our customers, and because of all that I’ve implemented this exact same process at home. So basically, I eat my own dog food. I’m not going to tell you all to do something that is in secure or full of shit. My email server is already receiving emails through this Postfix Proxy, my domains are hosted off of this BIND9 server, and, if I may say, it’s ALL working beautifully.
A good friend of mine, Nick (I’ll leave out his last name until he says it’s okay to mention him here), was the one who inspired me to get much of this stuff going. I worked with him at a past employer and showed me much of this stuff. Regardless, what I’m trying to get to here is, just the way that we have things setup now is pretty damn good. I have one domain passing all of my mail to a DMZ which has zero restrictions, and that domain forwards all the email it gets to my home server, which is the Proxy we’re about to setup. The reason I do this is to make sure that my SPAM filtering isn’t killing emails I WANT to see. SO, every so often I’ll check both accounts, side by side, and make sure that I’m filtering properly. And if I’m not, I’ll tweak the proxy accordingly. Eventually, maybe even in this blog, I’ll get a mail quarantine up and running so that I can just do away with the DMZ server and pass all my mail through this Proxy…
Lastly, I’ve gone out of my way to make this as absolutely clear as I can. I’ve referenced all the sites and pages at the bottom of this blog, as I always do, and made this as close to perfect as I can. If you want an “installer” for this process, then you’re in the wrong spot. I will never build an automated installer for this without charging a butt load of money. If that’s what you’re looking for, go buy some Windows based software. Here, we’re working with Debian server on the Bash Shell.
Anyways… So let’s get a base image up and running.
Debian Minimal Install: The base for all operations
When you’re done with that come back here and we’ll keep going… In the mean time let’s talk about the software we’re dealing with here…
Postfix
While Postfix can do a lot, just by itself, in filtering SPAM, it’s not the end all, be all, software. It’s literally just a Mail Transfer Agent (MTA), and it’s only purpose is to send and receive mail. So what we need to do here is arm Postfix with some weaponry, by the likes of Amavis-New, SpamAssassin, Anomy Sanitizer, and ClamAV. Now, I know your thinking, “ClamAV, huh?” But it’s better than nothing, it’s open source and it’s got over a million signatures. If you’re reading this thinking “WTF? My company wont be able to run this!”, then you’re in luck, because Postfix can forward mail for AV inspection to many of the top names in Anti Virus (Kaspersky, Symantec and McAfee). But for this article we’re going to work with ClamAV and some other tools, so deal with it. It’s free, and so is this blog…
Amavis-New
Amavis-New is a really good SPAM filtering engine, as well as SpamAssassin. What we’ll have to do is create two directories for Amavis and SpamAssassin to work in. They both receive mail from Postfix, unpack the email and attachments, inspect everything, then package everything back up the way they should be, and send it back to Postfix. This happens in two forks. Amavis gets the email first, then sends it back to Postfix, then it’s sent to SpamAssassin, then sent back to Postfix.
When Amavis first starts at system boot, it just sits there and waits until it gets work to do, as any good little daemon should do. But when an email comes in, Amavis instantly forks a child process to do the work that needs to be done. This child process will create a sub directory in, in the Amavis working directory, and to it’s unpacking, inspection and repacking in. In the Amavis conf file you can specify how many children can be spawned, but you’ll want to test this out. Our config will have 5 children, and on a box with 1GB of ram, we should have PLENTY of room to work with. Now, if you’re running a Enterprise level SPAM filtering service, you may want to setup multiples of these servers that sit on a few or more MX records so that you can spread out the work load. Then beef up how much RAM and CPU cores you allocate to the VM and then allow Amavis to spawn more children. Pending the amount of hardware you have to work with, you could filter a TON of email with this configuration.
Really though, at the end of the day, I strongly recommend that you investigate the Amavis-New website. Their FAQ’s are great and super informative. It’s truly amazing what this product can do.
SpamAssassin
As for SpamAssassin let’s talk about this for a minute. At the writing of this blog, Spam Assassin is at release 3.3.1. I’ll tell you the same thing I said a minute ago about Amavis: You should really look at the Spam Assassin website for more details about running, installing, configuring, testing and the operations of Spam Assassin. But I’ll briefly go over this stuff now. SpamAssassin works like many other filtering engines, “grading” the email on a multitude of different areas, including content, encoding, MIME settings, HTML markup and blacklists provided from different carriers like Spamhaus (which we’ll talk about later in this blog). Configured and monitored properly, Spam Assassin, just by itself, can filter over 97% of all SPAM, it’s false positive ratio is easily 1% or less, and the best part is that it has the ability to “learn” about new SPAM. The scoring engine is like a game of golf. The lower the score, the better. Other factors are looked at as well, such as Blacklisted IP’s, Reverse DNS lookups, list of banned words, list of banned file attachments (exe, vbs, etc…) sender and receiver addresses, valid date and time, etc…
SpamAssassin isn’t all by itself though. While SpamAssassin is able to do a LOT on it’s own, it also “calls” other programs in to help it, such as razor, pyzor, and dcc-client. Each of these programs have specialized duties that perform additional SPAM checking. Razor is a distributed network devoted to spam detection. Razor uses statistical and randomized signatures that effectively identify many different types of SPAM. Pyzor, not surprisingly, is built on Python and also is based on a network dedicated to identifying SPAM. Like Razor, it too is signature based. Lastly, DCC (Distributed Checksum Clearinghouses) is also an anti-spam content filter. According to the DCC website, “The idea.”
Back to SpamAssassin… The thing that really makes SpamAssassin great is the way that it handles SPAM. It’s completely configurable to the way YOU want SPAM handled. You can have it tag email as potential SPAM by just changing the email headers. There’s also ways that Spam Assassin will modify the Subject line of an email to include text like “***Potential SPAM***” or whatever you want it to say to your end users. This option truly is great, because there will always be false positives (email marked as SPAM that really isnt), and there will always be false negatives (SPAM that gets through to the end user that shouldn’t). With Subject line modification, we can alert the user to use their best judgement in looking at an email. If a message has a high enough score we can have the message quarantined until the user releases the message for review, or in extreme cases the email can just be dropped without notification.
On the contrary, not all email should be blocked either. And Spam Assassin can look into messages to see if they have good karma. This sounds strange, but while there are services like Spamhaus, there are services that do the exact opposite of them. For instance, there are services like ISIPP Email Accreditation and Deliverability, Return Path who actually owns Bonded Sender which used to be Iron Port‘s product (which now Cisco owns), and more.
Anomy
Just because I’m too lazy to keep going on with this, I’ll just forward you to the Anomy website and you can look at their information if you want to know more. The main reason why I’ve decided to incorporate Anomy is because of the fact that, while the other SPAM and Virus checkers need to perform inspection on the disk, which can get very intense (and in extremely large environments can cause performance issues), Anomy does everything in system memory. The other reason why is that Anomy comes with it’s own custom built MIME parser which performs more checks than some of the other options. The thing that we’re looking at here is security in layers. You’ll hear that concept driven into your head over and over until the end of time. Security in layers. The day that you can buy 1 product to perform ALL of your security needs is the day I’m out of a job. Until then, you’re going to have to use multiple scan engines, multiple security technologies and continue to drive a culture of knowledge for your employees.
Awesome, you got your VM up and running!!!
SSH and Server Certificates
In that tutorial I had you setup the IP address on your new Debian server to 192.168.0.100. We’ll reference that IP address for the rest of the time, but you can substitute it for whatever you made it on your network.
If you haven’t done this yet, we’re going to make life easy and get the SSH Server installed so we can get some remote access to this server from our Linux Desktop.
When that’s done test out connecting from your local machine to this virtual host using:
Now we can setup SSH keys on this system so that you can easily log in from your main Linux Desktop machine.
So go to your home directory on your local machine (NOT THE SERVER!) and your navigate to your home folder. From here CD into your .ssh directory and we’ll create your SSH Certificates.
ssh-keygen -t rsa
{save as default file, press enter}
{enter your own password and hit enter} <-- this can be blank
{confirm your password} <-- this can be blank
Once this is done we’ll setup your host with keys to stay authenticated
Now edit your “.ssh/config” file and add in your new server. If you dont have one just create one!
HostName 192.168.0.100
User steve
And now you can test your new ssh keys by doing this:
You may need to adjust your permissions properly. To do so, simply run this command on your local system:
And this command on your remote system that you’re trying to connect to:
Disable IPv6
For our install, we need to disable IPv6. I’ve seen issues with Postfix and Bind when there is IPv6 running on the same box. I always bitch about lazy admins, and here I am being lazy and turning off IPv6 instead of fixing the underlying issue. 🙁
SO! Let’s get IPv6 disabled! haha 🙂
I promise I’ll look into the issue over time, because I’ll need to make this solution work with IPv6 eventually. I can’t run from it forever. In the mean time, lets get going with editing your grub file:
While you’re in your Grub file, find the line that looks like this:
What you need to do here is make it look like this:
Then you need to update the loader by doing this:
Generating grub.cfg ...
Found linux image: /boot/vmlinuz-2.6.32-5-amd64
Found initrd image: /boot/initrd.img-2.6.32-5-amd64
done
steve @ debian ~ :) ?> sudo update-grub
Generating grub.cfg ...
Found linux image: /boot/vmlinuz-2.6.32-5-amd64
Found initrd image: /boot/initrd.img-2.6.32-5-amd64
done
Bind9 Domain Name System (DNS)
Perfect! Now, let’s get Bind9 installed and configured properly. What I’ve done in my network is allowed my Internal Name Servers keep a copy of the External DNS zones. It makes life easier than setting up all your internal servers to also look at your External Servers. We’ll run through that as well during the setup. You’ll also want to get a copy of the Bind 9 Administrator Reference Manual. It’s not critical, but there’s some pretty damn good information in that document. has both the online website and the downloadable PDF document.
Now that Bind is installed, lets configure the service to do what we want. We’ll start by editing our “named.conf” file where all the good stuff is.
sudo vim named.conf
### Named.conf";
This file is really tiny; it’s really just the spawn point for all the other configurations. And there’s two ways you can do this.
- 1. You can remove all the other files and just do all your configurations in here
- 2. You can continue to use the file structure the way it is
Either way will work. If you’re a small company with only a few domain names, you can easily get away with lumping everything into this file and still keep separate zone files. If you’re a large company you may want to stay with many separate, smaller, configuration files. Especially when you’re dealing with companies that own hundreds, if not thousands, of domain names… even more so if you’re dealing with companies dispersed over several continents… or globally!
In this scenario, we’re going to tighten things up just to make the initial config easy to see, but by no means am I telling you that you have to do it this way. DO it however you feel makes the most sense to you!
So here we have the named.conf file; go ahead and make a backup of all your config files into a backup folder here and then modify your named.conf to look like mine below.
sudo mkdir installer-backup
sudo cp * installer-backup/
rm named.*
And here is the code you can copy and paste into your “named.conf” file:
#####################################################################################
# This is not part of the default configuration that is included as part of the #
# Bind 9 package. This section is commented out because it isnt needed. #
# Also, for all of the files that were installed by default, #
# look in the "/etc/bind/installer-backup" directory #
#####################################################################################
# #
# CONFIGURED BY STEVE ERDMAN, updated 12/27/12 #
# #
#################################################################################
// The following section is the called the options section.
// Configures the working directory for this BIND9 installation
// Sets up BIND to allow query's from the Internet
// recursion only from the Internal network (Change to your Internal Network!)
// Forwarders set to Level 3, Google and OpenDNS public servers (if these guys dont work, the Internet is probably broken!
// Listening on all interfaces (make sure to update this address to your real IP on this server!)
// IPv6 turned off
// running "named" version
// auth-nxdomain states that this server will answer authoritatively for all domains configured on it
options {
directory "/etc/bind";
notify-source * port 53;
allow-query { any; };
allow-recursion { 127.0.0.1; 192.168.0.0/24; };
forwarders { 209.244.0.3; 209.244.0.3; 8.8.8.8; 8.8.4.4; 208.67.222.222; 208.67.220.220; };
listen-on { 127.0.0.1; 192.168.0.100; };
listen-on-v6 { none; };
version "named";
auth-nxdomain yes; # conform to RFC1035
};
// end of options
#---------------------------------------------------------------------------------------#
# Below are all of the zone files for all the forward and lookup zones that your #
# company is responsible for. #
#---------------------------------------------------------------------------------------#
// zone name
// 'type' only allows master, slave, stub, forward, hint... We own our zone, we're the master.
// specify the file that our zone sits in
// allow anyone to query our server
// allow our internal name servers to cache this zone as a slave server
// specify that if the zone data may have changed, that all servers with this zone data need to contact the SOA
// THE ERDMANOR
zone "example.com" IN {
type master;
file "/etc/bind/db.example.com";
allow-query { any; };
allow-transfer {192.168.0.7; 192.168.0.13; 192.168.0.18; 192.168.0.47; };
notify yes;
};
//same options apply as the above zone
// 111.222.333.44 Reverse DNS
zone "333.222.111.in-addr.arpa" {
type master;
file "/etc/bind/333.222.111.in-addr.arpa";
allow-query { any; };
allow-transfer {192.168.0.7; 192.168.0.13; 192.168.0.18; 192.168.0.47; };
notify yes;
};
#---------------------------------------------------------------------------------------#
# Consider adding the 1918 zones here, if they are not used in your organization #
# to use these just uncomment the following line: #
# include "/etc/bind/zones.rfc1918"; #
#---------------------------------------------------------------------------------------#
# Below are some zones that your server should cache #
# The for more info on this visit: #
#-----------------------------------------------------------------------------#
//";
};
Now we need to create some zone files. “What is a zone file?” you may be asking… Well, zone files are where all of your host information is stored, so that when a Internet customer queries “” your DNS server looks up in it’s zone file the “www” host A record, and returns the response. There are all kinds of records, and here is a site that can explain all of this for you: List of DNS record types at Wikipedia.
Now that you’re understanding records, lets get your zone file going. Working off of the example “named.conf” file above, let’s create our “db.example.com” and “333.222.111.in-addr.arpa” zone files. If you want to cheat a little bit, go ahead and use a zone file generator such as this one, but you really should understand how they work as well. So let’s look at one…
; BIND data file for example.com
;
$TTL 3600
@ IN SOA ns1.example.com. ns2.example.com. (
201212263453789 ; serial number YYMMDDNN + some numbers
28800 ; Refresh
7200 ; Retry
3600 ; Expire
3600 ; Min TTL
)
IN NS ns1.example.com.
IN NS ns2.example.com.
IN MX 10 mail.example.com.
IN MX 20 smtp.example.com.
$ORIGIN example.com.
IN A 111.222.333.41
ns1 IN A 111.222.333.42
ns2 IN A 111.222.333.43
mail IN A 111.222.333.44
smtp IN A 111.222.333.45
autodiscover IN A 111.222.333.46
vpn IN A 111.222.333.47
www IN A 111.222.333.48
Now let’s look at our Reverse Lookup zone so you can get an idea of what yours should look like:
; BIND data file for local loopback interface
;
$TTL 3600
@ IN SOA ns1.example.com. dns.example.com. (
201212263453789 ; serial number YYMMDDNN
28800 ; Refresh
7200 ; Retry
3600 ; Expire
3600 ; Min TTL
)
42 IN NS ns1.example.com.
43 IN PTR smtp.example.com.
44 IN PTR mail.example.com.
45 IN PTR smtp.example.com.
47 IN PTR vpn.example.com.
48 IN PTR.
Awesome, now, one last thing that has helped me is if the “/etc/bind/” directory was owned by the “bind” user that was created upon install. Let’s do that real quick!
Give your Bind server a quick restart, but you restart the service, open another bash shell tab (or session) and do a “sudo tail -f /var/log/syslog” and watch the output to make sure everything loads properly. It all should load up right, but if not, it’s better to find out now if there’s a problem than to wait until the end and troubleshoot tons of errors you *MAY* be having.
Stopping domain name service...: bind9 waiting for pid 2655 to die.
Starting domain name service...: bind9.
And dont forget your “tail”!
[sudo] password for steve:
Dec 26 22:17:01 debian /USR/SBIN/CRON[3353]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
Dec 26 22:48:05 debian named[2655]: received control channel command 'stop -p'
Dec 26 22:48:05 debian named[2655]: shutting down: flushing changes
Dec 26 22:48:05 debian named[2655]: stopping command channel on 127.0.0.1#953
Dec 26 22:48:05 debian named[2655]: stopping command channel on ::1#953
Dec 26 22:48:05 debian named[2655]: no longer listening on ::#53
Dec 26 22:48:05 debian named[2655]: no longer listening on 127.0.0.1#53
Dec 26 22:48:05 debian named[2655]: no longer listening on 192.168.0.100#53
Dec 26 22:48:05 debian named[2655]: exiting
Dec 26 22:48:06 debian named[3491]: starting BIND 9.7.3 -u bind
Dec 26 22:48:06 debian named[3491]: built with '--prefix=/usr' '--mandir=/usr/share/man' '--infodir=/usr/share/info'
Dec 26 22:48:06 debian named[3491]: adjusted limit on open files from 1024 to 1048576
Dec 26 22:48:06 debian named[3491]: found 2 CPUs, using 2 worker threads
Dec 26 22:48:06 debian named[3491]: using up to 4096 sockets
Dec 26 22:48:06 debian named[3491]: loading configuration from '/etc/bind/named.conf'
Dec 26 22:48:06 debian named[3491]: reading built-in trusted keys from file '/etc/bind/bind.keys'
Dec 26 22:48:06 debian named[3491]: using default UDP/IPv4 port range: [1024, 65535]
Dec 26 22:48:06 debian named[3491]: using default UDP/IPv6 port range: [1024, 65535]
Dec 26 22:48:06 debian named[3491]: listening on IPv4 interface lo, 127.0.0.1#53
Dec 26 22:48:06 debian named[3491]: listening on IPv4 interface eth0, 192.168.0.100#53
Dec 26 22:48:06 debian named[3491]: generating session key for dynamic DNS
Dec 26 22:48:06 debian named[3491]: set up managed keys zone for view _default, file 'managed-keys.bind'
Dec 26 22:48:06 debian named[3491]: automatic empty zone: 254.169.IN-ADDR.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: 2.0.192.IN-ADDR.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: 100.51.198.IN-ADDR.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: 113.0.203.IN-ADDR.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: 255.255.255.255.IN-ADDR.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: 0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: D.F.IP6.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: 8.E.F.IP6.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: 9.E.F.IP6.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: A.E.F.IP6.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: B.E.F.IP6.ARPA
Dec 26 22:48:06 debian named[3491]: automatic empty zone: 8.B.D.0.1.0.0.2.IP6.ARPA
Dec 26 22:48:06 debian named[3491]: command channel listening on 127.0.0.1#953
Dec 26 22:48:06 debian named[3491]: command channel listening on ::1#953
Dec 26 22:48:06 debian named[3491]: the working directory is not writable
Dec 26 22:48:06 debian named[3491]: zone 0.in-addr.arpa/IN: loaded serial 1
Dec 26 22:48:06 debian named[3491]: zone 333.222.111.in-addr.arpa/IN: ending notifies (serial 3289701)
Dec 26 22:48:06 debian named[3491]: zone 127.in-addr.arpa/IN: loaded serial 1
Dec 26 22:48:06 debian named[3491]: zone 255.in-addr.arpa/IN: loaded serial 1
Dec 26 22:48:06 debian named[3491]: zone example.com/IN: loaded serial 16381
Dec 26 22:48:06 debian named[3491]: zone localhost/IN: loaded serial 2
Dec 26 22:48:06 debian named[3491]: managed-keys-zone ./IN: loading from master file managed-keys.bind failed: file not found
Dec 26 22:48:06 debian named[3491]: managed-keys-zone ./IN: loaded serial 0
Dec 26 22:48:06 debian named[3491]: running
Dec 26 22:48:06 debian named[3491]: zone example.com/IN: sending notifies (serial 598703)
Success! Your DNS server started and all your zones are loaded! Let’s test a couple queries and just make sure 🙂
; <<>> DiG 9.8.1-P1 <<>> @192.168.0.100 erdmanor.com mx
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 55227
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 2, ADDITIONAL: 4
;; QUESTION SECTION:
;erdmanor.com. IN MX
;; ANSWER SECTION:
erdmanor.com. 3600 IN MX 20 smtp.erdmanor.com.
erdmanor.com. 3600 IN MX 10 mail.erdmanor.com.
;; AUTHORITY SECTION:
erdmanor.com. 3600 IN NS ns1.erdmanor.com.
erdmanor.com. 3600 IN NS ns2.erdmanor.com.
;; ADDITIONAL SECTION:
mail.erdmanor.com. 3600 IN A 65.55.37.62
smtp.erdmanor.com. 3600 IN A 64.4.59.173
ns1.erdmanor.com. 3600 IN A 74.125.228.105
ns2.erdmanor.com. 3600 IN A 74.125.228.96
;; Query time: 1 msec
;; SERVER: 192.168.0.100#53(192.168.0.100)
;; WHEN: Wed Dec 26 22:52:11 2012
;; MSG SIZE rcvd: 172
Fantastic, we’re looking good so far!
Now that you’re mostly updated, you’ll need to visit the registrar for your domain name and update the information for where your domain is hosted. These records are called glue records and normally they take a while to update. They could take up to 12 or 24 hours to update so dont get worried if you have and DNS issues in the next few hours. Really, the best time to update that information for production domains (domains that cant suffer down time) is early on a Saturday night. Many people are watching TV, busy with the family or out on the town after 8pm on a Saturday (unless you’re me, haha). By the time the propagation spreads across the Internet, it’s Sunday morning and no one really noticed. Also, you’ll want to get on the phone with your ISP to have them forward all reverse lookup queries to your name servers. This is critical if you want YOUR out going email not to be tagged as SPAM!
According to WikiPedia, .”
While your registrar information is updating let’s move forward and get some email action going!
If all you were looking for here was a DNS tutorial for a single DNS server, you’re done. If you’re looking to go any further into SPAM filtering, continue on!
I will be posting a blog as soon as I can on how to setup a distributed DNS server cluster. Stay tuned for that!
Postfix and SPAM Filtering
Alright, we need some software here, so… lets get Postfix installed!
sudo apt-get install -y postfix
Now, when the software is installing, you’ll want to setup Postfix in a certain way. You NEED to make sure you pick “Internet Site” at the first prompt, and enter your EXTERNAL MX A-record. Many times this MX A Record is either “mail.example.com” or smtp.example.com”, but you’ll want to verify from your DNS zone that we created back in the BIND9 section.. See my screenshots below:
Now that we have Postfix installed, we can setup a temporary mail relay to our Microsoft Exchange server. THIS SHOULD NOT BE IN PRODUCTION RIGHT NOW!
GO ahead and edit your “main.cf” file. There is a line we need to change that I’ll show you below:
# Uncomment the next line to generate "delayed mail" warnings
delay_warning_time = 4h
# Add the IP address of your Exchange server's Receive Connector responsible for your Domain. (See below Screenshot)
relayhost =192.168.0.125
# And lastly, find "myorigin", and right below that add in "relay_domains = mydomain.com, example.com, (other, domains, comma, separated)"
myorigin = /etc/mailname
relay_domains = erdman.cc, erdmanor.com, someone.net, assholes.org
# If you're hosting multiple domains, you'll want to setup a transport config file.
transport_maps = hash:/etc/postfix/transport
WE will talk about the /etc/postfix/transport file, and others, later, but this DOES need to be there!
Now that we have that complete, we’ll restart the service:
SPAM Filtering Engines
Alright, cool… Let’s get some more software installed!
As soon as that’s complete you’ll want to update the ClamAV virus definitions. They’re readily available, and even easier, you can run a simple command to do this:
[sudo] password for steve:
ClamAV update process started at Thu Dec 27 00:16:40 2012
main.cvd is up to date (version: 54, sigs: 1044387, f-level: 60, builder: sven)
daily.cvd is up to date (version: 16130, sigs: 427971, f-level: 63, builder: neo)
bytecode.cvd is up to date (version: 209, sigs: 40, f-level: 63, builder: neo)
If you’re really looking to have fun with this, just create a quick shell script and then make a cron job out of it to run daily 🙂
Alright, more software to install. Mainly more dependencies and stuff you’ll need that may not have been installed yet.
Perl Script Installs
Following some package installs, we’ll be needing some perl scripts. So to install those, follow these instructions:
CPAN is the world-wide archive of perl resources. It consists of about
300 sites that all replicate the same contents around the globe. Many
countries have at least one CPAN site already. The resources found on
CPAN are easily accessible with the CPAN.pm module. If you want to use
CPAN.pm, lots of things have to be configured. Fortunately, most of
them can be determined automatically. If you prefer the automatic
configuration, answer 'yes' below.
If you prefer to enter a dialog instead, you can answer 'no' to this
question and I'll let you configure in small steps one thing after the
other. (Note: you can revisit this dialog anytime later by typing 'o
conf init' at the cpan prompt.)
Would you like me to configure as much as possible automatically? [yes]
You’ll see a ton of information fly by as many values are automatically generated for you.
Feel free to look at that stuff if you want. When you’re ready install the perl modules we need:
(as you’re installing these Perl modules, you’ll see a lot of scrollback)
o conf commit
install IP::Country::Fast
install MIME::Base64
install MIME::QuotedPrint
install Net::DNS
install DB_File
quit
Now for the DCC install. I haven’t found a package for DCC in the Debian repo’s unfortunately, and while that is a drawback to this software, it’s not the end of the world. We’ll just need to do some quick building of the software. But first we need to acquire the software from the DCC download page. The newest version that is out was released on January 12, 2013.
From your Debian VM, run this command:
Then you can extract and build the software like this:
cd dcc-1.3.144/
./configure
make
sudo make install clean
And you’re ready to move forward! (we’ll configure DCC later, for now we just need to have the software installed)
NOTE
Perfect, we’re moving right along here. One other thing to note here is that with all this going on, you’re going to want a highly tuned box. What I mean by that is, think of it this way: Every time a message comes in, we’re sending that message through 4 scanning engines, each one of which invokes it’s own shell or child process, some using a Perl interpreter, and unpacking/repacking each message in a temporary folder, inspecting the message and then sending it back out to your internal Exchange server. There’s A LOT going on here. This may add a bit of latency to the delivery of your messages. Remember, I’m running a VM on an SSD, with a Core i7 960, and the VM has 2 cores and 1GB of RAM. The latency I’m seeing here, as opposed to my other email service, is less than 1 minute, which is more than reasonable. We’ll go over some tuning at the end of this and tweak this whole system to work as efficiently as possible.
Okay, now we need some user accounts created so that we can tighten up security a bit.
Start by cat’ing your /etc/passwd file. Pending if your following my tutorial on a Red Hat, CentOS, Ubuntu or other OS, I want to make sure that our “amavis”, “spamd”, “anomy” and “clamav” users are created.
...
...
steve:x:1000:1000:Steve Erdman,,,:/home/steve:/bin/bash
postfix:x:104:107::/var/spool/postfix:/bin/false
bind:x:105:109::/var/cache/bind:/bin/false
clamav:x:106:110::/var/lib/clamav:/bin/false
amavis:x:107:111:AMaViS system user,,,:/var/lib/amavis:/bin/sh
SpamAssassin Configure
Based on this information, we’re good on most user accounts, but we need to create a “spamd” account and an “anomy” account. We also need to setup working directories for both of these services and lock down access to them.
sudo mkdir /usr/local/anomy
sudo groupadd -g 112 spamd
sudo useradd -u 112 -g 112 -s /sbin/nologin -d /var/run/spamassassin spamd
sudo chown spamd:spamd /var/run/spamassassin
sudo chmod 750 /var/run/spamassassin
sudo groupadd -g 113 anomy
sudo useradd -u 113 -g 113 -s /sbin/nologin -d /usr/local/anomy anomy
sudo chown root:anomy /usr/local/anomy
sudo chmod 750 /usr/local/anomy
sudo usermod -a -G clamav amavis
sudo usermod -a -G amavis clamav
Now let’s modify the SpamAssassin conf file:
And modify these parameters: ( by default, SpamAssassin is disabled, we need to give it options to start)
OPTIONS="--username=spamd --create-prefs --max-children 5 --helper-home-dir"
PIDFILE="/var/run/spamassassin/spamd.pid"
CRON=1
Now lets try to start SpamAssassin:
And update the databases for SpamAssassin:
Amavis-New Configure
Now, let’s get Amavis running. Technically, it is already running, but we need to enable Virus and SPAM filtering. Start by editing this file:
There are 4 lines in the file that you need to “uncomment”. See below:
#
Now restart Amavis to take effect:
Anomy Configure
###I WANT TO STRESS THAT THIS PORTION (ANOMY) IS STILL UNDER INVESTIGATION AND YOU CAN SKIP THIS PART###
Now lets get Anomy installed and running. First we’ll have to download it from their website.
/home/steve
steve @ debian ~ :) ?> wget
HTTP request sent, awaiting response... 200 OK
Length: 172722 (169K) [application/x-gzip]
Saving to: “qc?mailtools.anomy.net%2Fdist%2Fanomy-sanitizer-1.76.tar.gz”
100%[================================================================================>] 172,722 168K/s in 1.0s
2012-12-27 15:26:38 (168 KB/s) - “qc?mailtools.anomy.net%2Fdist%2Fanomy-sanitizer-1.76.tar.gz” saved [172722/172722]
Now to move it to it’s new home and unpack it. (for some reason the file name wasnt right so we need to rename it)
cd /usr/local/
sudo su
tar -zxvf anomy-sanitizer-1.76.tar.gz
cd anomy
ls -alh
For starters on configuration, I found a site that provides a baseline config that we’ll work off of. Thanks to “advosys.ca” for this one! We’ll use this conf file to start with. If that link doesn’t work, here it is on my site: anomy.conf.
Download that file and place it in your /usr/local/anomy/ folder.
END OF ANOMY SECTION
Allow Mail to be Scanned: Postfix Configuration
Now what we need to do is setup Postfix to actually send the mail to the Spam Filtering engines. In order to make this happen we’re going to have to modify some postfix files. We’re also going to setup the “client_access”, “helo_access”, “sender_access” and “transport” files. We’ll talk more about that when after we modify the “main” and “master” files for Postfix. Basically, these files further enhance how Postfix is able to start the filtering process before mail even gets to the SPAM Filtering Engines. It is here that we start invoking services such as dsbl.org, spamhaus.org, abuseat.org, and dnsbl.sorbs.net that work by notifying servers like our that a domain is either blacklisted or black-holed. PLEASE Visit their sites for more information. Let’s start by looking at the “main.cf” file. To look at the “main.cf” file in all it’s glory, check this out. All of the descriptions below are accredited to this that page.
**NOTE**: I’m setting up my configuration with the ability to verify user accounts through Active Directory. The reason for this is to allow Postfix to verify that the email address is valid before processing the mail. This is yet another safeguard against SPAM. Why accept mail for an account that doesn’t exist in your domain? Just block it! I’ll also show you how to secure the communications between Postfix and the domain. We’ll talk about this later. I haven’t added this content yet, but I will in the future!**END NOTE**
What I’m going to do is just post my “main.cf” file in here and then comment the hell out of it so you understand the reasons for what is in the file. Please take out ALL of my comments before pasting this config into your “main.cf” file! If you don’t, you will most definitely have errors at run time!
# This is the banner that will be seen by all systems connecting to our Postfix server.
smtpd_banner = The Erd-Manor-dot-com ESMTP Relay
#Biff is an old legacy thing that isnt needed anymore and can cause performance issue if left on.
biff = no
#We dont want to help anyone out. If you're hosting more than 1 domain, you better leave this off (no).
append_dot_mydomain = no
#This is how much time Postfix will wait before sending a message back to the originating server
#that there is an issue.
delay_warning_time = 4h
#This tells Postfix where to send mail on the next hop. You need this if you have more than 1 domain.
transport_maps = hash:/etc/postfix/transport
#The Internet hostname of this mail system. The default is to use the fully-qualified domain name (FQDN)
#of your MX record.
myhostname = smtp.erdmanor.com
#The alias databases that are used for local mail delivery. We'll be modifying this later.
alias_maps = hash:/etc/aliases
#This is just where the aliases exist at.
alias_database = hash:/etc/aliases
#For most cases, your /etc/mailname file should contain the "myhostname" value. In this case, smtp.erdmanor.com
myorigin = /etc/mailname
#What destination domains (and subdomains thereof) this system will relay mail to.
#This can be a file or a list of domains, that, are, comma, separated
relay_domains = erdman.cc, erdmanor.com
#The list of domains that are delivered via the $local_transport mail delivery transport. By default
#this is the Postfix local delivery agent which looks up all recipients in /etc/passwd and /etc/aliases.
#The SMTP server validates recipient addresses with $local_recipient_maps and rejects non-existent
#recipients.This can be a file or a list of domains
mydestination = debian.example.com, localhost
#This is usually the primary IP address of your Internal Exchange Server. This value is trumped by "transport_maps"
# so if you have multiple relay servers, you can comment this out like I have.
#relayhost = 192.168.0.125
# This is just a list of your internal networks. The list of "trusted" remote SMTP clients that have more
#privileges than "strangers". You can also specify "/file/name" or "type:table" patterns.
mynetworks = 127.0.0.0/8, 192.168.0.0/24
#The maximal size of any local individual mailbox or maildir file, or zero (no limit). In fact, this limits
#the size of any file that is written to upon local delivery, including files written by external commands
#that are executed by the local delivery agent. This limit must not be smaller than the message size limit.
mailbox_size_limit = 0
#The separator between user names and address extensions (user+foo). Basically, the software tries user+foo
#and .forward+foo before trying user and .forward. Just leave it the way it is.
recipient_delimiter = +
#The network interface addresses that this mail system receives mail on. Specify "all" to receive mail on all
#network interfaces (default) and "loopback-only" to receive mail on loopback network interfaces only.
inet_interfaces = all
#After the message is queued, send the entire message to the specified transport:destination. The transport
#name specifies the first field of a mail delivery agent definition in master.cf; the syntax of the next-hop
#destination is described in the manual page of the corresponding delivery agent. More information about
#external content filters is in the Postfix FILTER_README file.
content_filter = smtp-amavis:[127.0.0.1]:10024
#Enable or disable recipient validation, built-in content filtering, or address mapping. Typically, these
# are specified in master.cf as command-line arguments... Specify zero or more of the following options.
#The options override main.cf settings and are either implemented by smtpd(8), qmqpd(8), or pickup(8)
#themselves, or they are forwarded to the cleanup server.
#no_address_mappings means that we will disable canonical address mapping, virtual alias map expansion,
#address masquerading, and automatic BCC (blind carbon-copy) recipients. This is typically specified
#BEFORE an external content filter.
receive_override_options = no_address_mappings
#Require that addresses received in SMTP MAIL FROM and RCPT TO commands are enclosed with <>, and that
#those addresses do not contain RFC 822 style comments or phrases. This stops mail from poorly written
#software. By default, the Postfix SMTP server accepts RFC 822 syntax in MAIL FROM and RCPT TO addresses.
strict_rfc821_envelopes = yes
#Reject the request when the HELO or EHLO hostname has no DNS A or MX record. The
#unknown_hostname_reject_code parameter specifies the numerical response code for rejected requests
#(default: 450). This is a strong way to stop many spammers.
unknown_hostname_reject_code = 450
#The numerical Postfix SMTP server response code when a client without valid address <=> name mapping
# is rejected by the reject_unknown_client_hostname restriction. The SMTP server always replies with
#450 when the mapping failed due to a temporary error condition. Do not change this unless you have a
# complete understanding of RFC 5321. Turning this on can cause a lot of false positives, test this out.
### unknown_client_reject_code = 450
#Disable the SMTP VRFY command. This stops some techniques used to harvest email addresses.
disable_vrfy_command = yes
#Wait until the RCPT TO command before evaluating $smtpd_client_restrictions, $smtpd_helo_restrictions
#and $smtpd_sender_restrictions, or wait until the ETRN command before evaluating
#$smtpd_client_restrictions.
smtpd_delay_reject = yes
#Require that a remote SMTP client introduces itself with the HELO or EHLO command before sending the
#MAIL command or other commands that require EHLO negotiation.
smtpd_helo_required = yes
#You need to read this -->
smtpd_client_restrictions =
permit_mynetworks,
check_client_access hash:/etc/postfix/client_access,
reject_unknown_client_hostname,
#Below are all of the DNS Blacklists that Spam originates from.
reject_rbl_client sbl-xbl.spamhaus.org,
reject_rbl_client cbl.abuseat.org,
reject_rbl_client dul.dnsbl.sorbs.net,
reject_rbl_client sbl.spamhaus.org,
permit
# You need to read this -->
smtpd_helo_restrictions =
permit_mynetworks,
check_helo_access hash:/etc/postfix/helo_access,
reject_non_fqdn_helo_hostname,
reject_invalid_helo_hostname,
# reject_unknown_helo_hostname, #This can cause false positives, test before production!
permit
smtpd_sender_restrictions =
permit_mynetworks,
check_sender_access hash:/etc/postfix/sender_access,
reject_non_fqdn_sender,
reject_unknown_sender_domain, #This can cause false positives, test before production!
permit
smtpd_recipient_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_unauth_destination,
reject_invalid_hostname,
reject_non_fqdn_hostname, #This can cause false positives, test before production!
reject_non_fqdn_recipient,
reject_unknown_recipient_domain,
permit
smtpd_error_sleep_time = 1s
smtpd_soft_error_limit = 10
smtpd_hard_error_limit = 20
# Basic SPAM prevention...Require that a remote SMTP client introduces itself with the HELO or
#EHLO command before sending the MAIL command or other commands that require EHLO negotiation.
smtpd_helo_required = yes
Wow, that took forever…
Now we need to jump into the “master.cf” file. This one is a bit more tricky than the “main.cf” in that it has a lot more little tweaks. For more info on “master.cf”, there is an excellent “FAQ” on Postfix’s website: HERE. Here we go, I’ll do this the same as I did for the “main.cf” file, attempting to explain as much as I can so that you understand what everything is doing. 🙂 Remember to take out ALL of my comments before pasting this config into your “master.cf” file! If you don’t, you will most definitely have errors at run time!
Here we go, here’s my “master.cf” file:
# service type private unpriv chroot wakeup maxproc command + args
# (yes) (yes) (yes) (never) (100)
# ==========================================================================
smtp inet n - - - - smtpd
#submission inet n - - - - smtpd
# -o milter_macro_daemon_name=ORIGINATING
#628 inet n - - - - qmqpd
pickup fifo n - - 60 1 pickup
-o content_filter=
-o receive_override_options=no_header_body_checks we need to take care of our “client_access”, “helo_access”, “sender_access” and “transport” files as we spoke of earlier. There are many types of these files that can be referenced by the “main.cf” file, but these are really the only ones we need. Theoretically, we could have created a bunch more of these, and in a large enterprise that owns hundreds or thousands of domains, it’s almost a necessity to do so. For all the info you need about these files look at the database webpage and the man 5 access page.
Back in the “main.cf” file, we added a line item in there that looks like this, “check_client_access hash:/etc/postfix/client_access“. The purpose of the Client Access file is to “search the specified access database for the client hostname, parent domains, client IP address, or networks obtained by stripping least significant octets.” So what does that mean? Basically it means that this file is like access control list for remote SMTP servers. It checks client information: host names, network addresses, and envelope sender or recipient addresses.
As a safeguard, we should NEVER be accepting email from our own domain, from a remote source. Our Exchange server is inside our organization already and will process our internal mail for us. This proxy will deny anyone out on the internet trying to spoof mail into our domain. You want to make sure to have every domain you own in this list. And you can also do some “whitelisting” in here as well. Let’s get our “client_access” file going:
erdman.cc REJECT
74.114.46.150 OK
directv.com OK
linuxmint.com OK
forums.linuxmint.com OK
Now for our “helo_access” file. This file is much the same, it’s another ACL that we are setting up. Postfix states that this command will tell the Postfix server to “Search the specified access database for the MX hosts for the HELO or EHLO hostname, and execute the corresponding action . Note 1: a result of “OK” is not allowed for safety reasons. Instead, use DUNNO in order to exclude specific hosts from blacklists. Note 2: specify “smtpd_helo_required = yes” to fully enforce this restriction (without “smtpd_helo_required = yes”, a client can simply skip check_helo_mx_access by not sending HELO or EHLO).
erdman.cc REJECT
/^smtp\.erdman\.cc$/ 550 Dont use my own hostname
/^smtp\.erdmanor\.com$/ 550 Dont use my own hostname
/^mail\.erdman\.cc$/ 550 Dont use my own hostname
/^mail\.erdmanor\.com$/ 550 Dont use my own hostname
/^ns1\.erdman\.cc$/ 550 Dont use my own hostname
/^ns1\.erdmanor\.com$/ 550 Dont use my own hostname
/^ns2\.erdman\.cc$/ 550 Dont use my own hostname
/^ns2\.erdmanor\.com$/ 550 Dont use my own hostname
/^\[108\.227\.33\.121\]$/ 550 Dont use my own IP address
/^\[108\.227\.33\.122\]$/ 550 Dont use my own IP address
/^\[108\.227\.33\.123\]$/ 550 Dont use my own IP address
/^\[108\.227\.33\.124\]$/ 550 Dont use my own IP address
/^\[108\.227\.33\.125\]$/ 550 Dont use my own IP address
/^[0-9.]+$/ 550 Your software is not RFC 2821 compliant
/^[0-9]+(\.[0-9]+){3}$/ 550 Your software is not RFC 2821 compliant
Moving right along here, lets look at the “Sender_Access” file here. Again, this is another ACL that is supposed to search the specified access database for the MAIL FROM address, domain, parent domains, or localpart@, and execute the corresponding action. We want all of our domains in here as well, and for the same reason as the “client_access” file.
erdman.cc REJECT
forums.linuxmint.com OK
linuxmint.com OK
And lastly, our transport file. This file is really important. Without this working properly we wont get any mail at all from this proxy.
erdman.cc smtp:[192.168.0.127]
Now that we have our access and transport files completed, we need to make them usable to Postfix. The only way that’s possible is to run the “Postmap” command on them.
sudo postmap helo_access
sudo postmap sender_access
sudo postmap transport
ANYTIME YOU MODIFY THESE 4 FILES YOU MUST RUN THE POSTMAP COMMAND AGAINST THEM AND THEN RESTART POSTFIX! NO EXCEPTIONS!
Now that Postfix is setup and ready to go, lets get that restarted and watch our log files at the same time. You should still have a second terminal open, so start your “tail” and then you can restart Postfix.
Stopping Postfix Mail Transport Agent: postfix.
Starting Postfix Mail Transport Agent: postfix.
Here is the output from the tail:
Dec 28 11:34:12 debian postfix/master[3266]: daemon started -- version 2.7.1, configuration /etc/postfix
At a bare minimum here, assuming your DNS records are setup properly, your MX records have propagated throughout the Internet, your Firewall is setup properly, your Exchange box is setup properly, and the other million variables are good, you should be able to drop this in between your firewall and your Exchange server. I would suggest putting this in a DMZ that is forward facing to the internet as I explained in one of my previous blogs “Serious network architecture that works for everyone“.
SPAM Filter: SpamAssassin Configuration
Now that our Postfix Proxy is moving mail properly, lets get some SPAM engines configured. 🙂 We’ll start with SpamAssassin. A brief background on SpamAssassin: This product is an open source code set that is actually used in a TON of other SPAM filtering products behind the scenes.
Let’s get a quick idea of where SpamAssassin stores it’s files:
/etc/cron.daily/spamassassin
/etc/default/spamassassin
/etc/init.d/spamassassin
/etc/mail/spamassassin
/etc/spamassassin/
/usr/bin/spamassassin
/usr/share/spamassassin
/usr/share/doc/spamassassin/
/usr/share/man/man1/spamassassin*
/usr/share/perl5/spamassassin-run.pod
/usr/share/spamassassin/
/var/lib/spamassassin
/var/lib/amavis/.spamassassin
/var/lib/dpkg/info/spamassassin.*
/var/lib/spamassassin/
Here is what my “/etc/spamassassin/local.cf” file looks like. I’ll comment on the file as I did earlier in this blog. Dont forget to remove ALL “#comments” before using this in your configuration. If you don’t, you will most definitely have errors at run time! Also, according to SpamAssassin, .” So we’re going to have to go through that stuff as well. Again, if you would like any further information regarding this, I urge you to visit the SpamAssassin page for the local.cf configuration settings.
# Exchange server. If you have internal servers that need to get mail to your users, then the best
# place to handle that workload is at the Exchange Server Receive connectors. Send you internal mail there.
# trusted_networks 192.168.0.0/24
#Here is where we do our subject line rewrite for mail that is marked as SPAM.
rewrite_header Subject [***** SPAM _SCORE_ *****]
#Score that a message needs to get to in order to be classified as SPAM.
# this number is actually pretty high, but after tweaking it, you can lower it to 4.5 or 5.0.
required_score 7.0
#If the mail message meets the two above requirements the message is then packed up into an attachment and
# forwarded to the recipient in plain text. It is up to the user to inspect and go from there.
report_safe 2
# Turn on DCC
# dcc
use_dcc 1
dcc_path /usr/bin/dccproc
dcc_add_header 1
dcc_dccifd_path /usr/sbin/dccifd
# Turning on the skip_rbl_checks setting will disable the DNSEval plugin, which implements Real-time Block
# List (or: Blackhole List) (RBL) lookups. We WANT Those checks to happen so leave this at ZERO (0).
skip_rbl_checks 0
#razor
use_razor2 1
razor_config /etc/razor/razor-agent.conf
#pyzor
pyzor_options --homedir /etc/mail/spamassassin discover
use_pyzor 1
pyzor_path /usr/bin/pyzor
pyzor_add_header 1
# Language and Location options. I have mine set to only allow English. If you work at a large international
# business you'll want to setup all the languages your company communicates in or just say allow all:
# ok_locales all (allow all locales)
# ok_locales en (only allow English)
# ok_locales en ja zh (allow English, Japanese, and Chinese)
ok_locales en
# The next three deal with the Bayes system and how SpamAssassin actually can "learn" spam.
use_bayes 1
use_bayes_rules 1
bayes_auto_learn 1
use_learneres_ignore_header X-Bogosity
bayes_ignore_header X-Spam-Flag
bayes_ignore_header X-Spam-Status
# To be accurate, the Bayes system does not activate until a certain number of ham (non-spam) and
# spam have been learned. The default is 200 of each ham and spam, but you can tune these up or
# down with these two settings.
bayes_min_ham_num 20 #default is 200
bayes_min_spam_num 20 #default is 200
# The Bayes system will, by default, learn any reported messages (spamassassin -r) as spam.
# If you do not want this to happen, set this option to 0.
bayes_learn_during_report 1
# SpamAssassin will opportunistically sync the journal and the database. It will do so once a day,
# but will sync more often if the journal file size goes above this setting, in bytes. If set to
# 0, opportunistic syncing will not occur.
bayes_journal_max_size 102400
#_expiry_max_db_size 200000
# If enabled, the Bayes system will try to automatically expire old tokens from the database.
# Auto-expiry occurs when the number of tokens in the database surpasses the
# bayes_expiry_max_db_size value.
bayes_auto_expire 1
#.
bayes_learn_to_journal (default: 0)
# Some shortcircuiting, if the plugin is enabled
#
ifplugin Mail::SpamAssassin::Plugin::Shortcircuit
# default: strongly-whitelisted mails are *really* whitelisted now, if the
# shortcircuiting plugin is active, causing early exit to save CPU load.
# Uncomment to turn this on
shortcircuit USER_IN_WHITELIST on
shortcircuit USER_IN_DEF_WHITELIST on
shortcircuit USER_IN_ALL_SPAM_TO on
shortcircuit SUBJECT_IN_WHITELIST on
# the opposite; blacklisted mails can also save CPU
shortcircuit USER_IN_BLACKLIST on
shortcircuit USER_IN_BLACKLIST_TO on
shortcircuit SUBJECT_IN_BLACKLIST on
# and a well-trained bayes DB can save running rules, too
#
shortcircuit BAYES_99 spam
shortcircuit BAYES_00 ham
endif # Mail::SpamAssassin::Plugin::Shortcircuit
Here’s that Exact same file without all the comments:
required_score 7.0
report_safe 2
use_dcc 1
dcc_path /usr/bin/dccproc
dcc_add_header 1
dcc_dccifd_path /usr/sbin/dccifd
skip_rbl_checks 0
use_razor2 1
razor_config /etc/razor/razor-agent.conf
pyzor_options --homedir /etc/mail/spamassassin discover
use_pyzor 1
pyzor_path /usr/bin/pyzor
pyzor_add_header 1
ok_locales en
use_bayes 1
use_bayes_rules 1
bayes_auto_learn 1
use_learner 1
bayes_ignore_header X-Bogosity
bayes_ignore_header X-Spam-Flag
bayes_ignore_header X-Spam-Status
bayes_min_ham_num 20 #default is 200
bayes_min_spam_num 20 #default is 200
bayes_learn_during_report 1
bayes_journal_max_size 102400
bayes_expiry_max_db_size 200000
bayes_auto_expire 1
bayes_learn_to_journal (default: 0)
ifplugin Mail::SpamAssassin::Plugin::Shortcircuit
shortcircuit USER_IN_WHITELIST on
shortcircuit USER_IN_DEF_WHITELIST on
shortcircuit USER_IN_ALL_SPAM_TO on
shortcircuit SUBJECT_IN_WHITELIST on
shortcircuit USER_IN_BLACKLIST on
shortcircuit USER_IN_BLACKLIST_TO on
shortcircuit SUBJECT_IN_BLACKLIST on
shortcircuit BAYES_99 spam
shortcircuit BAYES_00 ham
endif # Mail::SpamAssassin::Plugin::Shortcircuit
Now we need to restart SpamAssassin and test out our changes.
sudo /etc/init.d/spamassassin restart
echo "test" | sudo spamassassin -D pyzor 2>&1 | less
Alright, enough SpamAssassin stuff. Let’s get Amavis up and running.
SPAM Filter: Amavis-New Configuration
Now that our Postfix Proxy is moving mail properly, and SpamAssassin is filtering mail, lets get some Amavis-New configured. Remember what we said before: Amavis sends mail to SpamAssassin by default. That is the reason why we setup SpamAssassin first. In order to have Amavis properly scanning mail we’ll be configuring files in your /etc/amavis/ directory. Before we jump into that, lets get an Idea of where Amavis is located in your Server. Below is where Amavis has files by a default install:
/etc/amavis/conf.d/
/etc/cron.d/amavisd-new
/etc/cron.daily/amavisd-new
/etc/cron.hourly/amavisd-new
/etc/init.d/amavis
/etc/init.d/amavisd-new-milter
/etc/ldap/schema/amavis.schema
/etc/logcheck/ignore.d.server/amavisd-new
/etc/logcheck/violations.ignore.d/amavisd-new
/usr/sbin/amavis
/usr/sbin/amavis-milter
/usr/sbin/amavisd-agent
/usr/sbin/amavisd-nanny
/usr/sbin/amavisd-new
/usr/sbin/amavisd-new-cronjob
/usr/sbin/amavisd-release
/usr/share/amavis/
/usr/share/amavis/conf.d/
/usr/share/doc/amavisd-new/
/usr/share/lintian/overrides/amavisd-new
/var/lib/amavis/
/var/lib/dpkg/info/amavisd-ne*
/var/lib/update-rc.d/amavis
/var/lib/update-rc.d/amavisd-new-milter
I know that seems like a lot, but we’ll try cover it all. Amavis is really a different beast than SpamAssassin. But since SpamAssassin is already doing the brunt force of the work, we can take our time in this one a bit.
SPF Records
The last thing I wanted to cover in this blog, since we’re hosting our own DNS and Mail servers, it would only be right for us to cover DNS SPF records. This is just another layer of security that we *should be* using to help strengthen, not only our email, but our whole external domain.
STILL A WORK IN PROGRESS!
I updated this again on 2/3/13. But I’m lazy, so… there’s no change log. 🙂
References for this blog go out to:
|
http://www.erdmanor.com/blog/category/smtp-reverse-proxy/
|
CC-MAIN-2018-34
|
refinedweb
| 10,269
| 64.2
|
CPSC 124 (Fall 1998): Lab 5
Using Objects
IN THE FIFTH LAB for Computer Science 124, you will do two fairly short programming exercises in which you create and use objects. In a third exercise, you will learn about "mouse events" and how to make an applet respond to movements of the mouse.
Before you begin, copy the folder /home/cs124/lab5 into your home directory.
The exercises at the end of the lab are due in class on the Monday following the lab.
Outline of the Lab
- Mathematical Functions
- Back to Bouncing Balls
- Handling MouseDrag Events
- Exercises
Mathematical Functions
In this lab, you will create and use objects based on existing classes. (Next week, you will write your own class from scratch.) The ability to use existing classes is important, since it lets you build on previous work. Furthermore, its lets you work with objects on a black-box basis, without understanding the implementation details inside the box.
For the first exercise of the lab, you will work with mathematical functions of the variable x. A function of x is an object in the real world (the abstract, mathematical part of the real world), and it can be represented as a software object in a program. I have written the class Expr to represent such functions. The compiled class is in the file Expr.class in your lab5 directory, so you can use this class in a program.
An Expr object can be constructed from a String that contains the definition of the function. The String must be a legal mathematical expression, which can contain numbers; the variable x; operators +, -, *, /, and ^; parentheses; and the functions sin, cos, tan, sec, csc, cot, exp, ln, abs, and sqrt. For example, the following strings are legal expressions:"x^2 + x + 1" "sin(3*x)" "(2*x - 1) / (3*x + 1)" "exp(x^2) / exp(tan(x))"
(The operator ^ represents raising to a power. The function ln is the natural logarithm function. Abs represents the absolute value function. The trigonometric functions work with radians, not degrees. A function must always be followed by a parameter in parentheses.)
When you construct an object of type Expr with the new operator, you must specify the String that defines the function as an argument to the constructor. For example, you could sayExpr func; func = new Expr("sin(3*x)");
The String can, of course, be given by a variable instead of by a literal string: "func = new Expr(def);", where def is a variable of type String.
When the Expr constuctor is called and an error is found in the string, an IllegalArgumentException is thrown. This exception will crash the program unless it is caught and handled in a try statement. Here is how you could catch and handle the error:try { func = new Expr(def); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); ... // do something to handle the error? }
(The variable e contains information about the error that has been caught. In particular, e.getMessage() is an error message.)
Once an Expr object, func, has been created, you can call the method func.value(num) to evaluate the function at a given value of the variable x. The parameter to this method is a double number giving the value of the variable x. The method returns a double number that is the value of the function at the given value of x.
For your first exercise of the lab, write a complete program that reads in the definition of a function of x from the user. You can use TextIO.getln() to read the definition. (If the user types in an illegal definition, keep trying until the user gets it right.) Use this definition to create an Expr object. Then get values of x from the user and print the value of the function for each value of x that the user enters.
Here is an applet that does the same thing that your program is supposed to do. Try out the applet to see how it should work:
Back to Bouncing Balls
Your lab5 directory contains a file, BouncingBallsApplet.java, that defines an applet that shows a red ball bouncing around on a black background. The ball is an object belonging to the class BouncingBall, which is defined in the file BouncingBall.java. This is, of course, very similar to the bouncing ball applet from Lab 3, except that the variables that record the state of the ball and the subroutines that implement its behaviors have been encapsulated inside a class.
For the second exercise in the lab, you should add at least four more balls to the applet. The balls should be of different colors and sizes. Read the comments in the BouncingBall.java file if you need more information about how to use the constructor and methods in the BouncingBall class.
You can see a completed bouncing ball applet on a separate page.
Handling MouseDrag Events
The BouncingBall class includes a method headTowards(x,y) that makes the ball head in the direction of the point (x,y). In the third exercise of the lab, you will use this method to make all the balls in your bouncing balls applet move towards the mouse whenever the user holds down the mouse button and moves the mouse on the applet. To do this, you have to listen for the events that are produced when the user drags the mouse, and respond to those events when they occur. There are four steps you have to take to do this.
Step 1. Events in Java are objects. Event objects belong to classes that are defined in the package java.awt.event. To get access to the classes in this package, you should add the line "import java.awt.event.*;" to the beginning of your BouncingBallsApplet.java file. This goes right before or after the line "import java.awt.*;", which is already there.
Step 2. A class that is going to handle mouse drag events should implement an interface called MouseMotionListener. (Interfaces are discussed in Section 4.3 of the text.) This just means that you should add "implements MouseMotionListener" to the first line of the class definition:public class BouncingBallsApplet extends SimpleAnimationApplet implements MouseMotionListener {
Step 3. You have to tell the applet where to send mouse motion events when they occur. You can do this by adding the line "addMouseMotionListener(this);" to the applet's init() method. (The word "this", referring to the applet, means that mouse motion events will be sent from the applet back to this applet itself. See Section 4.2 for a discussion of the special variable "this".)
Step 4. When an applet says that it "implements MouseMotionListener", it makes a promise to define two methods:public void mouseDragged(MouseEvent evt) and public void mouseMoved(MouseEvent evt)
Add definitions for both of these methods to your applet. The mouseMoved method is called when the user moves the mouse without pressing any button. In the bouncing balls applet, you can leave this method empty. (Use just a pair of braces, { }, for the definition.) You have to include the method, even though it is empty, because it is part of the MouseMotionListener interface. The mouseDragged method is called when the user holds down a button and moves the mouse. You have to define this method so that it makes all the balls head towards the current position of the mouse. The current mouse position can be obtained from the parameter, evt:int x = evt.getX(); int y = evt.getY();
Once you have these coordinates, you can call the headTowards() method for each of the balls. For example, to make the red ball head towards the mouse, you would just callredBall.headTowards(x,y);
Once you've completed all these steps, your applet should be complete. Try it out! Copy the html file, bounce.html to your www directory, along with the relevant class files, BouncingBallApplet.class and BouncingBall.class. (You also need SimpleAnimationApplet.class, but that should already be in your www directory from previous labs. If not, copy it too.) Put a link on your index page to bounce.html.
Exercises to Turn in
Exercise 1. Turn in a printout of your first exercise, which is a program to ask the user to enter a mathematical function, f(x), and then to print the value of f(x) for various values of x specified by the user.
Exercises 2 and 3. Turn in a printout of your completed BouncingBallsApplet.java file. The second exercise is to make your applet show at least five bouncing balls, in various colors and sizes. The third exercise is to make the balls head towards the mouse when the mouse is dragged on the applet. Also, post your applet on the Web, and tell me its URL so that I can find it easily.
Exercise 4. Write a short essay comparing the "Bouncing Balls" exercises from Lab 3 with the "Bouncing Balls" exercise in this lab. Explain the advantages of using objects.
Exercise 5. You have now worked with both keyboard events and mouse events. Write a short essay explaining what is meant by an "event" and in particular what it means to say that events are "asynchronous." (See Section 1.1 of the text.) Although objects and events are very different things, they work naturally together. Try to explain why this is true. (Hint: Think in terms of "states" and "messages.")
|
http://math.hws.edu/eck/cs124/labs/lab5/
|
CC-MAIN-2018-47
|
refinedweb
| 1,575
| 65.22
|
Check for files that are ready for reading or writing
#include <sys/select.h> int select( int width, fd_set * readfds, fd_set * writefds, fd_set * exceptfds, struct timeval * timeout ); FD_SET( int fd, fd_set * fdset ); FD_CLR( int fd, fd_set * fdset ); FD_ISSET( int fd, fd_set * fdset ); FD_ZERO( fd_set * fdset );
(highest valued file descriptor in the sets) + 1
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The select() function examines the file descriptor sets whose addresses are passed in readfds, writefds, and exceptfds to see if some of their descriptors are ready for reading, ready for writing, or have an exceptional condition pending. Any of readfds, writefds, and exceptfds may be NULL pointers if no descriptors are of interest..
The select() function replaces the given descriptor sets with subsets consisting of those descriptors that are ready for the requested operation, and returns the total number of ready descriptors in all the sets.
If timeout isn't NULL, it specifies a maximum interval to wait for the selection to complete. If timeout is NULL, select() blocks until one of the selected conditions occurs. To effect a poll, the timeout argument should be a non-NULL pointer, pointing to a zero-valued timeval structure.).
/* * This example opens a console and a serial port for * read mode, and calls select() with a 5 second timeout. * It waits for data to be available on either descriptor. */ #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <sys/select.h> int main( void ) { int console, serial; struct timeval tv; fd_set rfd; int n; if( ( console = open( "/dev/con1", O_RDONLY ) ) == -1 || ( serial = open( "/dev/ser1", O_RDONLY ) ) == -1 ) { perror( "open" ); return EXIT_FAILURE; } /* * Clear the set of read file descriptors, and * add the two we just got from the open calls. */ FD_ZERO( &rfd ); FD_SET( console, &rfd ); FD_SET( serial, &rfd ); /* * Set a 5 second timeout. */ tv.tv_sec = 5; tv.tv_usec = 0; switch ( n = select( 1 + max( console, serial ), &rfd, 0, 0, &tv ) ) { case -1: perror( "select" ); return EXIT_FAILURE; case 0: puts( "select timed out" ); break; default: printf( "%d descriptors ready ...\n", n ); if( FD_ISSET( console, &rfd ) ) puts( " -- console descriptor has data pending" ); if( FD_ISSET( serial, &rfd ) ) puts( " -- serial descriptor has data pending" ); } return EXIT_SUCCESS; }
POSIX 1003.1
The select() function only works with raw file descriptors; it doesn't work with file descriptors in edited mode. See the ICANON flag in the description of the tcgetattr() function.
The select() function is thread safe as long as the fd sets used by each thread point to memory that is specific to that thread.
In Neutrino, if multiple threads block in select() on the same fd for the same condition, all threads may unblock when the condition is satisfied. This may differ from other implementations where only one thread may unblock.
errno, fcntl(), ionotify(), read(), sysconf(), tcsetattr(), write()
Tick, Tock: Understanding the Neutrino Microkernel's Concept of Time chapter of the QNX Neutrino Programmer's Guide
|
http://www.qnx.com/developers/docs/6.5.0SP1.update/com.qnx.doc.neutrino_lib_ref/s/select.html
|
CC-MAIN-2019-51
|
refinedweb
| 491
| 60.75
|
This article will show how to port a Visual Studio C++ project from a multi-byte configuration into Unicode, with a special emphasis on:
_T("")
std::string
std::ostringstream
std::ofstream
Once upon a time, I started a project in Visual Studio 6, C++, and the first line I ever wrote was:
AfxMessageBox("Hello World!");
When I hit "Build", it won't compile until I changed the project's configuration to Multibyte instead of the default Unicode.
I knew from that moment on that I better put the _T macro ahead of every string, but after some time, I stopped doing it.
_T
An year later, when the project became a 200,000 lines code monster, I was asked to translate the program to other languages, like Russian and Chinese. After changing the project configuration back to Unicode, it had thousands of errors, mostly because of quoted text not having added with the _T macro.
This article will show how to automatically add the _T("") macro to quoted strings, using Visual Studio's macro explorer.
Note that although the following code is written in VBScript, it is intended for C++ programs:
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module AutoT
Sub ReplaceXWithY(ByVal X As String, ByVal Y As String, _
Optional ByVal MatchCase As Boolean = False, _
Optional ByVal PatternSyntax As _
EnvDTE.vsFindPatternSyntax = _
vsFindPatternSyntax.vsFindPatternSyntaxLiteral)
DTE.Find.Action = vsFindAction.vsFindActionReplace
DTE.Find.FindWhat = X
DTE.Find.ReplaceWith = Y
DTE.Find.Target = vsFindTarget.vsFindTargetOpenDocuments
DTE.Find.MatchCase = MatchCase
DTE.Find.MatchWholeWord = False
DTE.Find.Backwards = False
DTE.Find.MatchInHiddenText = False
DTE.Find.PatternSyntax = PatternSyntax
If (DTE.Find.Execute() = vsFindResult.vsFindResultNotFound) Then
Throw New System.Exception("vsFindResultNotFound")
End If
End Sub
Sub QuotedTextTo_T()
ReplaceXWithY("{:q}", "_T(\1)", True, _
vsFindPatternSyntax.vsFindPatternSyntaxRegExpr)
End Sub
End Module
When you go back to your project, you will see a macro named "AutoT" in the Macro Explorer panel on the right.
AutoT
Every time you double click on that macro, it will mark the next quoted text in the currently opened C++ file. Another click on the macro will wrap the text with the _T macro:
which will be changed to:
AfxMessageBox(_T("Hello World!"));
and will compile both in Multibyte and Unicode configurations!
It is recommended to add a keyboard shortcut to the macro:
Now every time you press that keyboard combination, the macro will be executed.
Note: Don't be tempted to blindly let the script do all the job. Human verification is needed. The script will try to add _T macro to lines like:
#include "StdAfx.h"
In order to make the script skip such a line, simply press the "Right" arrow on your keyboard.
The script is also not smart enough to recognize in-text quotes like:
AfxMessageBox(_T("Hello \"World!\" "));
It will also fail to skip quoted text already wrapped with _T macro, but the good thing is it will never skip a quoted text
Note that you will also have to rename all occurrences like strcmp to their TCHAR.H routines like _tcscmp.
strcmp
_tcscmp
If in your multibyte project you've widely used std::string, std::ostringstream, or std::ofstream, those will work badly in a Unicode compilation.
The easiest way is to define the following, and rename all occurrences in your program from std::string to tstring for example.
tstring
#include <string>
typedef std::basic_string<TCHAR> tstring;
typedef std::basic_ostringstream<TCHAR> tostringstream;
typedef std::basic_ofstream<TCHAR> tofstream;
Also, replace all char in your code to TCHAR.
TCHAR
To store Unicode values, std::wstring can be used, but when you must store a Unicode value in a standard std::string or char array, you can store it in UTF-8 format, which is also used in TinyXML, among others.
std::wstring
The following helper functions may help you with the conversions:
std::string CStringToString(const CString& cs)
{
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
//std::string strStd (pszConvertedAnsiString);
return pszConvertedAnsiString;
}
tstring CStringTo_tstring(const CString& cs)
{
std::basic_string <TCHAR> bsConverted (cs);
return bsConverted;
}
std::string tstringTo_stdString(const tstring& ts)
{
return CStringToString(ts.c_str()).c_str();
}
tstring UTF8charTo_tstring( const char* strIn )
{
wchar_t buffer[2048];//!!H
MultiByteToWideChar(CP_UTF8, 0, strIn, -1, buffer, 2048 );//!!H
tstring ts1 = CString(buffer);
return ts1;
}
std::string tstringToUTF8string( tstring tsIn )
{
char buffer[2048];//!!H
WideCharToMultiByte( CP_UTF8, 0, tsIn.c_str() , -1, buffer, 2048, NULL, NULL );
std::string s1 = buffer;
return s1;
}
bool HasUnicodeChars( tstring tsIn )
{
std::string sNarrow = tstringTo_stdString(tsIn);
tstring tsFromNarrow = CString(sNarrow.c_str());
if ( tsFromNarrow != tsIn )
return true;
else
return false;
}
To convert tstring to char*:
char*
CStringToString(sName.c_str()).c_str()
To convert std::string to tstring:
tstring ts30 = CString(stdS1.c_str());
Note: UTF-8 strings are like char strings, but Unicode letters might take two chars, making the string longer:
tstring ts1;
ts1 = _T("Some foreign language text");
int nLen = ts1.length();
int nSize = ts1.size();
//Convert wide string to std string
std::string s2 = tstringToUTF8string(ts1);
int nLen2 = s2.length();
int nSize2 = s2.size();
//Convert std string back to wide string
tstring ts5 = UTF8charTo_tstring(s2.c.
|
http://www.codeproject.com/Articles/43046/Automatically-add-_T-macro-to-quoted-strings-and-o?fid=1550598&df=90&mpp=25&sort=Position&spc=Relaxed&tid=3246759
|
CC-MAIN-2016-22
|
refinedweb
| 848
| 55.74
|
Background
There are many cases in which you may need to populate your Model with some default data or bind the data in request in your model in controller/handler method. It are these cases when @ModelAttribute annotation comes in handy. So in this post we will see how exactly @ModelAttribute method works with some example.
Working of @ModelAttribute
- Before starting I would like to assert your class should be a controller class for this to work which means your class should be annotated with @Controller annotation .
- Method level OR
- Method argument level.
We will come to each in a moment. @ModelAttribute take an optional "value" that represents the name of this attribute. For eg. @ModelAttribute("test") Why we say it is optional? Because as per Springs "Convention over Configuration" principle it allows you to not to provide explicit value and in which case default name is assigned to the ModelAttribute. For eg. if you have a class called "Car" then the model attribute will be stored in the Model by name "car" (notice the small letter c).
The way this annotation works is as follows -
- Before invoking the handler method, Spring invokes all the methods that have @ModelAttribute annotation. So yeah a Controller annotated class can have multiple @ModelAttribute annotated methods. It adds the data returned by these methods to a temporary Map object. The data from this Map would be added to the final Model after the execution of the handler method.
- Then it prepares to invoke the the handler method. To invoke this method, it has to resolve the arguments. If the method has a parameter with @ModelAttribute, then it would search in the temporary Map object with the value of @ModelAttribute. If it finds, then the value from the Map is used for the handler method parameter.
- If it doesn't find it in the Map, then it checks if there is a SessionAttributes annotation applied on the controller with the given value. If the annotation is present, then the object is retrieved from the session and used for the handler method parameter. If the session doesn't contain the object despite of the @SessionAttributes, then an error is raised.
- If the object is not resolved through Map or @SessionAttribute, then it creates an instance of the parameter-type and passes it as the handler method parameter. Therefore, for it to create the instance, the parameter type should be a concrete-class-type (interfaces or abstract class types would again raise an error).
- Once the handler is executed, the parameters marked with @ModelAttributes are added to the Model.
Above is the general working of the annotation at method level or method argument level.
Styles for using ModelAttribute
You can use one of the following styles for adding ModelAttributes to Model -
- Implicitly return variables which will get added to the Model
@ModelAttribute("data") public String addData() { return "test"; }
NOTE : Above "test" String will be added to the Model as name "string"(small s) i.e string=test. If you do something like below -
@ModelAttribute public List<String> addTest() { return Arrays.asList("newValue"); }
then name will be "stringList" i.e stringList=[newValue].
- OR get the Model object and explicitly add multiple data to it
@ModelAttribute public void addData(Model model) { model.addAttribute("test"); model.addAttribute("tes1"); // add more ... }
NOTE : If you add in model two attributes with same name the later one will override the 1st one. Consequently in above code "test1" will override "test" as value for name "string" which is constructed with convention i.e string=test1(After all it is a Map underneath and keys of Map are unique (if you remember keys returns set data structure)).
Examples
Now let us see examples that will help us understand above concepts even more.
Following is a simple Controller class -
@Controller public class WelcomeController { @RequestMapping(value="/home", method = RequestMethod.GET) public String welcome() { return "welcome"; } @ModelAttribute("test") public String addTest() { return "testValue"; } }
Here is what is happening - As we know before handler methods are executed all methods annotated with @ModelAttribute are execute. Consequently out addTest() method gets executed and adds a String with name "test" in the Model. You can access the same in your JSP called "welcome.jsp" as follows -
- <h1><c:out</h1>
You can also access this ModelAttribute in your handler method as follows -
@RequestMapping(value="/home", method = RequestMethod.GET) public String welcome(@ModelAttribute("test") String test) { System.out.println(test); return "welcome"; }
and you should see "testValue" getting printed in your server console. You can even override the value of "test" ModelAttribute in your handler class.
@RequestMapping(value="/home", method = RequestMethod.GET) public String welcome(@ModelAttribute("test") String test, Model model) { System.out.println(test); model.addAttribute("test", "newTestValue"); return "welcome"; }
and now your JSP should show "newTestValue" in h1 heading.
NOTE: When using controller interfaces (e.g. for AOP proxying), make sure to consistently put all your mapping annotations — such as
@RequestMappingand
@SessionAttributes— on the controller interface rather than on the implementation class.
NOTE : SessionStatus.setComplete() method will trigger cleaning of Session Attributes, but only those which Spring will find "actual session attribute". Suppose that you declare 3 session attributes, but use only 1 of them in your handler method parameters then only that will be cleared.
Related Links
- Serving static resources with Spring MVC 3.0 in Java
- Difference between "/*" and "/**" in Spring MVC paths
- Using interceptors in Spring MVC
|
http://opensourceforgeeks.blogspot.com/2016_01_03_archive.html
|
CC-MAIN-2019-43
|
refinedweb
| 899
| 54.63
|
by Sacha Greif
A 5-minute Intro to Styled Components
CSS is weird. You can learn the basics of it in 15 minutes. But it can take years before you figure out a good way to organize your styles.
Part of this is just due to the quirks of the language itself. Out of the box, CSS is quite limited, with no variables, loops, or functions. At the same time, it’s quite permissive in that you can style elements, classes, IDs, or any combination of these.
Chaotic Style Sheets
As you’ve probably experienced for yourself, this is often a recipe for chaos. And while preprocessors like SASS and LESS add a lot of useful features, they don’t really do much to stop CSS anarchy.
That organizational job was left to methodologies like BEM, which — while useful — is entirely optional, and can’t be enforced at the language or tooling level.
The New Wave Of CSS
Fast forward a couple years, and a new wave of JavaScript-based tools are trying to solve these issues at their root, by changing the way you write CSS.
Styled Components is one of these libraries, and it has quickly attracted a lot of attention due to its mix of innovation and familiarity. So if you use React (and if you don’t, check out my JavaScript study plan and my intro to React), it’s definitely worth taking a look at this new CSS alternative.
I recently used it to redesign my personal site, and today I wanted to share a few things I learned in the process.
Components, Styled
The main thing you need to understand about Styled Components is that its name should be taken quite literally. You are no longer styling HTML elements or components based on their class or HTML element:
<h1 className="title">Hello World</h1>
h1.title{ font-size: 1.5em; color: purple;}
Instead, you’re defining styled components that possesses their own encapsulated styles. Then you’re using these freely throughout your codebase:
import styled from 'styled-components';
const Title = styled.h1` font-size: 1.5em; color: purple;`;
<Title>Hello World</Title>
This might seem like a minor difference, and in fact both syntaxes are very similar. But they key difference is that styles are now part of their component.
In other words, we’re getting rid of CSS classes as an intermediary step between the component and its styles.
As styled-components co-creator Max Stoiber says:
“The basic idea of
styled-components is to enforce best practices by removing the mapping between styles and components.”
Offloading Complexity
This will seem counter-intuitive at first, since the whole point of using CSS instead of directly styling HTML elements (remember the
<font> tag?) is to decouple styles and markup by introducing this intermediary class layer.
But that decoupling also creates a lot of complexity, and there’s an argument to be made that compared to CSS, a “real” programming language like JavaScript is much better equipped to handle that complexity.
Props Over Classes
In keeping with this no-classes philosophy, styled-components makes use of props over classes when it comes to customizing the behavior of a component. So instead of:
<h1 className="title primary">Hello World</h1> // will be blue
h1.title{ font-size: 1.5em; color: purple; &.primary{ color: blue; }}
You’d write:
const Title = styled.h1` font-size: 1.5em; color: ${props => props.primary ? 'blue' : 'purple'};`;
<Title primary>Hello World</Title> // will be blue
As you can see, styled-components let you clean up your React components by keeping all CSS and HTML-related implementation details out of them.
That said, styled-components CSS is still CSS. So things like this are also totally valid (although slightly non-idiomatic) code:
const Title = styled.h1` font-size: 1.5em; color: purple; &.primary{ color: blue; }`;
<Title className="primary">Hello World</Title> // will be blue
This is one feature that makes styled-components very easy to get into: when it doubt, you can always fall back to what you know!
Caveats
It’s also important to mention that styled-components is still a young project, and that some features aren’t yet fully supported. For example, if you want to style a child component from a parent, you’ll have to rely on using CSS classes for now (at least until styled-components v2 comes out).
There’s also no “official” way to pre-render your CSS on the server yet, although it’s definitely possible by injecting the styles manually.
And the fact that styled-components generates its own randomized class names can make it hard to use your browser’s dev tools to figure out where your styles are originally defined.
But what’s very encouraging is that the styled-components core team is aware of all these issues, and is hard at work on fixing them one by one. Version 2 is coming soon, and I’m really looking forward to it!
Learn More
My goal here is not to explain in detail how styled-components works, but more to give you a small glimpse so you can decide for yourself if it’s worth checking out.
If I’ve managed to make you curious, here some places where you can learn more about styled-components:
- Max Stoiber recently wrote an article about the reason for styled-components for Smashing Magazine.
- The styled-components repo itself has a extensive documentation.
- This article by Jamie Dixon outlines a few benefits of switching to styled-components.
- If you want to learn more about how the library is actually implemented, check out this article by Max.
And if you want to go even further, you can also check out Glamor, a different take on new-wave CSS!
Self-promotion time: we’re looking for open-source contributors to help with Nova, the easiest way to create full-stack React & GraphQL apps complete with forms, data loading, and user accounts. We don’t use styled-components yet, but you could be the first to implement them!
|
https://www.freecodecamp.org/news/a-5-minute-intro-to-styled-components-41f40eb7cd55/
|
CC-MAIN-2021-04
|
refinedweb
| 1,011
| 62.17
|
03 May 2016 1 comment Python, Web development, Django, Mozilla
ThreadedRequestsHTTPTransporttransport class to send Google Analytics pageview trackings asynchronously to Google Analytics to collect pageviews that aren't actually browser pages.
We have an API on our Django site that was not designed from the ground up. We had a bunch of internal endpoints that were used by the website. So we simply exposed those as API endpoints that anybody can query. All we did was wrap certain parts carefully as to not expose private stuff and we wrote a simple web page where you can see a list of all the endpoints and what parameters are needed. Later we added auth-by-token.
Now the problem we have is that we don't know which endpoints people use and, as equally important, which ones people don't use. If we had more stats we'd be able to confidently deprecate some (for easier maintanenace) and optimize some (to avoid resource overuse).
Our first attempt was to use statsd to collect metrics and display those with graphite. But it just didn't work out. There are just too many different "keys". Basically, each endpoint (aka URL, aka URI) is a key. And if you include the query string parameters, the number of keys just gets nuts. Statsd and graphite is better when you have about as many keys as you have fingers on one hand. For example, HTTP error codes, 200, 302, 400, 404 and 500.
Also, we already use Google Analytics to track pageviews on our website, which is basically a measure of how many people render web pages that have HTML and JavaScript. Google Analytic's UI is great and powerful. I'm sure other competing tools like Mixpanel, Piwik, Gauges, etc are great too, but Google Analytics is reliable, likely to stick around and something many people are familiar with.
So how do you simulate pageviews when you don't have JavaScript rendering? The answer; using plain HTTP POST. (HTTPS of course). And how do you prevent blocking on sending analytics without making your users have to wait? By doing it asynchronously. Either by threading or a background working message queue.
If you have a message queue configured and confident in its running, you should probably use that. But it adds a certain element of complexity. It makes your stack more complex because now you need to maintain a consumer(s) and the central message queue thing itself. What if you don't have a message queue all set up? Use Python threading.
To do the threading, which is hard, it's always a good idea to try to stand on the shoulder of giants. Or, if you can't find a giant, find something that is mature and proven to work well over time. We found that in Raven.
Raven is the Python library, or "agent", used for Sentry, the open source error tracking software. As you can tell by the name, Raven tries to be quite agnostic of Sentry the server component. Inside it, it has a couple of good libraries for making threaded jobs whose task is to make web requests. In particuarly, the awesome ThreadedRequestsHTTPTransport. Using it basically looks like this:
import urlparse from raven.transport.threaded_requests import ThreadedRequestsHTTPTransport transporter = ThreadedRequestsHTTPTransport( urlparse.urlparse(''), timeout=5 ) params = { ...more about this later... } def success_cb(): print "Yay!" def failure_cb(exception): print "Boo :(" transporter.async_send( params, headers, success_cb, failure_cb )
The call isn't very different from regular plain old requests.post.
This is probably the most exciting part and the place where you need some thought. It's non-trivial because you might need to put some careful thought into what you want to track.
Your friends is: This documentation page
There's also the Hit Builder tool where you can check that the values you are going to send make sense.
Some of the basic ones are easy:
Just set to
v=1
That code thing you see in the regular chunk of JavaScript you put in the head, e.g
tid=UA-1234-Z
Optional word you call this type of traffic. We went with
ds=api because we use it to measure the web API.
The user ones are a bit more tricky. Basically because you don't want to accidentally leak potentially sensitive information. We decided to keep this highly anonymized.
A random UUID (version 4) number that identifies the user or the app. Not to be confused with "User ID" which is basically a string that identifies the user's session storage ID or something. Since in our case we don't have a user (unless they use an API token) we leave this to a new random UUID each time. E.g.
cid=uuid.uuid4().hex This field is not optional.
Some string that identifies the user but doesn't reveal anything about the user. For example, we use the PostgreSQL primary key ID of the user as a string. It just means we can know if the same user make several API requests but we can never know who that user is. Google Analytics uses it to "lump" requests together. This field is optional.
Next we need to pass information about the hit and the "content". This is important. Especially the "Hit type" because this is where you make your manually server-side tracking act as if the user had clicked around on the website with a browser.
Set this to
t=pageview and it'll show up Google Analytics as if the user had just navigated to the URL in her browser. It's kinda weird to do this because clearly the user hasn't. Most likely she's used
curl or something from the command line. So it's not really a pageview but, on our end, we have "views" in the webserver that produce information to the user. Some of it is HTML and some of it is JSON, in terms of output format, but either way they're sending us a URL and we respond with data.
The full absolute URL of that was used. E.g.. So in our Django app we set this to
dl=request.build_absolute_uri(). If you have a site where you might have multiple domains in use but want to collect them all under just 1 specific domain you need to set
dh=example.com.
I actually don't know what the point of this is if you've already set the "Document location URL".
In Google Analytics you can view your Content Drilldown by title instead of by URL path. In our case we set this to a string we know from the internal Python class that is used to make the API endpoint.
dt='API (%s)'%api_model.__class__.__name__.
There are many more things you can set, such as the clients IP, the user agent, timings, exceptions. We chose to NOT include the user's IP. If people using the JavaScript version of Google Analytics can set their browser to NOT include the IP, we should respect that. Also, it's rarely interesting to see where the requests for a web API because it's often servers'
curl or
requests that makes the query, not the human.
Going back to the code example mentioned above, let's demonstrate a fuller example:
import urlparse from raven.transport.threaded_requests import ThreadedRequestsHTTPTransport transporter = ThreadedRequestsHTTPTransport( urlparse.urlparse(''), timeout=5 ) # Remember, this is a Django, but you get the idea domain = settings.GOOGLE_ANALYTICS_DOMAIN if not domain or domain == 'auto': domain = RequestSite(request).domain params = { 'v': 1, 'tid': settings.GOOGLE_ANALYTICS_ID, 'dh': domain, 't': 'pageview, 'ds': 'api', 'cid': uuid.uuid4().hext, 'dp': request.path, 'dl': request.build_request_uri(), 'dt': 'API ({})'.format(model_class.__class__.__name__), 'ua': request.META.get('HTTP_USER_AGENT'), } def success_cb(): logger.info('Successfully informed Google Analytics (%s)', params) def failure_cb(exception): logger.exception(exception) transporter.async_send( params, headers, success_cb, failure_cb )
The class we're using,
ThreadedRequestsHTTPTransport has, as you might have seen, a method called
async_send. There's also one, with the exact same signature, called
sync_send which does the same thing but in a blocking fashion. So you could make your code look someting silly like this:
def send_tracking(page_title, request, async=True): # ...same as example above but wrapped in a function... function = async and transporter.async_send or transporter.sync_send function( params, headers, success_cb, failure_cb )
And then in your tests you pass in
async=False instead.
But don't do that. The code shouldn't be sub-serviant to the tests (unless it's for the sake of splitting up monster-long functions).
Instead, I recommend you mock the inner workings of that
ThreadedRequestsHTTPTransport class so you can make the whole operation synchronous. For example...
import mock from django.test import TestCase from django.test.client import RequestFactory from where.you.have import pageview_tracking class TestTracking(TestCase): @mock.patch('raven.transport.threaded_requests.AsyncWorker') @mock.patch('requests.post') def test_pageview_tracking(self, rpost, aw): def mocked_queue(function, data, headers, success_cb, failure_cb): function(data, headers, success_cb, failure_cb) aw().queue.side_effect = mocked_queue request = RequestFactory().get('/some/page') with self.settings(GOOGLE_ANALYTICS_ID='XYZ-123'): pageview_tracking('Test page', request) # Now we can assert that 'requests.post' was called. # Left as an exercise to the reader :) print rpost.mock_calls
This is synchronous now and works great. It's not finished. You might want to write a side effect for the
requests.post so you can have better control of that post. That'll also give you a chance to potentially NOT return a
200 OK and make sure that your
failure_cb callback function gets called.
One thing I was very curious about when I started was to see how it worked if you really ran this for reals but without polluting your real Google Analytics account. For that I built a second little web server on the side, whose address I used instead of. So, change your code so that is not hardcoded but a variable you can change locally. Change it to and start this little Flask server:
import time import random from flask import Flask, abort, request app = Flask(__name__) app.debug = True @app.route("/", methods=['GET', 'POST']) def hello(): print "- " * 40 print request.method, request.path print "ARGS:", request.args print "FORM:", request.form print "DATA:", repr(request.data) if request.args.get('sleep'): sec = int(request.args['sleep']) print "** Sleeping for", sec, "seconds" time.sleep(sec) print "** Done sleeping." if random.randint(1, 5) == 1: abort(500) elif random.randint(1, 5) == 1: # really get it stuck now time.sleep(20) return "OK" if __name__ == "__main__": app.run()
Now you get an insight into what gets posted and you can pretend that it's slow to respond. Also, you can get an insight into how your app behaves when this collection destination throws a 5xx error.
Google Analytics is tricky to test in that they collect all the stuff they collect then they take their time to process it and it then shows up the next day as stats. But, there's a hack! You can go into your Google Analytics account and click "Real-Time" -> "Overview" and you should see hits coming in as you're testing this. Obviously you don't want to do this on your real production account, but perhaps you have a stage/dev instance you can use. Or, just be patient :)
Follow @peterbe on Twitter
cool
|
https://api.minimalcss.app/plog/ga-pageviews-on-non-web
|
CC-MAIN-2019-47
|
refinedweb
| 1,894
| 67.25
|
Subject: Re: [MTT users] unable to pull tests
From: Ethan Mallove (ethan.mallove_at_[hidden])
Date: 2007-11-14 18:25:30
Do you have access to the ompi-tests repository?
What happens if you do this command outside of MTT?
$ svn export
You could also try using "http", instead of "https" in
your svn_url.
-Ethan
On Wed, Nov/14/2007 02:04:27PM, Karol Mroz wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hello everyone...
>
> I've been trying to get MTT set up to run tests on the SCTP BTL Brad
> Penoff and I (over at UBC) have developed. While I'm able to obtain a
> nightly tarball, build and install the Open MPI middleware, I'm unable
> to pull any tests for the various svn repositories. Currently I've tried
> pulling IBM and Onesided tests as shown in the sample
> ompi-core-template.ini file.
>
> Here is the output I see from the console when running with --verbose:
> - ----------------------------------------------------------------------
> *** MTT: ./mtt -f ../samples/ompi-core-template-kmroz.ini --verbose
> *** Reporter initializing
> *** Reporter initialized
> *** MPI get phase starting
> >> MPI get: [mpi get: ompi-nightly-trunk]
> Checking for new MPI sources...
> No new MPI sources
> *** MPI get phase complete
> *** MPI install phase starting
> >> MPI install [mpi install: gcc warnings]
> Installing MPI: [ompi-nightly-trunk] / [1.3a1r16706] / [gcc warnings]...
> Completed MPI install successfully
> Installing MPI: [ompi-nightly-trunk] / [1.3a1r16682] / [gcc warnings]...
> Completed MPI install successfully
> Installing MPI: [ompi-nightly-trunk] / [1.3a1r16723] / [gcc warnings]...
> Completed MPI install successfully
> *** MPI install phase complete
> *** Test get phase starting
> >> Test get: [test get: onesided]
> Checking for new test sources...
> - ----------------------------------------------------------------------
>
> As you can see, MTT seems to hang on 'Checking for new test sources.'
>
> I will attach a copy of the .ini file in hopes that someone may be able
> to point me in the right direction.
>
> Thanks in advance.
>
>
> ompi-core-template-kmroz.ini:
> - -----------------------------------------------------------------------
> # Copyright (c) 2006-2007 Cisco Systems, Inc. All rights reserved.
> # Copyright (c) 2006-2007 Sun Microystems, Inc. All rights reserved.
> #
>
> # Template MTT configuration file for Open MPI core testers. The
> # intent for this template file is to establish at least some loose
> # guidelines for what Open MPI core testers should be running on a
> # nightly basis. This file is not intended to be an exhaustive sample
> # of all possible fields and values that MTT offers. Each site will
> # undoubtedly have to edit this template for their local needs (e.g.,
> # pick compilers to use, etc.), but this file provides a baseline set
> # of configurations that we intend you to run.
>
> # OMPI core members will need to edit some values in this file based
> # on your local testing environment. Look for comments with "OMPI
> # Core:" for instructions on what to change.
>
> # Note that this file is artificially longer than it really needs to
> # be -- a bunch of values are explicitly set here that are exactly
> # equivalent to their defaults. This is mainly because there is no
> # reliable form of documentation for this ini file yet, so the values
> # here comprise a good set of what options are settable (although it
> # is not a comprehensive set).
>
> # Also keep in mind that at the time of this writing, MTT is still
> # under active development and therefore the baselines established in
> # this file may change on a relatively frequent basis.
>
> # The guidelines are as follows:
> #
> # 1. Download and test nightly snapshot tarballs of at least one of
> # the following:
> # - the trunk (highest preference)
> # - release branches (highest preference is the most recent release
> # branch; lowest preference is the oldest release branch)
> # 2. Run all 4 correctness test suites from the ompi-tests SVN
> # - trivial, as many processes as possible
> # - intel tests with all_tests_no_perf, up to 64 processes
> # - IBM, as many processes as possible
> # - IMB, as many processes as possible
> # 3. Run with as many different components as possible
> # - PMLs (ob1, dr)
> # - BTLs (iterate through sm, tcp, whatever high speed network(s) you
> # have, etc. -- as relevant)
>
> #======================================================================
> # Overall configuration
> #======================================================================
>
> [MTT]
>
> # OMPI Core: if you are not running in a scheduled environment and you
> # have a fixed hostfile for what nodes you'll be running on, fill in
> # the absolute pathname to it here. If you do not have a hostfile,
> # leave it empty. Example:
> # hostfile = /home/me/mtt-runs/mtt-hostfile
> # This file will be parsed and will automatically set a valid value
> # for &env_max_np() (it'll count the number of lines in the hostfile,
> # adding slots/cpu counts if it finds them). The "hostfile" value is
> # ignored if you are running in a recognized scheduled environment.
> hostfile =
>
> # OMPI Core: if you would rather list the hosts individually on the
> # mpirun command line, list hosts here delimited by whitespace (if you
> # have a hostfile listed above, this value will be ignored!). Hosts
> # can optionally be suffixed with ":num", where "num" is an integer
> # indicating how many processes may be started on that machine (if not
> # specified, ":1" is assumed). The sum of all of these values is used
> # for &env_max_np() at run time. Example (4 uniprocessors):
> # hostlist = node1 node2 node3 node4
> # Another example (4 2-way SMPs):
> # hostlist = node1:2 node2:2 node3:2 node4:2
> # The "hostlist" value is ignored if you are running in a scheduled
> # environment or if you have specified a hostfile.
> hostlist = localhost
>
> # OMPI Core: if you are running in a scheduled environment and want to
> # override the scheduler and set the maximum number of processes
> # returned by &env_max_procs(), you can fill in an integer here.
> max_np = 2
>
> # OMPI Core: Output display preference; the default width at which MTT
> # output will wrap.
> textwrap = 76
>
> # OMPI Core: After the timeout for a command has passed, wait this
> # many additional seconds to drain all output, and then kill it with
> # extreme prejiduce.
> drain_timeout = 5
>
> # OMPI Core: Whether this invocation of the client is a test of the
> # client setup itself. Specifically, this value should be set to true
> # (1) if you are testing your MTT client and/or INI file and do not
> # want the results included in normal reporting in the MTT central
> # results database. Results submitted in "trial" mode are not
> # viewable (by default) on the central database, and are automatically
> # deleted from the database after a short time period (e.g., a week).
> # Setting this value to 1 is exactly equivalent to passing "--trial"
> # on the MTT client command line. However, any value specified here
> # in this INI file will override the "--trial" setting on the command
> # line (i.e., if you set "trial = 0" here in the INI file, that will
> # override and cancel the effect of "--trial" on the command line).
> # trial = 0
>
> # OMPI Core: Set the scratch parameter here (if you do not want it to
> # be automatically set to your current working directory). Setting
> # this parameter accomplishes the same thing that the --scratch option
> # does.
> # scratch = &getenv("HOME")/mtt-scratch
>
> # OMPI Core: Set local_username here if you would prefer to not have
> # your local user ID in the MTT database
> local_username = kmroz
>
> # OMPI Core: --force can be set here, instead of at the command line.
> # Useful for a developer workspace in which it makes no sense to not
> # use --force
> # force = 1
>
> # OMPI Core: Specify a list of sentinel files that MTT will regularly
> # check for. If these files exist, MTT will exit more-or-less
> # immediately (i.e., after the current test completes) and report all
> # of its results. This is a graceful mechanism to make MTT stop right
> # where it is but not lose any results.
> # terminate_files = &getenv("HOME")/mtt-stop,&scratch_root()/mtt-stop
>
> # OMPI Core: Specify a default description string that is used in the
> # absence of description strings in the MPI install, Test build, and
> # Test run sections. The intent of this field is to record variable
> # data that is outside the scope, but has effect on the software under
> # test (e.g., firmware version of a NIC). If no description string is
> # specified here and no description strings are specified below, the
> # description data field is left empty when reported.
> # description = NIC firmware: &system("get_nic_firmware_rev")
>
> # OMPI Core: Specify a logfile where you want all MTT output to be
> # sent in addition to stdout / stderr.
> # logfile = /tmp/my-logfile.txt
>
> # OMPI Core: If you have additional .pm files for your own funclets,
> # you can have a comma-delimited list of them here. Note that each
> # .pm file *must* be a package within the MTT::Values::Functions
> # namespace. For example, having a Cisco.pm file must include the
> # line:
> #
> # package MTT::Values::Functions::Cisco;
> #
> # If this file contains a perl function named foo, you can invoke this
> # functlet as &Cisco::foo(). Note that funclet files are loaded
> # almost immediately, so you can use them even for other field values
> # in the MTT section.
> # funclet_files = /path/to/file1.pm, /path/to/file2.pm
>
> #----------------------------------------------------------------------
>
> [Lock]
> # The only module available is the MTTLockServer, and requires running
> # the mtt-lock-server executable somewhere. You can leave this
> # section blank and there will be no locking.
> #module = MTTLockServer
> #mttlockserver_host = hostname where mtt-lock-server is running
> #mttlockserver_port = integer port number of the mtt-lock-server
>
> #======================================================================
> # MPI get phase
> #======================================================================
>
> [MPI get: ompi-nightly-trunk]
> mpi_details = Open MPI
>
> module = OMPI_Snapshot
> ompi_snapshot_url =
>
> [MPI install: gcc warnings]
> mpi_get = ompi-nightly-trunk
> save_stdout_on_success = 1
> merge_stdout_stderr = 0
> bitness = 32
>
> module = OMPI
> ompi_vpath_mode = none
> # OMPI Core: This is a GNU make option; if you are not using GNU make,
> # you'll probably want to delete this field (i.e., leave it to its
> # default [empty] value).
> ompi_make_all_arguments = -j 4
> ompi_make_check = 1
> # OMPI Core: You will likely need to update these values for whatever
> # compiler you want to use. You can pass any configure flags that you
> # want, including those that change which compiler to use (e.g., CC=cc
> # CXX=CC F77=f77 FC=f90). Valid compiler names are: gnu, pgi, intel,
> # ibm, kai, absoft, pathscale, sun. If you have other compiler names
> # that you need, let us know. Note that the compiler_name flag is
> # solely for classifying test results; it does not automatically pass
> # values to configure to set the compiler.
> ompi_compiler_name = gnu
> ompi_compiler_version = &get_gcc_version()
> ompi_configure_arguments = CFLAGS=-pipe --enable-picky --enable-debug
>
> #----------------------------------------------------------------------
>
> #======================================================================
> # MPI run details
> #======================================================================
>
> [MPI Details: Open MPI]
>
> # MPI tests
> exec = mpirun @hosts@ -np &test_np() @mca@ --prefix &test_prefix()
> &test_executable() &test_argv()
>
> # ORTE tests
> exec:rte = &test_executable() --host &env_hosts() --prefix
> &test_prefix() &test_argv()
>
> hosts = &if(&have_hostfile(), "--hostfile " . &hostfile(), \
> &if(&have_hostlist(), "--host " . &hostlist(), ""))
>
> # Example showing conditional substitution based on the MPI get
> # section name (e.g., different versions of OMPI have different
> # capabilities / bugs).
> mca = &enumerate( \
> "--mca btl sm,tcp,self_at_v1_1_mca_params@", \
> "--mca btl tcp,self_at_v1_1_mca_params@")
>
> # Boolean indicating IB connectivity
> is_up = &check_ipoib_connectivity()
>
> # Figure out which mca's to use
> mca = <<EOT
> &perl('
>
> # Return cached mca, if we have it
> if (defined(@mca)) {
> return \@mca;
> }
>
> my @hosts = split /\s+|,/, hostlist_hosts();
>
> if (scalar(@hosts) < 2) {
> push(@mca, "--mca btl self,sm");
> } else {
> if ($ib_up) {
> push(@mca, "--mca btl self,udapl");
> } else {
> push(@mca, "--mca btl self,tcp");
> }
> }
> return \@mca;
> ')
> EOT
>
> # OMPI v1.1 cannot handle heterogeneous numbers of TCP or OpenIB
> # interfaces within a single job. So restrict it to a finite number
> # that will be the same across all processes in the job (adjust for
> # your own site, of course -- this particular example is meaningless
> # if all nodes at your site have a homogeneous type and number of
> # network interfaces).
> v1_1_mca_params = &if(&eq(&mpi_get_name(), "ompi-nightly-v1.1"), \
> " --mca btl_tcp_if_include eth0 --mca oob_tcp_if_include eth0 --mca
> btl_openib_max_btls 1", "")
>
> #----------------------------------------------------------------------
> # WARNING: THIS DEFAULT after_each_exec STEP IS PRONE TO FAILURE!
> # Given that part of what we are testing is ORTE itself, using orterun
> # to launch something to cleanup can be problematic. We *HIGHLY*
> # recommend that you replace the after_each_exec section default value
> # below with something that your run-time system can performan
> # natively. For example, putting "srun -N $SLURM_NNODES killall -9
> # mpirun orted &test_executable()" works nicely on SLURM / Linux
> # systems -- assuming that your MTT run has all nodes exclusively to
> # itself (i.e., that the "killall" won't kill some legitimate jobs).
> #----------------------------------------------------------------------
>
> # A helper script is installed by the "OMPI" MPI Install module named
> # "mtt_ompi_cleanup.pl". This script is orterun-able and will kill
> # all rogue orteds on a node and whack any session directories.
> # Invoke via orterun just to emphasize that it is not an MPI
> # application. The helper script is installed in OMPI's bin dir, so
> # it'll automatically be found in the path (because OMPI's bin dir is
> # in the path).
>
> after_each_exec = <<EOT
> # We can exit if the test passed or was skipped (i.e., there's no need
> # to cleanup).
> if test "$MTT_TEST_RUN_RESULT" = "passed" -o "$MTT_TEST_RUN_RESULT" =
> "skipped"; then
> exit 0
> fi
>
> if test "$MTT_TEST_HOSTFILE" != ""; then
> elif test "$MTT_TEST_HOSTLIST" != ""; then
> fi
> orterun $args -np $MTT_TEST_NP --prefix $MTT_TEST_PREFIX mtt_ompi_cleanup.pl
> EOT
>
>
> #======================================================================
> # Test get phase
> #======================================================================
>
> #[Test get: ibm]
> #module = SVN
> #svn_url =
> #svn_post_export = <<EOT
> #./autogen.sh
> #EOT
>
> [Test get: onesided]
> module = SVN
> svn_url =
> svn_post_export = <<EOT
> ./autogen.sh
> EOT
>
> #----------------------------------------------------------------------
>
>
> #======================================================================
> # Test build phase
> #======================================================================
>
> [Test build: ibm]
> test_get = ibm
> save_stdout_on_success = 1
> merge_stdout_stderr = 1
> stderr_save_lines = 100
>
> module = Shell
> shell_build_command = <<EOT
> ./configure CC=mpicc CXX=mpic++ F77=mpif77
> make
> EOT
>
> #[Test build: onesided]
> #test_get = onesided
> #save_stdout_on_success = 1
> #merge_stdout_stderr = 1
> #stderr_save_lines = 100
> # Have the onesided tests skip the OMPI 1.1 testing; MPI-2 one-sided
> # just plain doesn't work there and won't be fixed.
> #skip_mpi_get = ompi-nightly-v1.1
> # Can also have a skip_mpi_install for the same purpose (skip specific
> # installs)
>
> #module = Shell
> #shell_build_command = <<EOT
> #./configure
> #make
> #EOT
>
> #----------------------------------------------------------------------
>
>
> #======================================================================
> # Test Run phase
> #======================================================================
>
> [Test run: ibm]
> test_build = ibm
> pass = &and(&cmd_wifexited(), &eq(&cmd_wexitstatus(), 0))
> skipped = &and(&cmd_wifexited(), &eq(&cmd_wexitstatus(), 77))
> timeout = &max(30, &multiply(10, &test_np()))
> save_stdout_on_pass = 1
> merge_stdout_stderr = 1
> stdout_save_lines = 100
> np = &env_max_procs()
>
> specify_module = Simple
> Similar rationale to the intel test run section
> simple_first:tests = &find_executables("collective", "communicator", \
> "datatype", "dynamic",
> "environment", \
> "group", "info", "io", "onesided", \
> "pt2pt", "topology")
>
> # Similar rationale to the intel test run section
> simple_fail:tests = environment/abort environment/final
> simple_fail:pass = &and(&cmd_wifexited(), &ne(&cmd_wexitstatus(), 0))
> simple_fail:exclusive = 1
> simple_fail:np = &env_max_procs()
>
> #[Test run: onesided]
> #test_build = onesided
> #pass = &and(&cmd_wifexited(), &eq(&cmd_wexitstatus(), 0))
> #timeout = &max(30, &multiply(10, &test_np()))
> #save_stdout_on_pass = 1
> #merge_stdout_stderr = 1
> #stdout_save_lines = 100
> #np = &if(>(&env_max_procs(), 0), &step(2, &max(2, &env_max_procs()),
> 2), 2)
>
> #specify_module = Simple
> #simple_pass:tests = &cat("run_list")
>
>
> #----------------------------------------------------------------------
>
>
> #======================================================================
> # Reporter phase
> #======================================================================
>
> #[Reporter: IU database]
> #module = MTTDatabase
>
> #mttdatabase_realm = OMPI
> #mttdatabase_url =
> # OMPI Core: Change this to be the username and password for your
> # submit user. Get this from the OMPI MTT administrator.
> #mttdatabase_username = you must set this value
> #mttdatabase_password = you must set this value
> # OMPI Core: Change this to be some short string identifying your
> # cluster.
> #mttdatabase_platform = you must set this value
>
> #----------------------------------------------------------------------
>
> # This is a backup for while debugging MTT; it also writes results to
> # a local text file
>
> #[Reporter: text file backup]
> module = TextFile
>
> textfile_filename = $phase-$section-$mpi_name-$mpi_version.txt
>
> textfile_summary_header = <<EOT
> hostname: &shell("hostname")
> uname: &shell("uname -a")
> who am i: &shell("who am i")
> EOT
>
> #textfile_summary_footer =
> #textfile_detail_header =
> #textfile_detail_footer =
>
> textfile_textwrap = 78
>
> - --
> Karol Mroz
> kmroz_at_[hidden]
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.6 (GNU/Linux)
>
> iD8DBQFHO3Druoug78g/Mz8RAiReAJ0fl9txgv+VjI2St+c88dN9iR8oBQCfead+
> qfz2+ijSfk8GMvy+z3Lbi04=
> =SHO4
> -----END PGP SIGNATURE-----
> _______________________________________________
> mtt-users mailing list
> mtt-users_at_[hidden]
>
|
http://www.open-mpi.org/community/lists/mtt-users/2007/11/0451.php
|
CC-MAIN-2014-15
|
refinedweb
| 2,483
| 52.19
|
Getting System.Web.Script.Services.ScriptService Is Not Defined Error?Jan 19, 2011
I created a small new webservice for AutoCompleteExtender and for some reason I am getting "type System.Web.Script.Services.ScriptService is not defined" error. I Googled this and found a few threads about similar issues but was unable to resolve mine. Here is the example of the code:
[Code]....
When I add Imports System.Web.Script.Services I get "Namespace or type specified in the Imports 'System.Web.Script.Services' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases".
I've tried adding Reference to System.Web.Extensions and it didn't do anything. What could be the problem?
|
https://asp.net.bigresource.com/Getting-System-Web-Script-Services-ScriptService-is-not-defined-error--IDlMtZRgh.html
|
CC-MAIN-2021-49
|
refinedweb
| 141
| 53.68
|
P∀scalP∀scal
Concise syntax for polymorphic, a.k.a. universally quantified (∀), values in Scala.
Introduction: Polymorphic valuesIntroduction: Polymorphic values
A polymorphic (also universally quantified) value
a of type
∀A. F[A] is a value that qualifies as a value of type
F[A] for any type
A. That is, a single value that is an instance of
F[Int],
F[String],
F[List[Boolean]], ... simultaneously.
Parametric polymorphism was introduced in System F with the following syntax:
Λα. t : ∀α. T
where
t is a term,
T is a type, and
α is a type variable that can occur in both
t and
T. (Τhe expression after the colon is the type of the lambda expression preceding it.)
For example, the following is the identity function:
Λα. λ(x:α). x : ∀α. α -> α
Encoding polymorphic values in ScalaEncoding polymorphic values in Scala
Scala lacks direct support for polymorphic values. It has generic types (
class Foo[A]) and methods (
def foo[A]). These are sufficient for some use cases. For example, the above polymorphic identity function can be written as a polymorphic method:
def identity[α](x: α): α = x
or, alternatively
def identity[α]: (α => α) = (x: α) => x
The shortcoming is that a method cannot be passed as an argument (i.e. value) to another method. The usual solution is to wrap the method in an object, which can be passed around as a value:
trait ForAll[F[_]] { def apply[A]: F[A] } type IdentityFun[A] = A => A val identity: ForAll[IdentityFun] = new ForAll[IdentityFun] { def apply[A]: IdentityFun[A] = x => x } // usage identity[Int](42)
Now
identity is a value that can be freely passed to other methods or functions.
This encoding, however, has several drawbacks:
- Verbose syntax for creating polymorphic values (an anonymous class implementing the interface).
- Requires a dedicated wrapper type for each arity of type parameters. In the example above, we used
ForAll[F[_]], but elsewhere we might also need
ForAll2[F[_, _]],
ForAllH[F[_[_]]], etc.
- Specialization of polymorphic values (
ForAll[F]) to a specific type (e.g.
F[Int]) may in general allocate new objects.
This project addresses (only) the first problem, namely the verbosity of polymorphic value creation.
The second problem would be addressed by kind-polymorphism (which, unfortunately, Scala also lacks).
The third problem can be addressed by other methods, e.g..
More concise syntaxMore concise syntax
This project provides more concise syntax for creation of polymorphic values (in the usual encoding (see above)). It tries to approximate the System F syntax mentioned above (
Λα. t : ∀α. T).
It works as a compiler plugin that performs the following rewrites:
Λ[α](t): T
is analogous to System F's
Λα. t : T
(where
T is of the form
∀α. U) and is rewritten to
new T { def apply[α] = t }
For example
Λ[α](x => x): ForAll[IdentityFun]
is rewritten to
new ForAll[IdentityFun] { def apply[α] = x => x }
Generalizing to multiple type parameters of arbitrary kinds,
Λ[A, B[_], ...](t): T
is rewritten to
new T { def apply[A, B[_], ...] = t }
Note that the type ascription (
: T) of the Λ-expression cannot be omitted (it cannot be inferred, since P∀scal runs before typer).
We see that we are basically just providing a more concise syntax for instantiating types with a single abstract generic parameterless method named
apply.
In addition to the
Λ-syntax above, we provide an alternative
ν-syntax that reads more like the expression that it is rewritten to:
ν[T][A, B[_], ...](t)
is rewritten to
new T { def apply[A, B[_], ...] = t }
"ν" is the Greek lowercase letter "Nu", pronounced "new".
In the common case when the generic method has a single monomorphic (i.e. of kind
*) type parameter which is not referenced in the method body (
t), the
ν-syntax allows one to omit the type parameter:
ν[T](t)
is rewritten to
new T { def apply[A] = t }
where
A is a fresh name.
The
ν-syntax also allows one to specify the method name in case it is different from
apply:
ν[T].foo[A, B[_], ...](t)
is rewritten to
new T { def foo[A, B[_], ...] = t }
See the test cases for some examples.
Self-referencesSelf-references
It is possible for a polymorphic value to reference itself. For this, add a self-identifier and '
=' before the polymorphic body. For example:
ν[T].foo[A](self = t)
where the term
t can use the identifier
self to refer to itself. It is rewritten to
new T { self => def foo[A] = t }
Using the pluginUsing the plugin
To use this plugin in your project, add the following line to your
build.sbt file:
addCompilerPlugin("com.github.tomasmikula" % "pascal" % "0.4.0" cross CrossVersion.full)
If your project uses Scala 2.10, also add
libraryDependencies ++= (scalaBinaryVersion.value match { case "2.10" => compilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full) :: Nil case _ => Nil })
Relation to
kind-projector
kind-projector's polymorphic lambdas provide similar functionality to this plugin. Our approach is more general in the following respects:
- Polymorphic values generalize polymorphic functions.
- We support quantification over:
- multiple type parameters;
- type parameters of arbitrary kinds.
- We support referencing type parameters from the method body.
Actually, this work started as a PR at
kind-projector. For the lack of interest and for the sake of separation of concerns, I eventually published this as a separate project. This project borrows some code directly from
kind-projector and is distributed under the same license (MIT) and original author's copyright notice.
|
https://index.scala-lang.org/tomasmikula/pascal/pascal/0.3.2?target=_2.12
|
CC-MAIN-2021-17
|
refinedweb
| 935
| 57.16
|
While I hope you’ll see just how easy they are to use. We’re also going to look at them without type signatures first, so that you get an idea of the usage patterns, and then we’ll investigate the types and see what they mean.
Everything in conduit begins with the
Source, which
yields data as it is demanded. The dumbest possible form of source is an empty source:
empty = return ()
The next dumbest is a source that yields only a single value:
single = yield 1
In order to use any
Source, I must ultimately connected it with a
Sink.
Sinks are nothing more than code which
awaits values from a
Source. Let’s look at an example in Python, where these concepts are features of the language itself:
def my_generator(): for i in range(1, 10): yield i for j in my_generator(): print j
Here we have a generator (aka Source): a function which simply yields values. This generator is being passed to
for statement that consumes the values from it and binds them one by one to a variable
j. It then prints each value after it is consumed.
The equivalent code using conduit employs a different syntax, but the general “shape” of the code is the same:
import Control.Monad import Control.Monad.IO.Class (liftIO) import Control.Monad.Loops (whileJust_) import Data.Conduit myGenerator = forM_ [1..9] yield main = myGenerator $$ whileJust_ await $ \j -> liftIO $ print j
I can make the code a little bit closer to Python’s example (making the call to
await implicit) if I use
Data.Conduit.List:
import Control.Monad import Control.Monad.IO.Class (liftIO) import Control.Monad.Loops (whileJust_) import Data.Conduit import qualified Data.Conduit.List as CL myGenerator = forM_ [1..9] yield main = myGenerator $$ CL.mapM_ $ \j -> liftIO $ print j
Just regular code
Neither
Sources nor
Sinks have to be special functions, however. They are just regular code written in the
ConduitM monad transformer:
import Data.Conduit import Control.Monad.IO.Class (liftIO) main = do (do yield 10 yield 20 yield 30) $$ (do liftIO . print =<< await liftIO . print =<< await liftIO . print =<< await liftIO . print =<< await)
Each time
await is called, it returns a value that was
yielded by the source wrapped in
Just, or it returns
Nothing to indicate the source has no more values to offer.
There, now you know the basics of the conduit library.
Conduits
Between sources and sinks, there is a third kind of conduit, which is actually called just
Conduit. A
Conduit sits between sources and sinks, and is able to call both
yield and
await, applying some kind of transformation or filter to the data coming from the source, before it reaches the sink. In order to use a
Conduit, you must fuse it to either a source or a sink, creating a new source/sink which has the action of the
Conduit bound to it. For example:
import Data.Conduit import Control.Monad.IO.Class (liftIO) import Control.Monad.Loops (whileJust_) main = do (do yield 10 yield 20 yield 30) $= (do whileJust_ await $ \x -> yield (x * 2)) $$ (do liftIO . print =<< await liftIO . print =<< await liftIO . print =<< await liftIO . print =<< await)
This example fuses a conduit that doubles the incoming values from the source to its left. We could equivalently have fused it with the sink to the right. In most cases it doesn’t matter whether you fuse to sources or to sinks; it mainly comes into play when you are using such fusion to create building blocks that will be used later.
Use the types, Luke
Now that we have the functionality of conducts down, let’s take a look at their types so that any errors you may encounter are less confusing.
A source has the type
Source m Foo, where
m is the base monad and
Foo is the type of what you want to pass to
yield.
A sink has the corresponding type
Sink m Foo a, to indicate that
await returns values of type
Maybe Foo, while the monadic operation of the sink returns a value of type
a.
A conduit between these two would have type
Conduit Foo m Foo.
You’re probably going to see the type
ConduitM in your types errors too, since the above three are all synonyms for it. It’s a more general type that these three specialized types. The correspondences are:
type Source m o = ConduitM () o m () type Sink i m r = ConduitM i Void m r type Conduit i m o = ConduitM i o m ()
The
Void you see in there is just enforcing the fact that sinks cannot call
yield.
What’s next?
Beyond this, most of the conduit library is a bunch of combinators to make them more convenient to use. In a lot of cases, you can reduce conduit code down to something which is just as brief and succinct as what you might write in languages with native support for such operations. It’s a testiment to Haskell, rather, that it doesn’t need to be a syntactic feature to be both useful and concise.
And what about
pipes, and the other competing libraries in this space? In many ways they are each equivalent to what I’ve described above. If you want to use
pipes, just write
respond and
request instead of
yield and
await, and you’re pretty much good to go! The operators for binding and fusing are different too, but what they accomplish is likewise the same.
If you’re interested in learning more about conduit and how to use it, check out the author’s own tutorial.
|
http://newartisans.com/2013/07/a-whirlwind-tour-of-conduits/
|
CC-MAIN-2017-13
|
refinedweb
| 941
| 72.76
|
This C Program illustrates the concept of unions. A union is a variable that may hold (at different times) objects of different types and sizes, with the compiler keeping track of size and alignment requirements. Unions provide a way to manipulate different kinds of data in a single area of storage, without embedding any machine-dependent information in the program.
Here is source code of the C program to illustrate the concept of unions. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to illustrate the concept of unions
*/
#include <stdio.h>
void main()
{
union number
{
int n1;
float n2;
};
union number x;
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 = %d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%f", &x.n2);
printf("Value of n2 = %f\n", x.n2);
}
$ cc pgm93.c $ a.out Enter the value of n1: 10 Value of n1 = 10 Enter the value of n2: 50 Value of n2 = 50.000000
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms
If you wish to look at other example programs on Simple C Programs, go to Simple C Programs. If you wish to look at programming examples on all topics of C, go to C Programming Examples.
|
http://www.sanfoundry.com/c-program-find-union-size/
|
CC-MAIN-2014-52
|
refinedweb
| 235
| 66.13
|
Not all location relevant properties of viewports are currently accessible through the Revit API, which makes it slightly challenging to precisely define their position.
Let us look at a clever trick to align viewports exactly that works around that limitation, sheds some light on their location calculation and the modification of it that was made between Revit 2013 and 2014.
After that, I would like to briefly present a non-Revit-API BIM topic, a single-page MSc thesis overview on completely conceptual design automation, and mention the new Graitec technology acqusition.
Exact Viewport Positioning
Question: I want to programmatically place views on a sheet and align them exactly with each other. In Revit 2013, my code works perfectly. I calculate the position of the view on the sheet from its crop box.
When I use the same calculation in Revit 2014, the insertion point is no longer correct.
The view is placed centred according to the viewport instead of the view. The viewport location differs from the view one, because it depends on shown annotations and grid lines which extend the viewport, so my views are no longer aligned due to the different placing.
Here is the code to reproduce and demonstrate this behaviour using hard-coded element ids, so it will obviously only work in the specific test model:
public class ViewSheetTest1 : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { var doc = commandData.Application .ActiveUIDocument.Document; test2( doc ); return Result.Succeeded; } private static void test; var vSheet = ViewSheet.Create( doc, typ.Id ); vSheet.Name = "test2"; ElementId vid = vSheet.Id; var p = XYZ.Zero; var v12 = Viewport.Create( doc, vid, go1.Id, p ); var v22 = Viewport.Create( doc, vid, vg1.Id, p ); } }
Here is the correct result produced in Revit 2013:
In Revit 2014, the viewport position is offset, as you can see from the highlighted hatch overlaps and gaps:
How can I solve this, please?
Is it possible to retrieve the coordinates of the view within the viewport, or is there some other possible solution for this?
Answer: The Viewport.Create method was fixed in 2014 to behave the way that was always documented – placement point being at the centre of the viewport. This was fixed because it was very difficult to lay out multiple views on a sheet where the viewport locations were determined by world coordinates and the size of the related view.
Unfortunately, you have encountered a drawback to this change – because many viewports will have a different centre relative to model coordinates, aligning them related to model coordinates is more difficult.
There is currently a gap in the API related to converting between model and sheet coordinates.
In the meantime, here is a workaround:
- Set the crop box for both views to be suitably large and identical.
- That will cause them to have identical viewport boundaries.
- You can therefore easily align them on the sheet.
- Then, restore the previous crop box settings.
Here is a function that does this for the two views in the original code:
void test values BoundingBoxXYZ savedBox1 = null; if( go1.CropBoxActive ) savedBox1 = go1.CropBox; BoundingBoxXYZ savedBox2 = null;"; ElementId vid = vSheet.Id; var p = XYZ.Zero; var v12 = Viewport.Create( doc, vid, go1.Id, p ); var v22 = Viewport.Create( doc, vid, vg1.Id, p );; } }
Response: The suggested workaround works like a charm. :-)
I still have a question regarding your statement "... because many viewports will have a different centre relative to model coordinates": how does Revit internally calculate the centre of a viewport? Is that controlled by the CropBox property value?
Answer: The viewport size is governed by both the annotation crop box and the model crop box at different times, depending on which is larger. Currently, the API only provides access to the model crop box.
Therefore, making the model crop box large enough (where 'enough' is not a very precise term) seems to help. When it is too small, the annotations in one of the views causes the mismatch you observed.
Response: I am happy to inform you that I have tested your workaround in a couple of scenarios in our main application and it continues to work
Conceptual Design Automation Thesis
Ritchie Jackson of the Adaptive Architecture and Computation programme at UCL, the University College London, provided several valuable contributions to this blog in the past and now completed his MSc. thesis on Conceptual Design Automation including this single-page complete overview:
It was implemented using the Unity game engine, C# and a neural network to facilitate the automation of the conceptual design process, so with no Revit API involvement.
Here is a short Q&A between me and Ritchie to gain better understanding:
Questions: After reading the text, I do not understand where the neural network enters into the picture, or what has been optimised or learned by the machine in the process. To me, it looks like random input and random output.
- What is the non-random part?
- What is the target or goal?
- What has been optimised or improved?
Answers:
- Random input only – for modular assembly.
- Non-random is the concept categorisation process by the neural network into definable clusters – aesthetic in this case.
- Goal is to reconstitute similar unique concepts from a preferred cluster once unsupervised learning is complete.
- The network is able to produce viable concepts far more quickly than traditional 'manual' CAD techniques.
Questions:
- How does the unsupervised learning work?
- Where is the supervised learning in this process?
- How do you identify viable concepts?
- What in an unviable concept?
Answers:
- Unsupervised learning works by finding patterns rather than matching them.
- There is no supervised learning as there are no specific pre-defined modular arrangements to be targeted.
- Viable concepts, in this particular case, are those that meet the designer's aesthetic preferences.
- Conversely, unviable concepts are those that don't.
In addition: –
- Machines are more capable than humans at swiftly producing serendipitous outcomes.
Many thanks to Ritchie for sharing this, and especially for the nice wording of the final conclusion :-)
Autodesk Acquires Additional Structural Engineering Knowhow
To close, a piece of breaking news: Autodesk has signed an agreement to acquire Graitec technology, including the Advance Steel and Advance Concrete product lines, and associated employees, thus expanding its BIM portfolio for structural fabrication and detailing.
Addendum: Here are new links to the new Advance Steel and Advance Concrete product centers:
|
https://thebuildingcoder.typepad.com/blog/2013/10/exact-viewport-positioning-conceptual-design-automation-and-graitec.html
|
CC-MAIN-2020-34
|
refinedweb
| 1,060
| 56.15
|
This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.These classes are used to read and write primitive data types and strings. If you deal only with primitive types, this is the best stream to use. Remember that this data is not easily readable by a human eyeing its contents since the data is read in its binary form.Table 6.13 lists some of the read and write methods. Table 6.13: Some Methods of the BinaryReader and BinaryWriter Classes The BinStream class shown in Listing 6.12 is again similar to the StreamRW class from Listing 6.10, with the distinction that the user profile here is stored in binary format. Listing 6.12: BinaryReader and BinaryWriter Example using System;using System.IO;public class BinStream{ public BinStream() { Writer(); Reader(); } public static void Main() { BinStream bs = new BinStream(); Console.ReadLine(); } private void Writer() { try { Console.Out.WriteLine("Preparing to Write ..."); //Open a FileStream on the file "aboutme" FileStream fout = new FileStream("aboutme.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); //Create a BinaryWriter from the FileStream BinaryWriter bw = new BinaryWriter(fout); //Create some arbitrary variables string name = "Saurabh"; int age = 20; double height = 5.11; bool single = true; char gender = 'M'; //Write the values to file bw.Write(name); bw.Write(age); bw.Write(height); bw.Write(single); bw.Write(gender); //Close the file and free resources bw.Close(); Console.WriteLine("Data Written!"); Console.WriteLine(); } catch (IOException e) { Console.WriteLine("An IO Exception Occurred :" + e); } } private void Reader() { try { Console.WriteLine("Preparing to Read ..."); //Open a FileStream in Read mode FileStream fin = new FileStream("aboutme.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Create a BinaryReader from the FileStream BinaryReader br = new BinaryReader(fin); //Seek to the start of the file br.BaseStream.Seek(0, SeekOrigin.Begin); //Read from the file and store the values to the variables string name = br.ReadString(); int age = br.ReadInt32(); double height = br.ReadDouble(); bool single = br.ReadBoolean(); char gender = br.ReadChar(); //Display the data on the console Console.WriteLine("Name :" + name); Console.WriteLine("Age :" + age); Console.WriteLine("Height :" + height); Console.WriteLine("Single? :" + single); Console.WriteLine("Gender M/F:" + gender); //Close the stream and free the resources br.Close(); Console.WriteLine("Data Read!"); } catch (IOException e) { Console.WriteLine("An IO Exception Occurred :" + e); } }}Output of above Listing 6.12.This example has defined a class called BinStream that has two methods: Writer and Reader. The Writer method creates a FileStream object on the file called aboutme.txt and then creates a BinaryWriter from the FileStream object. Then some primitive variables are written to the file using the Write method from the BinaryWriter class. Finally, the BinaryWriter is closed. The Reader method creates a FileStream object on the file previously written (aboutme.txt) in Read mode. A BinaryReader class is instantiated using the FileStream object. The different overloads of the Read method of the BinaryReader class are used to read different primitive data types from the file. Finally, the read values are displayed on the console and the stream is closed. ConclusionHope this article would have helped you in understanding BinaryReader and BinaryWriter Classes in C#. See other articles on the website on .NET and C#.
©2016
C# Corner. All contents are copyright of their authors.
|
http://www.c-sharpcorner.com/uploadfile/puranindia/binaryreader-and-binarywriter-classes-in-C-Sharp/
|
CC-MAIN-2016-30
|
refinedweb
| 552
| 52.97
|
I was playing around with Razor and CSS trying to start a website and searching a way to parameterize the CSS values for my site, because I always make a mess in the CSS . After a few hours of testing and thinking, I wrote this code. I hope this will be helpful. This code helps to use a dynamic CSS file generated with Razor engine. You can use all the power of Razor to generate the CSS, for example, you can use variables, conditionals, functions. I know that exists, but I think that using Razor is a more standard way because you are using all the power of the View Engine. Of course, is more complex and complete, but you can evaluate this approach.
The basic idea is to generate the CSS file dynamically, but not the entire file, just the important values, like the primary colors, fonts, all settings that define your site. Using this approach, you can have one (or more) CSS file and use this like a template and define variables and reuse in all CSS files.
The use is very simple With NuGet () installed, the first thing you have to do is install the package of razorengine. To do that, go to Tools > Library Package Manager > Package Manager Console and write in console:
install-package razorengine
After that, create an ASP.NET MVC 3 Web Application Project.
and select:
Go to _Layout View:
_Layout
and change the CSS link:
Then add a Controller named Home, add a View named Index. You can create any Controller and View. I suggest that because they are the default MVC. Then create the controller that will create the CSS dynamically. Add the controller 'Style'. You can choose any name, but note that the name of controller must match with the 'link href="@Url.Action("Index", "Style")"' used in _Layout View.
Style
link href="@Url.Action("Index", "Style")"
The Style Controller will only have an Action, and will be the default Action Index. This Action returns the CSS generated in a string:
string
Like you can see, this Action will load the CSS file '~/Content/Site.css'. You can change or even add more complex logic to decide which CSS file loads, or whatever you want. And after load, the file parses with Razor.Parse(). This will parse the Razor template and generate a result content, in this case a CSS. Now let me show you what is inside the Site.css, here comes the good part.
Razor.Parse()
In the CSS, you just write Razor Code! You can define variables or whatever that Razor allows you, and then use in any part of the CSS:
and reuse, and reuse, and reuse, just use a Razor syntax '@{}':
@{}
Well, that's all. I hope this will be helpful in some way if you need to use dynamic CSS. I know that many improvements are needed, but this is just a beginning.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
var model = new
{
fontName = "Verdana",
fontSize= "10px",
otherVar = "xxxxxxx"
};
//CONTENT
string templateContent = File.ReadAllText(fileName);
cssBody = Razor.Parse(templateContent, model);
public class StyleController : Controller
{
public string Index()
{
string sourceCss = Server.MapPath("/Content/Site.css");
string compiledCss = Server.MapPath("/Content/Site._css");
DateTime sourceCssTimeUtc = System.IO.File.GetLastWriteTimeUtc(sourceCss);
DateTime compiledCssTimeUtc = System.IO.File.GetLastWriteTimeUtc(compiledCss);
Response.ContentType = "text/css";
if (sourceCssTimeUtc > compiledCssTimeUtc)
{
string sourceContent = System.IO.File.ReadAllText(sourceCss);
string compiledContent = Razor.Parse(sourceContent);
System.IO.File.WriteAllText(compiledCss, compiledContent);
return compiledContent;
}
else
{
return System.IO.File.ReadAllText(compiledCss);
}
}
}
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
http://www.codeproject.com/Articles/171695/Dynamic-CSS-using-Razor-Engine?msg=4141128
|
CC-MAIN-2016-36
|
refinedweb
| 627
| 65.83
|
#What will be part of in Clojure` 1.9.
In this article, we present
spec live coding examples provided byKLIPSE. (This article is a rewrite of with live examples instead of static code snippets.)
Get prepared to experience something really amazing, enabled by Self-Host Clojurescript: KLIPSE runs on
clojurescript version
1.8.51 while
spec is available only in
1.9 :
[*clojurescript-version*]
How is it possible?
At run time, KLIPSE loads the code from the
clojurecript gihub repository where the code for
spec has been ported on May 29 by David Nolen and Mike Fikes.
Because, all the magic (code loaded from github + execution) happens at run time, it takes about 15 seconds to execute all the code snippets of this page (sometimes the page might seem to hang :(). So please be patient and do not read too fast.
All the coding examples below are live and editable :
- the code is executed in your browser while you are reading
- you can edit the code and after 2 seconds it is evaluated
#Setup
Let’s start by requiring the
cljs.spec namespace:
(ns my.spec (:require [cljs") ;; true
-str : 1.9 introduces clojure.spec: tutorial with live coding examples #cljklipse @viebel
评论 抢沙发
|
http://www.shellsec.com/news/23677.html
|
CC-MAIN-2016-44
|
refinedweb
| 204
| 65.93
|
Tutorial
How To Upgrade from AngularJS to Angular with ngUpgrade (2+) is here, and we’re all super excited about it. For some of us, though, we’re still maintaining large AngularJS (1.x) codebases at work. How do we start migrating our application to the new version of Angular – especially if we can’t afford to take six months away from a feature development for a complete rewrite?
That’s where the ngUpgrade library comes in. ngUpgrade is the official tool to allow you to migrate your application litle by little. It lets Angular run side-by-side along with your AngularJS code for as long as you need to slowly upgrade.
In this guide, you will install and set up ngUpgrade and Angular. Then, you’ll learn the basics of rewriting components.
(P.S. If the length of this guide freaks you out, don’t worry. I’ve built a step-by-step, super detailed video program called Upgrading AngularJS that covers all of this in detail.)
<a href=“”\>
</a\>
Our Starting Point
To get started with ngUpgrade, your application needs to meet a few prerequisites:
- Code organized by feature (not by type) and every file contains only one item (like a directive or service)
- TypeScript set up
- Using a module bundler (most people use Webpack)
- Using AngularJS 1.5+ with controllers replaced by components
(If you’re lost on any of that, we cover it all in parts 1 and 2 of the course.)
For now, though, take a minute to clone or fork the course sample project on GitHub (don’t forget to run
npm install). Checkout this commit to see our starting point:
git checkout fdfcf0bc3b812fa01063fbe98e18f3c2f4bcc5b4
We’ve got an Order System project that we can use to work through ngUpgrade. Starting at this commit, our application meets all of the above criteria. We’re using component architecture, TypeScript, and Webpack (we’ve even got builds for both development and production).
Note: In many large AngularJS apps, you just can’t move everything into a brand new Git repository and wipe out years of history. You also might be using a different app structure than the CLI. If you can use the CLI for your upgrade, then feel free to do so. This guide, however, will teach you the manual setup here so that you can have complete control over your upgrade.
Installing Angular & ngUpgrade
We’re ready to install Angular, ngUpgrade, and all of the peer dependencies. In the sample project, go ahead and update your
package.json dependencies array so it looks like this:
"dependencies": { "@angular/common": "^5.2.5", "@angular/compiler": "^5.2.5", "@angular/core": "^5.2.5", "@angular/forms": "^5.2.5", "@angular/platform-browser": "^5.2.5", "@angular/platform-browser-dynamic": "^5.2.5", "@angular/router": "^5.2.5", "@angular/upgrade": "^5.2.5", "angular": "1.6.6", "angular-route": "1.6.6", "bootstrap": "3.3.7", "core-js": "^2.5.3", "jquery": "^2.2.4", "lodash": "4.17.4", "moment": "~2.17.1", "reflect-metadata": "^0.1.12", "rxjs": "^5.5.6", "zone.js": "^0.8.20" }
(We’re going to use Angular 5 in this series, even though the sample project uses version 4. Don’t sweat it - the steps are identical.)
We could put all of these packages in one long command in the terminal with the save flag, but we will take the time to explain what each of these packages are.
First are our libraries under the
@angular namespace:
@angular/common: These are the commonly needed services, pipes, and directives for Angular. This package also contains the new
HttpClientas of version 4.3, so we no longer need
@angular/http.
@angular/compiler: This is Angular’s template compiler. It takes the templates and converts them into the code that makes your application run and render. You almost never need to interact with it.
@angular/core: These are the critical runtime parts of Angular needed by every application. This has things like the metadata decorators (e.g.
Component,
Injectable), all the dependency injection, and the component life-cycle hooks like
OnInit.
@angular/forms: This is just everything we need with forms, whether template or reactive.
@angular/platform-browser: This is everything dom and browser related, especially pieces that help render the dom. This is the package that includes
bootstrapStatic, which is the method that we use for bootstrapping our applications for production builds.
@angular/platform-browser-dynamic: This package includes providers and another bootstrap method for applications that compile templates on the client. This is the package that we use for bootstrapping during development and we’ll cover switching between the two in another video.
@angular/router: As you might guess, this is just the router for Angular.
@angular/upgrade: This is the ngUpgrade library, which allows us to migrate our AngularJS application to Angular.
After all of our Angular packages come our polyfill packages that are dependencies of Angular:
core-jspatches the global context or the window with certain features of ES6 or ES2015.
reflect-metadatais a polyfill library for the annotations that Angular uses in its classes.
rxjs: This is the library that includes all of the observables that we’ll use for handling our data.
zone.jsis a polyfill for the Zone specification, which is part of how Angular manages change detection.
Sometimes, there are conflicts involving the version of TypeScript you’re using. This can be due to RxJS, the Angular compiler, or Webpack. If you start getting weird compilation errors, do some research to find out of any of those need a specific version range of TypeScript for the version you’re using.
Open your terminal,
cd into the
public folder of the project, and run
npm install (you’re welcome to install and use Yarn if you’d prefer). You will see that all of your packages were installed.
We’re now ready to make our application a hybrid application by dual-booting both AngularJS and Angular.
Setting Up ngUpgrade
To set up ngUpgrade, we need to do a series of steps to allow AngularJS and Angular to run alongside of each other.
Step 1: Removing Bootstrap from
index.html
The first thing we need to do is remove our bootstrap directive from
index.html. This is how AngularJS normally gets started up at page load, but we’re going to bootstrap it through Angular using ngUpgrade. So, just open
index.html and remove that
data-ng-app tag. (if you’re using strict DI in your own app, you’ll remove
ng-strict-di as well in this step.) Your
index.html file will look like this now:
<html> <head> <title>Amazing, Inc. Order System</title> </head> <body> <navigation></navigation> <div class="container" ng-view></div> </body> </html>
Step 2: Changing the AngularJS Module
Now we need to make some changes in AngularJS module. Open up app.ts. The first thing we need to do is rename
app.ts to
app.module.ajs.ts to reflect that it’s the module for AngularJS. It’s kind of a lengthy name, but in Angular we want to have our type in our file name. Here we’re using
app.module and then we’re adding that
ajs to specify that it’s for AngularJS instead of our root
app.module for Angular (which we’ll make in a second).
As the app is now, we’re just using AngularJS, so we have all of our import statements here and we’re registering everything on our Angular module. However, now what we’re going to do is export this module and import it into our new Angular module to get it up and running. So, on line 28 let’s create a string constant of our app name:
const MODULE_NAME = 'app';
Then we’ll replace our app string with module name in our Angular.module declaration:
angular.module(MODULE_NAME, ['ngRoute']) // component and service registrations continue here
And finally, we need to export our constant:
export default MODULE_NAME;
You can check out the finished AngularJS module at this stage here.
Step 3: Creating the Angular App Module
Our AngularJS module is ready to go, so we’re now ready to make our Angular module. We’ll then import our AngularJS module so we can manually bootstrap it here. That’s what let’s the two frameworks run together, and enables ngUpgrade to bridge the gap between them.
The first thing we need to do is create a new file at the same level as our AngularJS module called
app.module.ts. Now for the first time, you’re about to see a pattern that’s going to become familiar to you throughout your upgrade: making and exporting a class, decorating it with an annotation, and importing all of the dependencies.
In our new app module, let’s create a class named
AppModule:
export class AppModule { }
Now let’s add our first annotation (also called a decorator). An annotation is just a bit of metadata that Angular uses when building our application. Above our new class, we’ll use the
NgModule annotation and pass in an options object:
@NgModule({}) export class AppModule { }
If you’re following along in an editor like Visual Studio Code, you’ll see that TypeScript is mad at us because it doesn’t know what
NgModule is. This is because we need to import it from the Angular core library. Above our decorator, we can fix this with:
import { NgModule } from '@angular/core';
Now, in our options object for ngModule, we need to pass an array of imports. The imports array specifies other NgModules that this NgModule will depend on. (These imports are different than the TypeScript imports at the top of our file.) Right now, we need the BrowserModule and the UpgradeModule:
import { NgModule } from '@angular/core'; @NgModule({ imports: [ BrowserModule, UpgradeModule ] }) export class AppModule { }
Of course, we don’t have those imported either at the top of our file, so we need to do that too. After our first import, we can add:
import { BrowserModule } from '@angular/platform-browser';
import { UpgradeModule } from '@angular/upgrade/static';
There’s an UpgradeModule in both
upgrade and
upgrade/static. We want to use the static one because it provides better error reporting and works with AOT (ahead-of-time) compiling.
We’ve got the basic scaffolding of our root module for Angular set up and we’re ready to do the bootstrapping itself.
Step 4: Bootstrapping in the Angular Module
To bootstrap our application, the first thing we need to do is inject UpgradeModule using a constructor function:
constructor(private upgrade: UpgradeModule){ }
We don’t need to do anything in our constructor function. The next thing we’ll do is override the
doBootstrap function. After the constructor, type:
ngDoBootstrap(){ }
Next, we’ll use the UpgradeModule’s bootstrap function. It has the same signature as the Angular bootstrap function, but it does a couple extra things for us. First, it makes sure that Angular and AngularJS run in the correct zones, and then it sets up an extra module that allows AngularJS to be visible in Angular and Angular to be visible in AngularJS. Lastly, it adapts the testability APIs, so that Protractor will work with hybrid apps, which is super important.
Let’s add it:
ngDoBootstrap(){ this.upgrade.bootstrap(document.documentElement, [moduleName], {strictDi: true}); }
We’re first passing in our
document element and then our AngularJS module inside an array. Lastly, just so you can see an example of this, we’re adding a config object so we can switch on strict dependency injection.
You may be wondering where the
moduleName came from. We need to import it up with our other import statements:
import moduleName from './app.module.ajs';
Here’s what our completed app.module.ts file looks like now:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { UpgradeModule } from '@angular/upgrade/static'; import moduleName from './app.module.ajs'; @NgModule({ imports: [ BrowserModule, UpgradeModule ] }) export class AppModule { constructor(private upgrade: UpgradeModule) { } ngDoBootstrap(){ this.upgrade.bootstrap(document.documentElement, [moduleName], {strictDi: true}); } }
This is going to be a pattern that’s going to become familiar to you over time.
Step 5: Creating
main.ts
Now that we’ve got our AngularJS module and our Angular module set up, we need an entry point that’s going to bring these two together and get our application running. Let’s create a new file under our
src folder called
main.ts.
In
main.ts, we need to import a few things, tell Angular which version of AngularJS to load, and then tell it to bootstrap our Angular module. First, we need to import two polyfill libraries and Angular’s
platformBrowserDynamic function:
import 'zone.js'; import 'reflect-metadata'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
Why
platformBrowserDynamic instead of just
platformBrowser? Angular has two ways to compile: a dynamic option and a static option. In the dynamic option (known as just-in-time, or JIT), the Angular compiler compiles the application in the browser and then launches the app. The static option (known as ahead-of-time, or AOT) produces a much smaller application that launches faster. This is because the Angular compiler runs ahead of time as part of the build process. We’re just going to be using the JIT method here along with the Webpack dev server.
(In the course we spend an entire module setting up AOT compiling for production.)
Now we need to import both our Angular and AngularJS modules, as well as a method that tells Angular which version of AngularJS to use:
import { setAngularLib } from '@angular/upgrade/static'; import * as angular from 'angular'; import { AppModule } from './app.module';
Now to finish this off, we just need to call
setAngularLib and pass in our version of AngularJS, and we need to call
platformBrowserDynamic and tell it to bootstrap our app module. The finished file looks like this:
import 'zone.js'; import 'reflect-metadata'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { setAngularLib } from '@angular/upgrade/static'; import * as angular from 'angular'; import { AppModule } from './app.module'; setAngularLib(angular); platformBrowserDynamic().bootstrapModule(AppModule);
Now that we’ve got that set up, we just need to change our Webpack entry point in our config.
Step 6: Updating Webpack
Hopefully, this process of bootstrapping a hybrid application is starting to make sense to you. We have a
main.ts file that’s our entry point, which sets up our AngularJS library and bootstraps our Angular module. Then, our Angular module bootstraps our AngularJS module. That’s what let’s both frameworks run alongside each other.
We’re now ready to change our Webpack config so that it’s starting with our
main.ts file and not one of our app module files. Open up webpack.common.js (it’s under the
webpack-configs folder). Under
module.exports for
entry, we’ll change our app root to
main.ts:
entry: { app: './src/main.ts', }
Testing the Application
Now, we’re ready to see our hybrid application in action. You can run the dev server by opening a terminal and running these commands:
cd server npm start cd ../public npm run dev
You will see that Webpack is loading and that our TypeScript is compiled successfully.
Let’s go check out the browser at
localhost:9000. You can see that our application still runs on our dev server.
You might see a couple of warnings in the console about core-js depending on your version, but don’t worry about them, they won’t affect us. You can also open the network tab and see the vendor bundle and app bundle:
The vendor bundle is absolutely huge, and that’s because 1) we’re running Webpack dev server, which means it’s not minifying anything, 2) we’re running Angular in dynamic compiling, so it’s shipping the compiler code to the browser as well. We’ll fix this downstream when we talk about AOT compiling, but we can navigate around here and see that all of our data is still loading.
We now have Angular and AngularJS running alongside of each other, which means we’ve successfully set up our hybrid application. That means we’re ready to start upgrading our application piece by piece.
Rewriting & Downgrading Your First Component
Step 1: Rewriting the Component
We’ve got our application bootstrapped and running in hybrid mode, so we’re ready to get started with migrating each piece of our application. One common approach is to pick a route and then start from the bottom up to rewrite each piece, starting with whatever has the least dependencies. This allows us to iteratively upgrade our application so that every point along the way, we have something that’s deployable to production.
Let’s start with the home route because that’s an easy one with just the home component. We’ll first rename our home component to
home.component.ts.
Now we need to rewrite our home component as an Angular class. The first thing we need to do is import component from the Angular core library at the top of our file:
import { Component } from '@angular/core'
The next thing we’ll do is convert our function
homeComponentController to a class. We can also capitalize it and remove the
controller at the end of the name, so that it’s just called
HomeComponent. Lastly, let’s get rid of the parenthesis. It looks like this now:
class HomeComponent { var vm = this; vm.title = 'Awesome, Inc. Internal Ordering System'; }
Now let’s clean up what’s inside the class. We no longer need the declaration of
vm since we’re using a class. We can also add a property of
title as a string, and move setting the title to a constructor function. Our class looks like this now:
class HomeComponent { title: string; constructor(){ title = 'Awesome, Inc. Internal Ordering System'; } }
We also need to
export this class and then delete that
export default line.
Now we need to apply the
Component metadata decorator that we imported to tell Angular that this is a component. We can replace the home component object with the component decorator and an options object:
@Component({ }
The first option of our component decorator is the
selector. This is just the HTML tag that we’ll use to reference this component, which will just be ‘home’. Note that in Angular, the selector is a string literal. This is different than in AngularJS, where we would name the component in camel case, and then it would translate to an HTML tag with hyphens. Here, we’re going to put exactly the tag that we want to use. In this case, we’re just keeping it to 'home’, so it doesn’t matter too much. After that, we’ll specify our
template, just like we did with AngularJS, so I’ll just say
template: template. And believe it or not, that’s all there is to it. Our finished component looks like this:
import { Component } from '@angular/core'; const template = require('./home.html'); @Component({ selector: 'home', template: template }) export class HomeComponent { title: string; constructor(){ this.title = 'Awesome, Inc. Internal Ordering System'; } }
Note: If you’re working on an application that will use the AOT compiler, you’ll want to use
templateUrl instead of what we’re doing here and make some changes to Webpack. This is totally fine for JIT and the development server, though.
Step 2: Downgrading the Component for AngularJS
We now need to use the ngUpgrade library to “downgrade” this component. “Downgrading” means to make an Angular component or service available to AngularJS. “Upgrading,” on the other hand, means to make an AngularJS component or service available to Angular. We’ll cover that in another article. Luckily, downgrading is super easy.
First, we need to do two things at the top of our file along with our imports. We need to import the
downgradeComponent function from the Angular upgrade library declare a variable called
angular so we can register this component on our AngularJS module. This looks like this:
import { downgradeComponent } from '@angular/upgrade/static';
declare var angular: angular.IAngularStatic;
Downgrading the component is fairly straightforward. Down at the bottom of our component, we’ll register this component as a directive. We’ll pass in our directive name, which is just
home, the same as our selector in this case. Then after that, we’ll pass in the
downgradeComponent function from ngUpgrade. This function converts our Angular component into an AngularJS directive. Finally, we’ll cast this object as
angular.IDirectiveFactory. The finished registration looks like this:
app.module('app') .directive('home', downgradeComponent({component: HomeComponent} as angular.IDirectiveFactory);
Now we have a downgraded Angular component that’s available to our AngularJS application. You might be wondering why we registered that directive here at the bottom of this file instead of importing and registering it in our AngularJS module TypeScript file. The end goal is to get rid of that file altogether once all of our application is converted, so we want to gradually remove things from that file and then eventually delete it altogether when we uninstall AngularJS. This works great for sample applications or rapid migrations (more on that in a second).
Go ahead and open up
app.module.ajs.ts and remove the import of
homeComponent on line 12 and the component registration on line 37.
A Quick Note on AOT Compiling
This method of downgrading – registering the downgraded component in the component.
The downgrade is identical, but instead you’d:
- Import
downgradeComponentin
app.module.ajs.ts(you’ve already got
angularin there so you don’t need to declare it).
- Change the import of homeComponent to
import { HomeComponent } from './home/home.component';since we switched to a named export.
- Change the component registration to the exact same directive registration shown above.
You can read more about setting up ngUpgrade for AOT in this article, as well as in Course 3 of Upgrading AngularJS (there’s a whole module that lays it out step-by-step).
Step 3: Updating the Template
After a component is updated, we need to be sure to update its template so it complies with the new Angular syntax. In this case, there are only minimal changes you must make to
homeComponent. We just need to remove
$ctrl on line two. The template looks like this now:
<div class="row"> <h1>{{title}}</h1> </div>
Now we have a fully functional downgraded home component in our hybrid application.
Step 4: Add to the Angular App Module
Let’s add our new Angular component to our Angular module. Open up
app.module.ts. First, we need to just import our home component after all of our other imports:
import { HomeComponent } from './home/home.component';
Now, we need to add HomeComponent to our Angular application. All Angular components must be added to a
declarations array of our NgModule. So, after line 12 in our options object, we’ll add a new array called declarations and add our component:
declarations: [ HomeComponent ]
We also need to create an
entryComponents array and add our HomeComponent to that. All downgraded components must be added to this
entryComponents array. We’ll add it after our
declarations:
entryComponents: [ HomeComponent ]
With that, we’re finished.
Testing That it Works
Let’s run those same commands as before and make sure our application is still working. Here are those commands again:
cd server npm start cd ../public npm run dev
Head back over to
localhost:9000. You can see that our home component is loading in the browser as a rewritten Angular component! You can even go look at the Sources tab of Chrome devtools just to be positive. Open up
webpack://, scroll down to
./src/home/home.component.ts, and sure enough, there it is!
Conclusion
Here’s what you’ve accomplished in this guide:
- Installed Angular and ngUpgrade
- Set up an Angular module
- Bootstrapped Angular and AngularJS
- Updated Webpack
- Rewritten and downgraded your first component
In a followup to this guide, we’ll talk about the basics of rewriting and downgraded services.
|
https://www.digitalocean.com/community/tutorials/how-to-upgrade-from-angularjs-to-angular-with-ngupgrade
|
CC-MAIN-2020-40
|
refinedweb
| 4,021
| 55.95
|
C++ Programming Assignment Help | C++ Homework Help
The Programming Assignment help is the leading online solution provider for programming assignments and homework. We have been extending C++ assignment help for students pursuing their Bachelor’s degree and Master’s Degree in Computer Science. Our team of experienced programmers has been assisting students with their programming assignments and helps them secure A+ grade. Be it you lack time, knowledge or burdened with other assignments, our experts are always there for you to provide the needful assistance. They have years of experience dealing with coding tasks. They follow the university guidelines and specifications given by the students thoroughly to write the programs in C++. Our exceptional C++ Assignment Help services help students achieve their desired grades in academic.
To get hold of this programming language, students should keep on practicing the concepts of C++ practically. However, students pursuing computer science would often find difficult to complete C++ assignments. We offer the best C++ Programming homework Help besides helping students to understand the concepts. Our experts deliver quality outcomes by crafting even the complicated assignments in a short deadline.
What Is C++ Programming?
C++ is an object-oriented programming language. This is the base for many other programming languages like C#, JavaScript and Python. C++ is one of the oldest programming languages. It builds the platform for students with basic coding skills that are required to master other trending programming languages. C++ programming language was first developed by BjarneStroustrup. It is an extension of the C language with classes and holds all the properties that C language has with additional classes. This language holds the features of high and low level languages. This is the popular language that comprises of pointers, polymorphism, namespaces, virtual, friend functions, etc. There are many features that are not available in C, but are available in C++ language. This language is used to develop massive development projects.
With the team of more than 100 dedicated experienced programmers, we offer the best online C++ programming assignment help.
Key Advantages Offered By C++
Advantages that are offered by C++ programming language include :
- C++ programming language is portable and helps programmers to craft the program irrespective of the hardware and operating systems used
- Used in low-level programming and is widely used for general purpose
- Allows handling exceptions and overloaded functions
- Considers as a powerful programming language that is highly efficient and quick
- Allow you to explore a wide range of applications
- Allow programmers to construct different applications
- Easy to modify and maintain the current code
- Classes in C++ help the programmers a lot
- Every program that is written in this language can be consolidated or compiled in C++ language
- Execute programs at a rapid pace compared to other programming languages
- No assumptions are made by the compiler used in C++ while using data types
- Supports 7 different types of programming styles. Every programmer has the liberty to choose their favorite style to write programs. Unlike in Java and Python programming where you use an object to perform a task, a programmer would have to pick a style that meets their requirements
- Easy to solve complicated problems with this language by dividing complicated task into small chucks by creating objects
- Comprise of standard libraries and algorithms to code efficiently
C++ language is challenging only when you do not have a good understanding about the basics. You need to learn the basics than memorizing the concepts. Though, C++ programming language seems to be complicated, but with practice and by taking our C++ Programming Homework Help experts, you can secure A+ grade. This object oriented language is used to implement various entities like polymorphism, inheritance, hiding, etc. The main objective of the object-oriented programming language is that, it binds the data and functions to operate so that no other code can access this data barring the function.
The Programming Assignment Help Cover Wide Array Of Topics On C++ Programming
Our programming experts have expertise in solving assignments on variety of topics related to C++. Some of the key topics covered by us are:
Objects:
Objects are run-time entities that you find in the object oriented system. The objects are classes that are defined with the help of user defined data types. The object occupies a lot memory and has a unique address. When a program is run, objects interactand the messages are sent from one person to another. Every object comprises of data and code to change data. Objects will interact easily without knowing the complete details of the code. It is enough to know about the type of message that is accepted and type of response that is given back by the objects. Our programmers have expertise in writing the assignments related to this concept flawlessly. If you are stuck up in writing assignment on objects, you can take help with C++ Programming Assignment from ourexperts.
Class :
Class is a collection of data, methods or functions. Class will not occupy any space and is a user-defined structure. Basically, class variables are private, but the structure is public. If students need assignment help on this concept, our expert programmers are available round the clock to deliver top-notch quality assignment enabling you to secure best grades.
Encapsulationand Data abstraction :
Combining data together and functions into one unit is called as encapsulation. However, the data that is encapsulated cannot be accessed by others except the functions that are wrapped inside the class. The data that is insulated by accessing the program directly is called as information hiding. Data abstraction will offer required information and keep the implementation information secured. Students who need help in completing the assignment on this concept can approach us without any hesitation. We deliver the best outcome that helps them secure good grades.
Inheritance :
This is the process through which objects belonging to a class will gain the properties of another class. The best part of inheritance is to reuse. This helps to add new features to the existing class without actually amending it.
Polymorphism :
This ability to carry out a particular thing in multiple forms is called as polymorphism. This can be of two types. One is static and the other is dynamic. One single operation will showcase different behavior on different instances. The behavior totally depends on the data that is used to operate. C++ supports both operation and function overloading. Students who cannot invest time in writing assignment on this topic can take the aid of our C++ Programming homework Help experts. We are available 24/7 for extending the assistance.
Affordable and Quality C++ Language Assignment Help
Students are burdened with a lot of academic assignments and hence struggle to secure A+ grade on their own. Students pursuing computer science courses cannot escape from C++ assignments. We have designed our services keeping the needs of students in mind. Our well qualified and experienced team of programmers provides all kinds of C++ coding help. The codes are written from scratch and are well commented which helps students to enhance their subject understanding. We have been helping students across USA, UK and Australia with best in class programming help.
Why Students Avail Our C++ Programming Assignment Help Service?
Students from across the globe trust us for the quality of services we offer. They entrust the responsibility of completing the assignment to us. Below are the key salient features of our services:
Experienced and skilled programmers : We have a team of highly qualified and experienced C++ coders and programmers to prepare the assignments. We handpicked our C++ Project Help experts to add value to the assignments and help students’ secure top scores always.
100% plagiarism free content : We hate plagiarism as your professors and deliver a unique assignment every time with zero plagiarism. We, The Programming/7 and 365 days a year for students to help them from ordering until delivery. We are just an email away to serve you.
On-time delivery :.
C++ Assignment Solution Example
Problem 1 : Program to compute the average of three test scores.
//Program to compute average of three test scores #include < bits / stdc++.h > using namespace std; int main() { cout << "My name is K_Boy" << endl; cout << "#Assignment # 1" << endl; cout << endl; cout << endl; cout << endl; cout << "Enter test score #1: "; float t1; cin >> t1; cout << "Enter test score #2: "; float t2; cin >> t2; cout << "Enter test score #3: "; float t3; cin >> t3; float average = (t1 + t2 + t3) / 3; cout << "Your average is " << average << endl; }
Problem 2: Program to compute area and perimeter
//Program to compute area and perimeter #include < bits / stdc++.h > using namespace std; int main() { cout << "My name is K_Boy" << endl; cout << "#Assignment # 2" << endl; cout << endl; cout << endl; cout << endl; cout << "What is the length and with of the rectangle ( in feet) ? "; floatlength, breadth; cin >> length >> breadth; float area = length * breadth; float perimeter = 2 * (length + breadth); cout << "The area of the rectangle is " << area << " sq. ft" << endl; cout << "The perimeter is " << perimeter << " ft." << endl; }
Problem 3: Program to compute gross and net pay
//Program to compute gross and net pay #include < bits / stdc++.h > using namespace std; int main() { const double StateTaxRate = 0.0825; const double FederalTaxRate = 0.175; cout << "What is the number of hours worked? "; float hours; cin >> hours; cout << "What is the rate of pay? "; float rate; cin >> rate; floatStateTaxAmount, FederalTaxAmount, NetPay, GrossPay; GrossPay = hours * rate; cout << endl; cout << "The gross amount is $: " << GrossPay << endl; StateTaxAmount = StateTaxRate * GrossPay; FederalTaxAmount = FederalTaxRate * GrossPay; NetPay = GrossPay - StateTaxAmount - FederalTaxAmount; cout << "The net amount is : $" << NetPay << endl; cout << "The state tax amount is : $" << StateTaxAmount << endl; cout << "The federal tax amount is: $" << FederalTaxAmount << endl; }
If you need urgent help with C++ assignment, then reach out to our customer care executive now.
|
https://www.theprogrammingassignmenthelp.com/c-plus-plus-programming-assignment-help
|
CC-MAIN-2020-16
|
refinedweb
| 1,621
| 52.8
|
A Beginner's Guide to D/The Basics/Basic Input
From Wikibooks, open books for an open world
The built-in capabilities of D (meaning the capabilities of the runtime library Phobos) for input from a console (alias terminal or DOS-Box) are very restricted.
Here is a simple program that demonstrates string input with din.readLine() which reads a complete line of input. A line means all characters typed until the user pressed RETURN on keyboard. It doesn't mean a physical line in the console-window which is usually 80 characters wide.
import std.cstream; /* for din.readLine() */ import std.stdio; /* for writef()/writefln() */ void main() { char[] name; writef("Hello friend. Please enter your name: "); name = din.readLine(); writefln("Thanks, %s", name); }
|
https://en.wikibooks.org/wiki/A_Beginner%27s_Guide_to_D/The_Basics/Basic_Input
|
CC-MAIN-2016-44
|
refinedweb
| 124
| 60.41
|
.util;19 20 import java.io.FilterInputStream ;21 import java.io.IOException ;22 import java.io.InputStream ;23 24 /**25 * Class that can be used to wrap <tt>System.in</tt>26 * without getting anxious about any client closing the stream.27 *28 * <p>29 * In code-language it means that it is not necessary to do:30 * <pre>31 * if (out != System.in) {32 * in.close();33 * }34 * </pre>35 * </p>36 *37 * @since Ant 1.638 */39 public class KeepAliveInputStream extends FilterInputStream {40 41 /**42 * Constructor of KeepAliveInputStream.43 *44 * @param in an InputStream value, it should be standard input.45 */46 public KeepAliveInputStream(InputStream in) {47 super(in);48 }49 50 /**51 * This method does nothing.52 * @throws IOException as we are overridding FilterInputStream.53 */54 public void close() throws IOException {55 // do not close the stream56 }57 }58
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
|
http://kickjava.com/src/org/apache/tools/ant/util/KeepAliveInputStream.java.htm
|
CC-MAIN-2017-04
|
refinedweb
| 157
| 70.7
|
A lot of workarounds exist to debug the OnStart method of a service. A straight way with Debugger.Launch() is described in How to Debug a Windows Service. But what if this wouldn't work, e.g. on Windows Vista x64? This sample shows a simple method to attach the debugger to the service process and debug the OnStart method.
OnStart
Debugger.Launch()
The service process should wait till you have attached the debugger. The service process should not timeout. Just look at the code, it's quite easy.
All you have to do, is to copy this code snippet in your Onstart method of your service class (derived from ServiceBase).
Onstart
ServiceBase
using System.Diagnostics; // a quite useful namespace for debugging issues
using System.Threading;
protected override void OnStart(string[] args)
{
#if DEBUG
while (!Debugger.IsAttached) // Waiting until debugger is attached
{
RequestAdditionalTime(1000); // Prevents the service from timeout
Thread.Sleep(1000); // Gives you time to attach the debugger
}
RequestAdditionalTime(20000); // for Debugging the OnStart method,
// increase as needed to prevent timeouts
#endif
// here is your startup code with breakpoints
}
Start the service as usual. The service will wait until you attach the debugger to the service process. You can set breakpoints in your start code and debug.
|
http://www.codeproject.com/script/Articles/View.aspx?aid=20458
|
CC-MAIN-2014-42
|
refinedweb
| 208
| 59.8
|
ASP FoxPro.
Required Classes
To implement a membership provider, you create a class that inherits the abstract class from the namespace. The MembershipProvider abstract class inherits the abstract class from the or provider instance that is used for all of the requests served by an object. As a result, you can have multiple requests executing concurrently. ASP.NET does not ensure the thread safety of calls to your provider. You will need to write your provider code to be thread safe. For example, creating a connection to a database or opening a file for editing should be done within the member that is called, such as , rather than opening a file or database connection when the Initialize method is called.
|
https://www.yaldex.com/asp_net_tutorial/html/d8658b8e-c962-4f64-95e1-4acce35e4582.htm
|
CC-MAIN-2021-31
|
refinedweb
| 120
| 68.3
|
It is a new selection of tips and tricks about Python and programming from my Telegram-channel @pythonetc.
← Previous publications
If an instance of a class doesn’t have an attribute with the given name, it tries to access the class attribute with the same name.
>>> class A: ... x = 2 ... >>> A.x 2 >>> A().x 2
It’s fairly simple for an instance to have attribute that a class doesn’t or have the attribute with the different value:
>>> class A: ... x = 2 ... def __init__(self): ... self.x = 3 ... self.y = 4 ... >>> A().x 3 >>> A.x 2 >>> A().y 4 >>> A.y AttributeError: type object 'A' has no attribute 'y'
If it’s not that simple, however, if you want an instance behave like it doesn’t have an attribute despite the class having it. To make it happen you have to create custom descriptor that doesn’t allow access from the instance:
class ClassOnlyDescriptor: def __init__(self, value): self._value = value self._name = None # see __set_name__ def __get__(self, instance, owner): if instance is not None: raise AttributeError( f'{instance} has no attribute {self._name}' ) return self._value def __set_name__(self, owner, name): self._name = name class_only = ClassOnlyDescriptor class A: x = class_only(2) print(A.x) # 2 A().x # raises AttributeError
See also how the Django
classonlymethoddecorator works:
Functions declared in a class body can’t see the class scope. It makes sense since the class scope only exists during class creation.
>>> class A: ... x = 2 ... def f(): ... print(x) ... f() ... [...] NameError: name 'x' is not defined
That is usually not a problem: methods are declared inside a class only to become methods and be called later:
>>> class A: ... x = 2 ... def f(self): ... print(self.x) ... >>> >>> >>> A().f() 2
Somewhat surprisingly, the same is true for comprehensions. They have their own scopes and can’t access the class scope as well. That really make sense for generator comprehensions: they evaluate expressions after the class creation is already finished.
>>> class A: ... x = 2 ... y = [x for _ in range(5)] ... [...] NameError: name 'x' is not defined
Comprehensions, however, have no access to
self. The only way to make it work is to add one more scope (yep, that’s ugly):
>>> class A: ... x = 2 ... y = (lambda x=x: [x for _ in range(5)])() ... >>> A.y [2, 2, 2, 2, 2]
In Python,
Noneis equal to
Noneso it looks like you can check for
Nonewith
==:
ES_TAILS = ('s', 'x', 'z', 'ch', 'sh') def make_plural(word, exceptions=None): if exceptions == None: # ← ← ← exceptions = {} if word in exceptions: return exceptions[word] elif any(word.endswith(t) for t in ES_TAILS): return word + 'es' elif word.endswith('y'): return word[0:-1] + 'ies' else: return word + 's' exceptions = dict( mouse='mice', ) print(make_plural('python')) print(make_plural('bash')) print(make_plural('ruby')) print(make_plural('mouse', exceptions=exceptions))
This is a wrong thing to do though.
Noneis indeed is equal to
None, but it’s not the only thing that is. Custom objects may be equal to
Nonetoo:
>>> class A: ... def __eq__(self, other): ... return True ... >>> A() == None True >>> A() is None False
The only proper way to compare with
Noneis to use
is None.
Python floats can have NaN values. You can get one with
math.nan.
nanis not equal to anything including itself:
>>> math.nan == math.nan False
Also, NaN object is not unique, you can have several different NaN objects from different sources:
>>> float('nan') nan >>> float('nan') is float('nan') False
That means that you generally can’t use NaN as a dictionary key:
>>> d = {} >>> d[float('nan')] = 1 >>> d[float('nan')] = 2 >>> d {nan: 1, nan: 2}
typingallows you to define type for generators. You can additionally specify what type is yielded, what type can be sent into a generator and what is returned.
Generator[int, None, bool]is a generator that yields integers, returns boolean value and doesn’t support
g.send().
Here is slightly more complicated example.
chain_whileyields from other generators until one of them returns something that is a signal to stop according to the
conditionfunction:
from typing import Generator, Callable, Iterable, TypeVar Y = TypeVar('Y') S = TypeVar('S') R = TypeVar('R') def chain_while( iterables: Iterable[Generator[Y, S, R]], condition: Callable[[R], bool], ) -> Generator[Y, S, None]: for it in iterables: result = yield from it if not condition(result): break def r(x: int) -> Generator[int, None, bool]: yield from range(x) return x % 2 == 1 print(list(chain_while( [ r(5), r(4), r(3), ], lambda x: x is True, )))
Annotating a factory method is not as simple as it may seem. The immediate urge is to use something like this:
class A: @classmethod def create(cls) -> 'A': return cls()
However, that is not a right thing to do. The catch is,
createdoesn’t return
A, it returns an instance of cls that is
Aor any of its descendants. Look at this code:
class A: @classmethod def create(cls) -> 'A': return cls() class B(A): @classmethod def create(cls) -> 'B': return super().create()
The mypy check result is
error: Incompatible return value type (got "A", expected "B"). Again, the problem is
super().create()is annotated to return
Awhile it clearly returns
Bin this case.
You can fix that by annotating cls with TypeVar:
AType = TypeVar('AType') BType = TypeVar('BType') class A: @classmethod def create(cls: Type[AType]) -> AType: return cls() class B(A): @classmethod def create(cls: Type[BType]) -> BType: return super().create()
Now
createreturns the instance of the
clsclass. However, this annotations are too loose, we lost the information that
clsis a subtype of
A:
AType = TypeVar('AType') class A: DATA = 42 @classmethod def create(cls: Type[AType]) -> AType: print(cls.DATA) return cls()
The error is
"Type[AType]" has no attribute "DATA".
To fix that you have to explicitly define
ATypeas a subtype of
Awith the
boundargument of
TypeVar:
AType = TypeVar('AType', bound='A') BType = TypeVar('BType', bound='B') class A: DATA = 42 @classmethod def create(cls: Type[AType]) -> AType: print(cls.DATA) return cls() class B(A): @classmethod def create(cls: Type[BType]) -> BType: return super().create()
|
https://habr.com/en/company/vk/blog/466317/
|
CC-MAIN-2021-49
|
refinedweb
| 1,013
| 62.68
|
The QImageIO class contains parameters for loading and saving images. More...
#include <qimage.h>
List of all member functions.
The QImageIO class contains parameters for loading and saving images.
QImageIO contains a QIODevice object that is used for image data I/O. The programmer can install new image file formats in addition to those that Qt provides.
Qt currently supports the following image file formats: PNG, BMP, XBM, XPM and PNM. It may also support JPEG, MNG and GIF, if specially configured during compilation. The different PNM formats are: PBM (P1 or P4), PGM (P2 or P5), and PPM (P3 or P6).
You don't normally need to use this class; QPixmap::load(), QPixmap::save(), and QImage contain sufficient functionality.
For image files that contain sequences of images, only the first is read. See QMovie for loading multiple images.
PBM, PGM, and PPM format output is always in the more condensed raw format. PPM and PGM files with more than 256 levels of intensity are scaled down when reading.
Warning: If you are in a country which recognizes software patents and in which Unisys holds a patent on LZW compression and/or decompression and you want to use GIF, Unisys may require you to license the technology. Such countries include Canada, Japan, the USA, France, Germany, Italy and the UK.
GIF support may be removed completely in a future version of Qt. We recommend using the PNG format.
See also QImage, QPixmap, QFile, QMovie, Graphics Classes, Image Processing Classes, and Input/Output and Networking.
flags is a string of single-character flags for this format. The only flag defined currently is T (upper case), so the only legal value for flags are "T" and the empty string. The "T" flag means that the image file is a text file, and Qt should treat all newline conventions as equivalent. (XPM files and some PPM files are text files for example.)
format is used to select a handler to write a QImage; header is used to select a handler to read an image file.
If readImage is a null pointer, the QImageIO will not be able to read images in format. If writeImage is a null pointer, the QImageIO will not be able to write images in format. If both are null, the QImageIO object is valid but useless.
Example:
void readGIF( QImageIO *image ) { // read the image using the image->ioDevice() } void writeGIF( QImageIO *image ) { // write the image using the image->ioDevice() } // add the GIF image handler QImageIO::defineIOHandler( "GIF", "^GIF[0-9][0-9][a-z]", 0, readGIF, writeGIF );
Before the regex Qt assumes that there is only one handler per format; if two handlers support the same format, Qt will choose one arbitrarily. It is not possible to have one handler support reading, and another support writing.
Returns the image description string.
See also setDescription().
Returns the file name currently set.
See also setFileName().
Returns the image format string or 0 if no format has been explicitly set.
See also setGamma().
Returns the image currently set.
See also setImage().
Returns a string that specifies the image format of the image read from IO device d, or 0 if the device cannot be read or if the format is not recognized.
Make sure that d is at the right position in the device (for example, at the beginning of the file).
See also QIODevice::at().
Returns the IO device currently set.
See also setIODevice().
Example: scribble/scribble.cpp.
See also setParameters().
See also setQuality() and QImage::save().
Before reading an image you must set an IO device or a file name. If both an IO device and a file name have been set, the IO device will be used.
Setting the image file format string is optional.
Note that this function does not set the format used to read the image. If you need that information, use the imageFormat() static functions.
Example:
QImageIO iio; QPixmap pixmap; iio.setFileName( "vegeburger.bmp" ); if ( image.read() ) // ok pixmap = iio.image(); // convert to pixmap
See also setIODevice(), setFileName(), setFormat(), write(), and QPixmap::load().
Currently, no image format supported by Qt uses the description string.
See also setIODevice().
It is necessary to specify a format before writing an image, but it is not necessary to specify a format before reading an image.
If no format has been set, Qt guesses the image format before reading it. If a format is set the image will only be read if it has that format.
See also read(), write(), and format().
The default value is 0.0.
See also gamma().
Setting the IO device allows images to be read/written to any block-oriented QIODevice.
If ioDevice is not null, this IO device will override file name settings.
See also setFileName().
See also image().
Although the current image formats supported by Qt ignore the parameters string, it may be used in future extensions or by contributions (for example, JPEG).
See also parameters().
q must be in the range -1..100. Specify 0 to obtain small compressed files, 100 for large uncompressed files. (-1 signifies the default compression.)
See also quality() and QImage::save().
See also status().
Returns the image's IO status. A non-zero value indicates an error, whereas 0 means that the IO operation was successful.
See also setStatus().
Before writing an image you must set an IO device or a file name. If both an IO device and a file name have been set, the IO device will be used.
The image will be written using the specified image format.
Example:
QImageIO iio; QImage im; im = pixmap; // convert to image iio.setImage( im ); iio.setFileName( "vegeburger.bmp" ); iio.setFormat( "BMP" ); if ( iio.write() ) // returned TRUE if written successfully
See also setIODevice(), setFileName(), setFormat(), read(), and QPixmap::save().
This file is part of the Qt toolkit. Copyright © 1995-2007 Trolltech. All Rights Reserved.
|
http://idlebox.net/2007/apidocs/qt-x11-free-3.3.8.zip/qimageio.html
|
CC-MAIN-2013-48
|
refinedweb
| 976
| 68.67
|
Wrap it in parens and it can span multiple lines
Advertising
On March 13, 2018 5:40:15 PM PDT, Rob Clark <robdcl...@gmail.com> wrote: >On Tue, Mar 13, 2018 at 7:47 PM, Rob Clark <robdcl...@gmail.com> wrote: >> On Tue, Mar 13, 2018 at 7:27 PM, Rob Clark <robdcl...@gmail.com> >wrote: >>> On Tue, Mar 13, 2018 at 7:10 PM, Dylan Baker <dy...@pnwbakers.com> >wrote: >>>> Quoting Rob Clark (2018-03-13 16:04:00) >>>>> --- >>>>> I'm a bit unsure about the xcb-present version dependency, as that >was >>>>> added in a different commit. OTOH I guess Dave is building vulkan >with >>>>> his patch so it is perhaps not a built-time dependency. >>>>> >>>>> meson.build | 11 ++++++++--- >>>>> 1 file changed, 8 insertions(+), 3 deletions(-) >>>>> >>>>> diff --git a/meson.build b/meson.build >>>>> index c201644c372..30f1919e6f5 100644 >>>>> --- a/meson.build >>>>> +++ b/meson.build >>>>> @@ : >>>>> + dep_xcb_dri3_modifiers = dependency('xcb-dri3', version : >'>= 1.13', required : false) >>>>> + if dep_xcb_dri3_modifiers.found() >>>> >>>> I think you could simplify this by doing: >>>> >>>> if dep_xcb_dri3.version().version_compare('>= 1.13') >>> >>> ahh, yeah, and I guess that will get rid of the confusing error msg >>> about xcb-dri3 1.13 not found.. >>> >>> >>>> >>>> Or should we be checking for xcb_dri3 and xcb_present >= 1.13? >>> >>> I'm not entirely sure why we were checking for xcb-present >= 1.13.. >>> if that is actually a build time requirement then I think Dave's >>> initial patch needs some more ifdef.. (but otoh, if it was, I guess >>> he would have noticed.) >>> >>> Anyways, I did a build w/ anv+radv enabled with xcb-present == 1.12 >>> (and xcb-dri3 1.12).. and 61309c2a727d52d543207d6ae79fcb3e68b5cff3 >>> looks like it just cares about >= 1.12 of both of those (although >not >>> sure if it is a compile time dependency). >>> >>> So *possibly* for both meson and autotools we should require 1.12, >and >>> optionally 1.13 for HAVE_DRI3_MODIFIERS? >>> >> >> so mystery solved, Dave #ifdef'd out the present dependencies too ;-) >> >> so this is what I end up with: >> >> @@ : >> + if dep_xcb_dri3.version().version_compare('>= 1.13') and >> + dep_xcb_present.version().version_compare('>= 1.13') > >hmm, annoyingly enough I found that on rawhide (meson 0.45.0), I seem >to need the entire if statement on a single line, instead of split in >two like this. > >BR, >-R > >> + pre_args += '-DHAVE_DRI3_MODIFIERS' >> + endif >> dep_xcb_sync = dependency('xcb-sync') >> dep_xshmfence = dependency('xshmfence', version : '>= 1.1') >> endif
_______________________________________________ mesa-dev mailing list mesa-dev@lists.freedesktop.org
|
https://www.mail-archive.com/mesa-dev@lists.freedesktop.org/msg187378.html
|
CC-MAIN-2018-34
|
refinedweb
| 397
| 69.28
|
Subject: Re: [boost] Arbitrary precision arithmetic
From: DE (satan66613_at_[hidden])
Date: 2009-08-19 16:31:17
on 19.08.2009 at 9:50
joel wrote :
> THis may end up as a test case for the general numerical functions
> library I'm trying to generate out of my Boost.SIMD proposal.
> In a large scope, it provides a large number of stub functions that are
> tag dispatched rather efficiently based on "arithmetic"-like value types.
> So basically, it defines 150+ functions that looks at their parameters
> and decide which implementation to use at compile-time. I use that to
> discriminate between scalar and SIMD functions, but if you "tag" this
> bignum class correctly and follow my extension mecanism, then we can
> statically choose between implementation. Roughly :
> bignum<> x;
> bignum<impl::gmp> y;
> x = abs(x); <-- call the "standard bignum" implementation
> y = abs(y); <-- call the GMP implementation
i consider it a poor solution
if i want debug version to use native c++ code and release version to
use a back end i would be forced to type something like
#ifdef NDEBUG
typedef bignum<impl::gmp> mybignum; //release
#elif
typedef bignum<> mybignum; //debug
#endif
and to replicate it in every compilation unit
what comes to my mind is for example
build main.cpp funcs.cpp -dUSE_SPECIFIC_BACK_END -dNDEBUG
for release version and
build main.cpp funcs.cpp
for debug version (i hope you got the point)
note that i decide to use it or not by leaving the code unchanged
or
to enable back end explicitly in code i can
#include <bignum/specific_back_end.h>
-- Pavel
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
|
https://lists.boost.org/Archives/boost/2009/08/155186.php
|
CC-MAIN-2020-29
|
refinedweb
| 285
| 58.32
|
From: Andre Hentz (ahentz_at_[hidden])
Date: 2004-10-18 20:01:28
Vladimir Prus wrote:
>
> Milestone 10 of Boost.Build V2 is getting closer. The preview packages are
> available at:
>
>
>
> and in the CVS (the Milestone_10 tag). I'd very appreciate testing of this
> version. I'd welcome both results of the automated tests (see
>), and
> running this version on your projects.
>
I believe the following is necessary for the gcc link flags to be
properly inherited. Two test still fail after this change (see below.
I'll look into them if I can find some time).
--- darwin.jam Mon Oct 18 17:48:09 2004
+++ darwin.oring.jam Mon Oct 18 17:48:00 2004
@@ -15,7 +15,12 @@
toolset.register darwin ;
import gcc ;
toolset.inherit-generators darwin : gcc ;
+# we can't pass -s to ld unless we also pass -static
+# so we removed -s completly from OPTIONS and add it
+# to ST_OPTIONS
+toolset.inherit-flags darwin : gcc : <debug-symbols>off ;
toolset.inherit-rules darwin : gcc ;
+flags darwin.link ST_OPTIONS <debug-symbols>off : -s ;
# No additional initialization should be necessary
rule init ( version ? : command * : options * )
@@ -24,13 +29,6 @@
local command = [ common.get-invocation-command darwin : g++ :
$(command) ] ;
common.handle-options darwin : $(condition) : $(command) :
$(options) ;
-
- gcc.init-link-flags gnu ;
- # we can't pass -s to ld unless we also pass -static
- # so we removed -s completly from OPTIONS and add it
- # to ST_OPTIONS
- toolset.inherit-flags darwin : gcc : <debug-symbols>off ;
- flags darwin.link ST_OPTIONS <debug-symbols>off : -s ;
}
# Darwin has a different shared library suffix
====================== Test Results =================
searched_lib FAILS:
-------- all changes caused by last build command ----------
Added files : ['lib/bin/darwin/debug/libtest_lib.dylib',
'lib/bin/darwin/debug/test_lib.o']
Removed files : []
Modified files: []
Touched files : []
STDOUT ============
ld: warning can't open dynamic library:
bin/darwin/debug/libtest_lib.dylib (checking for undefined symbols may
be affected) (No such file or directory, errno = 2)
ld: Undefined symbols:
foo() referenced from helper expected to be defined in
bin/darwin/debug/libtest_lib.dylib
...failed updating 1 target...
STDERR ============
END ===============
library_order FAILS:
STDOUT ============
ld: Undefined symbols:
b()
ld: Undefined symbols:
c()
...skipped <pbin/darwin/debug>main for lack of
<pbin/darwin/debug>liba.dylib...
...failed updating 2 targets...
STDERR ============
/usr/bin/libtool: internal link edit command failed
/usr/bin/libtool: internal link edit command failed
END ===============
Boost-Build list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
|
https://lists.boost.org/boost-build/2004/10/7683.php
|
CC-MAIN-2019-13
|
refinedweb
| 413
| 52.66
|
In this tutorial, I am going to show you how to use Attribute in Lightning Component Salesforce. Attributes in Lightning Component can be thought as a member variable of a class. This has some type and used to store data.
Attribute in Lightning Component Salesforce:
Attributes in Lightning Component can be thought as a member variable of a class. This has some type and used to store data.The attribute can be used for creating a dynamic component. <aura:attribute> tag is used for creating an attribute in a lightning component. To use the value of an attribute we use the expression syntax.
The syntax for declaring Attribute in Lightning Component Salesforce:
<aura:attribute
Where,
name (required): Name of an attribute.
type (required): Type of information to be stored.
default(optional) : Default value of an attribute.
access (optional): Indicates whether the attribute can be used outside of its own namespace. Possible values are public (default), and global, and private.
description (optional): Summary of an attribute and its usage.
required (optional): represent a boolean value. Determines if the attribute is required. The default is false.
Access attribute in Lightning Component.
To access attribute in Lightning Component use the expression:
{!v.attrname}
Example of Attribute in Lightning Component:
Create a lightning component called Attribute Demo.
<aura:component > <aura:attribute <aura:attribute <aura:attribute <p>Name {!v.FirstName}</p> <p>{!v.FirstName} is {!v.Age} Years Old.</p> <p>{!v.FirstName} is male? = {!v.isMale}</p> </aura:component>
Create an App called TestApp and write the following code:
<aura:application <c:AttributeDemo/> </aura:application>
Run the App and see the output:
Naming Convention for Attribute in Lightning Component:
An attribute name must follow these naming rules:
- Must begin with a letter or an underscore.
- Must contain only alphanumeric or underscore characters.
View More:
- How to dynamically bind picklist field value in Lightning Component.
- How to Implement Pagination in Lightning Component Salesforce.
- Display Record List in Lightning Component Salesforce.
- How to fetch records from sobjects using REST API in apex class salesforce.
Conclusion:
I hope you would love this post. Please feel free to comment for any technical help. Your feedback and suggestions are important for us.
Thank You.
erection pills canadian pharmacies mens ed pills
board of pharmacy pharmacies online canadian pharmacy
pharmacies near me best drugstore face moisturizer 24 hr pharmacy
medicine for erectile pharm rx pharmacy coupons
erectile dysfunction causes my canadian pharmacy canadian drug pharmacy
pharmacy canada drug pharmacy rx pharmacy
online drugstore pharmacy 24 hour pharmacy canadian mail order pharmacy
|
http://debugonweb.com/2020/01/attribute-lightning-component/
|
CC-MAIN-2021-04
|
refinedweb
| 421
| 50.84
|
WSDL2Java ANT script, no proxy Class generation?
Discussion in 'Java' started by victor.s.email
wsdl2java axis class not foundeq, Oct 15, 2004, in forum: Java
- Replies:
- 1
- Views:
- 4,706
- The Abrasive Sponge
- Oct 15, 2004
Web Services Client generation using WSDL2Java on the commandlineAkaketwa, Jan 12, 2007, in forum: Java
- Replies:
- 0
- Views:
- 3,010
- Akaketwa
- Jan 12, 2007
Ant Build.xml - Cant get wsdl2java target to compile directory of filesDaveJ, May 18, 2007, in forum: Java
- Replies:
- 1
- Views:
- 989
- =?ISO-8859-1?Q?Arne_Vajh=F8j?=
- May 19, 2007
Ant wsdl2java namespacemappingfile attribute doesn't workDaveJ, May 21, 2007, in forum: Java
- Replies:
- 2
- Views:
- 1,947
- p.lechev
- Nov 4, 2010
Run ant script from ant script?, Jul 25, 2007, in forum: Java
- Replies:
- 6
- Views:
- 914
|
http://www.thecodingforums.com/threads/wsdl2java-ant-script-no-proxy-class-generation.586492/
|
CC-MAIN-2014-52
|
refinedweb
| 131
| 54.32
|
I have written my code, but can't seem to figure out why it doesn't enter the while loop and start asking for Input. Any insight would be greatly appreciated. Just need a direction to go in.
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare variables
string cityName = "";
string stateName = "";
string zipCode = "";
string fullAddress = "";
string loopValue = "";
cout << "Enter -1 to end or press enter to key in a date: ";
getline(cin, loopValue);
while (loopValue != "-1");
{
cout << "Enter city: ";
getline(cin, cityName);
cout << "Enter state: ";
getline(cin, stateName);
cout << "Enter zip code: ";
getline(cin, zipCode);
fullAddress = cityName + ", " + stateName + " " + zipCode;
cout << fullAddress << endl;
cout << "Enter -1 to end or press enter to key in a date: ";
getline(cin, loopValue);
}
cin.get();
return 0;
} //end of main function
|
http://forums.codeguru.com/printthread.php?t=536281&pp=15&page=1
|
CC-MAIN-2014-35
|
refinedweb
| 129
| 59.43
|
Metal Tutorial with Swift 3 Part 1: Getting Started
Update: This tutorial has been updated for Xcode 8.2 and Swift 3.
In iOS 8, Apple released their own API for GPU-accelerated 3D graphics: Metal.
Metal is similar to OpenGL ES, in that it is a low-level API for interacting with 3D graphics hardware.
The difference is that Metal is not cross-platform. Instead, it is designed to be extremely efficient with Apple hardware, offering improved speed and low overhead compared to using OpenGL ES.
In this tutorial, you’ll get some hands-on experience using Metal and Swift to create a bare-bones app: drawing a simple triangle. In the process, you’ll learn about some of the most important classes in Metal, such as devices, command queues, and more.
This tutorial is designed so that anyone can go through it, regardless of your 3D graphics background — however, things will move along fairly quickly. If you do have some prior 3D programming or OpenGL experience, you will find things much easier, as many of the concepts you’re already familiar with apply to Metal.
This tutorial assumes you are familiar with Swift. If you are new to Swift, check out some of our Swift tutorials first.
Metal vs. Sprite Kit, Scene Kit, or Unity
Before we get started, I wanted to discuss how Metal compares to higher-level frameworks like Sprite Kit, Scene Kit, or Unity.
Metal is a low-level 3D graphics API, similar to OpenGL ES, but with lower overhead. It is a very thin layer above the GPU, so doing just about anything, such as rendering a sprite or a 3D model to the screen, requires you to write all of the code to do this. The tradeoff is you have full power and control.
Higher level game frameworks like SpriteKit, SceneKit, or Unity are built on top of a lower-level 3D graphics API like Metal or OpenGL ES. They provide much of the boilerplate code you normally need to write in a game, such as rendering a sprite or 3D model to the screen.
If all you’re trying to do is make a game, most of the time I’d recommend you use a higher level game framework like Sprite Kit, Scene Kit, or Unity because it will make your life much easier. If this sounds like you, we have tons of tutorials to help you get started with Apple Game Frameworks or Unity.
However, there are still two really good reasons to learn Metal:
- Push the hardware to its limits: Since Metal is at such a low level, it allows you to really push the hardware to its limits and have full control over how your game works.
- It’s a great learning experience: Learning Metal teaches you a lot about 3D graphics, writing your own game engine, and how higher level game frameworks work.
If either of these sound like good reasons to you, keep reading!
Metal vs OpenGL ES
OpenGL ES has been designed to be cross-platform. That means you can write C++ OpenGL ES code, and most of the time (with some small modifications) you can run it on other platforms, such as Android.
Apple realized that although the cross-platform support of OpenGL ES was nice, it was missing something fundamental to how Apple designs its products: the famous Apple integration of the operating system, hardware, and software as a complete package.
So Apple took a clean-room approach to see what it would look like if they were to design a graphics API specifically for their hardware with the goal of being extremely low overhead and performant, and supporting the latest and greatest features.
The result was Metal, which can provide up to 10x the number of draw calls for your application compared to OpenGL ES. This can result in some amazing effects, like you may remember from the Zen Garden example in the WWDC 2014 keynote.
Let’s dig right in and see some Metal code!
Getting Started
Xcode’s iOS Game template comes with a Metal option, but you won’t be choosing that here. This is because I want to show you how to put together a Metal app from scratch, so you can understand every step of the process.
Open Xcode and make a new project with the iOS\Application\Single View Application template. Enter HelloMetal for the ProductName, set the Language to Swift, and set Devices to Universal. Click Next, choose a directory, and click Create.
There are seven steps required to set up Metal so you can begin rendering:
- Create a MTLDevice
- Create a CAMetalLayer
- Create a Vertex Buffer
- Create a Vertex Shader
- Create a Fragment Shader
- Create a Render Pipeline
- Create a Command Queue
Let’s go through them one at a time.
1) Create a MTLDevice
The first thing you need to do is get a reference to a
MTLDevice.
You can think of a
MTLDevice as your direct connection to the GPU. You will create all the other Metal objects you need (like command queues, buffers, and textures) using this
MTLDevice.
To do this, open ViewController.swift and add this import to the top of the file:
import Metal
This imports the Metal framework so that you can use Metal classes such as
MTLDevice inside this file.
Next, add this property to the
ViewController class:
var device: MTLDevice!
You are going to initialize this property in
viewDidLoad() rather than in an initializer, so it has to be an optional. Since you know you’re definitely going to initialize it before you use it, you mark it as an implicitly unwrapped optional for convenience purposes.
Finally, add this line to the end of
viewDidLoad():
device = MTLCreateSystemDefaultDevice()
This function returns a references to the default
MTLDevice your code should use.
2) Create a CAMetalLayer
In iOS, everything you see on screen is backed by a
CALayer. There are subclasses of
CALayers for different effects, such as gradient layers, shape layers, replicator layers, and more.
If you want to draw something on the screen with Metal, you need to use a special subclass of
CALayer called
CAMetalLayer. You’ll add one of these to your view controller.
First add this new property to the class:
var metalLayer: CAMetalLayer!
This will store a handy reference to your new layer.
Next, add this code to the end of
viewDidLoad():
metalLayer = CAMetalLayer() // 1 metalLayer.device = device // 2 metalLayer.pixelFormat = .bgra8Unorm // 3 metalLayer.framebufferOnly = true // 4 metalLayer.frame = view.layer.frame // 5 view.layer.addSublayer(metalLayer) // 6
Going over this line-by-line:
- You first create a new
CAMetalLayer.
- You must specify the
MTLDevicethat the layer should use. You simply set this to the device you obtained earlier.
- You set the pixel format to
bgra8Unorm, which is a fancy way of saying “8 bytes for Blue, Green, Red, and Alpha, in that order — with normalized values between 0 and 1.” This is one of only two possible formats to use for a
CAMetalLayer, so normally you’d just leave this as-is.
- Apple encourages you to set
framebufferOnlyto
truefor performance reasons unless you need to sample from the textures generated for this layer, or if you need to enable compute kernels on the layer drawable texture. Most of the time, you don’t need to do this.
- You set the frame of the layer to match the frame of the view.
- Finally, you add the layer as a sublayer of the view’s main layer.
3) Create a Vertex Buffer
Everything in Metal is a triangle. In this app, you’re just going to draw one triangle, but even complex 3D shapes can be decomposed into a series of triangles.
In Metal, the default coordinate system is the normalized coordinate system, which means that by default you are looking at a 2x2x1 cube centered at (0, 0, 0.5).
If you consider the Z=0 plain, then (-1, -1, 0) is the lower left, (0, 0, 0) is the center, and (1, 1, 0) is the upper right. In this tutorial, you want to draw a triangle with these three points:
You’ll have to create a buffer for this. Add the following constant property to your class:
let vertexData:[Float] = [ 0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0, -1.0, 0.0]
This creates an array of floats on the CPU. You need to send this data to the GPU by moving it to something called a
MTLBuffer.
Add another new property for this:
var vertexBuffer: MTLBuffer!
Then add this code to the end of
viewDidLoad():
let dataSize = vertexData.count * MemoryLayout.size(ofValue: vertexData[0]) // 1 vertexBuffer = device.makeBuffer(bytes: vertexData, length: dataSize, options: []) // 2
Taking it comment by comment:
- You need to get the size of the vertex data in bytes. You do this by multiplying the size of the first element by the count of elements in the array.
- You call
makeBuffer(bytes:length:options:)on the
MTLDeviceyou created earlier to create a new buffer on the GPU, passing in the data from the CPU. You pass empty array for default configuration.
4) Create a Vertex Shader
The vertices you created in the previous section will become the input to a little program you will write called a vertex shader.
A vertex shader is simply a tiny program that runs on the GPU, written in a C++-like language called the Metal Shading Language.
A vertex shader is called once per vertex, and its job is to take that vertex’s information, such as position and possibly other information such as color or texture coordinate, and return a potentially modified position and possibly other data.
To keep things simple, your simple vertex shader will return the same position as the position passed in.
The easiest way to understand vertex shaders is to see it yourself. Go to File\New\File, choose iOS\Source\Metal File, and click Next. Enter Shaders.metal for the filename and click Create.
Add the following code to the bottom of Shaders.metal:
vertex float4 basic_vertex( // 1 const device packed_float3* vertex_array [[ buffer(0) ]], // 2 unsigned int vid [[ vertex_id ]]) { // 3 return float4(vertex_array[vid], 1.0); // 4 }
Here’s what’s going on in the code above:
- All vertex shaders must begin with the keyword
vertex. The function must return (at least) the final position of the vertex – you do so here by indicating
float4(a vector of 4 floats). You then give the name of the vertex shader; you will look up the shader later using this name.
The first parameter a pointer to an an array of
packed_float3(a packed vector of 3 floats) – i.e. the position of each vertex.
The
[[ ... ]]syntax is used to declare attributes which can be used to specify additional information such as resource locations, shader inputs, and built-in variables. Here you mark this parameter with
[[ buffer(0) ]], to indicate that this parameter will be populated by the first buffer of data that you send to your vertex shader from your Metal code.
- The vertex shader will also take a special parameter with the
vertex_idattribute, which means it will be filled in with the index of this particular vertex inside the vertex array.
- Here you look up the position inside the vertex array based on the vertex id and return that. You also convert the vector to a
float4, where the final value is 1.0 (long story short, this is required for 3D math purposes).
5) Create a Fragment Shader
After the vertex shader completes, another shader is called for each fragment (think pixel) on the screen: the fragment shader.
The fragment shader gets its input values by interpolating the output values from the vertex shader. For example, consider the fragment between the bottom two vertices of the triangle:
The input value for this fragment will be a 50/50 blend of the output value of the bottom two vertices.
The job of a fragment shader is to return the final color for each fragment. To keep things simple, you will make each fragment white.
Add the following code to the bottom of Shaders.metal:
fragment half4 basic_fragment() { // 1 return half4(1.0); // 2 }
Line-by-line:
- All fragment shaders must begin with the keyword
fragment. The function must return (at least) the final color of the fragment. You do so here by indicating
half4(a 4-component color value RGBA). Note that
half4is more memory efficient than
float4because you are writing to less GPU memory.
- Here you return (1, 1, 1, 1) for the color (which is white).
6) Create a Render Pipeline
Now that you’ve created a vertex and fragment shader, you need to combine them (along with some other configuration data) into a special object called the render pipeline.
One of the cool things about Metal is that the shaders are precompiled, and the render pipeline configuration is compiled after you first set it up. This makes everything extremely efficient.
First add a new property to ViewController.swift:
var pipelineState: MTLRenderPipelineState!
This will keep track of the compiled render pipeline you are about to create.
Next, add the following code to the end of
viewDidLoad():
// 1 let defaultLibrary = device.newDefaultLibrary()! let fragmentProgram = defaultLibrary.makeFunction(name: "basic_fragment") let vertexProgram = defaultLibrary.makeFunction(name: "basic_vertex") // 2 // 3 pipelineState = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor)
Taking it section by section:
- You can access any of the precompiled shaders included in your project through the
MTLLibraryobject you get by calling
device.newDefaultLibrary()!. Then you can look up each shader by name.
- You set up your render pipeline configuration here. It contains the shaders you want to use, and the pixel format for the color attachment — i.e. the output buffer you are rendering to, which is the
CAMetalLayeritself.
- Finally you compile the pipeline configuration into a pipeline state that is efficient to use here on out.
7) Create a Command Queue
The final one-time-setup step you need to do is to create a
MTLCommandQueue.
Think of this as an ordered list of commands that you tell the GPU to execute, one at a time.
To create a command queue, simply add a new property:
var commandQueue: MTLCommandQueue!
Then add this line at the end of
viewDidLoad():
commandQueue = device.makeCommandQueue()
Congrats – your one-time setup code is done!
Rendering the Triangle
Now it’s time to move on to the code that executes each frame, to render the triangle!
This is done in five steps:
- Create a Display Link
- Create a Render Pass Descriptor
- Create a Command Buffer
- Create a Render Command Encoder
- Commit your Command Buffer
1) Create a Display Link
You need a function to be called every time the device screen refreshes so you can redraw the screen.
On iOS, you do this with the handy
CADisplayLink class. To use this, add a new property to the class:
var timer: CADisplayLink!
Initialize it at the end of
viewDidLoad() as follows:
timer = CADisplayLink(target: self, selector: #selector(ViewController.gameloop)) timer.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
This sets up your code to call a method named
gameloop() every time the screen refreshes.
Finally, add these stub methods to the class:
func render() { // TODO } func gameloop() { autoreleasepool { self.render() } }
Here
gameloop() simply calls
render() each frame, which right now just has an empty implementation. Time to flesh this out.
2) Create a Render Pass Descriptor
The next step is to create a
MTLRenderPassDescriptor, which is an object that configures which texture is being rendered to, what the clear color is, and a bit of other configuration.
Simply add these lines inside
render():
guard let drawable = metalLayer?.nextDrawable() else { return } let renderPassDescriptor = MTLRenderPassDescriptor() renderPassDescriptor.colorAttachments[0].texture = drawable.texture renderPassDescriptor.colorAttachments[0].loadAction = .clear renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.0, green: 104.0/255.0, blue: 5.0/255.0, alpha: 1.0)
First you call
nextDrawable() on the Metal layer you created earlier, which returns the texture you need to draw into in order for something to appear on the screen.
Next you configure the render pass descriptor to use that texture. You set the load action to Clear, which means “set the texture to the clear color before doing any drawing”, and you set the clear color to the green color we use on the site.
3) Create a Command Buffer
The next step is to create a command buffer. Think of this as the list of render commands that you wish to execute for this frame. The cool thing is nothing actually happens until you commit the command buffer, giving you fine-grained control over when things occur.
Creating a command buffer is easy. Simply add this line to the end of
render():
let commandBuffer = commandQueue.makeCommandBuffer()
A command buffer contains one or more render commands. You’ll create one of these next.
4) Create a Render Command Encoder
To create a render command, you use a helper object called a render command encoder. To try this out, add these lines to the end of
render():
let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) renderEncoder.setRenderPipelineState(pipelineState) renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, at: 0) renderEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3, instanceCount: 1) renderEncoder.endEncoding()
Here you create a command encoder and specify the pipeline and vertex buffer you created earlier.
The most important part is the call to
drawPrimitives(type:vertexStart:vertexCount:instanceCount:). Here you are telling the GPU to draw a set of triangles, based on the vertex buffer. Each triangle consists of three vertices, starting at index 0 inside the vertex buffer, and there is 1 triangle total.
When you’re done, you simply call
endEncoding().
5) Commit your Command Buffer
The final step is to commit the command buffer. Add these lines to the end of
render():
commandBuffer.present(drawable) commandBuffer.commit()
The first line is needed to make sure the new texture is presented as soon as the drawing completes. Then you commit the transaction to send the task to the GPU.
Phew! That was a ton of code, but at long last you are done! Build and run the app and bask in your triangular glory:
Where to Go From Here?
Here is the final example project from this part of this Metal tutorial series.
You have learned a ton about the new Metal API! You now have an understanding of some of the most important concepts in Metal, such as shaders, devices, command buffers, pipelines, and more.
Next, check out part 2 of this series on moving to 3D.
Also, be sure to check out some great resources from Apple:
- Apple’s Metal for Developers page, with tons of links to documentation, videos, and sample code
- Apple’s Metal Programming Guide
- Apple’s Metal Shading Language Guide
- The Metal videos from WWDC 2014
You also might enjoy the Beginning Metal course on our site, where we explain these same concepts in video form, but with even more detail.
I hope you enjoyed this tutorial, and if you have any comments or questions, please join the forum discussion below!
|
https://www.raywenderlich.com/146414/metal-tutorial-swift-3-part-1-getting-started
|
CC-MAIN-2018-30
|
refinedweb
| 3,188
| 63.09
|
Closed Bug 499655 Opened 13 years ago Closed 13 years ago
Selectors should have dual atoms: HTML and other
Categories
(Core :: CSS Parsing and Computation, defect)
Tracking
()
People
(Reporter: hsivonen, Assigned: dzbarsky)
Details
(Keywords: html5)
Attachments
(1 file, 6 obsolete files)
Steps to reproduce: 1) Load Expected results: Expected log to say 1 1 Actual results: Log says 1 0 See As of HTML5, SVG names with uppercase ASCII letters can enter into a text/html DOM. Even without an HTML5 parser, such elements can be introduced with createElementNS(). Currently, selectors associated with text/html DOMs are lowercased. This makes it impossible to match SVG camelCase names. Going forward, element and attribute selectors should be compiled with dual atoms: one atom for matching against elements in the namespace and another for matching against all other elements. The atom for matching against elements in the namespace should be ASCII-lowercased if the document is a text/html document. The other atom should always be in the original case.
See also bug 499656.
Attachment #390816 - Attachment is obsolete: true
Two comments here: mNewTag doesn't seem like a good name for a variable; it should have a name that describes what it is, not when it was introduced. But more importantly, my understanding of what we ought to be doing here is making style sheet parsing not use any notion of case sensitiveness; in other words, removing mCaseSensitive. But that's a slightly bigger task, and there may already be another bug report on that. I'd need to think about it a little longer whether the goal of this bug can be accomplished without doing that (right now I'm not sure).
So if I understood our desired behavior correctly, we want something like this: 1) In HTML documents, HTML tagnames are matched "case-insensitively" (in practice, by lowercasing tagnames during parsing and using a lowercase version of the tag selector in the matching). This means that if someone inserts a node in the XHTML namespace with a non-lowercase localName into the document using createElementNS, it will be impossibly to match it with a tag selector. This is no worse than what we have now. 2) In HTML documents, non-HTML tagnames are matched case-sensitively. 3) In XHTML documents and other XML documents, all tagnames are case-sensitive. This involves having a notion of "HTML document" in either the parser or the matching code. Either one works for tag names, which is what this bug was primarily about, as long as a single stylesheet which tries to match on non-lowercase tagnames for HTML nodes is not used for both HTML and XHTML documents. To solve bug 282328, we'd indeed need to make sure the "HTML document" check happened during matching, not during parsing.
Attachment #390821 - Attachment is obsolete: true
Attachment #391106 - Flags: review?(dbaron)
Attachment #391106 - Attachment is obsolete: true
Attachment #391462 - Flags: review?(dbaron)
Attachment #391106 - Flags: review?(dbaron)
Attachment #391462 - Attachment is obsolete: true
Attachment #391463 - Flags: review?(dbaron)
Attachment #391462 - Flags: review?(dbaron)
Comment on attachment 391463 [details] [diff] [review] Patch with tests, fixed previous error(didn't compile) There are a bunch of places where you're missing the space after "if" (which is local style throughout the code you're touching). In nsICSSStyleRule.h, you should add a comment that for pseudo-elements, mCasedTag is null but mLowercaseTag contains the name of the pseudo-element. (This distinction will actually be useful for distinguishing pseudo-element selectors from elements that have an escaped-colon in them, which will help with bug 475216 comment 1.) A few comments on the change in SelectorMatches: + if(data.mContentTag != aSelector->mCasedTag) This line is over-indented. + if(aSelector->mLowercaseTag) { For this check, I think you should actually add a inline method to nsCSSSelector called HasTagSelector() that returns whether you have a tage selector that's *not* a pseudo-element, and that's what you should test here. (You don't need to test pseudo-elements at all here if you change PseudoEnumFunc as I describe below.) + if(data.mIsHTMLContent) { You should add a comment that if we had a stricter test here (i.e., that it was an HTML node in a text/html document) and perhaps some tweaks to RuleHash, we could completely remove the notion of case sensitivity from style sheets. (I think this would fix some existing bugs related to the handling of our user-agent style sheets.) Maybe I could convince you to do that in a followup patch? + !aSelector->mLowercaseTag && !aSelector->mIDList && !aSelector->mAttrList && This should: 1) call HasTagSelector rather than look at mLowercaseTag directly 2) be wrapped to a width less than 80 characters + NS_ASSERTION(aSelector->mLowercaseTag == data->mPseudoTag, "RuleHash failure"); I think you add, *before* this assertion, a test that calls aSelector->IsPseudoElement() and returns early if it's not. This would be a second inline function that you'd need to add to nsCSSSelector. There's another badly-indented } in nsCSSSelector::SetTag. In nsCSSStyleRule.cpp you can remove the IsPseudoElement static function and replace it with calls to your new function (added per above), which is more correct. \ No newline at end of file You should have a newline. nsTreeBodyFrame::PseudoMatches doesn't actually need to check if the tag matches; its only caller is PseudoEnumFunc, and PseudoEnumFunc's caller (a hash table enumerator) has already done that, so you should actually change PseudoMatches to begin with: NS_ABORT_IF_FALSE(aSelector->mLowercaseTag == aTag, "should not have been called"); and remove the runtime test. I'm a bit puzzled by your tests. I don't see any tests for behavior that differs between HTML and XHTML, and I'd expect some. Shouldn't you get three elements for each query in the HTML version of the test? Or is createElementNS supposed to create a case-sensitive element, even when used in an HTML document? ? +ok(list[0] == htmldiv, "First element didn't match"); this is probably better tested using |is|. Did you check that the tests fail without the patch but pass with the patch? This looks good, but I'd like to have another look at a revised patch.
(In reply to comment #9) > (From update of attachment 391463 [details] [diff] [review]) > There are a bunch of places where you're missing the space after "if" > (which is local style throughout the code you're touching)... > and remove the runtime test. > All done. > > I'm a bit puzzled by your tests. I don't see any tests for behavior > that differs between HTML and XHTML, and I'd expect some. When matching on 'TEst' the HTML document matches the html test and test:TEst while the XHTML matches the html TEst and test:TEst >Shouldn't you > get three elements for each query in the HTML version of the test? Or > is createElementNS supposed to create a case-sensitive element, even > when used in an HTML document? I think it should create a case-sensitive element, as I understand. > ? Done, I used them for testing. > +ok(list[0] == htmldiv, "First element didn't match"); > > this is probably better tested using |is|. Done. > Did you check that the tests fail without the patch but pass with the > patch? > > This looks good, but I'd like to have another look at a revised patch. Yes, the HTML test fails without the patch.
Attachment #391463 - Attachment is obsolete: true
Attachment #391519 - Flags: review?(dbaron)
Comment on attachment 391519 [details] [diff] [review] Patch adressing comments Requesting an additional review from Henri >+ if (data.mIsHTMLContent) { >+ if (data.mContentTag != aSelector->mLowercaseTag) >+ return PR_FALSE; >+ } >+ else if (data.mContentTag != aSelector->mCasedTag) { >+ return PR_FALSE; >+ } I actually preferred the symmetry of the way you had it before. > static void PseudoEnumFunc(nsICSSStyleRule* aRule, nsCSSSelector* aSelector, > void* aData) > { >+ if(!aSelector->IsPseudoElement()) >+ return; >+ > PseudoRuleProcessorData* data = (PseudoRuleProcessorData*)aData; You need a space after "if". Also probably better to declare |data| the very first thing, if only because it tends to be the style for callback functions to have the casts to the "correct" types at the very start. >+ inline PRBool HasTagSelector() const { >+ return mLowercaseTag && mCasedTag; >+ } This can be just !!mCasedTag. I want to come back to this in the morning because I'm not awake enough right now to grant review...
(In reply to comment #12) > Requesting an additional review from Henri Never mind this bit; forgot to delete it.
Comment on attachment 391519 [details] [diff] [review] Patch adressing comments >+ nsCOMPtr<nsIAtom> mLowercaseTag; //For pseudo-elements, mCasedTag will be null >+ nsCOMPtr<nsIAtom> mCasedTag; //but mLowercaseTag contains their name. Could you also add a comment here that mLowercaseTag is the same as mCasedTag in case-sensitive (non-text/html) documents, but is lowercase in case-insensitive (text/html) ones? (And with those two comments, probably better to put them above the variables rather than squeeze them in the margin.) r=dbaron with that and the above comments
Attachment #391519 - Flags: review?(dbaron) → review+
Pushed
Status: NEW → RESOLVED
Closed: 13 years ago
Resolution: --- → FIXED
Flags: in-testsuite+
Assignee: nobody → dzbarsky
I backed this out temporarily: since we're about to ship an alpha, and I don't want to ship this in a weird half-fixed state. Once bug 507487 gets sorted out, we can reland this along with that fix.
Status: RESOLVED → REOPENED
Resolution: FIXED → ---
So do we want to try landing this (and bug 507487) before alpha (whenever the tree reopens), or just wait till after?
Status: REOPENED → RESOLVED
Closed: 13 years ago → 13 years ago
Resolution: --- → FIXED
|
https://bugzilla.mozilla.org/show_bug.cgi?id=499655
|
CC-MAIN-2022-33
|
refinedweb
| 1,583
| 52.8
|
11 November 2008 10:19 [Source: ICIS news]
SINGAPORE (ICIS news)--Crude prices fell more than $2/bbl on Tuesday after worries over the global economy and a stronger US dollar cancelled out gains made the previous day on Saudi supply cuts and China’s stimulus package.
At 08:09 GMT on Tuesday, December NYMEX light sweet crude futures were trading at $60.90/bbl, down $1.51/bbl on Monday’s settlement level, after hitting a low of $60.29/bbl, down $2.12/bbl.
At the same time, December Brent on ?xml:namespace>
Concerns over the effectiveness of government initiatives to stave off a global economic recession helped to push down stock markets in Asia following an earlier slide in the
Worries had been heightened by news on Monday that General Motors (GM) shares slumped to their lowest levels in 62 years.
The fall in GM shares raised dangers that the company could fail if it is not saved by the
New data
|
http://www.icis.com/Articles/2008/11/11/9170470/crude-falls-2bbl-on-global-economic-fears.html
|
CC-MAIN-2014-41
|
refinedweb
| 165
| 60.85
|
One of the little utility libraries in the DirectX SDK is a static library for converting HRESULTs to text strings for debugging and diagnostics known as
DXERR.LIB. There were once even older versions of this library,
DXERR8.LIB and
DXERR9.LIB, but they were removed from the DirectX SDK many years back in favor of a unified
DXERR.LIB. The DirectX Error Lookup Utility is nothing more than a little front-end UI tool for getting results from
DXERR.LIB.
For the Windows SDK 8.0 this library was not brought forward (see "Where is the DirectX SDK?"). This is primarily because HRESULTS for DirectX graphics APIs were added to the FormatMessage function when using
FORMAT_MESSAGE_FROM_SYSTEM in Windows 8 which already supports most of the system error codes reported by DXERR. The DirectX SDK version of
DXERR.LIB also contained a lot of error codes for legacy components that are no longer relevant to development using the Windows SDK 8.0.
DXERR.LIB contained the following functions (both ASCII and UNICODE):
DXGetErrorString
DXGetErrorDescription
DXTrace
And the macros
DXTRACE_MSG, DXTRACE_ERR, DXTRACE_ERR_MSGBOX
If you are still using legacy components like D3DX, DXUT, etc. from the DirectX SDK then you can continue to link to the legacy version of
DXERR.LIB as well. For those wanting to get away from dependancies on the DirectX SDK as we've recommended, I've attached a streamlined version of the library to this post. It only supports UNICODE and I had to change
DXGetErrorDescription to copy the result to a buffer rather than return a static string in order to make use of
FormatMessage where possible, but otherwise it should serve much the same purpose. You can modify it to suit your needs a well.
Note: The
FormatMessage flag
FORMAT_MESSAGE_ALLOCATE_BUFFER is not supported for Windows Store apps because it makes use of
LocalAlloc.
The source code for this package is bound to the Microsoft Public License (Ms-PL).
While we are on the topic of utility libraries, the
DXGUID.LIB static library is also present in the Windows SDK 8.0 with the Direct3D 11.1, Direct2D, DirectWrite, and WIC GUIDs added; and the XACT and XAUDIO2 GUIDs removed. There's nothing particular special about
DXGUID.LIB because you could easily define the GUIDs using
#define INITGUID before including the relevant headers in one (and only one) module of your program yourself, but it is very convenient not to have to do that.
Update: in
DXTraceW now takes
__FILEW__ along with some /analyze and /W4 cleanup, support for
WINAPI_FAMILY macros; define NOMINMAX; some fixes for VS 2015 printf string portability, package updated on November 9, 2015.
DXUT: This DXERR is included in the DXUT for Win32 Desktop Update
VS 2015: The VS 2015 C Runtime is not compatible with the
DXERR.LIB that ships in the legacy DirectX SDK. You will get link errors trying to use it. You can use this module to replace DXERR LIB but will have to rebuild the code that uses it. You can try linking with
legacy_stdio_definitions.lib instead, but ideally you'd remove this dependency on the legacy DirectX SDK.
Nice, thanks.
What happens when someone with Windows Vista, for example, runs your code? Their version of their OS won't have the directx error codes for DirectX?
If you look at the code for DXGetErrorDescriptionW, you see it falls back to a bunch of built-in translations if the FormatMessageW fails to recognize the error.
Oh, ok. Why deprecate dxerr when you now need to use a third-party library to get error messages now :/
@Kevin – DXERR in particular was not deprecated. The whole DirectX SDK was deprecated in favor of the Windows SDK, and the 'in box' solution for error to message translation is to use FormatMessage as described here. If you use Windows 8 and avoid legacy APIs, you never need to use DXERR. The DXERR in the blog post is a shared source solution to fill the gap for down-level OSes, legacy APIs, etc.
This doesn't work — as written — on the v110_xp or v120_xp toolsets, because version 7.1A of the Windows SDK doesn't include d3d11_1.h (even though it does include other Direct X headers and libraries).
What's the right preprocessor symbol to use to distinguish this case?
@Jon: You could use _WIN32_WINNT, assuming you explicitly set _WIN32_WINNT to 0x0501 as part of your project settings.
#if (_WIN32_WINNT >= 0x0600)
#include <d3d11_1.h>
#endif
I'm trying to get error description but without any luck. On win7 with vs2013 I have a nice error message in console. Is there any way to obtain the same description? I've asked on gamedev.net – there's a more detailed description.…/662849-get-error-description-from-hresult
@Nikita – the "better" output you are seeing is from the DXGI debug device which is intended for developers to get better diagnostics during development, not for 'friendly output' for a user in a released product. The HRESULT is still a generic error that has a fairly generic description. The whole point of the Direct2D, Direct3D, and DXGI debug device layer is to provide more detailed information when you get something that's not specific as an HRESULT at runtime during development because you can actually fix it. A user cannot do anything about a component in your code getting an "INVALIDCALL" error.
Thank you, Chuck. As I understood, I need to work with debug layer if I want to get output like in vs console.
So, it is OK to break DirectX applications that rely on DirectX libraries, but we still have to define NOMINMAX in every single application…
Do you see the problem here?
Not that I do not appreciate the effort. You are trying to provide a solution. But if there is one thing the bloody MIN MAX macros taught us is that this blog post should not exist! Are we going to keep retro-compatibility only for the worst parts of the SDKs?
The DXERR implementation shouldn't care about NOMINMAX or not, so I assume the problem is that dxerr.h is pulling in windows.h and not setting NOMINMAX for your application? For the CodePlex projects, I have adopted a pattern of "#ifndef NOMINMAX #define NOMINMAX #endif" in the public headers. Fundamentally the problem with the <windows.h> min/max macros conflicting with C++11 <algorithm> is not the fault of the DirectX SDK. It's a decision made a long time ago in the Windows platform headers (see KB143208).
FormatMessage does NOT support D3D errors! In Visual Studio 2013, Intellisense shows a popup with the detailed message "The device does not support a specified texture-blending argument for the alpha channel." if hovering on the symbol D3DERR_UNSUPPORTEDALPHAARG. Where the heck does it get that string from? FormatMessage works for E_FAIL and the like but yields no string for D3DERR* errors. It's so frustrating. The proper error message does exist but my code is not allowed to query it!
What version of Windows are you running?
Windows 8.1 Pro, Visual Studio Premium 2013, Version 12.0.31101.00 Update 4
FormatMessage supports the Direct3D 11, DXGI, etc. errors in winerror.h on Windows 8. For other APIs that are missing, the DXERR implementation in this blog post should help. I found some bugs and updated the package today, so try it out.
@Chuck Walbourn Thanks for the prompt service! But I still wonder where Visual Studio finds the elaborate error strings, like "The device does not support a specified texture-blending argument for the alpha channel.". I doubt that these are hard-coded into Visual Studio.
Thanks!
six six six and thanks!
|
https://blogs.msdn.microsoft.com/chuckw/2012/04/24/wheres-dxerr-lib/?replytocom=2153
|
CC-MAIN-2018-05
|
refinedweb
| 1,283
| 65.32
|
HorseSetPhenotype(object, int)
Set a creature to the riding phenotype.
void HorseSetPhenotype( object oRider, int bJoust = FALSE );
Parameters
oRider
The creature whose phenotype is to be changed to the riding position.
bJoust
If TRUE, it will set the rider to the mounted jousting phenotype. This is a special phenotype with differing animation sets, designed to hold the lance in a very specific way.
Description
This function will set oRider to the correct mounted phenotype for riding a horse.
Remarks
When mounted, this function can be used to switch the rider in and out of Joust mode.
By default, it will set oRider to the normal mounted phenotype.
It is only needed in connection with jousting, because the normal mounted phenotype is the default for other functions.
If the rider is dismounted, it will make them look as though they are riding an invisible horse, but in all other respects they remain dismounted.
It is more convenient than SetPhenotype, because there is no need to check whether the dismounted phenotype is normal or large.
Requirements
#include "x3_inc_horse"
Version
1.69
Example
// This script will ensure that the PC adopts the normal mount posture. #include "x3_inc_horse" void main() { object oPC = GetPCSpeaker(); if(HorseGetIsMounted(oPC)) { HorseSetPhenotype(oPC, FALSE); } }
See Also
author: Proleric, editor: Mistress
|
http://palmergames.com/Lexicon/Lexicon_1_69/function.HorseSetPhenotype.html
|
CC-MAIN-2014-41
|
refinedweb
| 211
| 55.44
|
Seam doesn't inject members with ScopeType pageDaniel Lechner Feb 16, 2010 10:11 AM
Hello!
We're using JSFUnit here to test our application from the backing-beans downwards. So we don't care about the HTML pages - we want to call the backing-bean methods directly from the JSFUnit-test-classes.
So first we create a session by creating a new JSFSession with some URL (this is the only line which "depends" on the UI). Everything else is done without WebUI (and thus without HttpUnit).
Many tests are already running, but now I came to a point where I don't know what to do. I've created a little example with 3 classes to show whats the problem:
@Name("bean1")
@Scope(ScopeType.PAGE)
public class Bean1
{
private String myString = "1234";
public String getString() { return myString; }
}
@Name("bean2")
@Scope(ScopeType.EVENT)
public class Bean2
{
@In(create = true)
private Bean1 bean1;
public void someMethod() {
System.out.println("bean returns " + bean1.getString());
}
}
public class SomeTest extends ServletTestCase
{
public void test1() throws IOException {
WebClientSpec wcSpec = new WebClientSpec("/evaluations.seam");
wcSpec.getWebClient().setCssErrorHandler(new SilentCssErrorHandler());
// Send an HTTP request for the initial page
JSFSession jsfSession = new JSFSession(wcSpec);
Bean2 bean2 = (Bean2) Component.getInstance("bean2", true);
bean2.someMethod();
}
}
When executing the test, seam throws an exception:
org.jboss.seam.RequiredException: @In attribute requires non-null value: bean2.bean1
But this only happens when the ScopeType of Bean1 is PAGE. When using finer or more coarse types like EVENT or CONVERSATION, everything is fine and there is no exception.
So is there anything I am missing?
Thanks!
Daniel
1. Re: Seam doesn't inject members with ScopeType pageStan Silvert Feb 16, 2010 2:04 PM (in response to Daniel Lechner)
Hi Daniel,
Nice to see you using JSFUnit in a different way. I've often wondered how far you can get with this type of testing if you use JSFUnit to start the session and then just do lots of fine-grained unit tests in-container.
You might also take a look at the Arquillian which seems to have this kind of testing as its main goal. So you would use Arquillian for fine-grained in-container tests and then use JSFUnit for course-grained tests where you need to test integrated application logic and UI.
That being said, I'm not sure why you are getting that error. I'm going to see if someone from the Seam team has any ideas.
Stan
cross-posted:
2. Re: Seam doesn't inject members with ScopeType pageDaniel Lechner Feb 17, 2010 3:18 AM (in response to Stan Silvert)
Hi Stan!
Thank you for your promt answer. And thanks for introducing Arquilian. I'll keep an eye on this project. But since it hasn't already reached alpha stage, I'll be loyal to JSFUnit
In the meantime I've deactivated the problematic testcases. So it would be very nice if you could inform me if there are any news on this topic. Of course, I will check the seam-forum at regular intervals.
Thanks again!
3. Re: Seam doesn't inject members with ScopeType pageDaniel Lechner Mar 1, 2010 11:04 AM (in response to Stan Silvert)
Hello Stan!
Do you have any new insights on this topic? I've seen, that there were no responses in the Seam forum up to now.
daniel
|
https://developer.jboss.org/message/526569?tstart=0
|
CC-MAIN-2016-30
|
refinedweb
| 560
| 65.32
|
, SCSS and LESS.
Installation
Install Sprockets from RubyGems:
$ gem install sprockets
Or include it in your project's
Gemfile with Bundler:
gem 'sprockets', '~> 2.0'
Understanding the Sprockets Environment
You'll need an instance of the
Sprockets::Environment class to
access and serve assets from your application. Under Rails 3.1/jquery' 3.1::BundledAsset instance back:
environment['application.js'] # => #<Sprockets::BundledAsset ...>
Call
to_s on the resulting asset to access its contents,
length to
get its length in bytes,
mtime to query its last-modified time, and
pathname to get its full path on the filesystem.
Using Engines
Asset source files can be written in another language, like SCSS or CoffeeScript, and automatically compiled to CSS or JavaScript by Sprockets. Compilers for these languages are called engines.
Engines are specified by additional extensions on the asset source
filename. For example, a CSS file written in SCSS might have the name
layout.css.scss, while a JavaScript file written in CoffeeScript
might have the name
dialog.js.coffee.
.css.sass. For the
new SCSS syntax, use the extension
.css.scss.
Styling with LESS
LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions.
If the
less gem is available to your application, you can use LESS
to write CSS assets in Sprockets. Note that the LESS compiler is
written in JavaScript, and at the time of this writing, the
less gem
depends on
therubyracer which embeds the V8 JavaScript runtime in
Ruby.
To write CSS assets with LESS, use the extension
.css.less.
.js.
Note: Sprockets processes multiple engine extensions in order from
right to left, so you can use multiple engines with a single
asset. For example, to have a CoffeeScript asset that is first
preprocessed with ERB, use the extension
.js.coffee.erb..
String Interpolation Syntax
If you need access to Ruby from an asset but cannot use ERB's
<% …
%> syntax, Sprockets also supports Ruby string interpolation syntax
(
#{ … }) with the
.str engine extension.
include Directive
include path works like
require, but inserts the contents of the
specified source file even if it has already been included or
required..
2.4.0 (March 27, 2012)
- Added global path registry
- Added global processor registry
2.3.2 (March 26, 2012)
- Fix Context#logical_path with dots
2.3.1 (February 11, 2012)
- Added bytesize to manifest
- Added Asset#bytesize alias
- Security: Check path for forbidden access after unescaping
2.3.0 (January 16, 2012)
- Added special Sass importer that automatically tracks any
@imported files.
2.2.0 (January 10, 2012)
- Added
sprocketscommand line utility.
- Added rake/sprocketstask.
- Added json manifest log of compiled assets.
- Added
stubdirective that allows you to exclude files from the bundle.
- Added per environment external encoding (Environment#default_external_encoding). Defaults to UTF-8. Fixes issues where LANG is not set correctly and Rubys default external is set to ASCII.
2.1.2 (November 20, 2011)
- Disabled If-Modified-Since server checks. Fixes some browser caching issues when serving the asset body only. If-None-Match caching is sufficent.
2.1.1 (November 18, 2011)
- Fix windows absolute path check bug.
2.1.0 (November 11, 2011)
- Directive comment lines are now turned into empty lines instead of removed. This way line numbers in CoffeeScript syntax errors are correct.
- Performance and caching bug fixes.
2.0.3 (October 17, 2011)
- Detect format extensions from right to left.
- Make JST namespace configurable.
2.0.2 (October 4, 2011)
- Fixed loading stale cache from bundler gems.
2.0.1 (September 30, 2011)
- Fixed bug with fingerprinting file names with multiple dots.
- Decode URIs as default internal.
- Fix symlinked asset directories.
2.0.0 (August 29, 2011)
- Initial public release.
License
Sprockets is distributed under an MIT-style license. See LICENSE for details.
|
http://www.rubydoc.info/gems/sprockets/2.4.0
|
CC-MAIN-2018-09
|
refinedweb
| 623
| 59.19
|
:
#include "mbed.h" Ticker flipper; DigitalOut led1(LED1); DigitalOut led2(LED2); void flip() { led2 = !led2; } int main() { led2 = 1; flipper.attach(&flip, 2.0); // call flip function every 2 seconds // spin in a main loop. flipper will interrupt it to call flip while(1) { led1 = !led1;" #include "rtos.h" DigitalOut led1(LED1); DigitalOut led2(LED2); void led2_thread(void const *args) { while (true) { led2 = !led2; Thread::wait(1000); } } int main() { //Create a thread to execute the function led2_thread Thread thread(led2_thread); //led2_thread is executing concurrently with main at this point while (true) { led1 = !led1; Thread::wait(500); } }" #include "rtos second.
button_press is used to denote what value the switch uses to represent the state pushed. Most switches are by default open (unpressed), so they will read as 0 while pressed. If you see your LED blinking without the button being pressed - try changing
button_press to
1.
Interrupt button
An alternative way to poll the button is to use an interrupt. Interrupts let you say
when that pin changes value, call this function. In other words, we can tell the MCU to call a function when the button is pressed. In our case, that function toggles the LED:
#include "mbed.h" InterruptIn button(SW1); DigitalOut led(LED1); DigitalOut heartbeat(LED2); void toggle() { led = !led; } int main() { button.rise(&toggle); // call toggle function on the rising edge while(1) { // wait around, interrupts will interrupt this! heartbeat= !heartbeat; wait(0.25); } }
In the code above a heartbeat function runs on LED2, which lets you see that your code is running. Then we connect an InterruptIn object to the button and set it so that when the button rises from 0 to 1, the toggle function is called; the function toggles LED1. This way.
|
https://os.mbed.com/docs/mbed-os/v5.9/tutorials/application-flow-control.html
|
CC-MAIN-2019-47
|
refinedweb
| 289
| 75
|
The System.Windows.Forms.UserControl class (I'm listing its full namespace here to differentiate it from the System.Web.UI.UserControl, which we'll also see in this chapter) is the class that supports user controls. Here is the inheritance hierarchy for this class:
You can find the more notable public events of the System.Windows.Forms.UserControl class in Table 24.5. (This class has no non-inherited properties or methods.) Note that as with other Windows controls, I am not listing the notable properties, methods, and events System.Windows.Forms.UserControl inherits from the Control class, such as the Click event—you can see all that in Chapter 5, Tables 5.1, 5.2, and 5.3.
|
http://www.yaldex.com/vb-net-tutorial-2/library.books24x7.com/book/id_5526/viewer.asp@bookid=5526&chunkid=0521548765.htm
|
CC-MAIN-2018-05
|
refinedweb
| 120
| 58.79
|
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.
On 11-12-2015 14:40, H.J. Lu wrote: > On Fri, Dec 11, 2015 at 8:23 AM, Adhemerval Zanella > <adhemerval.zanella@linaro.org> wrote: >> >> >> On 11-12-2015 13:59, H.J. Lu wrote: >>> On Fri, Dec 11, 2015 at 7:39 AM, Joseph Myers <joseph@codesourcery.com> wrote: >>>>> On Fri, 11 Dec 2015, H.J. Lu wrote: >>>>> >>>>>>> +++ b/sysdeps/unix/sysv/linux/x86_64/64/mmap.c >>>>>>> @@ -0,0 +1,49 @@ >>>>>>> +/* Copyright (C) 2015 Free Software Foundation, Inc. >>>>> >>>>> All new files should have a descriptive first line before the copyright >>>>> notice. >>>>> >>> Here is the updated patch. >> >>> >>> diff --git a/sysdeps/unix/sysv/linux/x86_64/64/mmap.c b/sysdeps/unix/sysv/linux/x86_64/64/mmap.c >>> new file mode 100644 >>> index 0000000..c34f633 >>> --- /dev/null >>> +++ b/sysdeps/unix/sysv/linux/x86_64/64/mmap.c >> >>> + >>> +__ptr_t >>> +__mmap (__ptr_t addr, size_t len, int prot, int flags, int fd, off_t offset) >>> +{ >>> + /* If the Prefer_MAP_32BIT_EXEC bit is set, try to map executable pages >>> + with MAP_32BIT first. */ >>> + if (addr == NULL >>> + && (prot & PROT_EXEC) != 0 >>> + && HAS_ARCH_FEATURE (Prefer_MAP_32BIT_EXEC)) >>> + { >>> + addr = (__ptr_t) INLINE_SYSCALL (mmap, 6, addr, len, prot, >>> + flags | MAP_32BIT, >>> + fd, offset); >>> + if (addr != MAP_FAILED) >>> + return addr; >>> + } >>> + return (__ptr_t) INLINE_SYSCALL (mmap, 6, addr, len, prot, flags, >>> + fd, offset); >>> +} >>> + >> >> I would advise not add another syscall variant implementation, but rather >> work on make a generic implementation with adjustments made by each platform. >> Something like >> >> __ptr_t >> __mmap (__ptr_t addr, size_t len, int prot, int flags, int fd, off_t offset) >> { >> flags = MMAP_ARCH_FLAGS (flags); >> return (__ptr_t) INLINE_SYSCALL( mmap, 6, addr, len, prot, flags, fd, offset); >> } >> >> And then define MMAP_ARCH_FLAG for x86 to add the MAP_32BIT when required. >> > > This won't work here since we fallback to the default mmap when > MAP_32BIT fails. So just change the MMAP_ARCH_FLAGS hook to something like: __ptr_t ret = __mmap_arch (addr, len, prot, flags, fd, offset)); if (ret != MAP_FAILED) ret = INLINE_SYSCALL (mmap, 6, addr, len, prot, flags, fd, offset); return ret The default value for __mmap_arch could be a constant value so compiler could remove the the comparison if it is the case. Another issue is this is basically limiting ALSR really hard on x86_64. I also would prefer to make the default to *not* include this flag and set the env. variable to actually enable it. If the cpu is slow doing what's intended because it is buggy, let it be slow at default. Do not break what was intended (full ALSR).
|
https://sourceware.org/legacy-ml/libc-alpha/2015-12/msg00230.html
|
CC-MAIN-2022-05
|
refinedweb
| 413
| 75
|
A template language grammar inspired by the Python code aesthetic
Project description
A python-inspired templating language.
DEMO
import app.url import request from plywood.plugin import compress doctype(5) # or doctype('strict') doctype('xhtml'), etc. html: # this'll start looking a lot like jade, but with quotes and colons # even though 'html' is a function call, the parentheses are optional. head: meta(charset="utf-8") title: if self.title: # context variables are available on 'self' # docstrings are stripped of preceding whitespace and the first and # last newline is removed. """ {{self.title}} | """ # string interpolation uses plywood in 'inline' mode. Each line # will be joined with a space. 'Welcome' # string literals require quotes compress('css'): # passing values to tag attributes are escaped (html-entitized) automatically # if you want to escape using xml, pass {'format': 'xml'} in your options. link(: <isbn:number>: 1568491379 header: block('header'): # inlining is easy p(class="logo"): 'logo' # more complicated inlining p: a(href=url.reverse("login")): 'Login' block('header_title'): if self.user: 'Welcome, '{self.user.name}' else: 'Welcome' if not self.user: p(class="login"): a(href=url.reverse("login")): 'Log In' a(href=url.reverse("logout")): 'Log Out' nav: ul: block('nav'): section(class="breadcrumb"): block('breadcrumb') section(class="main"): block('messages'): if messages: ul(class="messages"): for message in self.messages: li(class=message.tags): message script: # code literals, so that savvy editors can color the source code '''javascript $(document).ready(function(){ $("ul.messages").addClass("animate"); var fade_out = _(function() { this.addClass("fade-out") }).bind($("ul.messages")) setTimeout(fade_out, 5000); $("ul.messages").bind("click", fade_out); }); ''' block('content') footer: p: '©{now(%Y)} colinta'
INSTALLATION
$ pip install plywood $ ply < in.ply > out.html # local development $ pip install -e .
RUNTIME
When you run a plywood template, a lot of the work is done using plugins, which are loaded into the global context - the PlywoodEnv object. This only needs to happen once per application - the PlywoodEnv can be reused by any number of templates (though it is not thread safe - that will be remedied soon).
When you actually run a compiled Plywood object, you can pass in a dict of values that you want
WHY!?!?
The main reason: I envisioned an HTML templating language that had python-like syntax, and the options that are out there now (Haml, Coffekup, Jade) don’t hit the mark.
Plain-Jane HTML? Sure, if you want. That is, I think, the best alternative to plywood! For that, use Jinja2.
The template languages that take an HTML-agnostic view (jinja2, django) is HTML made nastier by inserting additional markup. I looked at Jade and Haml as “yeah, you’re getting there”, but they didn’t nail it. Plus, have you tried writing extensions for those systems? Ooof. Nasty stuff. Writing a plugin for plywood is much easier, and since you can take some part in the parsing and runtime process, you can write some pretty hefty plugins!
I’m unapologettically a DIY-er. I think that sometimes wheels just need re-inventing!
LICENSE
See LICENSE for more details (it’s a simplified BSD license).
RELEASE
python setup.py sdist twine upload dist/*
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/plywood/
|
CC-MAIN-2022-05
|
refinedweb
| 548
| 50.84
|
In Python I'm using the numpy package to do some math with matrices. In the code below I'm trying to calculate a new matrix from my orignal.
xFactors
yFactors
3x3
size = self.matrix.shape
for x in range(1, size[0] - 1):
for y in range(1, size[1] - 1):
subMatrix = self.matrix[x-1:x+2, y-1:y+2]
newX = (xFactors * subMatrix).sum()
newY = (yFactors * subMatrix).sum()
self.newMatrix[x-1][y-1] = newX + newY
500x500
If
xFactors and
self.matrix are both
numpy.array and not
numpy.matrix (in other words if you are using element-wise multiplication and not matrix multiplication in calculating newX and newY), then this should do the same thing a lot faster:
from scipy.signal import convolve2d self.newMatrix = convolve2d(self.matrix, xFactors + yFactors, mode='valid')
In the original code, it was not clearly stated that xFactors and yFactors were square. If they weren't one would need to make them square by repeating them as needed if the above addition doesn't broadcast correctly.
|
https://codedump.io/share/FGFqUdxzKgYQ/1/inefficient-numpy-code
|
CC-MAIN-2016-50
|
refinedweb
| 175
| 60.51
|
1,505 Mix IE11 Babel Issues
I'm currently trying to install Laravel Mix inside a WordPress project to handle my asset compilation.
I have my
webpack.mix.js file set up as follows:
let mix = require("laravel-mix"); mix.babel("src/js/app.js", "dist/js/app.js") .sass("src/scss/style.scss", "dist/css/style.css") .sourceMaps() .setPublicPath("dist");
I also have a
.babelrc set up as follows:
{ "presets": [ [ "@babel/preset-env", { "targets": { "ie": "11" } } ] ] }
The only code I'm currently using inside
app.js is this:
import Vue from "vue";
However, when I go to the page I get the following error:
Uncaught ReferenceError: require is not defined at app.js:3
And file compiled looks like this (the issue apparently lies on the
var _vue line):
"use strict"; var _vue = _interopRequireDefault(require("vue")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
I'm really stuck on this issue as I'm unsure what to do. Any ideas appreciated!
Replied to Install Wordpress From Git Repo?
@nathangross I achieved this using the Bedrock Wordpress installation, it's up and running nice and easy :)
Replied to Wordpress, Forge & Version Controlled WP Themes
Thanks @sutherland this'll be tonights project :)
Replied to Wordpress, Forge & Version Controlled WP Themes
@sutherland good shout dude, I totally forgot about Bedrock. What would be the process for setting up the Forge account with it? Do I create a site as a standard PHP/Laravel site or still set up as Wordpress?
Thanks for the reminder :)
Started a new conversation Wordpress, Forge & Version Controlled WP Themes
Hey friends,
I'm currently developing a Wordpress site for my photography and I'm using Git to control the theme files. I know that I can set Wordpress up on Forge which is awesome, but how can I go about setting my server up to read from the theme's repo?
Do I need to do anything specific with the deploy script or will it work fine out of the box so to speak if I reuse a deploy script from one of my Laravel sites? I've not installed WP on Forge before.
Thanks in advance for any guidance :)
Andy
Replied to Install Wordpress From Git Repo?
@nathangross I haven't yet I'm afraid, I need to take another look into it. Let me know if you find anything :)
Replied to Install Wordpress From Git Repo?
@alenabdula I know this question is old but what's the best way to set up automated pull when listening to the master branch when working with git controlled themes in Wordpress? I'm about to set my Forge up the same way you suggested above
Replied to Tightening Up Security For An Upcoming App Idea
Replied to Tightening Up Security For An Upcoming App Idea
@36864 If they're stored in a table, with a foreign key, does that not then make an obvious correlation with what user it belongs to? If only the database is compromised, they can decrypt everything right? But if one key was stored in the .env, and they didn't get access to that (just the DB) the data would be useless - right? I know it's a lot of what if's though haha.
Yeah I use Spatie's Laravel-Permission in a couple of projects already, works really well :)
No worries on the JWT, new ground for me too haha
Replied to Tightening Up Security For An Upcoming App Idea
@bashy haha thanks dude, much appreciated :)
@36864 Aye, I definitely don't assume it's safe from any attack because it's encrypted; but it's saf_er_ with the encryptions.
I have thought about trying to work out how to use unique keys for each user, but is there a simple way to pass each user's key on the request etc rather than using the global? I was originally going to use a trait to encrypt/decrypt.
It's hard to share anymore than I already have at this point in time: I'd like the details of users, those user's clients and any associated jobs/files to be encrypted so that they aren't plain text - one box ticked when it comes to security.
I'll also want to roll JWT or similar into it so the API can be consumed by an app.
Just want to get a little bit of a clear picture on a good place to start so I don't need to rewrite the app a couple of times - though sometimes that's required
Replied to Tightening Up Security For An Upcoming App Idea
@bashy haha ah yeah, that was my reptile genetics calculator :P I saw your laptop skin on Twitter a while back, was meant to tweet you to see where you got it as I'd forgotten.
This is true, this particular project needs a lot of thought overall. I'm going to look into how to really lock down a server and keep that key as safe as possible - If any of you guys have recommendations on securing linux or similar I'm all ears.
Thanks for the suggestions so far, really don't want to go down one path with this and then have to totally rewrite it haha
Replied to Tightening Up Security For An Upcoming App Idea
@bashy Ah dude I wondered if you'd ever see me post on here, blows my mind we're in the same building haha.
I'll take a look at the suggestions and see what we can do. Can any of you see any immediate issues with what I'm proposing at all? Is encrypting multiple columns going to cause me some speed issues or will it be negligible?
Easy to get an idea and run before you walk so doing my best to do this properly :P
Started a new conversation Tightening Up Security For An Upcoming App Idea
Hey guys,
I've got a little system that I plan to work on soon (which when its ready will be released worldwide), but I want to try and make the data that's stored in the server as secure as possible. We will be capturing user details (name, email, password etc.), details of their clients (name, address, email etc.) and then details of jobs for those clients (job number, description etc.). There will also be PDF contracts created that have a digital version of the user & client signatures
We will be using Stripe for payments to us, and perhaps offer it as a platform for user's to be paid via Stripe from their clients - so not too much of a worry there as we can leverage Stripes API.
I know that I can use
Crypt::encrypt and
Crypt::decrypt which utilises the key stored in the
.env - is this enough security inside the application itself, or are there other things that I should look into?
Also, what steps should I take when setting up a server for this kind of application - would something like AWS be a good option? I usually just use linux servers with mysql but looking to use a better stack as I feel like I'm using an archaic setup.
Thanks in advance for any advice on this,
Andy
Started a new conversation Will The "How To Accept Payments" Series Be Updated To Reflect Stripe's Changes?
Hey @JeffreyWay ,
I was browsing twitter this morning and saw that Adam Wathan tweeted about the changes to Stripe.js. Will this be reflected in upcoming episodes of the series?
Thanks for all you do on Laracasts :)
Andy
Replied to Laracasts Refresh
omfg this design is so good
Replied to Modify Authenticated() Method Inside AuthenticatesUsers.php Class
Replied to Modify Authenticated() Method Inside AuthenticatesUsers.php Class
Started a new conversation Modify Authenticated() Method Inside AuthenticatesUsers.php Class
Hi guys.
I'm looking for the correct way to modify the
authenticated() method inside the
\Illuminate\Foundation\Auth\AuthenticatesUsers.php file.
I don't want to just modify this file as the changes won't reflect on the server, as it's inside the vendor folder which is git ignored.
I've not had to modify a core method before so don't know the best way to do this? Any advice is appreciated :)
Andy
Replied to Stripe New Tutorial For 5.2
@darrynsmith Looks like you don't need to wait any longer ;)
Started a new conversation Laravel Passport Questions
Hey friends,
I've set up a central app (let's call this
maindomain.com), where I've setup Passport. This site will be where users register to gain access to all other apps I create.
To test it out, I've followed Matt Stauffer's blog post to create a client app that will use the user data stored on
maindomain.com, let's call this
app1.com.
I can confirm that my callback and whatnot work fine. When you go to
app1.com/login (as per my route) it redirects to
maindomain.com and allows you to authorise
app1.com to use your login details - beautiful.
As per Matt's post, right now it prints the token to the screen. I need to change this so that it saves to the database - I assume I should just create a column on my user's table and store it there?
I've tested the token and can access the API routes using PostMan. However, because at the moment I'm creating web apps that all need to use this centralised user system, I'm not sure how I can use a login form to authorise users and allow them access to their dashboard.
If user's are logging into
app1.com do I send a POST request to
maindomain.com? Isn't that going to be a problem with CSRF? I've read the documentation but as this is my first venture into
oauth2 I am pretty confused.
If you guys can help me out at all I'd seriously appreciate it :)
Andy
Replied to Is There Any Way To Run `php Artisan` On Forge?
Wow holy crap I totally forgot to run
composer install. Thanks for that @tykus_ikus, now I feel stupid ;)
Replied to Is There Any Way To Run `php Artisan` On Forge?
Started a new conversation Is There Any Way To Run `php Artisan` On Forge?
I'm spinning up some new servers and on one of the sites I want to put it in maintenance mode - I planned on using
php artisan down but forge doesn't allow it saying
Could not open input file: artisan.
How on earth do I go about doing this?
Replied to One Login For Multiple Sites
Replied to One Login For Multiple Sites
But if you go to another one of the sites (where no login session exists), how would you login?
Started a new conversation One Login For Multiple Sites
Hey friends,
I've got a couple of apps I'm building on Laravel. They are all going to be separate systems, likely on separate servers but part of one "ecosystem". I have a goal of allowing people to sign up on any of the sites that I create, and that login can then be used on any of the other sites.
Is this the sort of thing Passport is used for? If so, what's the best way to implement it? Should I pick just one site and make that the "main" user database, or spin up a single app just for holding all the user data?
Thanks in advance for your feedback/ideas,
Andy
Replied to 'Minimize Redirects' When Using SSL On Forge
Started a new conversation 'Minimize Redirects' When Using SSL On Forge
Hey guys,
I've got a couple of sites on Forge that have LetsEncrypt enabled, neither of them are Laravel at the minute. When I run them through they always come back with this warning:
Remove the following redirect chain if possible:
Is it possible to fix this or is it just not worth worrying about?
Andy
Replied to What Is The Correct Approach To Adding Extra Fields To Spark's Registration Form?
@zaffarsaffee Yes unfortunately, this is based off of experimentation due to lack of documentation in the beginning. Taylor has now added this as a cookbook tutorial on the Spark documentation with the proper implementation
Replied to Integrating Socialite With Spark
@zanematthew Could well be a better way of doing it than my way. I just tied it into the already existing
LoginController but honestly didn't think about the impact of updates. The rest of what I did is incredibly similar to your own except I just put the token for Facebook and Twitter into a column on my
Users table.
Did you just make your Socialite routes point to your new
SocialAuthController and handle all the Socialite stuff there? Seems like a much cleaner way of doing it ;)
A lot of my spark work is experimentation at the moment as I couldn't find any good docs on integrating Socialite properly or creating additional registration fields, but Taylor has created a little cookbook for that bit now ;) haha.
Replied to Integrating Socialite With Spark
Sorry all, have been on holiday in Portugal. I'll go through my files tonight but not a lot is actually different to how you would usually implement Socialite to a Laravel app.
I can confirm that Socialite works with Spark, quite nicely too.
Andy
Replied to What Is The Correct Approach To Adding Extra Fields To Spark's Registration Form?', ]; }
Replied to Cannot Find A Way To Make Spark Register Fields Show Errors?', ]; }
Started a new conversation Cannot Find A Way To Make Spark Register Fields Show Errors?
I've added a new field to my form. But I can't find where to set the errors so that my new
username input must be unique.
I've spent hours trying to work this out and I'm really quite stuck :(
Andy
Started a new conversation What Is The Correct Approach To Adding Extra Fields To Spark's Registration Form?
Hi all,
I'd like to add some extra fields to my Spark registration form but can't find anything in the docs explaining how to do this. Can anyone point me in the right direction on what I need to alter in order for the new fields to work? For example I'd like to add a username field so that users can log in with either their username and password or email and password after signing up.
Update
Okay so I've worked out that I literally just need to update the view for the form in order to add the field, and then handle the field in the
UserRepository, that's done. What I can't quite get my head around is why when the field is empty and I try and submit the form, there are no errors returned for the
username field?
<!-- Username --> <div class="form-group" : <label class="col-md-4 control-label">Username</label> <div class="col-md-6"> <input type="username" class="form-control" name="username" v- @{{ registerForm.errors.get('username') }} </span> </div> </div>
Replied to Integrating Socialite With Spark
The answer is no, not really lol. I just used
LoginController to control all the Socialite stuff, updated my routes, job done.
Started a new conversation Integrating Socialite With Spark
Hi all,
I've got Socialite working on my "standard" Laravel App. I'm just wondering if the way to integrate Socialite into a Spark based App is exactly the same process? I've noticed that Spark uses a different
AuthController file which I think is called
LoginController. Apart from that, is there much different?
Cheers, Andy
Started a new conversation "Sign In" Link Gets Lost In Header When Previously Visited
Hey Jeffrey,
Just noticed that the contrast seems a little off for the previously visited "Sign In" link in the header. I almost missed it ;)
Andy
Replied to Reviewing My Routes, Do They Make Sense?
@frezno Thanks for that info, I think I'll restructure my routes file today as I wasn't aware that was available haha.
@Snapey The logic behind naming is all sorted don't worry. My system is working well, I'm just crap with knowing the best way to do the API.
I think your suggestion of
/gecko/images/{gecko_name}/upload is good, would you also do something like
/gecko/images/{gecko_name} in order to view a gallery?
Thanks for your feedback guys, trying to think of a logical route is difficult at times haha.
Replied to Reviewing My Routes, Do They Make Sense?
Started a new conversation Reviewing My Routes, Do They Make Sense?
Hi everyone,
I'm still working on my first Laravel app - it's a reptile tracker app. Anyways I'm still trying to understand the best way of doing RESTful routes, below are my current routes:
// Weight routes... Route::resource('weights', 'WeightController'); Route::get('weights/{gecko_name}/create', 'WeightController@create'); // Gecko routes... Route::get('geckos', 'GeckoController@index'); Route::resource('gecko', 'GeckoController'); Route::get('gecko/{gecko_name}/view', 'GeckoController@show'); Route::get('gecko/{gecko_name}/edit', 'GeckoController@edit');
So to give you an idea, a couple of the routes could be:
app.dev/gecko/Zilly/view
app.dev/gecko/Zilly/update
app.dev/weights/Zilly/create
And I want to implement some image uploads, so I'm thinking the following routes:
app.dev/gecko/Zilly/images
app.dev/gecko/Zilly/images/upload
app.dev/gecko/Zilly/images/delete
Have I got my endpoints correct? Does the way I'm doing things make sense or could I make them better/more understandable?
I appreciate any help with this stuff,
Andy
Started a new conversation Submitting Array In Laravel Gives Error - Preg_replace(): Parameter Mismatch, Pattern Is A String While Replacement Is An Array
I'm trying to use the following in my application:
<div class="form-group"> <label for="genetics">Bell Albino</label> <select name="genetics[]" class="form-control"> <option>N/A</option> <option value="BA">Visual</option> <option value="ba">Recessive</option> </select> </div> <div class="form-group"> <label for="genetics">Tremper Albino</label> <select name="genetics[]" class="form-control"> <option>N/A</option> <option value="TA">Visual</option> <option value="ta">Recessive</option> </select> </div>
Which you would assume works okay, however when I try submitting my form, I get the error:
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
This is my model, not sure if it will help:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Gecko extends Model { /** * Fillable fields for a gecko * @var array */ protected $fillable = [ 'name', 'aquisition_date', 'morph', 'sex', 'genetics', 'bio', 'bred', 'hatchling', 'clutch', 'user_id' ]; /** * A gecko has many photos * @return \Illuminate\Database\Eloquent\Relations\HasMany; */ public function photos() { return $this->hasMany('App\GeckoPhoto'); } /** * A gecko has many weights * @return \Illuminate\Database\Eloquent\Relations\HasMany; */ public function weights() { return $this->hasMany('App\Weight'); } }
The store method:
public function store(GeckoRequest $request) { Gecko::create($request->all()); flash()->success('Success!', 'Your gecko has been added to the system'); return redirect()->action('GeckoController@show', [$request['name']]); }
The GeckoRequest file:
<?php namespace App\Http\Requests; use Auth; use App\Http\Requests\Request; class GeckoRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'morph' => 'required', 'sex' => 'required', 'genetics' => 'required', 'name' => "required|unique:geckos,name,NULL,id,user_id," . \Auth::user()->id ]; } }
All it saves into the database is the word
Array.
I'm sure it's super simple, but I'm unsure on how to fix it
Replied to Laravel 5.1 Don't Allow Duplicate Gecko Name For Current User
Wonderful, thank you!
Started a new conversation Laravel 5.1 Don't Allow Duplicate Gecko Name For Current User
I have a situation with my app and I shall do my best to explain what it is i'm trying to do.
In my migration, I made my gecko
name column unique (
$table->string('name')->unique()). This obviously means that gecko names must be unique across the board for all users - this isn't what I want to do, I want to make sure that the current user cannot use the same name for another gecko.
For example:
If user 1 makes a gecko called Bob and user 2 made a gecko called Bob that would be fine.
If user 1 made a gecko called Bob, and then made another gecko called Bob - This wouldn't be fine.
What is the best way/practice to make this work?
|
https://laracasts.com/@andyjh07
|
CC-MAIN-2019-43
|
refinedweb
| 3,456
| 58.82
|
Hello All,
Caché.
Hi All,
I am planning on doing some maintenance in 2020, I was wondering if it is possible to run a query to get a log on when a DTL and/or Business Rules was called in HEALTHSHARE, the idea behind this is to do some cleaning and remove some clutter.
Your help or ideas are highly appreciated.
LW21
Hello community,
I am receiving a HL7 message over TCP connection.
Is there a way to get a good performing index on a date field? I have tried various date property indexes and the query plan is always in a pretty high range. Below are query plan result values I have observed:
StartDate > '2019-12-01' --cost = 699168
StartDate = '2019-12-21' --cost 70666
StartDate between '2019-12-21' and '2019-21-28' --cost = 492058
The query plans above were for type %TimeStamp.
Hello All,
I am working on Files where I have to compare contents of two files and display result.
e.g Suppose file1 contains data in Name and Roll form and file2 contains data in name and class form, so it should compare name from file1 and file2 and display those matching data(Name,Roll,class).
I have piece of idea about file system so any help would be appreciated.
Thanks in advance.
Regards,
Gunwant
Hi All,
I am getting server application error in salesforce outbound message after upgrading the HealthShare (from version 2015.1.0 to 2015.1.4). Please guide me to resolve this error.
Hi,
I have written a procedure with the help of object scripting to export data to a csv file. There is more data than the csv limit.
Can anyone please tell me how to get the row count of csv file using object scripting, so that I can write an if condition and write to a second csv file.
Please find the code writing to the csv given below.,
In the previous part of this series, we saw how to reference a web page that will enhance our dashboard experience. Now we will look into referencing data that is already in our cubes.
In this example, we will be referencing the controller object and we will be extracting data from it. This data will then be displayed as text in our Dashboard. In Part 5, we will show how to incorporate this data into other charting libraries.
I am trying to use the %ListOfDataTypes functionality, but am hitting a limit of 50 characters for each entry, when being used in a Web Service. Is there a way to increase the number of characters that can be used in the %ListOfDataTypes through a web service?
Hello team,
I am trying to do a basic read file of HL7 messages. Need to count how many FT1 segments are there in each file and how many messages are in each file.
Any help will be appreciated. I have the stream object.
Just need to loop through the stream and get the info in some way.
Any help will be appreciated.
Thanks,
Jimmy Christian.
Hello All
Could someone help me in the details of the ODBC connection I need to connect to the Healthshare Cache databases for the CMC application?
Much appreciated in advance
Andrew
Does anyone know of an API that will do a hostname look-up based on IP? We could of course use call-out but the format of the results vary based on OS and if there is already an ObjectScript tool which will parse this then we'd rather use what is already available.
Thanks!
Ben
Hi All,
I trying to get the DisplayList data of the ValueLIst from Java using Springboot. when I try to get the DislayList data via java code but I'm getting the VALUELIST data. I don't get any idea to get that DisplayList data. Below is the example
Hello, InterSystems community!
Lately, you have probably heard of the new InterSystems Package Manager - ZPM. If you're familiar with it or with such package managers as NPM, Dep, pip/PyPI, etc. or just know what is it all about -- this question is for you! The question I want to arise is actually a system design question, or, in other words, "how should ZPM implement it".'ve been having a blast with the Advent of Code puzzles this year - though I'll be heading into a busy span of time with family soon and will probably drop off toward the end. (At least, that's what always seems to happen - it's a good thing, though!)
Hi All,
I am getting error while opening the PDF report in cache 2017 instance, I am using this below piece of code to open PDF in browser.
I configured a SQL inbound adapter to monitor my local Cache database.
But I got "ERROR <Ens>ErrOutConnectFailed: ODBC Connect failed for 'SAMPLES' /
'' with error ERROR #6022: Gateway failed: DSN/User Connect."
Same error if the DSN setting is blank or set to my namespace.
Question is whether SQL inbound adapter is for external database server ONLY?
Hello All,
We need to develop a small csp application which shows data in simple paginated / searchable table for business users.
It is to be built on an old version of Cache and is not a big full fledged application but something temporary. We can't use Zen and using a combination of csp & Bootstrap as bootstrap makes the pages look beautiful with little effort.
I have built the table in boostrap and it works fine with pagination and search working perfectly.
For unknown reason, my Studio "Find" button is greyed out even when Studio is restarted.
What
Hello guys,
Is it possible to map a package as read only?
I know it is possible to mount the source database as read only and map the package in the target namespace. But I would like to make the mapping read only so that the package would be "read only" only in the target namespace.
This would avoid someone to forget to set the database read only again if a modification in the package is needed.
Thanks in advance.
Jonas Zanon
DeepSeeButtons is available on Open Exchange! This tool will generate a diagnostic report of your DeepSee environment.
I am converting an object to json, but in the result a "_class" property appears, is there any way to remove this?
.png)
Result:
.png)
|
https://community.intersystems.com/tags/cach%C3%A9?period=lastmonth
|
CC-MAIN-2020-05
|
refinedweb
| 1,071
| 71.65
|
I'm new to HTTP requests, and have tried accessing Instagram users' follower count using the getJSON function
import {getJSON} from 'wix-fetch'; async function setIGFollowers (instagramID) { getJSON("" + instagramID + "/?__a=1") .then(json => { console.log(json); let followers = json.graphql.user.edge_followed_by.count $w("#text1").text = "Followers: " + followers }) .catch(err => console.error(err)) }
It worked at first, but now overtime I try to run it again, the catch returns the error:
SyntaxError: The string did not match the expected pattern.
What could be the problem? What are the required string patterns for the getJSON function?
Important to Note: This code did work a few hours ago, and does still work at another function, getting YouTube channel subscriber counts, below:
async function setYTSubs (youtubeID) { getJSON("" + youtubeID + "&key=[AUTH TOKEN]") .then(json => { let subs = json.items[0].statistics.subscriberCount $w("#text2").text = "Subscribers: " + subs }) }
Thank you for your time
Make sure that you stay on top of any companies code or API changes etc as this is a issue with Facebook and nothing to do with Wix, you just need to use different code from Instagram.
UPDATE: Starting October 15, 2019, new client registration and permission review on Instagram API platform are discontinued in favor of the Instagram Basic Display API.
Does this still work? Or has it been culled along with those listed at instagram.com/developer?
2@Ollie unfortunately this too has been deprecated. Currently there is no easy method for accessing public data via a public json request.
You will now have to do your own research within Instagram API info and use their new code,
|
https://www.wix.com/corvid/forum/community-discussion/getjson-syntax-error
|
CC-MAIN-2019-47
|
refinedweb
| 267
| 55.13
|
145+ extra higher-level functional tools beyond standard and third-Party libraries.
Project description
Featured on GitHub's Trending Python repos on May 25, 2018. Thank you so much for support!
145+ extra higher-level functional tools that go beyond standard library's
itertools,
functools, etc. and popular third-party libraries like
toolz,
funcy, and
more-itertools.
Like
toolzand others, most of the tools are designed to be efficient, pure, and lazy. Several useful yet non-functional tools are also included.
While
toolzand others target basic scenarios, this library targets more advanced and higher-level scenarios.
A few useful CLI tools for respective functions are also installed. They are available as
extratools-[func].
Full documentation is available here.
Why this library?
Typical pseudocode has less than 20 lines, where each line is a higher-level description. However, when implementing, many lower-level details have to be filled in.
This library reduces the burden of writing and refining the lower-level details again and again, by including an extensive set of carefully designed general purpose higher-level tools.
Current status and future plans?
There are currently 140+ functions among 17 categories, 3 data structures, and 3 CLI tools.
- Currently adopted by TopSim and PrefixSpan-py.
This library is under active development, and new tools are added on weekly basis.
- Any idea or contribution is highly welcome.
Besides many other interesting ideas, I am planning to make the following updates in recent days/weeks/months.
Add
dicttools.unflattenand
jsontools.unflatten.
Add
trieand
suffixtree(according to generalized suffix tree).
Update
seqtools.alignto support more than two sequences.
No plan to implement tools that are well covered by other popular libraries.
Which tools are available?
Function Categories:
debugtools
dicttools
gittools
graphtools
htmltools
jsontools
mathtools
misctools
printtools
rangetools
recttools
seqtools
settools
sortedtools
stattools
strtools
tabletools
Data Structures:
defaultlist
disjointsets
segmenttree
CLI Tools:
dicttools.remap
jsontools.flatten
stattools.teststats
Any example?
Here are ten examples out of our hundreds of tools.
jsontools.flatten(data, force=False)flattens a JSON object by returning all the tuples, each with a path and the respective value.
import json from extratools.jsontools import flatten flatten(json.loads("""{ "name": "John", "address": { "streetAddress": "21 2nd Street", "city": "New York" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" } ], "children": [], "spouse": null }""")) # {'name': 'John', # 'address.streetAddress': '21 2nd Street', # 'address.city': 'New York', # 'phoneNumbers[0].type': 'home', # 'phoneNumbers[0].number': '212 555-1234', # 'phoneNumbers[1].type': 'office', # 'phoneNumbers[1].number': '646 555-4567', # 'children': [], # 'spouse': None}
rangetools.gaps(covered, whole=(-inf, inf))computes the uncovered ranges of the whole range
whole, given the covered ranges
covered.
from math import inf from extratools.rangetools import gaps list(gaps( [(-inf, 0), (0.1, 0.2), (0.5, 0.7), (0.6, 0.9)], (0, 1) )) # [(0, 0.1), (0.2, 0.5), (0.9, 1)]
recttools.heatmap(rect, rows, cols, points, usepos=False)computes the heatmap within rectangle
rectby a grid of
rowsrows and
colscolumns.
from extratools.recttools import heatmap heatmap( ((1, 1), (3, 4)), 3, 4, [(1.5, 1.25), (1.5, 1.75), (2.75, 2.75), (2.75, 3.5), (3.5, 2.5)] ) # {1: 2, 7: 1, 11: 1, None: 1} heatmap( ((1, 1), (3, 4)), 3, 4, [(1.5, 1.25), (1.5, 1.75), (2.75, 2.75), (2.75, 3.5), (3.5, 2.5)], usepos=True ) # {(0, 1): 2, (1, 3): 1, (2, 3): 1, None: 1}
setcover(whole, covered, key=len)solves the set cover problem by covering the universe set
wholeas best as possible, using a subset of the covering sets
covered.
from extratools.settools import setcover list(setcover( { 1, 2, 3, 4, 5}, [{1, 2, 3}, {2, 3, 4}, {2, 4, 5}] )) # [{1, 2, 3}, {2, 4, 5}]
seqtools.compress(data, key=None)compresses the sequence
databy encoding continuous identical items to a tuple of item and count, according to run-length encoding.
from extratools.seqtools import compress list(compress([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])) # [(1, 1), (2, 2), (3, 3), (4, 4)]
mergeseqs(seqs, default=None, key=None)merges the sequences of equal length in
seqsinto a single sequences. Returns
Noneif there is conflict in any position.
from extratools.seqtools import mergeseqs seqs = [ (0 , 0 , None, 0 ), (None, 1 , 1 , None), (2 , None, None, None), (None, None, None, None) ] list(mergeseqs(seqs[1:])) # [2, # 1, # 1, # None] list(mergeseqs(seqs)) # None
strtools.smartsplit(s)finds the best delimiter to automatically split string
s. Returns a tuple of delimiter and split substrings.
from extratools.strtools import smartsplit smartsplit("abcde") # (None, # ['abcde']) smartsplit("a b c d e") # (' ', # ['a', 'b', 'c', 'd', 'e']) smartsplit("/usr/local/lib/") # ('/', # ['', 'usr', 'local', 'lib', '']) smartsplit("a ::b:: c :: d") # ('::', # ['a ', 'b', ' c ', ' d']) smartsplit("{1, 2, 3, 4, 5}") # (', ', # ['{1', '2', '3', '4', '5}'])
strtools.learnrewrite(src, dst, minlen=3)learns the respective regular expression and template to rewrite
srcto
dst.
from extratools.strtools import learnrewrite learnrewrite( "Elisa likes Apple.", "Apple is Elisa's favorite." ) # ('(.*) likes (.*).', # "{1} is {0}'s favorite.")
tabletools.parsebymarkdown(text)parses a text of multiple lines to a table, according to Markdown format.
from extratools.tabletools import parsebymarkdown list(parsebymarkdown(""" | foo | bar | | --- | --- | | baz | bim | """)) # [['foo', 'bar'], # ['baz', 'bim']]
tabletools.hasheader(data)returns the confidence (between
0and
1) of whether the first row of the table
datais header.
from extratools.tabletools import hasheader t = [ ['Los Angeles' , '34°03′' , '118°15′' ], ['New York City', '40°42′46″', '74°00′21″'], ['Paris' , '48°51′24″', '2°21′03″' ] ] hasheader(t) # 0.0 hasheader([ ['City', 'Latitude', 'Longitude'] ] + t) # 0.6666666666666666 hasheader([ ['C1', 'C2', 'C3'] ] + t) # 1.0
How to install?
This package is available on PyPI. Just use
pip3 install -U extratools to install it.
To enable all the features, please install extra dependencies by
pip3 install -U sh RegexOrder TagStats.
How to cite?
When using for research purpose, please cite this library as follows.
@misc{extratools, author = {Chuancong Gao}, title = {{extratools}}, howpublished = "\url{}", year = {2018} }
Any recommended library?
There are several great libraries recommended to use together with
extratools:
regex
sortedcontainers
toolz
sh
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/extratools/
|
CC-MAIN-2019-04
|
refinedweb
| 1,041
| 50.84
|
Memory leak in zope.i18nmessageid.MessageFactory
Bug #257657 reported by Gary Poster
This bug affects 2 people
Bug Description
(zope.i18nmessa
The following code leaks memory:
import zope.i18nmessageid
_ = zope.i18nmessag
while 1:
_('a string')
Apparently the message instances (C code) are not being garbage collected.
This affects persistent objects that have a reference to a message (every time the state is loaded, a new version of the same string is created and never released).
It will also affect any code that generates message instances dynamically; templates, for instance, may be affected.
This has been reproduced using both Python 2.4 and 2.5.
|
https://bugs.launchpad.net/zope.i18nmessageid/+bug/257657
|
CC-MAIN-2022-27
|
refinedweb
| 106
| 51.95
|
Jabber::NodeFactory - Simple XML Node Factory for Jabber
my $nf = new Jabber::NodeFactory(fromstr => 1); print $nf->newNode('presence')->toStr; -> <presence/> my $tag1 = $nf->newNode('iq'); $tag1->attr('type', 'get'); my $query = $tag1->insertTag('query', 'jabber:iq:auth'); $query->insertTag('username')->data('qmacro'); print $tag1->toStr; -> <iq type='get'><query xmlns='jabber:iq:auth'> <username>qmacro</username></query></iq> my $tag2 = $nf->newNodeFromStr("<message><body>hi</body></message>"); $tag2->attr('to','qmacro@jabber.org'); my $msg = $tag2->getTag('body')->data; print $tag2->toStr, "\n"; print $msg; -> <message to='qmacro@jabber.org'><body>hi</body></message> -> hi
Jabber::NodeFactory is a library for creating and manipulating XML nodes. It was created to offer similar functions to the xmlnode library in the Jabber server implementation.
It provides enough functions to create and manipulate XML fragments (nodes) in the Jabber XML stream world. The functions are low level, RISC-style :-)
There are two packages - Jabber::NodeFactory and Jabber::NodeFactory::Node. The former is a wrapper which offers two node construction methods; the latter is the package that represents the actual node objects that are created and manipulated.
Use Jabber::NodeFactory to contruct new nodes (which will be Jabber::NodeFactory::Node objects) and Jabber::NodeFactory::Node to manipulate those nodes.
The Connection package will present stream fragments received in the form of Jabber::NodeFactory::Node objects; use Jabber::NodeFactory::Node to parse and manipulate these fragments.
The Jabber::NodeFactory constructor. Call this to create a new Jabber::NodeFactory, with which you can build nodes.
You can create nodes in one of two ways - building them up starting from the tagname (
newNode()), or creating them from a string (
newNodeFromStr()). If you want to be able to do the latter, you need to specify the flag
fromstr => 1
like this
my $nf = new Jabber::NodeFactory(fromstr => 1)
Creating nodes from strings requires the strings to be parsed; an XML parser is only created as part of the Jabber::NodeFactory object being constructed if you set this flag. If you don't set the flag and subsequently try to call
newNodeFromStr(), you'll get an error.
Call this to create a new node. This will return a new Jabber::NodeFactory::Node object. There is one mandatory argument to this call - the name of the tag for the node being created.
my $node = $nf->newNode('tag');
will create a node that looks like this:
<tag/>
If you want to create a node like this, by specifying a tag name, you can also use the
new method in Jabber::NodeFactory::Node to achieve the same thing; the
newNode method has been made available here just to have some consistency with
newNodeFromStr.
Like
newNode, this also returns a new Jabber::NodeFactory::Node object. The single argument to be passed is a string. The NodeFactory will use an XML parser to parse this string and create a node or hierarchy of nodes.
my $node = $nf->newNodeFromStr(qq[<test><child attr1='a'/></test>]);
will create a node object that represents the <test> node having a child node as shown.
Construct a new node. Returns a Jabber::NodeFactory::Node object. You must specify a tag name for the node.
Example:
my $tag1 = new Jabber::NodeFactory::Node('tag1');
$tag1 represents a node that looks like this:
<tag1/>
Returns the name (the tag name) of the node, in the form of a string.
Returns the node's parent. This will be a node object or undef (if it doesn't have a parent).
Sets or gets a node attribute. Pass one argument - an attribute name - to get the value, or two arguments - the name and a value - to set the value. In both cases the value is returned.
Example:
$tag1->attr('colour' => 'red'); print $tag1->attr('colour');
prints
red
Sets or gets a node's data. Pass no arguments to get the data, or one argument - the data - to set the data. In both cases the data is returned.
Example:
$tag1->data('hello world');
results in $tag1 representing
<tag1 colour='red'>hello world</tag1>
The common character entities will be encoded/decoded on the fly. These are & (&), " ("), ' ('), < (<) and > (>). This means that if you call data() with the string "this & that", what actually will get stored is "this & that". If you receive a string containing "--> this way", calling data() to retrieve it will give you "--> this way".
See the rawdata() function for a contrast.
Similar to data(), this function allows you to get and set the data for a node. Unlike data(), there is no encoding or decoding of character entities. It's up to you to make sure you don't break the XML stream by sending a stray "<" or something.
This will insert a tag - with the name given in the first (mandatory) argument - into the node object on which the method call is made.
A namespace can be specified in an optional second argument.
Example:
my $tag2 = new Jabber::NodeFactory::Node('tag2'); $tag2->insertTag('a'); $tag2->insertTag('b', 'fish:face'); $tag2->insertTag('c')->data('hello');
results in $tag2 looking like this:
<tag2><a/><b xmlns='fish:face'/><c>hello</c></tag2>
Returns a string representation of the node (and all its children).
Example:
my $x = new Jabber::NodeFactory::Node('tag'); my $y = $x->insertTag('anothertag'); $y->attr('number',3); print $x->toStr, "\n"; print $y->toStr, "\n";
results in:
<tag><anothertag number='3'/></tag> <anothertag number='3'/>
Retrieves a child tag and returns it as a node. Specify the name of the tag to retrieve, and an optional namespace attribute (that must be explicitly specified as an xmlns attribute in the child tag you want) to distinguish it from other tags of the same name.
If you don't know the tagname but know what namespace you want (common in Jabber), then specify an empty string for the tagname.
Example:
$node->getTag('x','jabber:x:event');
Will return the <x> tag(s) that have xmlns='jabber:x:event'. If you only want the first one, make the call in scalar context:
my $event = $node->getTag('x','jabber:x:event');
otherwise make it in array context:
my @xtags = $node->getTag('x');
to get multiple tags (node objects).
Another example:
my $query = $node->getTag('', 'jabber:iq:version');
This gets a 'query' node that's qualified by the iq:version namespace.
Use this method to remove a child tag. Use getTag to identify the tag to remove.
Example:
my $tag = $nf->newNodeFromStr(qq[<a><b fruit='banana'>yellow</b></a>]); $tag->getTag('b')->hide; print $tag->toStr;
outputs this:
<a/>
This returns a list (array) of the direct child tags of the tag on which the method is called.
Example:
my $node = $nf->newNodeFromStr(qq[<a><a1/><a2/><a3><a31/></a3></a>]); print $_->name, "\n" foreach $
Jabber::Connection, Jabber::NS
DJ Adams
early
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
|
http://search.cpan.org/~qmacro/Jabber-Connection-0.04/lib/Jabber/NodeFactory.pm
|
CC-MAIN-2015-27
|
refinedweb
| 1,148
| 53.71
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.