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
class CIFAR10Record(object): pass result = CIFAR10Record() # Dimensions of the images in the CIFAR-10 dataset. # See # input format. label_bytes = 1 # 2 for CIFAR-100 result.height = 32 result.width = 32 result.depth = 3 This code uses a class in order to "bunch together" a number of related fields. The pros are that it's very flexible. The class is defined without any members. Any function can decide which fields to add. Different invocations can create objects of this class, and populate them in different ways (so, simultaneously, you could have objects of the same class with different members). This flexibility is also a con. This lacks structure: it's harder to look at the code and decide which members the class will have. It's also less straightforward to get such an object, and iterate over the members. Finally, the class is an extreme case of no encapsulation. Altogether, I think there are better alternatives: If this flexibility is really needed (which is a question in itself), you might want to consider using a dict instead. result = {} result['height'] = 32 result['width'] = 32 result['depth'] = 3 It's much clearer here (IMHO) that result is just a grouping of fields, and it's easier to iterate over the fields using dict's methods. If this flexibility is not needed, and it's just a way to minimize the amount of code, you should consider using collections.namedtuple. import collections CIFAR10Record = collections.namedtuple('CIFAR10Record', ['height', 'width', 'depth'])
https://codedump.io/share/wRpwIUsPW0L3/1/what-are-the-advantages-and-disadvantages-of-creating-class-and-instance-in-this-way-in-python
CC-MAIN-2017-13
refinedweb
246
59.4
public class Solution { public int sumNumbers(TreeNode root) { if(root==null){ return 0; } int sum = 0; TreeNode curr; Stack<TreeNode> ws = new Stack<TreeNode>(); ws.push(root); while(!ws.empty()){ curr = ws.pop(); if(curr.right!=null){ curr.right.val = curr.val*10+curr.right.val; ws.push(curr.right); } if(curr.left!=null){ curr.left.val = curr.val*10+curr.left.val; ws.push(curr.left); } if(curr.left==null && curr.right==null){ // leaf node sum+=curr.val; } } return sum; } } I think this is a level order traversal solution, though the normal method is using queue to store node and here you use stack. But still a good solution, iteratively. Thanks for sharing. no,I think it is dfs, storing both children nodes aims at returning from one finished path. i also think it is DFS,not preorder( its order:root ,root.right,root.right.right...),not level order @demonxiaojian said in Non-recursive preorder traverse Java solution: I think it is not preorder, it's level order using BFS. and your code modified value of each node, which is not ideal, you may use a list to store it. @lxclinton I like the way you solved using Preorder traversal iteratively. It's different from others, that said, changing a value of each node may not be ideal sometimes. Nevertheless, it looks different !!! its good to come up with a non-recursive solution. however currently you are changing the value of the treeNode which is not ideal It is actually pre-order. Since it is using a stack, it puts three if statement: right node, left node, leaf node into the stack. But when we pop out of stack(LIFO) we reverse that order, we actually start from root, then left, then right, so it is definitely pre-order. Smart solution! Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/10705/non-recursive-preorder-traverse-java-solution
CC-MAIN-2018-05
refinedweb
318
56.86
Posted 3 August 2017, 3:22 pm ESTAs Data Dynamics is being discontinued, can you advise on how we transfer our large investment in Data Dynamics to Active Reports. Can a DD report be used directly in Active Reports 7 or do we have work to do on a report by report basis? Does Active Reports support drill through reports that we have set up in Data Dynamics? Does it use our Master reports or will these have to be rewritten? Using Data Dynamics reports in ActiveReports 7 due to Data Dynamics being discontinued Posted by: davidm06 on 3 August 2017, 3:22 pm EST Replied 3 August 2017, 3:22 pm ESTI'm only aware of a couple things that are not implemented in AR7 that existed in DDR. 1) The toolbars in the viewer controls no longer contain options to export the current report. This can be added through custom toolbar code, for example see my AR7ExportToolbar project on github: 2) The "DateOnly" Date/Time parameter option is ignored. James Replied 3 August 2017, 3:22 pm ESTThe areas we are worried about are as follows: - handling of html tags. We run reports on a database with a significant number of formatted html fields. The Active Reports website suggests a limited number of html tags are supported, significantly less than Data Dynamics. This will create all sorts of problems in the reports. - We programmatically insert images and maps into our reports and also default parameters based on database settings and are concerned these will no longer work unless the object models are the same. Given these issues, could you advise if there are plans for Active Reports to support the range of html tags that Data Dynamics does and when that might happen and equally if it is likely to support our programmatic sql insertion. If there are no such development plans for Active Reports7, we will probably have to discard our investment and move to another system. Replied 3 August 2017, 3:22 pm ESTHi, The PageReport option in ActiveReports 7 is the Data Dynamics Reports reporting engine with new features added to it. If you use the FormattedText control in a Page Report you'll get the same HTML tag support you found in Data Dynamics Reports. SectionReports offer a RichTextBox control which, as you noted, does not support the same range of tags. There are currently no plans to enhance the tag support in the RichTextBox control. Some class names have changed (Report -> PageReport, ReportRuntime -> PageDocument) as have the namespaces, but the same capability to modify a report programmically still exists for PageReports. James Replied 3 August 2017, 3:22 pm ESTHello, ActiveReports7 supports two different types of reports i.e Section Reports and Page Reports. Section Reports are based on the Active Reports model and Page Reports are based on the Data Dynamics Reports model, hence you can directly use the Data Dynamics Reports in ActiveReport7. Most of the features of Data Dynamics Reports are supported in ActiveReports7. Please refer to the following links that provide you with more details about ActiveReports7. Hope it will help you. Please let me know if you have any queries further. Thanks, Manpreet Kaur Replied 3 August 2017, 3:22 pm ESTThank you for this. When you say "Most of the features of Data Dynamics Reports are supported in ActiveReports7", could you give details of what features are not supported so we can work out the implications of moving. I cannot find this information on the links you provided. Replied 3 August 2017, 3:22 pm EST> Does this mean that actually its exactly the same code that has been ported across - or is it a re-write to support the same range of tags? The reason I ask is that data dynamics reporting has a fair few pretty critical bugs in html rendering even limited to the tags its supposed to support. Most notably pagination and page formatting issues - which can range from just overflowing other text to throwing 100s of pages. Obviously if the code is a direct port the bugs are likely to remain - if its a rewrite they may have been fixed - or more added. I have to say we are pretty disapointed with the lack of information that has been available around the retiring of this product and previously to that as seems to have been found by others the fact that bugs persist from version to version even when logged on your system. Can you give any guarantees that the same won't just repeat itself with AR7 ? Thanks Replied 3 August 2017, 3:22 pm ESTHello, I apologize for the inconvenience caused to you in the past. Could you please list down the bugs that were reported in Data Dynamics Reports. It would help me to verify the status of the bugs and if required, I would request the development team to fix the same in ActiveReports7. Thanks, Manpreet Kaur
https://www.grapecity.com/en/forums/ar-archive/using-data-dynamics-report
CC-MAIN-2018-13
refinedweb
829
58.72
On a Windows Phone application, or actually in any application, you will sometimes want to keep information around from one session to another. On a Windows Phone it is sometimes especially important as it is a little difficult to type on these small devices. If you need the user to login, fill in their name and email, or enter other information each time they use the application, then you might want to store that data on the phone and retrieve it each time they come back in to the application. Isolated storage is the place where you are can store this information for your application. This article assumes that you have VS.NET 2010 and the Windows Phone tools installed along with it. The Windows Phone tools must be downloaded separately and installed with VS.NET 2010. You may also download the free VS.NET 2010 Express for Windows Phone developer environment. Figure 1: Store Data on your Phone The LastUser Class For this example, I will be taking the data from the screen and putting it into a class called “LastUser”. This class is shown in the code below: public class LastUser : INotifyPropertyChanged { #region INotifyPropertyChanged Event public event PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } private string mFirstName = string.Empty; private string mLastName = string.Empty; private string mEmail = string.Empty; public string FirstName { get { return mFirstName; } set { mFirstName = value; RaisePropertyChanged("FirstName"); } } public string LastName { get { return mLastName; } set { mLastName = value; RaisePropertyChanged("LastName"); } } public string Email { get { return mEmail; } set { mEmail = value; RaisePropertyChanged("Email"); } }} This class implements the INotifyPropertyChanged interface as I want the user interface to automatically update when I load this data into an instance of this class. Hooking up this Class to the Page In the sample page (shown in Figure 1) you will need to bind the LastUser class to the DataContext of this page. In the page class create an instance of the LastUser class like the shown here: private LastUser _User = new LastUser(); In the Loaded event procedure for the page you will set the DataContext of the page to the _User variable as shown here: private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e){ this.DataContext = _User;} The first time in, this user class will be completely blank. All of the text boxes on the XAML page that are bound to each of the properties in the LastUser class will also be blank. Later you will add two additional lines of code to the Loaded event procedure to retrieve user data stored, but first let’s learn to store a user into isolated storage. Storing Data into Isolated Storage After the user has filled in some information on this phone page and click the Submit button you will save the data from the LastUser class into isolated storage. After you save the user data you will then redirect back to the main page. private void btnSubmit_Click(object sender, RoutedEventArgs e){ SaveUser(); NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));} The SaveUser Method The SaveUser method will take the data from the _User variable and serialize it as an XML string so it can be stored into isolated storage. The process for serializing an object into XML is the same on Windows Phone as in any other .NET application. You create an instance of the XmlSerializer class passing in the Type of LastUser. You call the Serialize method on the XmlSerializer object to convert all the properties of the LastUser object to Xml and store the result into a MemoryStream. Next, use a StreamReader class to read the MemoryStream and convert that memory stream into an XML string (stored in the “xml” variable). Finally you use the IsolatedStorageSettings.ApplicationSettings to create a new key (in this case a constant USER_KEY defined as “LastUser”) and store the data in the “xml” variable into storage. private void SaveUser(){ string xml = string.Empty; using (MemoryStream ms = new MemoryStream()) { XmlSerializer serializer = new XmlSerializer(typeof(LastUser)); serializer.Serialize(ms, _User); ms.Position = 0; using (StreamReader reader = new StreamReader(ms)) xml = reader.ReadToEnd(); } // Store user in Isolated Storage IsolatedStorageSettings.ApplicationSettings[USER_KEY] = xml;} NOTE: The USER_KEY is a constant defined in the page class as shown below: private const string USER_KEY = "LastUser"; Checking if Data Exists The next time you come into this phone page, after storing the user data, you will want to retrieve that data and fill it into the _User variable. You will now add two more lines to the Loaded event procedure to detect if the data has been stored into isolated storage with the key name of USER_KEY (“LastUser”). For this you use the ApplicationSettings.Contains method to check to see if the USER_KEY key name is in isolated storage. If the key exists, you will call the GetUser method to retrieve the data. private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e){ if (IsolatedStorageSettings.ApplicationSettings. Contains(USER_KEY)) GetUser(); this.DataContext = _User;} The GetUser Method The GetUser method is just the opposite of the SaveUser method. This method will use the IsolatedStorageSettings.ApplicationSettings to retrieve the data as a string from the key USER_KEY. You now need to take the string and convert it into a stream. I am using a MemoryStream object in the code below and calling the GetBytes method on the Unicode object to convert the string into a byte array. Once in the byte array, you create an instance of the XmlSerializer and use the Deserialize method to convert the byte array in the memory stream back into an instance of the LastUser class. private void GetUser(){ string xml; xml = IsolatedStorageSettings.ApplicationSettings[USER_KEY].ToString(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(xml))) { XmlSerializer serializer = new XmlSerializer(typeof(LastUser)); _User = (LastUser)serializer.Deserialize(ms); }} After you have deserialized the data from isolated storage and placed it into the _User variable, the data will automatically display in the bound text boxes on the page. Summary You have now seen how easy it is to store data from one invocation of your phone app to another. I added two pages within the phone application so you can see that the data does indeed stick around in between calls to the pages. You need to do this because on the emulator you can’t save the data in isolated storage because it is wiped out each time you stop and start your project in VS.NET. However, on a real Windows Phone, the storage will stay around in between each instance of running the application. NOTE: You can download the complete sample code at my website.. Choose Tips & Tricks, then "Using Isolated Storage on Windows Phone" from the drop-down. Good Luck with your Coding,Paul Sheriff ** SPECIAL OFFER FOR MY BLOG READERS **Visit for a free video on Silverlight entitled Silverlight XAML for the Complete Novice - Part 1. Developing for Windows Phone does require you to think a little differently. For example on a regular computer you only have to worry about the screen orientation being in portrait mode. However, on a phone the user can turn the phone sideways and even upside down. If the user switches from portrait orientation (Figure 1) to landscape orientation (Figure 2) you end up with more room to display your data horizontally. You can take advantage of this extra room by switching between two different XAML templates when the phone orientation changes. Figure 1: Windows Phone in Portrait Mode Figure 2: Windows Phone in Landscape Mode The Product Class For and Figure:local="clr-namespace:WPListBoxImage" Next you create an instance of the Products and PriceConverter class in XAML. The constructor for the Products class will create the initial collection of product objects. <phone:PhoneApplicationPage.Resources> <local:Products x: <local:PriceConverter x:</phone:PhoneApplicationPage.Resources> These two classes may now be used within the rest of your XAML by referencing them by their Key name. Create Portrait Template Also in the Resources section of your phone application page is where you will create two different XAML templates for displaying data in a list box. The first template you will create is for when the phone is in portrait mode. <DataTemplate x: ></DataTemplate> This <DataTemplate> with the key name “listPortrait” has a <StackPanel> control to display the text for the product name and the price stacked vertically on top of each other.. Create Landscape Template The next XAML template you create in the Resources section of the phone application page has a key name of “listLandscape”. The XAML for this <DataTemplate> is shown below. <DataTemplate x: <StackPanel Orientation="Horizontal"> <Image Margin="8" VerticalAlignment="Top" Source="{Binding Path=ImageUri}" Width="100" Height="100" /> <StackPanel> <TextBlock Margin="8" Width="400"> In this template you add a <StackPanel> control around the <StackPanel> you created in the “listPortrait” template. Set the Orientation property of this stack panel to be horizontal. Then you place an <Image> control that will display the image for the product before the product name and price. Notice also that the Width property of the product name TextBlock control has also been increased so the product name may not have to wrap as it might have to in portrait mode. The List Box Definition The List Box control used for this phone application page is fairly simple. You simply set the ItemsSource property and the ItemsTemplate property to the appropriate static resources defined in the Resources section of this page. <ListBox x: The ItemsTemplate is set to listPortrait to start out because in the Page definition the Orientation attribute is set to “Portrait”. OrientationChanged Event Now all you need to do is to hook up an event so when the user changes the orientation of the phone you can switch between the two templates you have created. There are just a couple of things you have to do to prepare the page. First you must set the attribute in the PhoneApplicationPage called SupportedOrientation to the value “PortraitOrLandscape”. This attribute will allow the OrientationChanged event to fire. SupportedOrientations="PortraitOrLandscape" So, next you add the OrientationChanged event to the Page. Type in OrientationChanged in the page XAML and have it build the event procedure for you. OrientationChanged="PhoneApplicationPage_OrientationChanged" In the OrientationChanged event procedure you will is fired the new orientation is passed in the “e” argument as the Orientation property. This property can be one of 7’s ItemTemplate property. This causes the list box to redraw itself using the defined data template. In this article you learned how to respond to the OrientationChanged event and switch between two pre-defined templates. Since the user can physically move the phone into almost any orientation it is useful for us to take advantage of the extra screen width. By creating different XAML templates and responding to just one event you can give your users a great experience when using your application. NOTE: You can download the complete sample code at my website.. Choose Tips & Tricks, then "Change Orientation/Templates on Windows Phone" from the drop-down. ** SPECIAL OFFER FOR MY BLOG READERS **Visit for a free videos on Silverlight entitled Silverlight XAML for the Complete Novice - Part 1.
http://weblogs.asp.net/psheriff/archive/2010/11.aspx
CC-MAIN-2014-15
refinedweb
1,850
52.6
import time import logging import multiprocessingdef sleep_5_seconds(): logging.info(' Will sleep 5 seconds') time.sleep(5) logging.info(' Done sleeping 5 seconds')def sleep_10_seconds(): logging.info(' Will sleep 10 seconds') time.sleep(10) logging.info(' Done sleeping 10 seconds')def main(): logging.basicConfig(level = logging.INFO) PROCESS1 = multiprocessing.Process(target = sleep_5_seconds) PROCESS2 = multiprocessing.Process(target = sleep_10_seconds) PROCESS1.start() PROCESS2.start()main()OUTPUT: INFO:root: Will sleep 5 seconds INFO:root: Will sleep 10 seconds After 5 seconds INFO:root: Done sleeping 5 seconds After another 5 seconds INFO:root: Done sleeping 10 seconds Sometimes, we might be in a situation where we have to send emails to multiple people in a personalised manner (like mailing each student their grades, mailing bank statements to customers, etc.). Although these emails follow the same format, the information inside it varies from receiver to receiver. When done… Almost every interview for coding and software development roles is incomplete without a programming interview. There are thousands of questions in coding sites like LeetCode and it is impossible to cover all the topics within a short period. In this series, I will provide solutions to frequently asked interview questions… “When was the last time you tried a coding challenge?” “I tried it just yesterday and it’s way out of my league. I’m just a beginner.” said the apprentice. “About a year ago, when I began learning about stacks, trees and heaps. Now, I’m all caught building websites.” … Netflix began its journey to becoming the world’s biggest streaming service in 1997. Initially, Netflix offered DVD sales and rental by mail. In 2007, Netflix began its streaming media services as the world’s first online DVD rental store with 925 titles. … I’m a Computer Science Undergrad on a quest to innovate and build stuff with code. Find all my posts at
https://madhumithakannan7.medium.com/
CC-MAIN-2021-43
refinedweb
308
50.84
#include <lvt/Camera.h> Inheritance diagram for Perspective. [inline] Returns the camera's aspect ratio. In general, the aspect ratio of a camera should match the aspect ratio of the viewport. Wnd::AdjustCamera can be used to ensure that the two are consistent. Returns the camera's field of view. "Draws" the camera Sets the view on the scene, and initializes the OpenGL projection matrix. Sets the camera's aspect ratio. The aspect ratio that determines the field of view in the x direction. Sets the camera's field of view. The field of view is the angle, in degrees, in the y-direction that determines the vertical size of the view plane. See the man page for gluPerspective, or chapter 3 of the OpenGL Programming Guide for more information.
http://liblvt.sourceforge.net/doc/ref/class_l_v_t_1_1_perspective_camera.html
CC-MAIN-2017-17
refinedweb
130
68.67
On Sun, 2008-01-20 at 18:18 +0000, Lauri Pesonen wrote: > Hi, > > I'm relatively new to Haskell so please bear with me. I'm trying to > parse Java class files with Data.Binary and I'm having a few problems: > > (The class file format is described here: > > and the bytecode instructions are described here: > > ) > > 1. The class file format contains a number of tables. The table > definitions start with the length of the list and carry on with that > many table entries. Lists would be a good representation for them in > Haskell, because there is not need to index them directly (except > with the constants table). I've created my own list type so that I can > redefine the serialisation functions for it so that the serialisation > matches the format defined in the class file format: > > newtype MyList e = MkList ([e]) > deriving Show > > instance (Binary e) => Binary (MyList e) where > put (MkList es) = do > put (fromIntegral (length es) :: Word16) > mapM_ put es > > get = do > n <- get :: Get Word16 > xs <- replicateM (fromIntegral n) get > return (MkList xs) > > The problem is that one of the tables, namely the attribute_info > structures, use a u32 length field whereas all the other tables use a > u16 length field. My implementation uses u16, but it would be nice to > be able to use the same data type for both types of tables. I think I > can do it by adding a lenght field to MyList and specifying the type > when I use MyList in some other data structure, but that would also > mean that I have to keep track of the length of the list manually?." Nevertheless, one way to solve your problem is with a phantom type. Change MyList to, newtype MyList t e = MkList [e] deriving Show getLengthType :: MyList t e -> t getLengthType = undefined instance (Binary e) => Binary (MyList t e) where put l@(MkList es) = do put (fromIntegral (length es) `asTypeOf` getLengthType l) mapM_ put es get = do n <- get xs <- replicateM (fromIntegral (n `asTypeOf` getLengthType t)) get return (MkList xs `asTypeOf` t) where t =. > 2. This is the bigger problem. The Java class file contains a > constants table in the beginning of the file. The other fields later > on in the class file contain indexes that reference entries in that > constants table. So in order to be able to replace an index in a data > structure with the actual string, I need to be able to look up the > string from the constants table while I'm deserialising the field. > > My guess is that I should be able to put the constants table into a > state monad. On the other hand Data.Binary already uses the state > monad for holding onto the binary data being deserialised. So it's not > clear to me if I can use StateT with Data.Binary.Get? And if not, can > I implement my own state monad and do it that way? I'm not very > comfortable with Monads yet, so I might be missing something very > obvious..
http://www.haskell.org/pipermail/haskell-cafe/2008-January/038383.html
CC-MAIN-2014-15
refinedweb
503
64.85
Written by Shay ShmeltzerOracle Corporation May 2005 Since this article was created a new Subversion extension has started shipping from Oracle - for integration with Subversion please refer to the Subversion Developer Guide. This document can however be used for integration of other version management tools and as an intro to the external toole option in JDeveloper. Oracle JDeveloper 10.1.3 developer preview comes with built in support for CVS and Clearcase as source control management tools, offering exceptional support for working with these code repositories. But what can you do if you need to use another version control tool? One option is to use the JDeveloper Extension SDK to build an extension that will integrate JDeveloper with your tools. But building such an extension, although not a complex task, will require you to learn the JDeveloper development API. In this how-to I'll describe a quick and dirty way to build basic integration of third party tools that offer a command line interface into JDeveloper. All this without writing a single line of Java code. Sounds too good to be true? - Let me introduce you to the "External Tools" menu option. The "External Tools" menu option (located in the tools menu option) provides a dialog that lets you add calls to the command line of external tools. It also allows you to provide parameters from the JDeveloper environment to the command line. You can then add menu and context menu options to activate your extension. In this how-to I'll show you how to integrate with Subversion, but the concepts explained here can be applied to any other tool. Subversion is an open-source version control product that you can get at. For more information about Subversion and services from its primary sponsor, go to. After installing subversion on your machine, the first operation you'll probably want to do is create a subversion repository (unless you are going to connect to an existing repository). To do this issue the following command from the command line prompt: Svnadmin create c:\svnrep (c:\svnrep is the directory where you want the repository to be located). Now that you have a repository, the next logical step is to import a project into this repository. Let's add the ability to do project imports directly from the JDeveloper development environment. Activate the External Tools option and click the "New" button to create a new command. In the dialog that comes up choose "External Program" in step 1. In Step 2 fill out the following details: For program executable - svn. For Arguments - write import and then press the insert button and from the list select "Project Directory" then you need to add a pointer to your repository in our example this will be: . The last argument should be a message that you provide when importing the module, so add -m and then click the insert button and choose Prompt (place the prompt between double quotes to handle spaces). The complete arguments parameter should look like: import ${project.dir} -m "${prompt}" For the run directory click the insert button and add the project directory. The next step lets you add a caption for the menu option "SVN Import Project" is a good fit here. You can also specify a tooltip and an icon for your command. In the next step you specify where you want the menu option to appear, I specified here that the option should appear in the navigator context menu. And in the next step we can specify when this option needs to be on - I chose "Always". To test your new command, create a simple project in JDeveloper - stand on the project node - right click and choose the new "svn Import" option you have just added. You can see the svn command that was issued and the results in the log window, and your code should now be checked-in inside the Subversion repository. We'll skip adding a check-out project option to JDeveloper, instead just do it manually from a command line. The command to issue from the command line is: Svn checkout Project1.jpr To use the code you just checked out in JDeveloper, create a new workspace without a project. Then, choose file->open and locate the jpr file for the project you just checked out. The next three commands that we want to add to JDeveloper will enable us to Add, Update and Commit files from the repository. For the Add option the command attributes should be: add ${file.path} Add the menu to the Navigator context menu, and in the integration select "When a file is selected or open in the code editor" Similarly add the Update command - which gets the latest copy of the code from the repository to your code directory: The arguments for this command are: update ${file.path} For the commit command - that checks in a file after you changed it -the arguments are: commit -m "${prompt}" ${file.path} Again add the menu to the Navigator context menu, and in the integration select "When a file is selected or open in the code editor". In a similar way you can also add the Diff command of Subversion, which allows you to compare to a specific version of the code. Here are the attributes in the JDeveloper command: diff --revision "${prompt}" ${file.path} Another useful command of Subversion is the Status command, which let you check the status of the file in the repository compared to your local copy without actually updating the local copy. Here are the attributes in the JDeveloper command: status --verbose ${file.path} Now you are ready to develop and use Subversion. Have a look at this on-line demo to see a basic working scenario. This paper showed you the power of the "External Tool" menu option in JDeveloper as a simple and fast way to add integration between JDeveloper and other tools. For more powerful integration, check out the JDeveloper Extension SDK and the code samples that come with it.
http://www.oracle.com/technology/products/jdev/101/howtos/extools/subversion.html
crawl-002
refinedweb
1,007
60.35
rel_ops allow the automatic generation of operators !=, >, <=, >= from just operators == and <. These are intentionally in the rel_ops namespace so that they don't conflict with other similar operators. To use these operators, add "using namespace std::rel_ops;" to an appropriate place in your code, usually right in the function that you need them to work. In fact, you will very likely have collision problems if you put such using statements anywhere other than in the .cpp file like so and may also have collisions when you do, as the using statement will affect all code in the module. You need to be careful about use of rel_ops.
http://trilinos.sandia.gov/packages/docs/r10.10/packages/stk/doc/html/namespaceeastl_1_1rel__ops.html
CC-MAIN-2013-48
refinedweb
107
64.71
This section describes how to add a replica server to an existing system using the nismkdir command. An easier way to do this is with the nisserver script as described in Solaris Naming Setup and Configuration Guide. Keep in mind the following principles: Root domain servers reside in (are part of) the root domain. Subdomain servers reside in (are part of) the parent domain immediately above the subdomain in the hierarchy. For example, if a namespace has one root domain named prime and a subdomain named sub1: The master and replica servers that serve the prime domain are themselves part of the prime domain because prime is the root domain. The master and replica servers that serve the sub1 subdomain are also part of the prime domain because prime is the parent of sub1. While it is possible for a master or replica server to serve more than one domain, doing so is not recommended. To assign a new replica server to an existing directory, use nismkdir on the master server with the -s option and the name of the existing directory, org_dir, and groups_dir: The nismkdir command realizes that the directory already exists, so it does not recreate it. It only assigns it the additional replica. Here is an example with rep1 being the name of the new replica machine: Always run nismkdir on the master server. Never run nismkdir on the replica machine. Running nismkdir on a replica creates communications problems between the master and the replica. After running the three iterations of nismkdir as shown above, you need to run nisping from the master server on the three directories: You should see results similar to these: It is good practice to include nisping commands for each of these three directories in the master server's cron file so that each directory is "pinged" at least once every 24 hours after being updated.
http://docs.oracle.com/cd/E19455-01/806-1387/a10dirs-67417/index.html
CC-MAIN-2014-23
refinedweb
315
55.37
Type: Posts; User: D_Drmmr Are you benchmarking unoptimized code? That's not very useful. This might be a (premature) optimization trick to prevent branching due to the short-circuiting behavior of &&. Look how much easier to read your code becomes with a few local variables. You should really stop copy-pasting source code; it's a very bad habit. template<class T> ObjectBase*... Yes, you could do that. but it sounds to me like a list box is better suited for your user interface. This would also allow the user to select an item by typing multiple characters, which is much... I'm sure you can come up with a test case that fails the second algorithm. As to why the first one may be too slow: a std::set keeps all its elements sorted. Dijkstra's algorithm only needs to... That's basically the algorithm for finding a topological order. ;) That's because there is no specialization for 'implements_load' and 'implements_store'. Don't know if you removed this to get a minimal example or if they are missing in your actual code (maybe the... Compiles fine in VC9. What is the complete error message you get? Could you please remove this BULLSHIT? Ever heard of sampling bias? When we are allocating POD types, probably. But the overhead is constant, i.e. independent of sizeX and sizeY. However, for non-POD types I think my solution will use less memory for non-tiny... Assuming you use the code I posted above, you can access the data like this int x = 1, y = 2; // second row, third column values[x][y] = 1.23; [code] const int nRows = int(values.size());... That's not the same. decltype(pvalue) will be double*[4], not double**. I assume you meant "new double[sizeY]" inside the loop. This is also considered bad style. You perform sizeX + 1... AFAIK, this is invalid in C++11 just as it is in C++03. The call to new returns a double*[4], which is not convertible to a double**. Could you please fix the compiler errors, such that people can just copy-paste the code if they want to run it? What about the serialization "does not work"? Please use code tags! Your code is practically unreadable without them. Did you step through your code with the debugger? What values are you getting for x and y? That's horrible. Why would you advice someone to use a macro for this? A simple text-replace can solve this without obfuscating the code. @OP Using two different names for the same variable will... What do you mean with "doesn't work"? That doesn't look like the rotation axis. When rotating about an axis, all point on the axis remain in the same location. Is there an RSS feed to get notifications? What kind of platform do you want to run on? You could always call the algorithm with a pair of boost::zip_iterators. You'll need to write a custom (or generic reusable) comparator though, which is not so nice without having support for generic... In C++ I would recommend using this instead: template<typename T, size_t N> size_t arraySize(T(&)[N]) { return N; } It's much harder to use incorrectly. Yes, it's a possible way to tackle the problem. You can model the problem as a longest path problem by representing each (unique) input string as a node in the graph and adding edges between any pair... That doesn't seem like an exact definition of the solution. You'll need to define formally what you mean with "longest possible runs". Is a solution with three runs of length 8, 5, 3 better or worse... There is always std::make_pair(...) to prevent some repetition. I think in this case overload resolution would pick the non-template overload, so it would pick the (key_type, mapped_type)... #include <string.h> I guess you wanted the <string> header. char filename[256]; string n; string filelist; void CreateNew(ofstream & FileNew); void ReadNew(ifstream & FileGet);
http://forums.codeguru.com/search.php?s=f70ae27c0af86c1627643fad02d4aac3&searchid=4872173
CC-MAIN-2014-35
refinedweb
673
69.18
Objects - create instances of types. Note Static types behave differently than what is described here. For more information, see Static Classes and Static Class Members. Struct Instances vs. Class Instances Because classes are reference types, a variable of a class object holds a reference to the address of the object on the managed heap. If a second variable of the same type is assigned to the first variable, then both variables refer to the object at that address. This point is discussed in more detail later in this article. Instances of classes are created by using the new operator. In the following example, Person is the type and person1 and person2 are instances, or objects, of that type. using System; isn't required, as shown in the following example: using System; namespace's declared. This is one reason why structs are copied on assignment. By contrast, the memory that is allocated for a class instance is automatically reclaimed (garbage collected) by the common language runtime when all references to the object have gone out of scope. It isn't possible to deterministically destroy a class object like you can in C++. For more information about garbage collection in .NET, see Garbage Collection. Note The allocation and deallocation of memory on the managed heap is highly optimized in the common language runtime. In most cases there is no significant difference in the performance cost of allocating a class instance on the heap versus allocating a struct instance on the stack. Object Identity vs. Value Equality When you compare two objects for equality, you must first distinguish whether you want to know whether the two variables represent the same object in memory, or whether the values of one or more of their fields are equivalent. If you're intending to compare values, you must consider whether the objects are instances of value types (structs) or reference types (classes, delegates, arrays). To determine whether two class instances refer to the same location in memory (which means that they have the same identity), use the static Object: // Person is defined in the previous example. //public struct Person //{ // public string Name; // public int Age; // public Person(string name, int age) // { // Name = name; // Age = age; // } //} Person p1 = new Person("Wallace", 75); Person p2 = new Person("", 42); p2.Name = "Wallace"; p2.Age = 75; if (p2.Equals(p1)) Console.WriteLine("p2 and p1 have the same values."); // Output: p2 and p1 have the same values. The System.ValueType implementation of Equalsuses boxing and reflection in some cases. For information about how to provide an efficient equality algorithm that is specific to your type, see How to define value equality for a type. Records are reference types that use value semantics for equality. and Object.Equals(Object). Related Sections For more information:
https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/object-oriented/objects
CC-MAIN-2021-39
refinedweb
463
56.35
Best comment ever made on any board EVAR. Best comment ever made on any board EVAR. That game was such BS. yeah... hopefully you won't be undefeated anymore ;) Finally things are starting to turn around for me. I don't need a TE. I need more in the RB position, so why would I give one up, even a backup? At least I'll probably win in one league this week :( And only because "Cheat Commandos" really blew goats this week. This league is gonna blow for me. Not that it's any different from my other ones. I got shafted this year. And hey SM! There is no "buckeye" in the portion of the state that I live in. As far... I have no problem with that. I'm not going to be able to make the draft either. SUCK. Hell, the system will probably draft me a better team anyways. Oh, and PJ, I don't live in Pittsburgh...... I'd sleep with one eye open if I were you. ........... ugh... I hate censorship. Talk trash!.... or something. Hell, i don't know. Or argue about the rules... something. Anything. Wow... this league is kind of dead... I'm starting to wonder if I should have even signed up. By the way, I might not be able to make that draft time. Tuesdays and Thursdays are bad for me :( Alright, I finally signed up. We need to mirror this thread on ES. ;) Count me in! I'm good with Yahoo. I've never used anything else, so I guess I'm biased. I'm up for something else if someone has a positive experience with another provider. Hold the phone... you want to create a database? Or you want to connect to and USE a database on the web? There's a difference. I'd suggest using MySQL because it's going to be hard to find a... Nope, Win32 project, not console. Alright... now I get this error when I try to link it. It compiles fine: I feel like an idiot that I can't even get this working. I'm so babied by VB. Ok, now I'm getting an error that it can't open "stdafx.h" :( OK, I copied the Shellexecute() version and I get this error: # include <windows.h> //You need shell32.lib for this one int main(void) { char szPath[] =... Ok, so I need to write a very simple app and I thought I'd give it a go in C++. One of our old applications is being phased out and I'd like to write a small app that does nothing but open IE and... Welcome. You should find plenty of help here. Well, since it's not me, I don't want them screwing with the registry. And either I can't find the "Outlook Security Template" or it doesn't exist. No dice. I've tried all variations of the URL. It's back up, you whiny bunch of...... ;) Yeah... I'm content. :) :: BLAST IT!! :: You weren't supposed to remember that! Besides... that only took a combined 16 hours... I still have 8 to work with, and by my calculations, of that 8, I have 3 remaining.
https://cboard.cprogramming.com/search.php?s=1dc9d54440565ab5f1943f99077e568c&searchid=2220742
CC-MAIN-2019-51
refinedweb
541
86.91
----------By Polymath Table of Contents: ----------Part 1: Introduction ----------Part 2: Opening, Coding, Testing, and Final Work ----------Part 3: Line-By-Line Breakdown of the C++ Code Supplied Introduction This Tutorial assumes that you have little-to-no knowledge of the C++ Programming Language and are using Microsoft Visual Studio as you first compiler to create a CONSOLE application. The "Help" documentation provided with the piece of software was not helpful to a non-C++ savvy programmer (me at the time), so I had to start from scratch. I couldn't find a sufficiently easy step by step tutorial for creating basic first-time applications, so I wanted to help any similarly-situated people by writing a concise, easy-to-follow, step-by-step w/screenshots tutorial. Plain and Simple. Due to the uselessness and waste of memory of such programs as "helloworld.exe", in this tutorial we are going to create an EXTREMELY SIMPLE calculator that can add two numbers together. An added advantage of using this program for the tutorial is that it allows me to demonstrate more aspects of C++. Since this tutorial does not cover object-oriented-programming or other C++ -only functions, this could technically be considered a C tutorial, but it works for C++. All that aside, let's begin. Opening, Coding, Testing, and Final Work Step 1. First, if you haven't already, download Microsoft Visual C++ Studio 2008 Express Edition for free at The Microsoft Visual Studio Downloads Page. This download may take a while to install. Step 2. Register and Launch Microsoft Visual C++ Studio 2008 (from here-on-out I will refer to this as Visual C++). The registration process is quick and easy. Step 3. In Visual C++, select "File Menu-->New-->Project" (as shown). Step 4. In the dialog box that pops up, click on "Win32" in the side pane and select "Win32 Console Application." Make sure that the "Create Directory for Solution" box is NOT checked and leave the default path the same (as shown---You can leave the Create Directory for Solution box checked and change the default path, but for purposes of this tutorial, leave it at the settings shown) Step 5. The Win32 Application Wizard will pop up (as shown). Click "Next." Step 6. Make sure that the following are checked (as shown): ----------1. Under "Application type": Console Application ----------2. Under "Additional Options": Empty Project ----------Then: Press "OK" Step 7. Go to the "Solution Explorer" on the left side and right-click on "AddCalc" but be sure not to right click on "Solution AddCalc (1 project)." Once you have right clicked on AddCalc select "Add-->New Item" Step 8. In the Dialog Box that appears, on the left pane select "Visual C++" and on the top section choose "C++ file (.cpp)" and change the name to AddCalc (as shown). Press "OK". Step 9. A blank screen will appear showing the contents of "AddCalc.cpp" (as shown in SS1). Copy and Paste the following code into this blank white area (for a line-by-line breakdown of the code, go to part 3): // initializing C++ #include <iostream> using namespace std; // declaring function prototypes float addition (float a, float b); //main function int main () { float x; // float y; //declares variables float n; // int b; b = 1; //sets value of b to 1 cout << "Simple Addition Calc- First Program"; //displays info about program while (b==1) //creates loop so the program runs as long as the person wants to add numbers { //following code prompts the user for 2 numbers to add and calls function addition to display results cout << "\n" << "Type a number to add (can also use negetive, decimals, etc.): "; cin >> x; cout << " Second number: "; cin >> y; n = addition (x,y); cout << "Ans: " << x << " + " << y << " = " << n << "\n"; //following code sets b to the value the user imputs to determine if the loop is broken to end the program cout << "Solve another operation? (1=yes, 2=no): "; cin >> b; cout << "\n"; if (b==2) cout << "Terminating application."; } //ends the main function of the code return 0; } //following function adds the numbers float addition (float a, float b) { float c; c = a+b; return (c); } //END C++ CODE Step 9. (con.) The blank area with the code in it is shown in SS2 along with the SAVE ALL button highlighted (you may wish to save your work here). SS1: SS2: Step 10. Go to the Build Menu and select "Build Solution" (as shown). Step 11. Your Output Screen (near the bottom of the page) should show the following (the most important being: *Build: 1 succeeded, 0 failed, 0 skipped, 0 up-to-date*): Step 12. PRESS F5 on you keyboard, and a small box should pop up that is running your program that will add 2 numbers together (as shown). This is command to debug your application, which for our purposes is synonymous to testing. Step 13. The Debug window should work. Assuming it does, to save your program to AddCalc.exe, first go to the drop down menu near the top of the screen which says "Debug" and change it to "Release" (as shown). Step 14. Go to the Build menu and select "Rebuild" (as shown). This should give output that is SIMILAR, not the SAME as the output from Step 11. Step 15. Go to Windows Explorer and go to: "C:\Documents and Settings\your_username_here\My Documents\Visual Studio 2008\Projects\AddCalc\Release" (as shown below) Double click on AddCalc.exe, and if it runs, you can delete the other files in this directory. Line-by-Line breakdown of the AddCalc.exe code Some notes: There are some basic things about C++ that you should know beforehand. First, in C++ all spacings are equivilant (space, tab, enter), and you can have any number of the spacings, so an enter and a space both together means the same thing as a single enter or a single space. Second, a line that has // in it has a comment in it. The comment is whatever is in that line of code after the // untill there is an enter character (this is the only case in which an enter character is not the same as a tab or a space). I will ignore all comments in this code. Finally, all lines of code should end with a semicolon. And without further ado, let's begin. I ignored comments because the comment will be the explination aligned to the right of the line it is in. LINE-BY-LINE #include <iostream> // this tells c++ that we want to use the normal imput and output library NO ; REQUIRED using namespace std; // this tells c++ that we are using the standard section of this library and the C++ language float addition (float a, float b); //this says that after the main function we will have a seperate function "addition" int main () //says that the next block of code is the main code to be executed. { //the curly brace starts the main function's block of code float x; //declares a variable that can use numbers with decimels and negetives float y; //declares variables that is the same as above float n; //declares a variable, same type as x int b; //declares a variable that can only use whole numbers b = 1; //sets value of b to 1 cout << "Simple Addition Calc- First Program"; //displays info about program while (b==1) //creates loop so the program runs as long as the person wants to add numbers (when b=1) { //curly brace starts the loop block of code cout << "\n" << "Type a number to add (can also use negetive, decimals, etc.): "; // prints a newline "/n" and outputs for the user to specify a number cin >> x; // provides imput for x after the string in the previous line. cout << " Second number: "; // outputs "Second number: " cin >> y; // provides imput for y after previous string n = addition (x,y); // sets n to the value returned by addition for x and y cout << "Ans: " << x << " + " << y << " = " << n << "\n"; // Displays answer //following code sets b to the value the user imputs, and b is the variable for the loop above cout << "Solve another operation? (1=yes, 2=no): "; //output cin >> b; //imput cout << "\n"; //Outputs new line if (b==2) //if the user imput is 2 cout << "Terminating application."; //output } //curly brace sends ends the loop and then it is reassesed whether or not b fits the loop to go again. return 0; //ends the main function of the code } //curly brace ends main function float addition (float a, float b) //creates a function returning a decimal value //this function requires two variables in its call of type float. { //starts function float c; //creates a variable called c c = a+b; //stores the value a+b as c return ( c ); //c is the value given to the function call for addition } //ends function And thats it! the basics of c++ are very simple. For those of you who prefer a list of commands and definitions: #include <library> --------------- says you are using commands from a library of c++ commands using namespace [namespace] ------------- says you are using a subset of commands called namespace cin >> variable ----------- stores user imput to variable cout << variable/"string" << variable/"string" << ... ---------------------- outputs varType function ([paramaters]) -----------------defines a function later in the program, or with {} creates function commands varType = value --------------------defines variable while (variable==value) {}-------creates a loop that repeats as long as the variable is the same as the value if (variable==value) [if more than one command: {}] ----------------------- runs a conditional statement functionName ([paramaters]) --------------"calls" a function, the value of the call= the "return" of the function return (variable)/value ------------------says what value the function should send back to its "caller" This is only the very basics, I would suggest you go to the cplusplus.com C++ Language Tutorial for a more complete reference of the language that includes commands not used in the AddCalc.exe program and a better syntax reference. Otherwise, this should be simple egnough for learning how to use a new interface (the basis of this tutorial).
http://www.dreamincode.net/forums/topic/49569-getting-started-in-microsoft-visual-studio-2008/page__p__649798
CC-MAIN-2016-18
refinedweb
1,682
63.93
Akka anti-patterns: shared mutable state © Shutterstock / Who is Danny When I work with clients on designing actor systems there are a few anti-patterns that seem to make it into initial, non-reviewed designs no matter what. In this series of short articles I would like to cover a few of those. Anti-pattern #1: sharing mutable state across actors Even though the Akka documentation points this out in various places, one of the favorite anti-patterns I’ve seen is use is sharing mutable state across actor boundaries. What do I mean with this? Well, let’s have a look at the following actor: public class BadActor extends AbstractLoggingActor { private Map<String, String> stateCache = new HashMap<String, String>(); public BadActor() { receive( ReceiveBuilder.match(GetState.class, request -> { sender().tell(new State(stateCache), self()); }).build() ); } public static final class GetState { public static final GetState Instance = new GetState(); private GetState() { } } public static final class State { private final Map<String, String> state; public State(Map<String, String> state) { this.state = state; } public Map<String, String> getState() { return state; } @Override public boolean equals(Object o) { ... } @Override public int hashCode() { ... } } }_2<< Internally what makes Akka Actors “tick” is a nifty little thing called a dispatcher. Every actor has a dispatcher, by default the same dispatcher is shared across the actor system but you can use specific and separate dispatchers for individual actors if you would like. The dispatchers job, roughly speaking, is to distribute the work (the messages) of one or more actors across_3<< across across, there are more anti-patterns to come! This post was originally published on Manuel Bernhardt’s blog. 2 Comments on "Akka anti-patterns: shared mutable state" Out of curiosity, by referential transparency, aren’t you actually referring to location transparency? These are two VERY different things… Yes indeed, thanks for spotting. This is fixed now
https://jaxenter.com/akka-anti-patterns-shared-mutable-state-128827.html
CC-MAIN-2019-26
refinedweb
307
54.63
The Problem A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. Given an m x nmatrix matof integers, sort each matrix diagonal in ascending order and return the resulting matrix. Example 1: Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 100 1 <= mat[i][j] <= 100 Tests import pytest from .Day23_SortMatrixDiagonally import Solution s = Solution() @pytest.mark.parametrize( "mat,expected", [ ( [[3, 3, 1, 1], [2, 2, 1, 2], [1, 1, 1, 2]], [[1, 1, 1, 1], [1, 2, 2, 2], [1, 2, 3, 3]], ), ], ) def test_diagonal_sort(mat, expected): assert s.diagonalSort(mat) == expected Solution from typing import List class Solution: def sort(self, mat, x, y): current_diag = [] while x < len(mat) and y < len(mat[0]): current_diag.append(mat[x][y]) x += 1 y += 1 current_diag.sort() while x > 0 and y > 0: x -= 1 y -= 1 mat[x][y] = current_diag.pop() def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: # For each diagonal in the matrix starting at the bottom left for i in range(len(mat)): self.sort(mat, i, 0) # For each diagonal in the matrix starting at the top right for i in range(len(mat[0])): self.sort(mat, 0, i) return mat Analysis This solution was accepted but the analysis view on leetcode appears to be broken currently. Commentary The simplest way I could imagine to solve this was to add each diagonal to a list, sort that list and then put the sorted list back in place of the diagonal. Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/ruarfff/day-23-sort-the-matrix-diagonally-3om6
CC-MAIN-2021-25
refinedweb
334
53.51
Hebrews Thompson_Hebrews_JDE_djm.indd 1 10/10/08 10:23:49 AM C om m e n t a r i e s o n the N e w T e s t a m e n t General Editors Mikeal C. Parsons and Charles H. Talbert A d v i s o ry B o a r d Paul J. Achtemeier Loveday Alexander C. Clifton Black Susan R. Garrett Francis J. Moloney Thompson_Hebrews_JDE_djm.indd 2 10/10/08 10:23:52 AM Hebrews James W. Thompson K Thompson_Hebrews_JDE_djm.indd 3 10/10/08 10:23:52 AM © 2008 by James W. Thompson Thompson, James, 1942– Hebrews / James W. Thompson. p. cm. — (Paideia : commentaries on the New Testament) Includes bibliographical references and indexes. ISBN 978-0-8010-3191-5 (pbk.) 1. Bible. N. T. Hebrews—Commentaries. I. Title. BS2775.53.T77 2008 227 .8707—dc22 2008024697 Scripture quotations labeled NRSV are from the New Revised Standard Version of the Bible, copyright © 1989, by the Division of Christian Education of the National Council of the Churches of Christ in the United States of America. Used by permission. All rights reserved. 5 2 19 3 15 Thompson_Hebrews_JDE_djm.indd 4 10/10/08 10:23:52 AM For Everett Ferguson and Abraham Malherbe, teachers, mentors, and friends, who introduced me to the cultural and philosophical world of the New Testament, encouraged me to pursue graduate studies, and have continued the conversation throughout my academic career Thompson_Hebrews_JDE_djm.indd 5 10/10/08 10:23:52 AM Thompson_Hebrews_JDE_djm.indd 6 10/10/08 10:23:52 AM Contents List of Figures€€€€ix Foreword€€€€xi Preface€€€€xiii Abbreviations€€€€xiv Introduction€€€€3 Part 1 Hebrews 1:1–4:13 Hearing God’s Word with Faithful Endurance€€€€29 Hebrews 1:1–4 Encountering God’s Ultimate Word€€€€31 Hebrews 1:5–2:4 Paying Attention to God’s Word€€€€44 Hebrews 2:5–18 The Community’s Present Suffering€€€€60 Hebrews 3:1–4:13 Hearing God’s Voice Today€€€€78 Part 2 Hebrews 4:14–10:31 Discovering Certainty and Confidence in the Word for the Mature€€€€101 Hebrews 4:14–5:10 Drawing Near and Holding Firmly€€€€103 Hebrews 5:11–6:20 Preparing to Hear the Word That Is Hard to Explain€€€€119 Hebrews 7 The Priesthood of Melchizedek as the Anchor of the Soul€€€€143 Hebrews 8 The Sacrificial Work of Christ as the Assurance of God’s Promises€€€€166 Hebrews 9:1–10:18 The Ultimate Sacrifice in the Heavenly Sanctuary€€€€178 Hebrews 10:19–31 Drawing Near and Holding Firmly in an Unwavering Faith€€€€200 vii Thompson_Hebrews_JDE_djm.indd 7 10/10/08 10:23:52 AM Contents Part 3 Hebrews 10:32–13:25 On Not Refusing the One Who Is Speaking€€€€213 Hebrews 10:32–39 Remembering the Faithfulness of Earlier Days€€€€215 Hebrews 11:1–12:3 Remembering the Faithful Heroes of the Past€€€€226 Hebrews 12:4–13 Enduring Faithfully in the Midst of Suffering€€€€251 Hebrews 12:14–29 Listening to the One Who Is Speaking from Heaven€€€€258 Hebrews 13 Bearing with the Word of Exhortation€€€272 Bibliography€€€€289 Subject Index€€€€301 Index of Modern Authors€€€€305 Index of Scripture and Ancient Sources€€€€307 viii Thompson_Hebrews_JDE_djm.indd 8 10/10/08 10:23:52 AM List of Figures 1. The Opening of Hebrews in an Ancient Manuscript€€€€31 2. A Testimonia Collection at Qumran€€€€46 3. Reincarnating Hercules€€€€63 4. Moses with the Tablets of the Law€€€€80 5. A Hasmonean High Priest€€€€109 6. Hope: Anchor of the Soul€€€€140 7. Melchizedek through the Ages€€€€145 8. Emperor Constantine€€€€224 9. Abraham’s Journey€€€€235 ix Thompson_Hebrews_JDE_djm.indd 9 10/10/08 10:23:53 AM Thompson_Hebrews_JDE_djm.indd 10 10/10/08 10:23:53. xi Thompson_Hebrews_JDE_djm.indd 11 10/10/08 10:23:53 AM Foreword. Thompson_Hebrews_JDE_djm.indd 12 10/10/08 10:23:53 AM Preface As interpreters have acknowledged for the past two generations, the dominant image for Christian experience in the Epistle to the Hebrews is that of the journey of the people of God. This commentary is a stage in my own journey with this mysterious book. Because I was intrigued by the artistry and complex argument of Hebrews during my graduate studies, I began the journey with my dissertation, “‘That Which Abides’: Some Metaphysical Assumptions in the Epistle to the Hebrews,” in 1974. That work became the basis for the monograph, The Beginnings of Christian Philosophy (1982). Since that time, I have continued my work with Hebrews in lectures, classes, and journal articles. As with the people of faith in Hebrews 11, I have not yet reached the destination in my attempt to grasp the many nuances of this work. I am grateful to the editors of the Paideia series, Charles Talbert and Mikeal Parsons, for the invitation to continue my journey with Hebrews in this volume. I am also grateful to James Ernest and the editors at Baker Academic for the careful reading and editorial suggestions. Others have contributed to this work. My wife, Carolyn Roberts Thompson, read drafts of the commentary and made suggestions for stylistic improvement. My graduate assistant, Michael Coghlin, also read earlier drafts and did valuable research. My colleague, Mark Hamilton, offered helpful insights into Old Testament and rabbinic texts. The careful reading of the commentary by students in a Greek seminar on Hebrews in the spring semester of 2008 frequently raised important questions about the translation and interpretation of specific passages. Any errors that remain are, of course, my own. James W. Thompson March 1, 2008 xiii Thompson_Hebrews_JDE_djm.indd 13 10/10/08 10:23:53 AM Abbreviations General b. Babylonian Talmud lit. literally ca. circa NT New Testament d. died OT Old Testament dub. dubious par. parallel; and parallels ed. edition rev. revised ET English translation sp. spurious Bible Texts and Versions ASV American Standard Version NIV New International Version KJV King James Version NRSV LXX Septuagint New Revised Standard Version LXXB Septuagint (Vaticanus) RSV Revised Standard Version MT Masoretic Text Ancient Corpora Old Testament Gen Genesis 1–2 Chron 1–2 Chronicles Hab Habakkuk Dan Daniel Hag Haggai Deut Deuteronomy Hos Hosea Esth Esther Isa Isaiah Exod Exodus Jer Jeremiah Ezek Ezekiel Josh Joshua xiv Thompson_Hebrews_JDE_djm.indd 14 10/10/08 10:23:53 AM Abbreviations Judg Judges 1QS Rule of the Community 1–2 Kgs 1–2 Kings 1QpHab Lev Leviticus Commentary on Habakkuk from Qumran Cave 1 Mal Malachi 11QMelch Mic Micah Melchizedek from Qumran Cave 11 Neh Nehemiah Num Numbers Prov Proverbs Ps/Pss Psalm/Psalms 1–2 Sam 1–2 Samuel Zech Zechariah Zeph Zephaniah Deuterocanonical (Apocryphal) Books Targumic Texts Tg. Ps.-J. Targum Pseudo-Jonathan (Targum Yerushalmi I) Rabbinic Literature Gen. Rab. Genesis Rabbah Lev. Rab. Leviticus Rabbah Midr. Tanh. Midrash Tanhuma Ned. Nedarim Pesiq. Rab. Pesiqta Rabbati Sabb. Sabbat 1–2 Esd 1, 2 Esdras Jdt Judith 1–4 Macc 1–4 Maccabees Sir Sirach Sus Susanna Apoc. Ab. Apocalypse of Abraham Tob Tobit 2 Bar. 2 Baruch Wis Wisdom of Solomon 3 Bar. 3 Baruch (Greek Apocalypse) As. Mos. Assumption of Moses Ascen. Isa. Ascension of Isaiah 1 En. 1 Enoch (Ethiopic Apocalypse) New Testament Old Testament Pseudepigrapha Col Colossians 1–2 Cor 1–2 Corinthians Eph Ephesians Gal Galatians 2 En. 2 Enoch Heb Hebrews Epist. Ar. Letter of Aristeas Jas James Jos. Asen. Joseph and Aseneth Matt Matthew Jub. Jubilees 1–2 Pet 1–2 Peter Mart. Isa. Martyrdom of Isaiah Phil Philippians T. Dan Testament of Dan Phlm Philemon T. Jud. Testament of Judah Rev Revelation Rom Romans T. Levi Testament of Levi 1–2 Thess 1–2 Thessalonians T. Moses Testament of Moses 1–2 Tim Timothy Dead Sea Scrolls and Related Writings CD Damascus Document 1QM War Scroll from Qumran Cave€1 Apostolic Fathers Barn. Barnabas 1 Clem. 1 Clement Nag Hammadi Codices Gos. Truth Gospel of Truth xv Thompson_Hebrews_JDE_djm.indd 15 10/10/08 10:23:53 AM Abbreviations Ancient Authors Aelius Aristides Or. Orationes Aeschylus Ag. Agamemnon Albinus Didask. Didaskalikos (Handbook of Platonism) Aphthonius Prog. Hist. eccl. Historia ecclesiastica PE Praeparatio evangelica Galen Adv. Lyc. Adversus Lycum Diff. febr. De differentiis febrium Temp. De temperamentis Heliodorus Aeth. Progymnasmata Bibliotheca Progymnasmata (sp.) Herodotus Hist. Aristotle Aethiopica Hermogenes Prog. Apollodorus Bibl. Eusebius Historiae Eth. Nic. Ethica Nichomachea Mund. De mundo (sp.) Il. Iliad Pol. Politica Od. Odyssey Rhet. Rhetorica De officiis Demetrius Eloc. I socrates Antid. Cicero Off. Homer De elocutione John Chrysostom Capt. Eutrop. Homilia de capto Eutropio (dub.) Hom. Heb. Dio Chrysostom Or. Orationes Diodorus Siculus Bib. Bibliotheca historica Diogenes Laertius Vit. Vitae philosophorum Dissertationes Euripides Alc. Homiliae in epistulam ad Hebraeos Josephus Ant. Jewish Antiquities JW Jewish War Justin 1 Apol. First Apology Lactantius Epictetus Diss. Antidosis Epit. Epitome of the Divine Institutes M inucius Felix Alcestis Oct. Octavius xvi Thompson_Hebrews_JDE_djm.indd 16 10/10/08 10:23:54 AM Abbreviations Nicolaus Prog. Origen Cels. Contra Celsum Hom. Exod. Homily on Exodus On Rewards and Punishments Sacrifices On the Sacrifices of Cain and Abel Sobriety On Sobriety Spec. Laws On the Special Laws Unchangeable That God Is Unchangeable Ovid Metam. Rewards Progymnasmata Metamorphoses Philo of Alexandria Abraham On the Life of Abraham Agriculture On Agriculture Alleg. Interp. Allegorical Interpretation Virtues On the Virtues Worse That the Worse Attacks the Better Pindar Olymp. Olympian Odes Cherubim On the Cherubim Confusion On the Confusion of Tongues Crat. Cratylus Creation On the Creation of the World Gorg. Gorgias Prot. Protagoras Decalogue On the Decalogue Rep. Republic Dreams On Dreams Symp. Symposium Tim. Timaeus Drunkenness On Drunkenness Embassy On the Embassy to Gaius Flaccus Against Flaccus Flight On Flight and Finding Giants On Giants Plato Pliny Ep. Epistulae Plutarch Good Person That Every Good Person Is Free Adul. amic. Quomodo adulator ab amico Heir Who Is the Heir? Cohib. ira De cohibenda ira On the Life of Joseph Curios. De curiositate Migration On the Migration of Abraham E Delph. De E apud Delphos Frat. amor. De fraterno amore Moses On the Life of Moses Garr. De garrulitate Names On the Change of Names Is. Os. De Iside et Osiride Planting On Planting Pomp. Pompeius Posterity On the Posterity of Cain Prelim. Studies On the Preliminary Studies Quaest. conv. Quaestionum convivialum libri QE Questions and Answers on Exodus QG Questions and Answers on Genesis Joseph Thes. Theseus Virt. mor. De virtute morali Polybius Hist. Historiae xvii Thompson_Hebrews_JDE_djm.indd 17 10/10/08 10:23:54 AM Abbreviations Tacitus Porphyry Abstin. De abstinentia Quintilian Inst. Annales Tertullian Institutio oratoria Seneca Modesty On Modesty (De pudicitia) Thucydides Ep. Epistulae morales Herc. Oet. Hercules Oetaeus Sextus E mpiricus Pyrr. hyp. Ann. Hist. Historiae Xenophon Mem. Memorabilia Pyrrhoniae hypotyposes (Outlines of Pyrrhonism) Stobaeus Ecl. Eclogae Anonymous Ancient Works Rhet. Her. Rhetorica ad Herennium Modern Works, Series, and Collections BDAG Greek-English Lexicon of the New Testament and Other Early Christian Literature. Edited by F. W. Danker. 3rd ed. Chicago: University of Chicago Press, 2000. NPNF Nicene and Post-Nicene Fathers. 2 series. Edited by P. Schaff and H. Wace. 28 vols. Repr. Peabody, MA: Hendrickson, 1994. OTP Old Testament Pseudepigrapha. Edited by J. H. Charlesworth. 2 vols. Garden City, NY: Doubleday, 1983–1985. PG Patrologia graeca [= Patrologiae cursus completus: Series graeca]. Edited by J.-P. Migne. Paris, 1857–1866. SIG Sylloge inscriptionum graecarum. Edited by W. Dittenberger. 4 vols. 3d ed. Leipzig: S. Hirzelium, 1915–1924. TDNT Theological Dictionary of the New Testament. Edited by G. Kittel and G. Friedrich. Translated by G. Bromiley. Grand Rapids: Eerdmans, 1964–1976. xviii Thompson_Hebrews_JDE_djm.indd 18 10/10/08 10:23:54 AM Hebrews Thompson_Hebrews_JDE_djm.indd 19 10/10/08 10:23:54 AM Thompson_Hebrews_JDE_djm.indd 20 10/10/08 10:23:54 AM Introduction The Epistle to the Hebrews has played an important role in shaping the faith of the Christian church. Its rich imagery is evident in the church’s hymnody, and its memorable phrases have shaped Christian discourse. To speak of drawing nearer to God, marching to Zion, entering the promised land, finding a place of rest, and approaching the divine mercy seat is to enter into the world of Hebrews. Its description of the work of Christ as the offering of the great high priest and its emphasis on the humanity of the one who was “tempted in every respect” (4:15) has been the basis for Christian theological reflection for generations. As the book with the longest sustained argument in the NT, Hebrews is one of the earliest examples of Christian theology as faith seeking understanding. Despite its honored place in liturgy and theology, it is probably the most mysterious book in the NT. William Wrede labeled it “the riddle of the New Testament” (1906), and Erich Grässer described it (1993, 2:18), in words drawn from the book itself, as “the word that is hard to explain” (cf. Heb 5:11). This mystery includes the absence of information about the identity of the author or the original recipients and their location. Despite the title in early manuscripts, “To the Hebrews,” and the title in later translations, “The Epistle of Paul to the Hebrews,” the book identifies neither the recipients nor the author. Moreover, both the absence of the normal epistolary conventions, including the identity of the author and readers, and the distinctive literary form suggest that Hebrews can scarcely be included among the Epistles. The book also includes mysterious modes of argumentation that contribute to the riddle. Its claim that “it is impossible to restore to repentance those who have fallen away” (6:4–6) has puzzled Christians since the second century. Its description of the mysterious figure of Melchizedek (7:1–10) has also been the source of endless speculation. Only the author of Hebrews describes 3 Thompson_Hebrews_JDE_djm.indd 21 10/10/08 10:23:54 AM Introduction the work of Jesus in high priestly and sacrificial terms. Thus the placement of Hebrews between the letters of Paul and the General Epistles reflects an awareness among earlier scholars of the work’s distinctiveness. The Historical Puzzle: Author and Audience The Author One dimension of the mystery of Hebrews is the authorship of the book. Although the book is anonymous, Hebrews has been included among the letters of Paul since ancient times. As early as the second century, Christians in the East attributed the letter to Paul. The oldest complete extant manuscript of Hebrews, � 46, placed Hebrews after Romans in the collection of Pauline writings, as did numerous later manuscripts. Indeed, no evidence is available to suggest that Hebrews ever circulated independently or in any collection other than that of Paul (Eisenbaum 2005, 218–19). In Alexandria, where Hebrews was most influential, church leaders attributed the work to Paul and attempted to explain the anonymity of the book. Pantaenus (d. ca. AD 190) suggested that Paul omitted his name because of modesty (Eusebius, Hist. eccl. 6.14.4), while Clement of Alexandria suggested that Paul omitted his name because, as the apostle to the Gentiles, he would evoke suspicion among Jewish listeners (Eusebius, Hist. eccl. 6.14.3). Although ancient writers included Hebrews among the letters of Paul, many recognized problems in the attribution of Pauline authorship. The anonymity of the book and its refined Greek distinguished it from the Pauline letters. Clement of Alexandria recognized the stylistic differences between Hebrews and the letters of Paul and suggested that Paul wrote the letter in Hebrew and that Luke translated it into Greek (Eusebius, Hist. eccl. 6.14.2). Origen also recognized the stylistic differences between Hebrews and the Pauline letters, Clement and Origen Clement of Alexandria was born around AD 145 or 150 and died around 215–216 in either Athens or Alexandria (more likely the former). He became part of the catechetical school under Pantaenus ca. 190 and succeeded him as headmaster on his death, ca. 200. Origen (ca. AD 185–254), one of his students, succeeded Clement as head of the catechetical school. Origen possessed a powerful intellect and quickly gained a reputation as an exegete and theologian. He is best remembered for his major theological treatise, De principiis, the Hexapla (his parallel edition of Hebrew and Greek versions of the Old Testament), Contra Celsum (a lengthy rebuttal of an earlier pagan critic of Christianity), and his numerous commentaries. 4 Thompson_Hebrews_JDE_djm.indd 22 10/10/08 10:23:55 AM â•… The Historical Puzzle: Author and Audience concluding, “Who wrote the epistle, God truly knows” (Eusebius, Hist. eccl. 6.24.11–14). However, Origen commonly cited Hebrews as a letter of Paul (Koester 2001, 21, 41–42), and the Eastern church treasured this writing. The Western church, in its struggle with problems over those who lapsed in persecution and troubled by the references to the impossibility of repentance (6:4–6; 10:26–31; 12:16–17), contested Pauline authorship. Tertullian (ca. AD 160–225) proposed that it was written by Barnabas (Modesty 20; Koester 2001). Although Pauline authorship was generally accepted during the Middle Ages and the Reformation, questions continued to be raised about the authorship of the book, leading scholars to speculate on the identity of the author. Luther, for example, suggested that Apollos might be the author of Hebrews. In the modern era, scholars are virtually unanimous in concluding that Paul was not the author, and some have suggested the names of possible alternatives, including Luke, Barnabas, Apollos, and Priscilla. However, since no evidence exists to support a specific name from a list of candidates known to us from the NT, the attempt to identify the name of the author is not a worthwhile task, for this search involves only speculation. Although the name of the author is unknown, the book offers abundant evidence of the author’s background, education, worldview, relationship to the readers, and period of activity. The masculine participle in 11:32 suggests that the author is male. He claims neither apostolic authority nor a place in the first generation. Unlike Paul, he never offers himself as an example or speaks autobiographically. He refers to the leaders of the community, but does not claim to be one of them (cf. 13:7, 17, 24). He speaks, not on his own authority, but argues on the basis of scripture. With the community that he addresses, he belongs to the second generation that received the message “from those who heard him” (2:3). More than any other writer of the NT, he speaks in hortatory subjunctives (“let us”), identifying himself with his listeners. The postscript in 13:18–25 adds another dimension to the mystery surrounding the author, for this section not only mentions Timothy (Paul’s coworker?) but also contains the familiar phrases that are found in the Pauline letters. Here the author speaks in the first-person singular and offers information about himself. He requests the prayers (13:18) of the community and expresses his desire to be restored to them soon (13:19) along with Timothy (13:23), who has recently been released. The concluding greetings (13:24) and benediction (13:25) also correspond to the ending of Paul’s letters. Scholars have interpreted this postscript in two different ways. Some have argued that the postscript belongs to the later hand of someone who desired to integrate this work within the Pauline letter collection (cf. Grässer 1997, 3:409). Others suggest that the reference to Timothy is an indication that the author, like Timothy, belongs to a Pauline circle. Scholars have also examined the themes in Hebrews for evidence of dependence on the letters of Paul. The two writers occasionally cite the same texts 5 Thompson_Hebrews_JDE_djm.indd 23 10/10/08 10:23:55 AM Introduction Periodic Sentence A periodic sentence is a carefully structured statement in which a balance is created by the word order, or syntax, that may be described in terms of a path “around,” literally going in a circle and returning to where the sentence began. According to the rhetorical handbooks, the building blocks of the periodic sentence are the clauses (kommata = brief phrases and kōla = complete clauses) that the orator weaves together. Some orators arranged clauses antithetically, while others employed parallelism or a series of subordinate clauses. Most of the rhetorical handbooks, including those of Aristotle, Theophrastus, Demetrius, and Cicero, gave attention to the periodic sentence. According to Demetrius (Eloc. 16–18), the periodic sentence is composed of two to four clauses (kōla). The refined style gives grandeur to a speech (45–47) but is inappropriate for letters (229). Although Paul occasionally exhibits stylistic refinement (cf. 1€Cor 13; 2 Cor 4:16–18), he does not employ the periodic sentence. The prologue of Luke is a good example of this style. Hebrews employs the periodic sentence in 4:12–13; 5:7–10; 7:1–3; 12:18–24. (e.g., Jer 31:31–34 in 2€Cor 3:6; Heb 8:7–13; 10:16–17; Hab 2:4 in Rom 1:17 and Heb 10:38) and share such themes as the faith of Abraham (Rom 4; Gal 3) and the validity of the law. Nevertheless, the author’s use of these texts rarely shares significant themes with Pauline usage. Thus the view that the author belongs to a Pauline circle remains inconclusive. The evidence indisputably indicates that the author was well educated, displaying a linguistic refinement that is without parallel in the NT. Ceslas Spicq identified 152 words in Hebrews that appear nowhere else in the NT, of which most come either from the LXX or from educated Greek circles (Spicq 1952, 1:157). The author also speaks in complex periodic sentences (1:1–4; 2:2–4; 5:7–10; 7:26–28) that were characteristic of linguistic refinement. He delights in alliteration (cf. 1:1, polymerōs kai polytropōs palai .€.€. patrasin .€.€. prophētais), internal rhyme (5:8, emathen aph’ hōn epathen, “he learned from what he suffered”), and anaphora (11:3–39, “by faith .€.€. by faith .€.€. by faith .€.€.”). He employs a sophisticated rhetorical vocabulary and uses metaphors that are derived from the law courts (cf. 6:16; 7:7), athletics (12:1–2), and education (5:11–14), all of which were at home among Greek philosophers and rhetoricians. He was also acquainted with Greek philosophical categories (see below, pp. 23–26). The Audience The identity of the recipients is as mysterious as the identity of the author, who gives few clues about their location or the date of the book. The final greeting, “Those who are from Italy greet you” (13:24), is the only reference 6 Thompson_Hebrews_JDE_djm.indd 24 10/10/08 10:23:55 AM â•… The Historical Puzzle: Author and Audience to a location, but it is ambiguous, for it can mean either that the author is in Italy writing to a community in a distant place or that the author is writing to a community in Italy. Some scholars have argued vigorously that the community lives in Rome (Lane 1991a, lviii–lx; Weiss 1991, 76; Ellingworth 1993, 29), noting that Hebrews was first quoted by Clement of Rome at the end of the first century. Others (John Chrysostom; Westcott 1890; P.€Hughes 1977; Isaacs 1992) have suggested a destination in Jerusalem, maintaining that the argument based on the sacrificial system would be most intelligible to a Jerusalem community. However, proposals for the location of the readers, like those identifying the author, reflect more the scholar’s dissatisfaction with the mystery surrounding Hebrews than any supporting evidence. Similarly, the author gives few clues about the dating of this homily. Since the central argument focuses on the sacrificial system, many scholars have attempted to correlate the argument with the destruction of the temple in Jerusalem, maintaining that the use of the present tense for the activities of the tabernacle suggests a date before the destruction of the temple in AD 70. On the other hand, Marie Isaacs (1992, 67) has argued that Hebrews was written between 70 and 90 in order to reassure the community that atonement is possible without animal sacrifices. Inasmuch as Hebrews argues on the basis of the tabernacle rather than the temple, one cannot draw conclusions about the date of Hebrews by referring to the destruction of the temple in AD 70. The fact that writers spoke of the cultic activities in the present tense after the destruction of the temple (Josephus, Ant. 3.151–224) suggests that we can draw no conclusions based on the use of the present tense. The date remains unknown and of only marginal importance for understanding the book, for our interpretation requires that we know not the location or the date of the composition of this work but the issues that the author confronts. Ancient Christian writers assumed that the homily was addressed to Jewish Christians, as the title To the Hebrews suggests. The earliest identification we have after Clement and Origen comes from John Chrysostom (ca. 347–407), who located the addressees “in Jerusalem and Palestine” (Isaacs 1992, 24, 39). Nevertheless, we cannot be sure that To the Hebrews is an accurate description of its original recipients, for the author never refers specifically to the ethnic background of the readers. Although the superscription is to be found in all extant manuscripts, it probably reflects an inference based on the content of the work rather than information about the recipients of the book. Some modern commentaries continue to maintain that Hebrews is a letter written to Jewish Christians who were tempted to return to Judaism. This conclusion is based on the author’s consistent argument for the superiority of Christ to the institutions of the OT and his appeal to the authority of the OT. The author’s argument for the superiority of Christ would, according to this view, be intelligible only to a Jewish Christian audience that was having difficulty breaking its ties with the Jewish tradition. However, this reconstruction 7 Thompson_Hebrews_JDE_djm.indd 25 10/10/08 10:23:55 AM Introduction ignores the numerous references in the book to the situation of the readers. As is the case with authorship, the best evidence for the historical situation of the readers is to be found in the numerous references in the exhortations. In references to their situation, the author mentions a need to correct false teaching (13:9) only once, and he never indicates that the readers are Jewish Christians who are tempted to return to Judaism. Instead, he gives a coherent picture of the issues that his community now faces. The community’s current situation becomes evident in (1) the implied narrative of the community’s history, (2) direct statements about their situation, (3) warnings about future dangers, and (4) possible allusions to their situation. We may combine this information with the insights drawn from historical and sociological analogies to gain a better understanding of the readers’ situation. 1. The author refers to the narrative of the community’s existence that extends from their conversion to the time of writing. He recalls the “earlier days” (10:32) when their original leaders had taught them the word of God (13:7; cf. 2:3). The readers were then “enlightened” (6:4; cf. 10:32), became “partakers of the Holy Spirit” (6:4), and experienced the powers of the coming age (6:5). Shortly after their conversion they experienced the trauma of persecution that resulted in imprisonment, public abuse, confiscation of property, and other forms of suffering (10:32–34; 12:4–11). Their suffering was probably not officially sponsored by civic authorities, but was not unlike the experience of new converts elsewhere who had alienated themselves from their relationships and shamed their families by their conversion. The readers responded with extraordinary community solidarity (6:10; 10:32–34) to this suffering. Recent sociological analyses have illuminated the situation of this community by observing that its history conforms to common patterns within religious groups. At the beginning, many people accepted the Christian claim that the crucified and exalted Christ was the ultimate revelation of God and that the whole universe was subject to him. The one who stood in control of all reality demanded their total allegiance, separating them from all other loyalties and creating a new community of those who shared this view of reality. This allencompassing claim created hostility among the populace, which responded by subjecting the new movement to abuse. Thus in a society that valued honor above all else, the readers have experienced the shame of losing their place in the world (DeSilva 2000, 18). Despite their alienation from society, they could maintain their commitment because their teachers had initiated them into an alternative symbolic world in which Jesus Christ is Lord and reinforced their commitment with the solidarity of an alternative family in the community of faith. Therefore, like countless other new religious movements, this community began with a period of enthusiasm that empowered it to adopt an alternative worldview that evoked the hostility of the populace (Salevao 2002, 132). 2. The current status of the readers is evident in the author’s distinction between “earlier days” (10:32) and the time in which he writes (cf. 5:12). The 8 Thompson_Hebrews_JDE_djm.indd 26 10/10/08 10:23:55 AM â•… The Historical Puzzle: Author and Audience community belongs to the second generation after their original leaders have died (cf. 13:7), for the message was first declared to them “by those who heard him” (2:3). They now have drooping hands and weak knees (12:12). The author speaks of their current situation when he says, “You have become dull of hearing” and “you ought to be teachers because of the time” (5:11–12). Some are abandoning the assembly (10:25) and “need endurance” (10:36). Despite the history of alienation, he also indicates that no one has died (12:4). The current situation of the readers also conforms to the common patterns among new religious movements, which with the passage of time lose their initial intensity and wonder if the price for commitment is too high. The recipients of Hebrews have experienced the dissonance between the Christian claim and the reality they experience, for they do not see the world in subjection to the Christ. Having experienced the loss of property and status without seeing rewards commensurate to their loss, the group now faces the loss of solidarity: “While they could accept their loss in the fervor of religious solidarity, living with their loss has proven difficult” (DeSilva 2000, 19), leading them to ask if it is worth it to be a Christian. The readers are grappling with the religious instruction that they received at the beginning in the context of their contemporary experience, trying to make sense of them both (Isaacs 1992, 13). According to David DeSilva, “From a sociological perspective, the Persecution and Social Ostracism in the Early Church Although the Roman government conducted no comprehensive persecution designed to crush Christianity before the one promulgated by the emperor Decius in AD 249–51, strong opposition to Christianity existed from the beginning, often leading to governmental intervention against the Christians. Both 1€Peter (cf. 4:4) and the letters of Paul (cf. Phil 1:28; 1€Thess 1:6; 3:3) refer to external opposition experienced by the community, while Revelation probably refers to extensive localized persecution (cf. 2:9–10, 13; 6:9–11). In recalling the persecution of Christians by Nero after the fire of Rome (AD 64), Tacitus (ca. AD 56–ca. 115) indicates Roman attitudes long after the event, referring to Christianity as a “superstition” and a “disease” and to Christians as a people “loathed for their vices” (Tacitus, Ann. 15.44). Public hostility to Christians was based on several factors. The primary cause was their exclusive claim to religious truth, which led to extensive proselytizing. The confession that “Jesus is Lord” (cf. Phil 2:11) was an implicit challenge to the Roman imperial order. Conversions often resulted in division within families (cf. 1€Pet 3:1–7) and the breaking of social ties with close associates (Elliott 1981, 80). The rejection of pagan religion also led to withdrawal from civic life (1€Pet 4:4). As a result, rumors of Christian misdeeds circulated among the populace, and Christians inherited many of the same charges that ancient people made against Judaism. 9 Thompson_Hebrews_JDE_djm.indd 27 10/10/08 10:23:56 AM Introduction crisis appears to be one of the survival of the integrity of the sect as a viable subculture within the host society. The cost of maintaining the identity of the sect is, for some members at least, rising above the value of such an enterprise” (1994, 10). 3. In the numerous paraeneses, the author warns his readers about the dangers he envisions. He is concerned lest they “drift away” (2:1), “fall away” (3:12), “fall short” (4:11), “fall” (6:6), “sin deliberately” (10:26), throwing away the confidence that they have gained in Christ (10:35). The fact that the references to the threat facing the community are not specific (Isaacs 1992, 27) suggests that the author is more concerned with the community’s abandonment of the faith than with any alternative they might take. 4. Some allusions may provide further insight into the community’s situation. When the author concedes in 2:8 that “we do not yet see all things in subjection to him,” he is probably speaking for the community that struggles with the dissonance between its confession and the realities of alienation. The description of Jesus’ solidarity with humanity in suffering (2:10–18) undoubtedly reflects the author’s desire to address the community’s painful situation. The imagery of the people who are being tested on the way to the promised land (3:7–4:11) also suggests that the readers are tempted to abandon their faith. The emphasis in Heb 11 on the people of God as “sojourners” and “aliens” (cf. 11:13–16, 38) who are homeless in this world and subject to abuse (11:26) probably reflects the situation of the readers. The reminder that Jesus experienced “shame” and endured the cross (12:2) suggests that the author is addressing a community that has a history of alienation and shame. The Literary Puzzle: Genre and Structure The mystery of Hebrews extends to its distinctive literary form and structure, which are essential elements in the author’s attempt to persuade his audience to remain faithful. The genre is not merely the container for the author’s message, nor is the structure merely the table of contents. Both the genre and the structure are intertwined with the message to have the maximum persuasive impact on the wavering audience. The analysis of the genre and the structure reveals the author’s major emphasis and the relationship of the themes of the homily to each other. Literary Genre Except for the final chapter, the book lacks the essential characteristics of a letter. Unlike the Pauline letters, which commonly proceed from a recitation of prior events toward theology and exhortation, Hebrews is a series of biblical expositions, each followed by an exhortation that actualizes the passage for the audience. Although the author, like Paul, speaks directly to his audience 10 Thompson_Hebrews_JDE_djm.indd 28 10/10/08 10:23:56 AM â•… The Literary Puzzle: Genre and Structure The Pauline Letter Form Discoveries of ancient papyrus letters by Adolf Deissmann (ET 1965, 213–25) in Egypt revealed a pattern in ancient correspondence that Paul adopted in his own letters. Ancient letters Paul’s letters Opening Name of author and recipient Greeting Thanksgiving Name of author and recipient Greeting Thanksgiving Body Disclosure formula (“I want you to know”) Disclosure formula Autobiography Teaching Request/Ethical instructions Future travel plans Request (“I appeal to you”) Closing Greetings to individuals Greetings to individuals Request for prayer Doxology Hebrews contains only the final ethical exhortations, greetings, request for prayer, and doxology. in a dialogical manner, stylistic features distinguish Hebrews from the letters. The author speaks frequently with the hortatory subjunctive (“let us”; cf. 4:14; 10:19–23, 24; 13:15) rather than the imperative or the first-person singular (“I appeal to you”). He emphasizes the actions of speaking and listening, as if he were speaking directly to an audience (cf. 2:5; 5:11; 6:9; 8:1; 9:5; 11:32). Only in chapter 13 does Hebrews have the familiar epistolary forms. The exhortations in 13:1–6 resemble the ethical section of Paul’s letters in form and content. The conclusion in Heb 13:18–25 has elements characteristic of Pauline letters: the request for prayer (13:18; cf. Rom 15:30; 1€Thess 5:25), the expression of desire for a future visit by the author (13:19; cf. Phlm 22), a final benediction (13:20, 25; cf. Rom 15:33; 2 Cor 13:13; 1€Thess 5:23), and the final greetings (Heb 13:24; cf. 1€Cor 16:19–20). Thus the literary style of the first twelve chapters suggests that the author has employed a distinctive genre to persuade his audience. The author describes this work as a word of exhortation (13:22), a term that is used in Acts 13:15 for the synagogue homily. Lawrence Wills (1984) has examined the word of exhortation in Acts 13:34–41 and noted its similarity to Hebrews and to other works of that period. The word of exhortation consisted of (1) exempla containing authoritative evidence to commend the points that follow, (2) a conclusion based on scriptural evidence, and (3) an exhortation that was joined to the presentation by “therefore.” Wills observes that several speeches in Acts, including the speech of the town clerk 11 Thompson_Hebrews_JDE_djm.indd 29 10/10/08 10:23:56 AM Introduction in Ephesus (Acts 19:35–40), follow this pattern. Josephus records several speeches that follow a similar pattern (examples in Wills 1984, 295) that is also present in 1€Peter and 1 and 2€Clement. Wills notes that the homiletic pattern of exempla/conclusion/exhortation is recycled in Hebrews in successive expositions. Since this pattern exists in Jewish homiletical works, Hebrews is commonly identified as a synagogue homily. However, the pattern identified by Wills was not limited to synagogue homilies but was used also in the speeches of ancient Greek orators. The historian Thucydides (ca. 460–400 BC) also records speeches that have the pattern of exempla/conclusion/exhortation (Hist. 2.34–46; Black 1988, 14). Consequently, scholars in recent years have applied Aristotelian rhetoric to the analysis of Hebrews. Of the three types of speeches identified in the handbooks, two of them have analogies in Hebrews. Only judicial rhetoric, which calls for decisions about the past, does not fit into this form of rhetoric. With Hebrews’ glorification of the status and work of Christ, it resembles epideictic rhetoric, which was intended to offer praise and reinforce the values of the audience. Since deliberative rhetoric called for decisions about future conduct, many scholars have identified Hebrews with this form of speech. Thus one can conclude that Hebrews has elements of both deliberative and epideictic rhetoric, for it contains both praise for the work of Christ and a call for action by the readers. The author’s use of rhetorical devices is evident in numerous respects. In the first place, the predominance of synkrisis in Hebrews, according to which the saving events in Christ are compared to the institutions of the OT, reflects the author’s rhetorical training. In the second place, the author’s mode of argumentation suggests rhetorical training, for he not only argues from scripture but also makes abundant use of terminology from logical Rhetorical Persuasion and Rhetorical Handbooks Ancient rhetorical theorists analyzed the components of effective persuasion in handbooks designed for practitioners in the law courts and other areas of public life. The two oldest extant handbooks, both from the fourth century BC, are Aristotle’s Rhetorica and the Rhetorica ad Alexandrum, attributed to Anaximenes of Lampsacus (380–320 BC). All the handbooks from the fourth to the first century BC are lost. Later handbooks that included some are all of the major guidelines for orators included De elocutione by Demetrius (first or second century BC), several works by Cicero (Topica, De inventione, Partitiones oratoriae, De oratore) and the anonymous Rhetorica ad Herennium from the first century BC, and the Progymnasmata of Theon and Institutio oratoria of Quintilian from the first century AD (see Anderson 1999, 38–96). The handbooks delineated the types of speeches, appropriate arguments, and the arrangement and style most suitable for the audience. 12 Thompson_Hebrews_JDE_djm.indd 30 10/10/08 10:23:57 AM â•… The Literary Puzzle: Genre and Structure Synkrisis Ancient rhetorical theorists described synkrisis as comparison for the purpose of evaluation. Comparisons could involve (a) good with good, (b) bad with bad, and (c) good with bad. Thus synkrisis could be used in speeches of either praise or blame. According to Aphthonius (fourth century bc), one employed synkrisis to compare “fine things with good things or poor things beside poor things” (Prog. 31). According to Nicolaus, “Our subjects will be great when they seem greater than the great” (Prog. 61). Topics for comparison of individuals included birth, ancestry, education, health, strength, and beauty. Exercises in synkrisis were a part of the curriculum of teenage students of rhetoric. Plutarch’s Parallel Lives, a comparison of Greek and Roman leaders, was a major example of extended synkrisis. proof commonly in use by orators (cf. Thompson 1998; Löhr 2005). Frequent arguments based on what is “necessary” (7:12; 9:16, 23), “impossible” (6:18; 10:4), and “appropriate” (2:10) indicate the author’s rhetorical training. Thus ancient readers would have recognized the author’s training in both the homiletic tradition of the synagogue and Greek rhetoric. Structure Although most scholars agree that the structure of the homily is an indispensable part of the message, the artistry of this homily makes it a challenge for anyone who wishes to analyze its structure, as the widely divergent structural analyses of Hebrews demonstrate. The author’s artistry is evident in the fact that he skillfully avoids displaying the scaffolding of his work as one topic blends into another. Consequently, scholars have identified multiple structural signals, resulting in a wide diversity of opinion. Views of the structure of Hebrews extend from structural agnosticism (e.g., Moffatt 1924, xxiii) to elaborate and detailed analyses. Some look for thematic signals to the structure of the book, while others identify either literary or rhetorical signals. The complexity of the problem is evident in the fact that several books have been devoted to the topic (Vanhoye 1976; Übelacker 1989; Guthrie 1994). No NT book has elicited a more rigorous examination of its structure. Our view of the structure is also related to our understanding of the purpose of the book. A traditional structure of Hebrews locates the structural signals in Hebrews in the comparisons (kreittōn, “better than”), concluding that Hebrews is a series of comparisons intended to demonstrate that Christianity is better than Judaism. An example of this structure is found in the commentary by Philip Hughes (1977). 13 Thompson_Hebrews_JDE_djm.indd 31 10/10/08 10:23:57 AM Introduction Christ Superior to the Prophets, 1:1–3 Christ Superior to the Angels, 1:4–2:18 Christ Superior to Moses, 3:1–4:13 Christ Superior to Aaron, 4:14–10:18 Christ Superior as the New and Living Way, 10:19–12:29 Concluding Exhortations, Requests, and Greetings, 13:1–25 This structure follows the themes of the book, focusing on the expositions but paying little attention to the exhortations that are interspersed throughout the homily. Inasmuch as the exhortations indicate that the author is not engaged in a polemic, but employs the expositions to lay the foundation for the exhortations, the thematic approach does not acknowledge the essential focus of the homily. In the twentieth century, most scholars turned from the thematic approach to the literary aspects of Hebrews to identify the structural signals of the book. Most of the discussion has focused on two alternative approaches. Albert Vanhoye (1976) recognizes structural signals in (1) the announcement of the subject to be discussed (e.g., 1:4; 2:17–18; 6:20), (2) hook words that appear at the end of one section and the beginning of the next, (3) inclusions that demarcate the boundaries of units (e.g., 3:1 and 4:14), (4) variations of literary genre (exposition or exhortation; e.g., 2:1–4), and (5) words that are concentrated in a unit (e.g., angels in chaps. 1 and 2). Using these structural signals, he outlines Hebrews in five parts that are framed by an introduction (1:1–4) and conclusion (13:20–21): I. The Son superior to the angels (1:5–2:18) II. Christ’s faithfulness and compassion (3:1–5:10) Hook Words in Hebrews Hook words in Hebrews link apparently unrelated topics together by concluding one section with the topic for the next unit of the book. Examples of hook words include the following: • “Greater than angels” (1:4) introduces the extended comparison of the Son and angels in 1:5–28. • “Faithful .€.€. high priest” (2:17) is a link to the comparison of the faithfulness of Jesus (3:1–6) with the unfaithfulness of the ancestors (3:7–4:11). • “High priest after the order of Melchizedek” (6:20) introduces the discussion of Melchizedek in chapter 7. • “My righteous one will live by faith” (10:38) is a link to the discussion of faith in chapter 11. 14 Thompson_Hebrews_JDE_djm.indd 32 10/10/08 10:23:58 AM â•… The Literary Puzzle: Genre and Structure Table 1. Matching Bookends for the Central Section of Hebrews 4:14–16 10:19–23 Therefore, having a great high priest Therefore, having .€.€. a great priest who has passed through the heavens through the curtain Jesus, the Son of God by the blood of Jesus let us hold fast to the confession let us hold fast the confession let us draw near .€.€. with boldness let us draw near with a true heart III. The central section on sacrifice (5:11–10:39) IV. Faith and endurance (11:1–12:13) V. The peaceful fruit of justice (12:14–13:19) Vanhoye’s structure then becomes an elaborate chiasm. The result is that the center of gravity becomes the central section on the high priestly work of Christ (5:11–10:39). Vanhoye’s approach, despite its helpful insights, is not totally satisfactory. The focal point of the argument is not the high priesthood of Christ but the climactic exhortation at the latter part of the homily. Recent scholars have insisted that any structural analysis must recognize that the theological expositions do not stand on their own but lay the foundation for the exhortation. For example, Wilhelm Nauck (1960) observed the inclusio in 4:14–16 and 10:19–23 and concluded that these passages form the “bookends” for the central section on the priestly work of Christ. (See table€1.) This inclusio results in a tripartite structure. Part 1 has an inclusio formed by the opening periodic sentence focusing on the fact that God “has spoken in his Son” (1:1–4) and the periodic sentence on God’s word in 4:12–13. The bookends in part 2 (4:14–10:31) indicate that the exposition on the high priestly work of Christ builds the case for the exhortation to hold on to the Christian confession (4:14; 10:23). The final section (10:32–13:25) is composed primarily Inclusio Inclusio, a Latin word meaning “imprisonment, confinement,” is a literary term for similar wording placed at the beginning and end of a section as a framing device. In some instances the inclusio marked the place for a digression from a subject to which the speaker returned, while in other instances the repetition was helpful as emphasis in oral address. Examples in Hebrews include 1:3, 13 (right hand of God); 3:12, 19 (unfaithfulness); 4:14; 5:10 (high priest); 8:7–13; 10:16–17 (new covenant). The first two major sections (1:1–4:13; 4:14–10:31) are framed in this way. 15 Thompson_Hebrews_JDE_djm.indd 33 10/10/08 10:23:58 AM Introduction of exhortations that draw the consequences of the theological section and call for faithfulness. With the juxtaposition of the theological and paraenetic sections, the author shows that the center of gravity is in the exhortations. Thus the author of Hebrews demonstrates how theology serves preaching. Nauck’s tripartite structure, which recognized the importance of paraenesis in the structure of Hebrews, has been widely accepted, often with minor variations, especially in demarcating the end of the central section and the beginning of the final section (Weiss [1991] places the end of the central section at 10:18; Hegermann [1988] places it at 10:31; and Michel [1966] places it at 10:39). This structure recognizes essential elements in the message of Hebrews. The fact that Hebrews shows elements of epideictic and deliberative rhetoric (see above) suggests to many scholars that classical rhetorical patterns provide the model for the arrangement of Hebrews. However, despite the growing popularity of the rhetorical analysis of Hebrews, scholars have reached little agreement in determining how Hebrews fits the arrangement commended in the rhetorical handbooks. While they discover in Hebrews most, if not all, of the parts of the speech delineated by Aristotle, they do not agree on the identification of these units. For example, while some identify Heb 1:1–4 as the exordium, others extend it to include all of chapter 1 or even 1:1–2:4 (Koester 2001, 84). Scholars debate the boundaries of the narratio, which states the facts of the case. Übelacker (1989) and Nissilä (1979) place it at 1:5–2:18; Berger (1968) and Weiss (1991) at 1:5–4:13. The propositio is equally elusive. Übelacker (1989) places it at 2:17–18; Koester (2001) places it at 2:5–9; and Backhaus (1996) places it at 4:14–16. Widespread disagreement does not, however, render rhetorical analysis impossible, for most of the disagreements involve the boundaries of each section. Scholars are in general agreement that rhetorical analysis is intended to determine the persuasive power of the argument by following its movement. Like orators who often used some, but not all, of the standard arrangement, the author has adapted numerous rhetorical strategies to persuade his audience. Thus the reader may analyze the sermon with the tools of rhetorical Elements of the Rhetoric of Persuasion Ancient handbooks on oratory recommended several standard elements, which speakers adapted for their own purposes, sometimes omitting one or more of them. The introduction (exordium) was intended to introduce the topic and make the audience favorably disposed. A narration (narratio) of the facts pertaining to the case commonly followed. The narration was then followed by a proposition (propositio) stating the case to be argued. The main body of the argument (probatio) offered the proofs, and the concluding section (peroratio) summarized the case, often with increased emotional intensity. 16 Thompson_Hebrews_JDE_djm.indd 34 10/10/08 10:23:59 AM â•… The Literary Puzzle: Genre and Structure criticism. This commentary follows an approach that employs the tripartite division identified by Nauck and Aristotelian rhetorical analysis to determine the rhetorical effectiveness of the author. Hebrews 1:1–4. The first four verses of Hebrews fit well with the Aristotelian definition of the exordium. The author makes the audience favorably disposed and attentive with the beautiful periodic sentence that suggests the importance of the message. He also introduces the major themes of the homily: God’s speaking (1:1–2; cf. 2:1–4; 4:12–13; 12:25), the relationship between the many and the one (“in many and various ways .€.€. in these last days”; cf. 7:23–24; 9:26–27; 10:11–14), the purification for sins (9:1–10:18), the exaltation to God’s right hand (1:3; 7:3; 8:1; 10:12), and the comparison of the superiority of the exalted Christ to everything on earth (cf. kreittōn, “greater than,” in 6:9; 7:7, 19; 8:6; 11:16, 40; 12:24). In sum: God spoke the final word to us when the Son made purification for sins and sat down at God’s right hand, becoming greater than angels (or any other object of comparison). The claim for the universal importance of the topic is a model for what one expects in the exordium (Lausberg 1998, 270). The remainder of the homily will elaborate and draw the implications for this claim as the author recycles these themes. In the recycling of themes using synkrisis, or comparison, the author employs the rhetorical device of amplification, following the advice of Aristotle:. (Rhet. 1.9.38–39, trans. Freese 1939, 103–5) Amplification was also a device for repeating points that had already been made (Aristotle, Rhet. 3.19.1–2). The remainder of the homily continues with a series of comparisons between the exalted Christ and the institutions of the OT. 1:5–4:13. The author supports and clarifies the exordium in 1:5–4:13 by extending the synkrisis (1:5–13; 3:1–6), clarifying its content (2:5–18), and drawing the paraenetic conclusions with examples from the past (2:1–4; 3:7–4:11). The clarification in 2:5–18 is necessary because the claims in chapter 1 do not correspond to the experience of the readers, who “do not see everything in subjection” (2:8) to the Son. Their experience of suffering and alienation has placed their most fundamental conviction in doubt. Consequently, the author introduces the humanity of Christ as a precondition for his status as exalted high priest (2:17–18). This clarification offers encouragement to the readers by interpreting their own struggle as a necessary prelude to the ultimate glory. They are following the leader who shared in their suffering in order that he might help them in their current struggles (2:17–18). Because the 17 Thompson_Hebrews_JDE_djm.indd 35 10/10/08 10:23:59 AM Introduction leader is faithful, the community should respond with faithful endurance in its present situation (3:1–4:11), knowing that it dares not reject God’s ultimate word (1:1–2; 2:1–4; 4:12–13). God continues to speak through the scriptures, summoning the people to faithful endurance. The faithfulness of Jesus and the unfaithfulness of the fathers from the basis for exhortation to faithfulness. The word of God (cf. 1:1–2) has the power to expose the community’s unfaithfulness (4:12–13). Because 1:5–4:13 introduces all the themes that the author will unfold in the remainder of the homily it functions as the narratio, stating the facts of the case to be argued (Backhaus 2005, 58–59; Berger, 1984, 1368). The victorious christological claim (1:5–13) requires clarification in light of the community’s present suffering (2:5–18). The description of Christ as the one who was “like his brothers in every respect” (2:17) anticipates the claim in 4:15 that he “was tempted in every respect.” The author introduces the Son as the exalted high priest in 2:17 and develops that theme in 4:14–10:31. He indicates the dire consequences of rejecting God’s ultimate word (2:1–4; 3:12–19; 4:12–13) and develops that theme throughout the homily (5:11–6:20; 10:26–31). His recollection of examples of unfaithfulness by Israel’s ancestors (3:7–4:11) anticipates his summary of examples of faithfulness in chapter 11. 4:14–10:31. Since 4:14–10:31 develops the themes announced in 1:5–4:13, it conforms to what the rhetorical handbooks called the probatio, the major argument. The transitional exhortation in 4:14–16 is the propositio, introducing the main argument. The author develops in greater detail the themes of Christ’s humanity and his path from suffering to triumph (4:14–5:10) as well as the exalted high priesthood (7:1–10:18), drawing the paraenetic consequences (5:11–6:20; 10:19–31). The “word” that is “hard to explain” (5:11) describes the sacrificial event that transcends earthly existence, guaranteeing the future and providing a reality to which the faltering community can hold firmly. Thus the author has built the case by the recycling of themes, employing the rhetorical device of synkrisis to compare the heavenly priesthood, sanctuary, and sacrifice with their earthly counterparts. As the inclusio of 4:14–16 and 10:19–25 indicates, this section is not meant as a polemic against a false teaching but is intended to demonstrate that the community’s confession is firm and that the community can “hold on” (4:14; 6:19; 10:23). The sacrifice of Christ is the guarantee of God’s covenantal promise. The central section elaborates on the purification for sins brought by Christ (cf. 1:3; 2:17–18), reassuring the community of the certainty of its confession. The guarantee of God’s saving work provides access to God and the stability to persevere. 10:32–13:25. Having built his case for the superiority of the Christian confession to all alternatives, the author now reaches the climax of the homily, calling for the community to respond faithfully to the work of Christ in the heavenly sanctuary. The author builds on the previous two sections to show their relevance for his readers. The author’s memory of the faithfulness of Jesus (2:17; 18 Thompson_Hebrews_JDE_djm.indd 36 10/10/08 10:23:59 AM â•… The Literary Puzzle: Genre and Structure 3:1–6) and the unfaithfulness of the ancestors (3:19; 4:2; cf. 4:11) in a time of testing corresponds to 10:32–12:11, in which the author exhorts the readers to be faithful (10:32–39; 12:4–11), recalls the faithfulness of the fathers in times of trial (chap. 11), and describes the faithfulness of Jesus (12:1–3). Similarly, the opening and concluding sections correspond in significant ways; the theme of God’s speaking to the people provides the frame for the argument. The author’s opening statement that “God has spoken in a Son” (1:2) and the call to pay attention to “what we have heard” (2:1) anticipate the author’s “see that you do not refuse the one who is speaking” (12:25, recapitulating 1:1–4; 2:1–4; 4:12–13) and the reference to the “word of exhortation” (13:22), providing a frame for the entire letter. Those who hear the divine voice live obediently in the present (13:1–6) and follow the pioneer outside the camp, faithfully enduring abuse with him. The author recapitulates earlier ethical reflections (6:10–12) and the theme of following the pioneer (2:10) on the path of suffering. With its summary of the preceding argument and emotional intensity, the final section, therefore, conforms to the Aristotelian understanding of the peroratio, while the first two sections are the narratio (1:5–4:13) and the probatio (4:14–10:31), amplifying the An Outline of Hebrews Hearing God’s word with faithful endurance (1:1–4:13) Exordium: Encountering God’s ultimate word (1:1–4) Narratio: Hearing God’s word with faithful en durance (1:5–4:13) Paying attention to God’s word (1:5–2:4) The community’s present suffering (2:5–18) Hearing God’s voice today (3:1–4:13) Probatio: Discovering certainty and confidence in the word for the mature (4:14–10:31) Drawing near and holding firmly: following the path of Jesus from suffering to triumph (4:14–5:10) Preparing to hear the word that is hard to ex plain (5:11–6:20) Grasping the anchor in the word for the ma ture: the sacrificial work of Christ as the assur ance of God’s promises (7:1–10:18) The priesthood of Melchizedek as the anchor of the soul (7:1–28) The sacrificial work of Christ as the assurance of God’s promises (8:1–13) The ultimate sacrifice in the heavenly sanctuary (9:1–10:18) Drawing near and holding firmly in an un wavering faith (10:19–31) Peroratio: On not refusing the one who is speaking (10:32–13:25) Enduring in hope: the faithfulness of Jesus and the faithfulness of the ancestors (10:32–12:13) Remembering the faithfulness of earlier days (10:32–39) Remembering the faithful heroes of the past (11:1–12:3) Enduring faithfully in the midst of suffering (12:4–13) Listening to the one who is speaking from heaven (12:14–29) Bearing with the word of exhortation (13:1–25) 19 Thompson_Hebrews_JDE_djm.indd 37 10/10/08 10:24:00 AM Introduction author’s opening words. With this rhetorical structure, the author confronts the discouragement of his community with a call to persevere. Because the author lives between cultures, he has adopted elements from the Jewish homily and from Greco-Roman rhetoric. The ultimate test of structural analyses is the extent to which they illuminate the author’s essential purpose. With this structural analysis we note that Hebrews is indeed a “word of exhortation,” for the expositions lay the foundation for the exhortations. The center of gravity for Hebrews is not the exposition of the high priestly work of Christ but the call to endure articulated in the final section. The expositions serve to reestablish the community’s symbolic world, and the emphasis on God’s word indicates the seriousness with which the community should respond to God’s word. The homily’s central message becomes evident in the accompanying outline. The Purpose of Hebrews As the alternation between exposition and exhortation indicates, the purpose of Hebrews is to reorient a community that has been disoriented by the chasm between the Christian confession of triumph and the reality of suffering that it has experienced. The centerpiece of the author’s persuasive effort is the claim that “God has spoken in these last days by a Son,” which he announces in the opening line (1:1–2a) and amplifies throughout the homily (cf. 2:1–4; 3:6, 7–14; 4:2, 12–13; 5:11–6:3, 13–20; 12:18–29). The Son’s coming to earth, death, and exaltation are God’s ultimate word (cf. 12:24–25) to the community. As the elaboration on this theme in 4:14–10:31 indicates, this event is God’s word of promise, the basis for the hope that is the “firm and steadfast anchor of the soul” (6:19), the confidence to draw near to God (4:16; 10:19), and the guarantee (7:22) of God’s covenant. God’s speech is both a promise and a summons “not to refuse the one who is speaking” (12:25). Thus the community that is the beneficiary of the certainty of God’s ultimate promise can now live with the apparent uncertainty of its own situation, knowing that God’s ultimate word is the guarantee of the future. The author’s frequent comparisons are not intended to engage in a polemic against Judaism or other competitors but to provide certainty for a wavering community and to rebuild their shattered world in order to ensure that they maintain their endurance. The theological sections indicate that the Christian experience is not only better than Levitical cultic practices but also superior to any alternative to the work of Christ. For people whose own world is shattered by disappointment and alienation from the world around them, the author offers an alternative reality that does not belong to the material world and is superior to the values of the dominant culture. In the examples of the faithful people—including Jesus himself—who endured shame and alienation because 20 Thompson_Hebrews_JDE_djm.indd 38 10/10/08 10:24:00 AM â•… The Story World of Hebrews they could see what was invisible to the rest of the world (11:27), the author indicates that their suffering is not a misfortune but a sign that they have a place to belong among the people of God. While the readers may be a small minority in this world, they have a new family in the community of faith that shares their confidence in the alternative reality, providing support to them in time of need. Believers can live as strangers without seeing the ultimate triumph of God if they are able to see beyond the realities of this world. The Story World of Hebrews The community’s own narrative, as we have seen above, involves the dissonance between its confession and the reality that it experiences. At the beginning the community learned the confession that the Son is at God’s right hand, but it now lives within the sphere of alienation and testing and does not see “everything in subjection” to Christ (2:8). The author responds by reminding the community of its confession and placing its experience within all of reality. In order to make his case, the author moves from the known to the unknown, appealing to traditions that the community shares and reminding them of their original confession (cf. 3:1; 4:14; 10:23), the common ground on which he builds his argument. This confession is consistent with early Christian traditions reflected in other NT witnesses. From early Christian tradition, the author and the community have received the confession that Jesus is the Son who has come “in these last days” (1:2), lived a sinless life (4:15; cf. 2€Cor 5:21), died on the cross to take away sins (1:3), was exalted to God’s right hand (1:3, 13; 8:1), and will return (9:28). He has inherited an exegetical tradition, according to which Ps 110:1 and Ps 2:7 are interpreted in christological terms and linked with Ps 8 to describe the exalted Christ at God’s right hand (1:5, 13; 2:6–8; cf. 1€Cor 15:25–27; Eph 1:20–23). In continuity with other NT writers, the author confirms the Christian claims with an appeal to the OT, describing the readers as the heirs of Israel who hear God’s voice through scripture. He assumes the biblical narrative that includes creation (1:1–3; 11:3), humanity’s condition under the power of sin and death (cf. 2:14–15), and hope for a coming age (cf. 6:5) of a new covenant when God would “remember their sins no more” (8:12; cf. Jer 31:34). He also shares the prophetic hope for the consummation of the narrative when God will shake the heavens and the earth (12:26–27). The author places the community within the story world of the Hebrew scriptures, indicating that they have experienced that for which Israel had hoped: the coming of the “last days” (1:2), the “powers of the coming age” (6:5), and the “new covenant” (8:7–13; 10:15–17; cf. 9:15–22). In contrast to God’s ultimate revelation, Israel’s means of atonement were a mere “shadow of the coming good things” (10:1), destined to be replaced. “Another priest” 21 Thompson_Hebrews_JDE_djm.indd 39 10/10/08 10:24:00 AM Introduction has replaced the Levitical high priesthood (7:11); the new covenant has rendered the old one obsolete (8:13); and the once-for-all sacrifice of Christ has replaced the sacrifices of the old covenant (10:1–10). As participants in Israel’s story, the community now lives between the coming of the last days (1:2) and the ultimate “day” (10:25) when Christ returns (9:27–28). He holds before the community the promise of (4:1; 6:12, 15, 17; 10:36; cf. 10:23; 12:26) and hope for (3:6; 6:11; 10:23) the reward that God once gave to the patriarchs. Indeed, the promised land that Israel did not enter is now available to the readers (cf. 4:9), and Israel’s ancestors wait for the church to complete its course faithfully (11:40). Like other NT witnesses, the author shares the apocalyptic understanding that anticipates the end of the narrative and awaits the consummation of history. Thus the apocalyptic dimension of Hebrews is an undeniable part of the author’s mental furniture. Inasmuch as the community’s original confession interpreted the coming of Christ in eschatological terms, one can assume that the author’s community had already placed its confession within the framework of Israel’s eschatological hope. Because other dimensions of the story world of Hebrews are unique to the author, scholars have searched for the background that would have made his reflections intelligible. For example, the author’s interest in the obscure figure of Melchizedek has analogies in the Dead Sea Scrolls (11Q Melchizedek) and in some strands of Judaism (2€Enoch). The author’s metaphorical world of entering behind the cosmic curtain (6:19–20; 10:19) to draw near to God in the heavenly world belongs to another stream of Judaism. Ernst Käsemann argued in The Wandering People of God (1984; first published in German in 1938, and probably the most influential book on Hebrews in the twentieth century) that this imagery, along with the motif of being on the way to a homeland opened up by the forerunner (cf. 2:10; 6:20), is rooted in gnostic Apocalyptic Literature Apocalyptic literature, derived from the Greek apokalypsis, meaning “disclosure” or “unveiling,” describes a heavenly or future reality revealed to humanity via divine messengers, dreams, or visions. Works of this kind were produced by a number of Jewish groups before and during the era of the New Testament, which shares a number of the characteristics of apocalyptic literature (see especially Revelation). Central to the apocalyptic worldview is the conviction that the world is presently in the final throes of rebellion against God, a situation that will be remedied in the near future when God intervenes dramatically to transform the world, punish the ungodly, vindicate the righteous, and establish his kingdom on earth. Most ancient apocalypses were written under the names of prominent people of the distant past (e.g., Enoch, Baruch, Ezra). 22 Thompson_Hebrews_JDE_djm.indd 40 10/10/08 10:24:00 AM â•… The Story World of Hebrews speculations. Käsemann’s most important contribution was his identification of the pervasive theme of pilgrimage throughout Hebrews; his claim for a gnostic background is more problematic. Otfried Hofius (1970b) offered alternative suggestions for the background of this central theme in Jewish apocalyptic texts. Furthermore, the discoveries of the gnostic texts at Nag Hammadi have not supported Käsemann’s view. The author’s reflections extend beyond the linear history of Israel’s story, for he places these events on a larger canvas that includes all of reality. With the claim that the Son is at God’s right hand, the author consistently demonstrates that Christian experience is the culmination of Israel’s experience in time and sets out its ontological superiority. The author not only contrasts the old with the new; he claims that the new is ontologically superior to the old because it belongs to the transcendent world. The author’s focus is evident in his use of comparisons, for what is “better” is ontologically superior to the object of comparison. The Son is better than angels (1:3–4, 13) because he is exalted above them. He is superior to earthly high priests (chap. 7) because only he is exalted. Consequently, the exalted high priest abides forever (cf. 1:10–12; 7:3, 24), in contrast to angels (1:7) and the Levitical priests (cf. 7:16, 23–24). Similarly, the contrast between the heavenly and the earthly dominates the author’s description of the sacrifice of Christ. Christ is the minister in the “true tent” (8:2) rather than the “copy” and “shadow” (8:5). Levitical priests serve in an “earthly” sanctuary (9:1) “made by hands” (9:11) whereas Christ entered “the greater and more perfect tent” (9:11). The author associates Christian experience with those things that are invisible (11:1, 27), “not made with hands” (9:11), and “cannot be touched” (12:18), in contrast to the experience of Israel, whose institutions and leaders belonged to this creation. The author’s appeal to metaphysics is one of the dimensions of the mystery of Hebrews, for the irony is that the book most rooted in scripture uses the vocabulary of Hellenistic philosophy more than any other NT document. The distinction between the “true tent” and the copy echoes the language of Plato (Rep. 514–17) and his heirs. The distinction between the abiding transcendent world (1:10–12; 7:3, 24; 10:34; 12:27–28) and the transitory world also echoes the categories of Platonism (cf. Plato, Tim. 28–30). Moreover, the author’s distinction between the one and the many (7:23–25; 10:1–14) would have been intelligible to one who had been shaped in the Platonic tradition, which distinguished the transcendent and eternal “One” from the earthly and mortal “many.” Since the seventeenth century, scholars have noticed the affinities between the argument of Hebrews and the biblical expositions of Philo of Alexandria (ca. 20 BC–AD 50), who consistently employed Platonic categories in his interpretation of the OT, maintaining that the Greek sages were indebted to the Pentateuch for their wisdom (Spec. Laws 4.61; Alleg. Interp. 1.108; Heir 23 Thompson_Hebrews_JDE_djm.indd 41 10/10/08 10:24:01 AM Introduction Plato Plato (427–347 bc) was born into an aristocratic family but abandoned politics for philosophy after meeting Socrates. He produced twenty-seven works in dialogue form. Central to Platonic philosophy as it was understood in the first century was the distinction between the heavenly world of “archetypes,” which are unique, unchanging, and eternal, and the mundane world of “types,” which are multiple, subject to change, and temporary. Only the heavenly, ideal world is ultimately real. 214). Philo and Hebrews share not only the insistence of the two levels of reality derived from the Platonic tradition; they also cite numerous passages (e.g., Gen 2:2; Exod 25:40; Josh 1:5; Prov 3:11–14) in ways found only in their writings (Runia 1993, 76). By far the most remarkable parallel is the way Heb 13:5 splices together Josh 1:5; Deut 31:8; and possibly Gen 28:15 in the same way that Philo does (Confusion 66; Schenck 2005, 81). Furthermore, as Spicq (1952, 1:39–91) has shown, the two writers share a common vocabulary, mode of exegesis, and major themes. Philo’s description of the logos employs vocabulary that resembles the christological language of Heb 1:1–4 (cf. Creation 146; Cherubim 127; Worse 83). The two writers employ similar arguments to indicate the ineffectiveness of Levitical sacrifices (Heb 9:1–10; 10:1–18; Moses 2.107; Spec. Laws 1.257–261). Both Philo and the author of Hebrews present lists of examples (Heb 11; Philo, Virtues 198–225). Despite the numerous parallels, there is insufficient evidence that the author of Hebrews was actually dependent on Philo. The two writers undoubtedly belonged to the circle of educated people schooled in both the LXX and Greek rhetoric and philosophy. The author is only a representative of many in the NT era who appropriated the categories of Platonism and Stoicism to explain the faith. Indeed, Philo is one of the major witnesses to the Middle Platonism of the period. He shares much in common with Plutarch (ca. AD 45–125) and other Middle Platonists who also employed philosophy to interpret inherited religious traditions. Both the author and Philo share with Middle Platonists a focus on the ontological distinction between the transcendent and the phenomenal world. For Middle Platonists, as for Hebrews, the individual “sees the invisible” (Heb 11:1, 27; Philo, Unchangeable 3; Posterity 15) but lives on earth as a stranger (Philo, Cherubim 120–121; Dreams 1.46). The individual searches for and finds stability only through access to the transcendent world. The major debate in scholarship on Hebrews has been the determination of the author’s intellectual worldview. We need not choose one over the other, as if the Jewish and Greek worlds existed in isolation from each other. The author lives between the world of scripture and that of Greek philosophy. 24 Thompson_Hebrews_JDE_djm.indd 42 10/10/08 10:24:01 AM â•… The Story World of Hebrews Philo of Alexandria and the Logos Philo, who lived between approximately 30 BC and AD 50, was a leader of the Jewish community in Alexandria. Like other young men of the Jewish aristocracy, he received a comprehensive Greek education. He maintained his Jewish identity by keeping the laws, but he sought a philosophical interpretation of Jewish ceremonies, interpreting the laws allegorically with the philosophical categories derived primarily from Middle Platonism. He produced a large body of literature, composed primarily of commentaries on the Pentateuch. Philo’s combination of Jewish and Greek wisdom is evident in his elaborate logos speculation. Logos has a wide semantic range: word, thought, speech, meaning, reason, proportion, principle, standard, or logic. In Stoic philosophy, the logos was universal reason, governing and permeating the world. Some Jews and, later, Christians saw Greek philosophical speculation about the logos as compatible with their traditional understanding of the creative and governing function of God’s “word.” For Philo the logos is the head of all creatures, neither created not uncreated, but rather the creative word and mediator between God and creation. Logos functions similarly to “Christ” in Hebrews: the founder and sustainer of all things, the ultimate intermediary between God and humankind, and the exact representation of God to humanity. His logos speculation also offers a significant parallel to other New Testament claims that God created the world through the word (John 1:1–3) and that Jesus Christ is God’s agent in creation (Heb 1:3; Col 1:15–20). He is one among many early Jewish and Christian writers who struggled to describe their faith in the language of philosophy. His Christian confession that “God has spoken to us in these last days” through a crucified savior is irreconcilable with Platonism. Since his task is to be not a systematic theologian but a pastor encouraging his audience to hold fast to its confession, he uses Platonic categories in his claim that, although believers do not “see” the world in subjection, faithful people see the invisible. In this heavenly world of the exaltation, Christ has completed his work and now abides forever while Christians are strangers on the way to the transcendent reality. Like Clement of Alexandria, Origen, and other early Christian writers, he affirmed Christian convictions that could not be reconciled with Platonism while employing Platonic categories to interpret Christian existence. Thus while the author is not a consistent Platonist, he employs categories that were probably known to educated people throughout the ancient world. The Platonic distinction between the transcendent/eternal and the earthly/ mortal could be easily incorporated into the biblical faith to provide the vocabulary for instructing believers that they should place their trust not in visible realities but in that which is beyond their perception. Christians 25 Thompson_Hebrews_JDE_djm.indd 43 10/10/08 10:24:02 AM Introduction Middle Platonism Middle Platonists combined aspects of Stoic and Platonic thought. According to Middle Platonists, all of reality may be divided into the two realms of the intelligible and the perceptible world. The former is characterized by “being,” while the latter is characterized by “becoming.” True “being” in the intelligible world exists in timeless eternity while the perceptible world is subject to constant “becoming.” Consistent with this dualism, Middle Platonists distinguish between the One, which transcends the universe, and the Indefinite Dyad, the principle of duality, which is infinitely divisible. The One belongs to the intelligible world, while the latter can be seen throughout nature. For the author and for Middle Platonists, the “better” reality belongs to the transcendent world. have access to this world, which is invisible, unshakable, untouchable, and not of this creation. These arguments, which the author apparently expected to be convincing to his addressees, who did not “see the world in subjection to Christ,” form the basis for his exhortation to hold fast. Thus the author places his readers within the sphere of totality in order that they “hold fast” to their possession. The assumptions of Middle Platonism provide him with a useful means to develop his argument, pointing his readers to the reality beyond what they see. Those who possess the invisible, eternal reality can have the courage to withstand the visible and temporary time of wandering through the wilderness. Encountering Hebrews Today Ghanaian theologian Kwame Bediako (2000) remarks, “Hebrews is our epistle” because its claim that the priestly work of Christ ends all sacrifices challenges a society that turns to tribal and national priests (28) to meet human needs. Those themes that resonate with Africans, however, are largely foreign to the people of Europe and North America, who have no experience with animal sacrifices. Moreover, the cosmology of Hebrews, with its overtones from Jewish apocalyptic thought and Middle Platonism, are remote for the modern reader. Thus the sustained argument over obscure themes makes Hebrews a particular challenge for many modern readers. Hebrews is not likely to resonate with readers who, like older interpreters, regard the book as a theological polemic against Judaism. However, readers who observe the pastoral and rhetorical dimensions of the homily may recognize the continuity between the original audience and many communities today and discover that “Hebrews is our epistle” as well. The author’s invitation to “bear with this word of exhortation” (13:22), despite the extended argument 26 Thompson_Hebrews_JDE_djm.indd 44 10/10/08 10:24:02 AM â•… Encountering Hebrews Today that is “hard to explain” (5:11), is also an invitation to contemporary readers to hear this homily just as the author invited his original listeners to hear the words of scripture once more. If the point of contact for the African reader is the claim that the sacrifice of Jesus ends all sacrifices, the point of contact for other readers may be continuity between the situation of ancient and modern readers. Hebrews speaks to communities experiencing marginalization from the larger society, declining numbers, and cognitive dissonance between their Christian confession and the reality of actual experience. Those who face the problems of church renewal in a changing world may find in Hebrews a model for addressing these challenges. The theological sections of Hebrews invite readers to see beyond the immediate context of suffering and marginalization and to recognize their place within the reality that is not limited by time and space. In his use of Platonic language to describe the tabernacle, the author challenges his readers to envision a world that is unchanging, which will be an anchor for those who live in insecurity. The author also invites readers to inhabit the world of scripture and to recognize their place in a larger narrative that begins with creation and ends with the fulfillment of God’s promises. The community is the culmination of a long line of witnesses who confronted insecurity and homelessness by finding their security in another world (11:40). By locating the readers within an alternative world, the author motivates readers to remain faithful. In acknowledging that “we do not see everything in subjection to him” (2:8), the author offers a distinctive understanding of faith, acknowledging that faithfulness involves living between the claims about the alternative world and the reality of experience. He offers no gospel of success complete with constant assurances of the benefits of believing, but depicts faith as the equivalent of endurance (10:36–39) in the midst of difficult tests. Indeed, only the author of Hebrews offers a Christology that portrays Jesus in unmistakable terms as the model of faith in the midst of testing (2:10–18). To have faith, therefore, is to endure for an indefinite period of time, even when one does not see the fulfillment of the promises (cf. 11:39). The imagery of Jesus as the leader through the wilderness on the way to the promised land (2:10; 3:7–4:11) indicates that faith involves enduring the tests that accompany the Christian community’s marginalized existence, joining the predecessors who accepted this insecurity because they found their security in “things not seen.” Undoubtedly, the reason that an anonymous homily of the first century was preserved, despite the mystery surrounding it, is that it continued to address the needs of Christians in changing circumstances. Käsemann wrote the first draft of The Wandering People of God from a German prison in 1937. At a time when Christian leaders who challenged the policies of the Third Reich were persecuted, Käsemann found in the image of Christians wandering without a homeland an appropriate description of their place in a world 27 Thompson_Hebrews_JDE_djm.indd 45 10/10/08 10:24:02 AM Introduction hostile to Christian faith. He wrote this important book not only to break new ground in the interpretation of Hebrews but also to challenge Christians who had made peace with the policies of the Third Reich to recognize that authentic discipleship involves following Jesus through the path of suffering toward the goal: “By describing the church as the new people of God on its wandering through the wilderness, following the Pioneer and Perfecter of faith, I of course had in mind the radical Confessing Church which resisted the tyranny in Germany, and which had to be summoned to patience so that it could continue its way through endless wastes” (Käsemann 1982, 1:17, as cited in Käsemann 1984, 13). As the Christian church becomes a minority voice in Europe and North America, this homily offers encouragement to those whose faith has made them strangers in their own land. 28 Thompson_Hebrews_JDE_djm.indd 46 10/10/08 10:24:03 AM P a r t 1 Hebrews 1:1–4:13 Hearing God’s Word with Faithful Endurance With the inclusio that binds together the first major section of Hebrews, the author focuses the attention on God’s word. “God .€.€. has spoken in a Son” (1:2); God’s word is “living and active, sharper than any two edged sword” (4:12). To say that God has spoken through a Son who is above the cosmos (1:3–4) is to recognize that this message is no ordinary word. It is the offer of a “great salvation” (2:2–3) and the promise (4:1) that the people of God will reach the ultimate place of rest (4:9). The author maintains the theme of God’s speech throughout the homily, finally reminding the community of the blood “that speaks better than the blood of Abel” (12:24). As the author begins this “word of exhortation” (13:22), the audience has not yet reached the promised land. Like their predecessors in ancient Israel they wander through the wilderness, and the promise appears more distant than ever. Consequently, their destiny rests on their willingness to “pay attention” (2:1), recognizing that they have reached the urgent moment when God speaks to them, “Today, if you hear his voice, do not harden your hearts” (3:7–8a). As ancient Israel learned, God’s promise of salvation is also the oath that declares, “They shall never enter my rest” (3:11), to those who refuse to listen. Thus God’s word is both the promise of salvation and the two-edged sword of judgment (März 1991, 263). Because “God has spoken to us in a Son” (1:2), “we 29 Thompson_Hebrews_JDE_djm.indd 47 10/10/08 10:24:03 AM Hebrews 1:1–4:13 Hebrews 1:1–4:13 in Context $Hearing God’s word with faith- ful endurance (1:1–4:13) Exordium: Encountering God’s ultimate word (1:1–4) Narratio: Hearing God’s word with faithful endurance (1:5–4:13) Paying attention to God’s word (1:5–2:4) The community’s present suffering (2:5–18) Hearing God’s voice today (3:1–4:13) Probatio: Discovering certainty and confidence in the word for the mature (4:14–10:31) Peroratio: On not refusing the one who is speaking (10:32–13:25) must give an account” (literally “to whom is our word,” 4:13). Only those who listen and demonstrate faithful endurance through the unpleasant conditions of the wilderness will enter the promised land. Part 1 of Hebrews sets the stage for the rest of the homily. The author maintains the wilderness setting, describing his listeners as the people on the move toward the promised land. He introduces the theme of Jesus as the pioneer (2:10) who leads the way and consistently invites readers to follow where Jesus has gone (4:14–16; 10:19–23; 12:1–2). He insists that readers endure faithfully, even when they have not received the promises (3:1–4:13; 10:32–12:13). Thus the urgent situation demands that the people hear the voice of the God who has spoken. 30 Thompson_Hebrews_JDE_djm.indd 48 10/10/08 10:24:03 AM Hebrews 1:1–4 Encountering God’s Ultimate Word Introductory Matters Hebrews begins with an elegant style that is without parallel in the NT. Although it has an epistolary ending (cf. 13:18–25), it begins not with the traditional epistolary form but with a carefully structured combination of clauses in 1:1–4 (one sentence in Greek) that ancient writers called a period (periodos), literally a “way around” (peri + hodos), that organizes several clauses into a well-rounded unity. This elegant style, which is rare in the NT but common in Hebrews (cf. 2:2–4; 4:12–13; 7:1–3, 26–28; 12:18–24), reflects the author’s gift for language. The literary quality of the book is evident also in the use of alliteration, with five words in verse 1 beginning with the letter p (polymerōs kai polytropōs palai .€.€. patrasin .€.€. prophētais). Figure 1. The Opening of Hebrews in an Ancient Manuscript. Codex Alexandrinus is a fifth-century manuscript of the Greek Bible. The photograph shows the beginning of Hebrews at the top of the second column of folio 139 recto. 31 Thompson_Hebrews_JDE_djm.indd 49 10/10/08 10:24:13 AM Hebrews 1:1–4 Alliteration, especially using the letter p, was also a common device at the beginning of a speech or literary work (cf. Homer, Od. 1.1–4, polytropon .€.€. polla .€.€. pollōn; Luke 1:1, polloi .€.€. peri .€.€. peplērophorēmenōn .€.€. pragmatōn). Like ancient orators, the author has artfully developed the opening words of his sermon, knowing that the beginning of the speech, known as the exordium, is the most critical part of the message (cf. Berger 1977, 19). Hebrews 1:1–4 conforms to the classical understanding of the exordium, establishing the expectations of the readers and preparing the way for the message that follows. The author crafts an artful periodic sentence in place of the customary epistolary introduction in order to prepare the audience for the distinctive form of address that will follow. The opening words in 1:1–2a introduce the theme of God’s speech, which the author later develops (cf. 4:12–13; 5:11; 12:24–25). The “purification for sins” in 1:3c anticipates the theme that the author develops in 9:1–10:18 (cf. 9:14, 22, 23; 10:2), indicating that the Levitical sacrifices provide the lens for the interpretation of the death of Christ. According to Exod 30:10, the Day of Atonement effected purification: “Aaron shall make atonement once a year upon its horns (of the altar); from the blood of the purification for sins of atonement he shall purify it once a year.” According to Lev 16:30, the sacrifice of the Day of Atonement purifies the people from sins. The claim that the Son has been exalted to God’s right hand is a pervasive theme in Hebrews (cf. 1:13; 8:1; 10:12). The declaration that God has spoken in the past and “in these last days” anticipates the homily’s consistent references to God’s speech in the past and in the present (cf. 2:1–4; 4:12–13; 12:25–29). Capturing the Audience’s Attention Ancient rhetoricians taught that the opening words of an address should introduce the topic and make the audience favorably disposed and attentive. According to the anonymous Rhetorica ad Herennium: “We shall have attentive hearers by promising to discuss something important, new and unusual matters, or such as appertain to the commonwealth, or to the hearers themselves, or to the worship of the immortal gods; . . . and by enumerating the points we are going to discuss.” (1.4.7, trans. Caplan 1954). In terms of style, the periodic sentence was a favorite way to begin a speech (Quintilian, Inst. 9.4.128; Lausberg 1998, 947), for it was an appropriate means to demonstrate that the subject matter was of global importance (Lausberg 1998, 270) and awaken the interest of an audience that was either indifferent to the topic or distracted by other issues. 32 Thompson_Hebrews_JDE_djm.indd 50 10/10/08 10:24:14 AM â•… Introductory Matters The note of continuity and discontinuity between God’s speech to the fathers and in a Son (1:1–2a) anticipates the comparison between the institutions of the old and the new covenant throughout the homily. Thus the author follows common rhetorical practice by providing a table of contents in the opening words of the homily. The rhythmic praise of the Son has suggested to numerous scholars that 1:1–4 contains a hymn, in whole or in part. Indeed, comparison with other NT passages that are widely recognized as hymns reveals numerous parallels with 1:1–4. Like Heb 1:1–4, NT hymns have a christological focus, commonly describing the Son’s role in creating and sustaining the universe (cf. Col 1:16–17), descent to earth, ascent to heaven, and adoration by heavenly beings (cf. Phil 2:6–11; 1€Tim 3:16; also 1€Pet 3:22). The titles describing the Son’s eternal nature (i.e., “radiance of his glory,” “exact representation of his being”) resemble early Christian hymns, which describe Christ as the “form” (Phil 2:6) or “image” (Col 1:15) of God. The fact that these titles are used nowhere else in Hebrews has also suggested that the author is citing the words of a hymn. In addition, the parallelism and the relative clauses introduced by “who(m)” are also common features of NT hymns that are found in Hebrews. Consequently, Günther Bornkamm (1963, 198) has suggested that the prologue of Hebrews is a hymn. His view is widely accepted among scholars (e.g., Deichgräber 1967, 367; Hengel 1983, 84; Hofius 1991, 80). These elements are not, however, sufficient evidence that the author is quoting a hymn. Indeed, most of the writers who identify the prologue of Hebrews as a hymn have difficulty demarcating the hymnic material from the surrounding prose. The introduction of major themes in 1:1–2a and 1:3b–4 indicates that the exordium is deeply rooted in the author’s own message. The author’s use of the periodic sentence at critical transition points throughout the homily suggests that he is not quoting a hymn (cf. 2:1–4; 4:12–13; 7:26–28). Indeed, the correspondence between the periodic sentence here and the one in 12:18–24 suggests that he has crafted this introduction to move the audience toward his goal. Only in the present participial phrases “[being] the radiance of his glory and exact representation of his being” and “bearing all things with his powerful word” (1:3a–b) is the language noticeably different from the author’s description of the Son and reminiscent of NT hymns. Although these descriptions are parallel in content to the NT hymns, the author’s terminology has no parallel in the NT, which nowhere else describes the Son as the “radiance of God’s glory” or the “exact representation of his being.” The author of Hebrews could have appropriated these terms from wisdom literature and Philo, where they are widely used. Whereas 1:1–2a and 1:3b–4 summarize God’s revelation of the Son within history (“in these last days,” “having made purification for sins”), 1:2b–3a describes the Son’s relationship to the cosmos in a series of relative clauses, 33 Thompson_Hebrews_JDE_djm.indd 51 10/10/08 10:24:14 AM Hebrews 1:1–4 Wisdom Literature Wisdom literature is a genre of literature common in the ancient Near East typified by praise of God, often in poetic form, and sayings of wisdom intended to instruct about God and wise living (e. g., Psalms and Proverbs) or to reflect on the mysteries of life and death (Job and Ecclesiastes). In the apocryphal or deuterocanonical books, it designates Sirach and the Wisdom of Solomon. In this literature, wisdom is often depicted anthropomorphically: Wisdom “speaks” to the readers, pleading for them to live wisely. The designation “wisdom literature” is based on the fact that more than half of the references to wisdom are found in Proverbs, Ecclesiastes, and Job. The Greek word sophia appears more than one hundred times in Sirach and the Wisdom of Solomon. Occasionally, personified Wisdom is depicted as God’s agent in creating and governing the world (Prov 8). The portrayals of Christ in John 1:1–14; Col 1:15–20; and Heb 1:1–4 resonate with images drawn from personified Wisdom. all in the present tense, that echo Hellenistic reflection about Wisdom and the logos as mediators between God and the world. “All things” is a common designation for the totality of the universe (cf. John 1:3; Rom 11:36; 1€Cor 8:6; Heb 2:10) in Hellenistic philosophy that was adopted in the literature of Hellenistic Judaism (cf. Philo, Spec. Laws 1.208; Heir 36). God made his firstborn Son (cf. 1:6) “heir” of all things, fulfilling the promise to David that he would receive the nations as an “inheritance” (Ps 2:8; Koester 2001, 178). “Through whom he made the worlds” echoes NT affirmations about the Son’s role in creation (cf. John 1:1–3; 1€Cor 8:6) and is reminiscent of the claims in Helle
https://pl.b-ok.org/book/2378026/9772f3?dsource=recommend
CC-MAIN-2020-10
refinedweb
16,662
51.28
- Code: Select all import random import turtle class Derpi(object): HP = 10 Attack = 5 class Dooey(object): HP = 10 Attack = 6 DerpiMoves = ['Derp','Shine'] #These are the moves for Derpi. DooeyMoves = ['Glop','Shine'] #And the moves for Dooey. DerplyMoves = ['Derp','Shine','Slug'] DoopeyMoves = ['Glop','Cry','Power Glop'] DerpliKingMoves = ['Power Derp','Glare','Slug','Suck'] Dooperly = ['Power Glop','Cry','Slug','Suck'] print ('Hello there! I am Proffesor Briggensburg!') print ('Who might you be?') myName=input('Input your name : ') print ('It\'s very nice to meet you,' + myName) print ('Oh wait! You are ' + myName + ' from that school aren\'t you? I remember you now, but it was a long time ago. Yes, I can see the resemblance.') print ('Well then, meet me at my house. I live on Birk Street, across from you.') myOtter=input('Press ENTER to continue') print ('It is early afternoon, and you are coming to eat lunch.') print ('') print ('') myOtter=input('Press ENTER to continue') print ('Mom : ' + myName + ' have you met Prof. Briggensburg yet? He is giving out prizes for who can win his contest! You should join it!') myOtter=input('Press ENTER to continue') print ('') print ('You join the large crowd at the park, expecting not to win any prizes.') print ('Prof B : It\'s a great day to get out here and have some fun, don\'t you all think?') print ('Prof B : In fact, my grandson, umm? I can\'t remember his name! *Chuckles lightly* Well anyway, he is also competing here today. There he is now!') print ('Rob: Hey ' + myName + ' , don\'t you know his name? I wanna know it.') myKid=input('Enter his name : ') print ('Rob : Oh yeah! ' + myKid + ' was his name.') print ('You and Rob quickly share this information with others as the Prof chooses slips of paper in the raffle box.') myOtter=input('Press ENTER to continue') print ('Prof. B: And the winner is.......') myOtter=input('Press ENTER to continue') print ('Prof. B : ' + myName + ' and ' + myKid + '! What a lucky pair you are!') print ('Prof B : Choose which Derpmon you will battle with. There are two, as you can see. There is Derpi and there is Dooey. You two have been rivals ever since you were children!') derpmon = [] #This is the derpmon list. Remember 'append' to add stuff to it derpmonChoice = input("Select your DerpMon!:") if derpmonChoice == ('Derpi'): print('Prof. B : Congratulations, you recieved Derpi!') derpmon.append('Derpi') print('Your pokemon: ' + derpmonChoice) elif derpmonChoice == ('Dooey'): derpmon.append('Dooey') #This is where the Pokemon is added to the first list. derpmon = str(derpmon) print('Your pokemon: ' + derpmon) print ( "Prof B : Good choice, " + myName) else print ('Sorry, that is not not one of the derpmon!) derpmonChoice2 = input('Please choose again: ') if derpmonChoice2 == ('Derpi'): print('Congratulations! You recieved Derpi!') if derpmonChoice2 == ('Dooey'): print('Congratulations! You recieved Dooey!') if derpmonChoice == ('Derpi'): print (myKid + ' : Then I will choose Dooey!') if derpmonChoice == ('Dooey'): print (myKid + ' : Then I will choose Derpi!') print ('') print ('') battleStart=input('Press any key to start the battle!') #Rememember to copy this for each battle! You dont want to type this again and again! moves=['Attack','Defend','Run','Bag']
http://www.python-forum.org/viewtopic.php?f=26&t=12000
CC-MAIN-2016-44
refinedweb
513
70.8
NAME BUS_BIND_INTR, bus_bind_intr -- bind an interrupt resource to a specific CPU SYNOPSIS #include <sys/param.h> #include <sys/bus.h> int BUS_BIND_INTR(device_t dev, device_t child, struct resource *irq, int cpu); int bus_bind_intr(device_t dev, struct resource *irq, int cpu); DESCRIPTION The BUS_BIND_INTR() method allows an interrupt resource to be pinned to a specific CPU. The interrupt resource must have an interrupt handler attached via BUS_SETUP_INTR(9). The cpu parameter corresponds to the ID of a valid CPU in the system. Binding an interrupt restricts the cpuset(2) of any associated interrupt threads to only include the specified CPU. It may also direct the low-level interrupt handling of the interrupt to the specified CPU as well, but this behavior is platform-dependent. If the value NOCPU is used for cpu, then the interrupt will be ``unbound'' which restores any associated interrupt threads back to the default cpuset. Non-sleepable locks such as mutexes should not be held across calls to these functions. The bus_bind_intr() function is a simple wrapper around BUS_BIND_INTR(). Note that currently there is no attempt made to arbitrate between multiple bind requests for the same interrupt from either the same device or multiple devices. There is also no arbitration between interrupt binding requests submitted by userland via cpuset(2) and BUS_BIND_INTR(). The most recent binding request is the one that will be in effect. SEE ALSO BUS_SETUP_INTR(9), cpuset(2), device(9) HISTORY The BUS_BIND_INTR() method and bus_bind_intr() functions first appeared in FreeBSD 7.2.
http://manpages.ubuntu.com/manpages/oneiric/man9/BUS_BIND_INTR.9freebsd.html
CC-MAIN-2014-15
refinedweb
249
54.63
The official blog of the Microsoft SharePoint Product Group Recommended Reading for March and April (click here for previous recommendations). Lots of useful content (I can hardly keep up anymore!) and tools generated by the community: And a bunch of quality content developed or commissioned by Microsoft: <Lawrence /> If you would like to receive an email when updates are made to this post, please register here RSS You know what I would like to read in April 2007? A completed SharePoint SDK. Too bad such a thing doesn't exist. Four months after SharePoint went RTM, there are still hundreds upon hundreds of classes in the Microsoft.SharePoint and Office.Server namespaces which have NO DOCUMENTATION. When will the SharePoint documentation resemble a commercial software product, as opposed to an open-source hobby project? Wait, I take that back. Many open-source hobby projects are actually quite well documented. The current state of SharePoint documentation in MSDN is an embarrassment. You people should be ashamed of yourself. Daryl, you've complained previously about the shortcomings in our SDKs. Rest assured that we have heard and appreciated your feedback. Since we have limited resource, it would help us if you can be more specific about what classes for which you'd like to see more or at least some documentation. We also enabled the SDKs for community generated content, and I'm seeing a growing number of content contributions or links from the community. WSS 3.0 is a huge platform and MOSS 2007 is a huge product, so it will take time for us to document every nook and cranny. The best way you can help is to give us specific examples of content gaps (microsoft.sharepoint.* is too high level) that will help us prioritize our content queue and optimize our resources. Thank you. I have specific requirements for the documentation, and would appreciate some help in areas not documented yet. Can you address these questions?: Even if you could tell me database tables that correspond to these settings, that would be helpful. 1. How do I programatically set a site's time zone? I can only see how to the default time zone of a ssp. 2. How can I programatically schedule the following?: a. profile import - incremental and full UserProfileManager.UserProfileChangeJobSchedule seems to have no effect b. audience compilation c. search d. news item search 3 how do i programatically manage permissions of a ssp ie: the page"Shared Services Administration: ScholarisSharedServices > Manage Permissions" at I am having trouble understanding how the permissions on the page relate to a SPRoleDefinition's SPBasePermissions Permissions on the page: Create personal site Use personal features Manage user profiles Manage audiences Manage permissions Manage usage analytics SPBasePermissions: Am i missing something? Are the permission on the page "Site Groups"? Thanks in advance, Cameron calzoni Well, it's good to see that the SharePoint team is at least aware of the woeful state of documentation. Classes for which I'd like to see at least some documentation? The short answer is "All of them." This is a commercial software product. Microsoft owes its customers documentation. I don't think it ever occured to the .Net team to ask, "Which classes in the System namespace would you like us to document?" I don't think the ASP.Net team ever debated which classes in System.Web namespace they would document and which they would leave you to figure out yourself. Public class = public documentation. Simple as that. So before I list some really sore spots in the documentation, I want to be very clear that it's not a list of "what should be documented". I think I speak for the whole community of developers when I say, "everything should be documented." In the five months since SharePoint 3 went RTM, I've spent more time staring at ILDasm then the previous four years working as a .Net developer. Often the best way to figure out how these things work is to just look at what the code in Microsoft.SharePoint.dll does. If Microsoft isn't going to document SharePoint's API, could we at least get the developers to stop running Dotfuscator on the DLL's? That would save us some time. A lot of core functionality is completely undocumented. The Workflow web service has no documentation at all. Not one single word!! Go look for yourself:. Speaking of workflows, ~harsh mentioned that SharePoint had a 'hard limitation of 15 simultaneous workflows that can be run'. 15 running workflows? Per what? Per list item? 15 workflows associated with any one list? 15 simultaneously running instances of any one workflow? Or 15 simultaneously running workflows, site-wide? He never responded to questions. This is not a minor issue. I work in a Lotus Notes shop of about 90,000 employees. At any given time, our Notes servers might have several hundred thousand workflows in-flight. What exactly does this 15 number refer to?? Guys, Im guessing you got the message, great product, poor documentation. Moaning at this point is unlikely to help, so here are some areas I have hit and would like to see further documentation for: Web Services: Workflow User Profile User Profile Change >Series on Customizing Wiki Pages by Kit Kai (SharePoint >MVP) -- provides drilldown and walkthrough on how to >customize the page layout of the SharePoint wiki, so >you can implement a mini-Wikipedia for your intranet. No, he doesn't. In fact, he starts out by saying "I won't be sharing with you how to make Wiki work like wikipedia" Too bad, as that is the functionality I am trying to set up...
http://blogs.msdn.com/sharepoint/archive/2007/03/25/recommended-reading-for-march-and-april-2007.aspx
crawl-002
refinedweb
947
57.87
Details of our official return and cancellation policies are below. At a high level, our terms and policies can be summarized as: Important Note that return and refund policies differ depending on whether the item being returned was purchased as a regular or pre-order, or if it was received from making a pledge to a crowdfunding campaign. Items from a campaign pledge are refunded/replaced at the discretion of the creator. Regular or pre-orders are refunded by Crowd Supply. If you don’t understand the difference, please take a look at the Guide page on supporting campaigns. At the discretion of the product creator, items committed to backers as a result of a crowdfunding campaign may, or may not, be exchanged or refunded. The product creator is responsible for providing a good faith estimate of the product description, risks, and timeline for their projects. However, backers need to know that due to the uncertainties inherent in creating products during the early stage of development, changes to features, performance, and/or appearance may occur between when a project is originally presented and when it is produced. Reasons for this may include technology limitations, supply issues, or other factors outside of the developer’s control. Timelines may slip, and in rare instances a project that was funded may not be completed and delivered. Backers should only pledge to a creator’s project if they are comfortable accepting this risk. If a backer is dissatisfied with a product they should contact the project creator to express their concerns. For all items pre-ordered from the Crowd Supply Store, customers can cancel their order for a refund (less transaction fees, if applicable) at any time prior to product shipment. For all items purchased from stock in the Crowd Supply Store, customers are provided a 30-day satisfaction guarantee. Should any item fail to meet your expectations, simply return the item in new condition and we will gladly exchange it or issue a refund. If you’re not sure a product is going to work for you, we ask you please keep all packing materials for shipping, should you decide to return it. No return authorization number is necessary. Just ship your items back to us with a copy of your invoice or a printout of your confirmation email and a note indicating how you’d like us to handle the return (refund or exchange). Please include your daytime phone number in case we have any questions. Please send all returns to our fulfillment center address listed on the contact page.
https://www.crowdsupply.com/returns
CC-MAIN-2021-17
refinedweb
428
58.72
If you have several arrays, how can you randomly choose one of the several arrays? I'm currently doing a project relating to a music playlist and I need to be able to print the first letter of a specific artist and song for the user to guess however the artist and song must be random. I have made a separate array for each artist and song but I don't know how to randomly select one of these arrays for me to use. This is my code of arrays:"] How can I randomly choose one of these arrays? 1 answer - answered 2018-10-22 11:45 Corentin Limier random.choice() does the trick. import random random.choice((BTS,SWIFTY,RUTH,ED,ARIANA,DRAKE,RICKY,IU,BTS2,PSY)) You should use a dictionary, it will make your code easier to maintain if the number of tracks grows : musics = { "]} import random random.choice(list(musics.values()))
http://quabr.com/52928531/if-you-have-several-arrays-how-can-you-randomly-choose-one-of-the-several-array
CC-MAIN-2019-09
refinedweb
155
62.88
Hello friends, hope you all are fine and having fun with your lives. Today, I am going to start a new series of tutorials on C++ Programming. and here’s my first tutorial in this series which is Introduction to C++. I am gonna share a lot of tutorials in this series in future, in which I am gonna explain all about C++. In the initials tutorials, we will cover the basics of C++ Programming and later on we will also cover the pro concepts of C++ Programming. I am planning on posting around 20 to 30 tutorials in this C++ Programming series, and I am quite sure that it will cover all about C++ and if you are a new learner then it will help you quite a lot.. I have started this series on a request of one of my readers. He suggested me this idea and I like it quite a lot so I though to pursue it. So, today let’s have a look at Introduction to C++, which is quite essential when you are learning a new language you must have its introduction first. Introduction to C++ - So, now let me first write a simple C++ code, which is gonna print Hello World on the screen. - Below is given the very basic C++ code and I am gonna explain this code below to give an Introduction to C++ in detail: - The above code is the simplest C++ code which is gonna print Hello World on the screen. - If you read the above code from start then you can see the first statement in the above code is #include <iostream>. - This first statement is actually including a library in our code file. - The C++ Compiler already has a lot of libraries in it which we use in our program and can get benefit out of it. - So, now question is what are these libraries. In any compiler the libraries are designed to create functions and then you can use these functions quite easily. - Let me explain it in a simple way. For example you want to add two numbers 2 + 2, now you know that the operator + is used for addition but the C++ won’t know about it unless you add the library for math. - So, here we want to print something on our screen so the C++ will not print it on the screen unless we include this iostream library in it. - There are many builtin libraries for C++ like conio, arithmetic etc. which we will cover in later tutorials. - But for rite now, I think you have got the idea what is library, and you really don’t need to know what they are doing. 🙂 - Next line used is using namespace std, its a namespace standard library and you just have to add it as it is in the C++ Library. - Now next we have the int main(void) command. Its basically a function, which is called the main function. - In C++ the compiler works top to bottom and the first thing it goes into is the main function so your code must have the main function otherwise it will generate error. - This Main function is of the form as shown below: - Now in this main function, you can add anything you wanna add or execute. - We can create many functions in C++ coding which we will surely cover in coming tutorials but the Main function will always remain single means you can’t add another Main function in it. - Now after the Main function, we have added a line whose initials are cout, its a c++ commands which is used to print something out and you can see rite after cout we have written a string “Hello World!!!”. - So, because of cout command our code is printing this Hello World on the screen. - If you notice we have << these signs between cout and our string to print. - These signs are called insertion operators. - At the end of this statement we have endl, which is called end line, and its similar to pressing enter button and after it we have our semi colon (;). Semi colon tells the C++ that our statement is ended. - So, as a whole its called a statement, and in this statement we first printed out Hello World!!! and then we Entered and finally we added a semi colon to tell our program that statement has ended. - Now in the next statement we have return 0; , it will return nothing back and will just stop. - So, in our simple above program we have Main function with two statements and its printing Hello World on the screen. - It was kind of an Introduction to C++ in which we have designed a small program and then discussed it. So, that’s all about the introduction to C++, and I hope you guys have learned something out of it. In the coming tutorials, I am gonna post more about C++ and we will cover about variable used in it and how we can make complex codes on c++. So stay tuned and have fun !!! 🙂
http://www.theengineeringprojects.com/2016/05/introduction-c.html
CC-MAIN-2017-13
refinedweb
851
76.45
I've been working with web views at the behest of a client. To a native app developer, web views can be particularly challenging. One such challenge I recently conquered was including a clickable phone number in the web view. The client's request was more than reasonable. The web page would display a phone number. When the user clicked the phone number, the app would launch the dialer pre-populated with the phone number from the website. According to everything I read, this should "just work" in a mobile browser. As long as the href in your link is prepended with "tel:" the device running the mobile browser is supposed to do the right thing for the platform. In reality I found that, while a fair number of devices from various manufacturers worked as advertised, a fair number didn't. Fortunately, the Android SDK has had a mechanism in place since version 1.0 that allows the app to intercept a loading URL and override the behavior as needed. This tutorial demonstrates how to intercept the user tapping the phone number link in a web view and the subsequent launching of the dialer app. The idea is that you can use this technique regardless of how the mobile browser on the device does (or does not) interpret the href. Feel free to follow along or download and import the entire project directly into Eclipse. 1. Create a new Android project in Eclipse. Target Android 2.3 (Gingerbread) or better. 2. In the /res/layout folder, add a web view to activity_main.xml. activity_main.xml <RelativeLayout xmlns: <WebView android: </RelativeLayout> 3. Create a new web view client inside the /src/MainAcitvity.java file and assign it to our web view in on create. The rest is a standard Android intent for opening the dialer and passing it the phone number embedded within the URL. MainActivity.java package com.authorwjf.webview_link_intercept; import android.net.Uri; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import android.app.Activity; import android.content.Intent; public class MainActivity extends Activity { private static final String HTML ="<!DOCTYPE html><html><body><a href='tel:867-5309'>Click here to call!</a></body></html>"; private static final String TEL_PREFIX = "tel:"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView wv = (WebView) findViewById(R.id.webview); wv.setWebViewClient(new CustomWebViewClient()); wv.loadData(HTML, "text/html", "utf-8"); } private class CustomWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView wv, String url) { if(url.startsWith(TEL_PREFIX)) { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); startActivity(intent); return true; } return false; } } } You probably noticed that, while in this instance we are launching the dialer, by returning true in the should override url loading function, we can redirect the app flow any way that's desired. I believe this device-agnostic technique will prove useful to me in a number of scenarios besides the one described here. If you want to see the web view in action, simply compile and load the APK to a device or emulator. Figure A Figure.
http://www.techrepublic.com/article/pro-tip-include-a-clickable-phone-number-in-androids-web-view/
CC-MAIN-2017-30
refinedweb
520
51.44
Science versus Engineering? I suppose it was inevitable that there would be infighting as academics jostle for an increase intheir share of what is likely to be a diminishing level of research funding to be announced at the end of the ongoing Comprehensive Spending Review. The first professional society to try to barge its way to the front of the queue appears to be the Royal Academy of Engineering, which has written to the Department of Business, Innovation and Skills (BIS) in terms that make it clear that they think egineering should prosper at the expense of research in fundamental physics. To quote the RAEng:. And where should the axe fall? BIS should also consider the productivity of investment by discipline and then sub-discipline. Once the cost of facilities is taken into account it is evident that ‘Physics and Maths’ receive several times more expenditure per research active academic compared to those in ‘Engineering. Obviously whoever wrote this hasn’t heard of the World Wide Web, invented at CERN – precisely the place singled out for vitriol. I couldn’t agree less with what the RAEng say in their submission to BIS, but instead of going on a rant here I’ll direct you to John Butterworth’s riposte, which says most of what I would want to say, but I would like to add one comment along the lines I’ve blogged about before. The reason I think that the RAEng is precisely wrong is that I think the Treasury (on behalf of the taxpayer) should only be investing in research that wouldn’t otherwise be carried out. In other words, the state should fund academic esearch precisely because of its “blue sky” nature, not in spite of it. Conversely, engineering and technology R&D should be funded primarily by the commercial sector precisely because it can yield short-term economic benefits. The decline of the UK’s engineering base has been caused by the failure of British companies to invest sufficiently in research, expecting instead that the Treasury should fund it and all they have to do is cash in later. I’m not calling for the engineering and technology budgets to be cut – I don’t have such a blinkered view as the RAEng – but I would argue that a much greater share should be funded by private companies. This also goes for energy research. As Martin Rees pointed out in a recent Reith Lecture, the UK’s energy companies spend a pathetically small proportion of their huge profits on R&D. The politicians should be “persuading” industry to get invest more in the future development of their products rather than expecting the taxpayer to fund it. I agree that the UK economy needs “rebalancing” but part of the balance is private companies need to develop a much stronger sense of the importance of R&D investment. And, while I’m tut-tutting about the short-sighted self-interest displayed by the RAEng, let me add that, following the logic I’ve stated above, I see a far stronger case for the state to support research in history and the arts than, e.g. engineering and computer science. I’d even argue that large commercial companies should think about sponsoring pure science in much the same way as they do with the performing art exhibitions and the Opera. We need as a society to learn to celebrate curiosity-driven research not only as a means to economic return (which it emphatically is) but also as something worth doing for its own sake. Finally, and most depressingly of all, let me point out that the Chief Executive Officer of the Royal Academy of Engineering, Philip Greenish, sits on the Council of the Science and Technology Facilities Council, an organisation whose aims include To promote and support, by any means, high-quality basic, strategic and applied research and related post-graduate training in astronomy, particle physics, space science and nuclear physics. Clearly, he should either disown the statements produced by the RAEng or resign from STFC Council. Unless he was put there deliberately as part of the ongoing stitch-up of British physics. If that’s the case we all have the dole queue to look forward to. July 13, 2010 at 3:20 pm Didn’t Martin Rees also point out in his Reith Lecture series that CERN takes up some 2% of the science budget? As you say Peter, it is precisely because fundamental research has no obvious commercial benefit that Government should support it, not private industry. I’m sure the RSEng would have cut funding to Faraday’s Blue Sky research on electromagnetism. And, as you say, the author of the piece obviously doesn’t know where the World Wide Web was invented. Who knows, MAYBE results from CERN could help us solve some of the problems in getting controlled fusion to work, we just don’t know. July 13, 2010 at 7:10 pm Oops, I meant RAEng…. July 13, 2010 at 4:00 pm One recalls the story about Faraday and, depending on the version, Gladstone or Disraeli: P.M.: What’s the use of this, young man? M.F.: I don’t know, Sir, but one day you may tax it. July 13, 2010 at 7:08 pm That’s a great quote Phillip. July 13, 2010 at 10:18 pm […]it is evident that ‘Physics and Maths’ receive several times more expenditure per research active academic compared to those in ‘Engineering and Technology'[…] Well, I’ve always suspected that one physicist can do the work of several engineers… July 13, 2010 at 11:03 pm I have tried in the past to find as early an occurrence of the Gladstone-Faraday story as I could. The earliest I have been able to find is from 1899 from a book “Democracy and Liberty” by somebody called W. E. H. Lecky, vol. 1, revised edition, page xxxi : The story is not well sourced there. I haven’t found anything as early involving Disraeli. July 13, 2010 at 11:28 pm Andrew If the RAEng’s statement is true than it probably reflects that fact(s) that doing physics is rather expensive and that we as a country don’t have all that many physicists. Most universities have some sort of engineering/technology departments whereas only about 40 do physics. In any case, particle physics represents a very small fraction of the UK’s STEM research so cancelling our CERN subscription would not make much difference to the overall budget, although it would require tearing up an international treaty. Peter July 14, 2010 at 1:28 am […] This post was mentioned on Twitter by Matt Hole, Peter Coles. Peter Coles said: Science versus Engineering?: […] July 14, 2010 at 6:28 am Looks like everyones at it in a mad scramble to get at the few crumbs of money that will be left: July 14, 2010 at 9:14 am I think the government will either cut funded places or cut the unit of resource (or both) but the loss of income will be offset by raising the tuition fee for those remaining. That’s in England, of course, Scotland, NI and Wales decide their own HE priorities. Cutting research would be traumatic across the entire country but it is, I fear inevitable. The only question is whether it will be more than the 25% average. Even if the STFC budget is only cut by 25% on top of what we’ve had already then it will be an irreversible disaster for UK astronomy and particle physics. July 14, 2010 at 4:17 pm “the loss of income will be offset by raising the tuition fee for those remaining” Assuming that it is no problem for the students to pay the increased fees. Maybe that’s part of the plan: the students quit because the fees are too expensive, and the government can bring on more cuts, justified by the decrease in the number of students. July 14, 2010 at 4:22 pm Well, places like Oxbridge, Imperial and UCL would probably prefer to have fewer students with more money per student. That way they can spend more time doing research. July 14, 2010 at 5:43 pm Peter, that’s both unfair and, especially in the present climate, divisive. :( July 14, 2010 at 5:56 pm Garret, I didn’t mean to be either divisive or unfair. I think you’ll find that’s what the VCs of those institutions actually think, although I should have specified that by “students” I meant undergraduate students. The link above supplied by mark has UCL’s Malcolm Grant saying precisely what I suggested. I’m not even arguing that it’s an unreasonable stance. If there is greater concentration of research funding including PG funding in the “Golden Triangle” it seems inevitable that UG numbers there will be cut there. In fact, I think if you ask most Heads of Department around the country they would much prefer to take in fewer students and teach them better rather than overcrowd lecture theatres and labs like in order to make ends meet. Given the choice, would you recruit 60 students per year at £10K per head or 120 at £5K for the same income? Peter July 14, 2010 at 7:03 pm Peter Apologies for being brusque, I am a bit touchy about the “Oxbridge academics don’t care about teaching” line which one gets hit with far too frequently from all sides. And while I don’t disagree with everything Malcolm Grant says, some of his views do anger me and it’s not nice to feel that one is being allied to them. On the bald extremes of the argument of course you’re correct, but with more realistic numbers I’m not so sure… for example holding total fee income constant I’d be prepared to take the personal time hit if we could take 5% more home undergrads rather than 5% less. At that sort of level you wouldn’t be stretching labs or lecture theaters. Much as many of us would love to work somewhere like Caltech with its tiny (and ultra-eiite) undergrad population, I certainly don’t think it would be healthy for the country if the majority of our science research effort were based in such institutions. Keep universities as, um, universities. Maybe my old-fashioned roots are showing… Best Garret July 15, 2010 at 4:58 am I worked at Chicago for 6 years and it, like Caltech, has a tiny undergraduate population. But my most extraordinary experience during my 9 years working in the States was a year lecturing at Swarthmore College on the outskirts of Philadelphia ( more.edu). It’s a TINY undergraduate liberal arts college with only 1200 students when I was there (this has since grown to 1600). And yet 5 of it’s graduates have won Nobel prizes, John Mather (class of 1968) being the most recent. All the students there could have gone to Harvard or Princeton or Caltech, but choose Swarthmore for its small college nature. The lecturers there are dedicated to undergraduate teaching (very different from my experience as an undergrad at Imperial where most of the lecturers didn’t give a damn about undergrads). July 15, 2010 at 7:48 am Good point Rhodri about Swarthmore. We really don’t have anything analogous to the elite liberal arts colleges do we? Would they work here? While I have found myelf in a position where I’m spending more time on teaching than on research I don’t think I’d want to forgo my research to the extent needed by some of the liberal arts colleges. At least, it’s always been my impression that the faculty there put their all into their teaching. Would you go back to somewhere like that permanantly? (issues like living overseas, etc, aside of course…) July 15, 2010 at 8:57 am I would go back to Swartmore tomorrow. You get a year off from testing every four years, so research is supported and expected. July 15, 2010 at 9:27 am …. from teaching, not testing. I was doing “typing” that in on a moving bus on my iPhone (at least that’s my excuse). July 14, 2010 at 4:58 pm The tories are looking increasingly anti-science: What exactly is the economic problem,” he said in a major speech at the Royal Institution in London on 9 July, “if the next scientific discoveries originate overseas, rather than here?” – David Willets We hardly spend any money on science in this country as it is, and now it seems they want to make sure they destroy what we do have left. July 14, 2010 at 5:22 pm Mark, To be fair to Willets I think you should quote the whole section, which makes it clear that this is a rhetorical question which he then attempts to answer… At least it’s not as bad as question as you can find being asked today by Silvio Berlusconi about Italian science.. Peter July 14, 2010 at 10:13 pm ok fair enough….serves me right for not reading the original speech and reposting someones quote of a quote…..it certainly sounds better now reading the full quote…. Mark July 15, 2010 at 1:53 pm David Willetts seems supportive of science. I note his degree is PPE from Oxford (who in government DOESN’T have a degree in PPE?). Have we ever had a science minister with a degree in a science subject? July 15, 2010 at 2:13 pm Thatcher. July 16, 2010 at 3:09 am Godwin! July 15, 2010 at 2:25 pm I thought she was schools minister. July 15, 2010 at 2:26 pm Before leading the party that is, under Ted Heath’s premiership. July 15, 2010 at 2:34 pm Margaret Thatcher was Minister for Education and Science for 4 years during the Heath government. Although portfolios have changed a lot since then, her role then is not dissimilar to Willetts role now. Let’s hope he makes a better fist of it than she did. July 15, 2010 at 3:03 pm So when was she schools minister? When did she steal the school milk?? Willetts couldn’t do a worse job. July 19, 2010 at 11:17 am Yes, Margaret Thatcher was Secretary of State for Education and Science throughout the Heath Government, that is from 1970 to 1974. Coincidentally, a few weeks ago I came across this transcript of a speech she gave to the Royal Society in 1972. There is free access to it at the present time (without the need for an institutional library subscription), but that may change soon. July 15, 2010 at 9:54 pm Education includes schools, in theory at least. October 25, 2010 at 6:22 pm […] time ago I posted an item explaining how, in the run-up to last week’s Comprehensive Spending Review, the Royal Academy […]
https://telescoper.wordpress.com/2010/07/13/science-versus-engineering/
CC-MAIN-2015-32
refinedweb
2,520
66.07
16 August 2007 14:53 [Source: ICIS news] LONDON (ICIS news)--Shares in coatings major Akzo Nobel fell 6% on Thursday amid market fears that its partner in the proposed ICI acquisition, Henkel, would have trouble financing the deal.?xml:namespace> German adhesives producer Henkel had agreed to pay ₤2.7bn ($5.6bn/€4.1bn) in cash to acquire ICI’s adhesives and electronic materials businesses as part of the proposed ₤8bn takeover from Netherlands-based Akzo Nobel. Henkel said it was still considering all options to fund the deal, including a combination of equity and debt and/or the divestment of non-core assets. “We are absolutely sure we are able to finance the acquisition,” said a Henkel spokesman. “We are looking at all areas before determining the financial structure of the transaction,” he added. The deal was expected to close in the first half of 2008. At 15:18 local time?xml:namespace> The European chemicals sector suffered a general downturn as markets continued to feel the effects of continued turmoil
http://www.icis.com/Articles/2007/08/16/9053432/akzo-nobel-shares-slide-on-ici-financing-worries.html
CC-MAIN-2013-48
refinedweb
173
53.61
In yet more testing I found a couple more issues. First, many systems allow you to change gid on files that you can't set the uid of, if you're a member of the group and own the file. Second, if we can't set the uid and/or gid we shouldn't enable the setuid and/or gid bits, as the result would be setuid and/or setgid to the wrong user. I pushed the following further patch into the trunk. *. === modified file 'src/fileio.c' --- src/fileio.c 2011-07-17 01:18:51 +0000 +++ src/fileio.c 2011-07-18 17:15:29 +0000 @@ -38,8 +38,6 @@ #include <selinux/context.h> #endif -#include <ignore-value.h> - #include "lisp.h" #include "intervals.h" #include "buffer.h" @@ -1961,9 +1959,21 @@ owner and group. */ if (input_file_statable_p) { + int mode_mask = 07777; if (!NILP (preserve_uid_gid)) - ignore_value (fchown (ofd, st.st_uid, st.st_gid)); - if (fchmod (ofd, st.st_mode & 07777) != 0) + { + /* Attempt to change owner and group. If that doesn't work + attempt to change just the group, as that is sometimes allowed. + Adjust the mode mask to eliminate setuid or setgid bits + that are inappropriate if the owner and group are wrong. */ + if (fchown (ofd, st.st_uid, st.st_gid) != 0) + { + mode_mask &= ~06000; + if (fchown (ofd, -1, st.st_gid) == 0) + mode_mask |= 02000; + } + } + if (fchmod (ofd, st.st_mode & mode_mask) != 0) report_file_error ("Doing chmod", Fcons (newname, Qnil)); } #endif /* not MSDOS */
https://lists.gnu.org/archive/html/bug-gnu-emacs/2011-07/msg01728.html
CC-MAIN-2019-43
refinedweb
236
70.9
Andrew Dalke <adalke at mindspring.com> wrote: ... > Suppose Python3.0 goes the other way and uses decimal as > the native number type and requires some suffix for floats? > > x = 3.04 # this is a decimal > y = 3.14159f # this is an IEEE 754 float I'd like that. But, playing devil's advocate: there would be no harm done if 3.04d meant just the same thing as 3.04 without a suffix. So, e.g., Python 2.5 would let you spell out explicitly 3.04d or 3.04f. If you didn't, writing just 3.04, that would currently default to the same as 3.04f for backwards compatibility. In Python 3.0 the 3.04d and 3.04f forms would remain and bare 3.04 would change meaning -- perhaps it might be arranged to go through a time where at least optionally warning would be given (not by default, but with a -W switch or so -- in "late" Python 2.* warning that 3.04 changes meaning in Python 3.0, in early Python 3.* warning that 3.04 used to mean something different in Python 2.*). So, even though I don't particularly love the proposed syntax, it seems that at least a good migration path would exist. > > But you sure find it more convenient to type (1.12+2.9i), don't you? > > My point is that I find it more convient that most > objects get created via the same call-style interface. > I would find > > s = url"" > > more convenient to type than > > s = urllib.urlopen("").read() > > Doesn't mean I want it. While I unfortunately don't think we can get there from here, I sometimes toy with the idea of making some <name><separator><content> form be taken by the parser as equivalent to <name>(stringifiedcontent), basically giving an alternative syntax for calls that's suitable for literals -- with the semantic twist that the call happens during parse time and the <name> must be known at that time in some suitable namespace. The problem is determining what separator is suitable, how does one tell when the content ends, etc. Strawman proposal to show concrete examples: let's have a 'binary @' like unary @ is used for decorators, and say content ends at nonescaped whitespace. Then one could have: x = d at 3.14 + d at 0.21 meaning x = d('3.14') + d('0.21') with the calls done at compile-time if 'd' is previously injected into some suitable namespace (not __builtins__, I think; rather, some other special module which is not normally accessed in the usual runtime lookup rules, so that such names can't be accidentally trampled). Similarly, s=url at would call such a 'url' named factory, which in turn could urlopen and read, or whatever. The alternative syntax <name><string> is also attractive for most uses, it matches existing u'foo' and r'fee' uses, but has the unfortunate connotation of 'stringiness' which might make d'3.14' not quite as attractive as d at 3.14 (personally I like it better, but that's just because the @ splat is SO ugly;-). Yet other alternatives might include parentheses-like separators to indicate compiletime rather than runtime call (and implied stringification, lexically speaking), say d{3.14} and url{}. One way or another, what I really dream of is an _extensible_ syntax to get arbitrary factories with names called at compiletime on string contents, once the names have been registered in the namespace dedicated to that task. Yeah, I'm aware that this might be abused to make the equivalent of a full-fledged macro system, with the attendant problems. I've toyed also with hypotheses on how to ameliorate that, e.g. making the dedicated namespace "write-once" -- if any code ever tries rebinding a name in that space, it gets an exception. But for all these musings, "we can't get there from here" IS quite possible. Alex
https://mail.python.org/pipermail/python-list/2004-September/270797.html
CC-MAIN-2014-10
refinedweb
659
75.2
GCC Command Line - -fplugin=/path/to/gcc_dehydra.so - -fplugin-arg-gcc_dehydra=/path/to/your/script.js Callback Functions The following functions may be provided by the analysis script and will be called by Dehydra while compiling. See the Dehydra object reference for details on the available object properties. process_type(type) Dehydra calls this for each class, struct, enum, union, and typedef declaration. process_type is called after process_function is called for all the member functions. - type is a type object representing the type that was declared. process_function(decl, body) Dehydra calls this for each function definition (declarations without bodies are not included), including both top-level functions, class member functions, and inline class member functions. - decl is a Variable Type object representing the function being processed - body is an array of {loc:, statements:array of Variable Types} representing an outline of the function stripped down to variables, function calls and assignments. process_decl(decl) process_decl is called for every global variable, function, or template declaration. - decl is a variable type input_end() Called once at the end of the C++ source file before the compiler quits. This is useful for finalizing analyses. Builtin functions The following functions are provided by dehydra and may be called by the user: print(msg) Print a string to stdout (or stderr if the compiler is piping output). If the current callback is associated with a particular location, the location will be printed first. - msg is a string to output To customize the location info printed set this._loc before calling print() include(file [, namespace]) Include a javascript file into a namespace. - file is a string representing the file to include - Optional: namespace is an object to include the file into. The default namespace is this The directories in sys.include_path are searched for the file, and the current working directory is searched last. Includes are guarded so a file is only included once and subsequent include calls are ignored. This is accomplished by recording every included file into the _includedArray in the current namespace. Include Example include("map.js") // includes map.js into toplevel var Map = {} include("map.js", Map) // includes map.js into the Map object require({version:, strict:, werror:, gczeal:}) require is used to set runtime execution flags. It also returns the current values of these flags. require supports optional named arguments via JavaScript object where each parameter is a property. If a property is not specified then it will not be passed to the runtime. - version integer: this sets js version similar to version() in JS 1.7. - strict boolean: Controls JS strict mode - werror boolean: Turns JS warnings into errors - gczeal int: This is a write-only parameter to set turn on frequent garbage collection. It is a mainly useful for debugging Dehydra for rooting bugs. gczeal is only enabled when SpiderMonkey and Dehydra are compiled with DEBUG macro defined. require() Example require({strict:true, gczeal:2}) if (require().werror) print("werror is set") warning([code,] msg [, loc]) Print a warning message using the GCC warning mechanism. If -Werror is specified this will cause compilation to fail. - Optional: code is an integer parameter that allows warnings to be enabled(-Wfoo) and disabled(-Wno-) on the GCC commandline. This parameter is used when the first argument to warning() is an integer. It is not possible to define new warnings in Dehydra, thus one has to figure out a warning code from an existing warning and hijack it for ulterior purposes. - msg is a string to be presented as a gcc warning - Optional: loc is the location that should be reported for the warning. If no location is provided, the location is inferred from the last process_type or process_function. error(msg [, loc]) Print an error message using the GCC error mechanism. This will cause compilation to fail. - msg is a string to be presented as a gcc error - Optional: loc is the location that should be reported for the warning. If no location is provided, the location is inferred from the last process_typeor process_function. _print(msg, ...) The low level function called by print(). It does not print the location. read_file(filename) Read a file a return it as a string. write_file(filename, data) Write a string to a file. Builtin Objects sys this.sys is a container for miscellaneous properties exposes by Dehydra - sys.gcc_version is a GCC version string - sys.include_path exposes the search path used by include(). The default value is the following directories: - the directory of the dehydra script being processed - the libs directory next to the gcc_dehydra.so plugin - User script may add additional directories - sys.aux_base_name exposes the base filename part of the file being compiled - sys.frontend exposes the compiler frontend (e.g. "GNU C" or "GNU C++") arguments this.arguments is a JavaScript array containing command-line arguments passed to a script. -fplugin-arg="foo.js a b c" would run foo.js with ["a", "b", "c"] arguments array. This page was auto-generated because a user created a sub-page to this page.
https://developer.mozilla.org/en-US/docs/Archive/Mozilla/Dehydra/Function_Reference
CC-MAIN-2018-26
refinedweb
836
50.02
right click menu? On 09/09/2014 at 10:23, xxxxxxxx wrote: Is it possible to create a list of "items" that I could right click on and have a custom menu popup inline? Essentially they way I'd like to it work is have a text box auto fill with a list and then be able to right click on individual items in the list to bring up a custom menu. On 09/09/2014 at 10:28, xxxxxxxx wrote: Duh, found it: On 09/09/2014 at 10:41, xxxxxxxx wrote: Well, maybe I spoke too soon. I can't get this to work :( Here's the code I'm using: class PositionCloner(c4d.plugins.CommandData) : dialog = None def Init(self, op) : return True def Message(self, msg, result) : if msg.GetId() == c4d.BFM_INPUT: if msg.GetLong(c4d.BFM_INPUT_CHANNEL)==c4d.BFM_INPUT_MOUSERIGHT: # put in your code which will be executed on right mouse click menu = c4d.BaseContainer() menu.SetString(1000, 'Item 1') menu.SetString(1001, 'Item 2') menu.SetString(0, "") # Append separator menu.SetString(1003, 'Item 2') result = c4d.gui.ShowPopupDialog(cd=None, bc=menu, x=c4d.MOUSEPOS, y=c4d.MOUSEPOS) return True # don't route message to window parents return c4d.gui.GeDialog.Message(self, msg, msg) def Execute(self, doc) : if self.dialog is None: self.dialog = PositionClonerDial, "PositionCloner", 0, bmp, "PositionCloner", PositionCloner()) On 09/09/2014 at 11:23, xxxxxxxx wrote: That code is for a GeDialog. But you're using it in a CommandData class. The CommandData class is only used to give you a way to launch the GeDialog from the menu. So you need to write your gizmo code for a GeDialog class. Put this code in your script manager and run it. Then RMB click in the dialog and select an item from the popup list. And it will put what you selected in the textbox. This is a script example. But works the same way in plugins. import c4d from c4d import gui class CustomDialog(c4d.gui.GeDialog) : def CreateLayout(self) : self.AddEditText(2222, c4d.BFH_CENTER, initw=120, inith=15) return True def Message(self, msg, result) : if msg.GetId() == c4d.BFM_INPUT: if msg.GetLong(c4d.BFM_INPUT_CHANNEL)==c4d.BFM_INPUT_MOUSERIGHT: #Put in your code which will be executed upon a RMB click entries = c4d.BaseContainer() entries.SetString(1000, 'Item 1') entries.SetString(1001, 'Item 2') entries.SetString(0, "") #Using a 0 Adds a separator entries.SetString(1003, 'Item 3') popupGizmo = c4d.gui.ShowPopupDialog(cd=None, bc=entries, x=c4d.MOUSEPOS, y=c4d.MOUSEPOS) popupText = entries.GetString(popupGizmo) self.SetString(2222, popupText) return c4d.gui.GeDialog.Message(self, msg, msg) def main() : myDialog = CustomDialog() myDialog.Open(dlgtype=c4d.DLG_TYPE_MODAL_RESIZEABLE, pluginid=1000001, defaultw=150, defaulth=100, xpos=-1, ypos=-1) if __name__=='__main__': main() -ScottA On 09/09/2014 at 11:25, xxxxxxxx wrote: Sweet!!! That'll help start me down the path! Thanks again! On 09/09/2014 at 22:41, xxxxxxxx wrote: So how would I incorporate this into a plugin? Here's what I have so far, but I just keep getting the default c4d right click menu: import c4d from c4d import plugins import os class PipelineDialog(c4d.gui.GeDialog) : def CreateLayout(self) : self.SetTitle("c4d Pipeline") self.AddEditText(2222, c4d.BFH_CENTER, initw=120, inith=15) class Pipeline(c4d.plugins.CommandData) : dialog = None def Init(self, op) : return True def Message(self, type, data) : return True def Execute(self, doc) : if self.dialog is None: self.dialog = PipelineDial, "c4d pipeline_part", 0, bmp, "c4d pipeline", Pipeline()) On 10/09/2014 at 08:52, xxxxxxxx wrote: Hmmm. That's a good question. I can't find anywhere in the SDK how to tell C4D to shut off the RMB stuff. Normally these popups are used in Tool plugins and this is not an issue. I'm not sure if it's possible to use the RMB with a GeDialog. You might have to use a keyboard key instead. Or possibly a qualifier key with the RMB. It's an annoying limitation for sure. -ScottA On 10/09/2014 at 10:27, xxxxxxxx wrote: Well, what I think might work instead is to have a select box with a series of buttons beneath. Essentially "buttonizing" the menu beneath. I only have a few functions that I need. Is there a way to create something similar to this? I'm originally an HTML guy so I usually think of things from that angle. Just FYI I'm trying to create an asset manager similar to this: So all I would need is a list of files where one could be selected so I can perform my actions on the selected list item. Is there a way to make selectable list items like that? On 10/09/2014 at 11:27, xxxxxxxx wrote: That's a linkbox gizmo. In C4D it's called this: CUSTOMGUI_LINKBOX This gizmo is not available in the Python SDK. Only in the C++ SDK. I know how to create the gizmo itself. But the functions for populating it are not available in the Python version of the SDK. Or at least AFAIK. NiklasR. wrote a gizmo like this using the UserArea class. I can't remember off hand where it is. But you might find it by searching the archives. Or by contacting him directly. -ScottA On 10/09/2014 at 11:57, xxxxxxxx wrote: Oh BTW: There does seem to be one way to shut off the RMB click thing. And that's to make the GeDialog modal. return self.dialog.Open(dlgtype=c4d.DLG_TYPE_MODAL, pluginid=PLUGIN_ID, defaultw=200, defaulth=150, xpos=-1, ypos=-1) Of course the down side of this is that the user has to close the dialog before they can do anything in the scene. And they won't be able to dock the dialog in the UI. But if that's not a deal breaker. Then using a modal dialog should work. -ScottA On 06/10/2014 at 09:44, xxxxxxxx wrote: I've been playing around with this some more and have discovered that you I can't detect any type of click in an ASYNC dialog. Is there no way to detect a click at all using ASYNC? On 06/10/2014 at 09:48, xxxxxxxx wrote: I found this and think it might be able to solve the problem but have no idea how to implement it. Any suggestions? On 06/10/2014 at 10:41, xxxxxxxx wrote: I figured it out!!! Turns out ASYNC only runs along with script execution, so if you need to continually poll the input you need to run it as a command plugin NOT a script. From my understanding a script is only listening to input as its running, but a plugin is continually listening for input while the dialog is open. I figured I could just build as a script and then port over to a plugin format, but that is NOT the case.
https://plugincafe.maxon.net/topic/8129/10589_right-click-menu
CC-MAIN-2020-40
refinedweb
1,160
68.26
This is a continuation from the previous module... Program examples compiled using Visual C++ 6.0 (MFC 6.0) compiler on Windows XP Pro machine with Service Pack 2. Topics and sub topics for this Tutorial are listed below: Figure 3: MYMFC15 project summary. Use the menu editor to replace the Edit menu options. Delete the current Edit menu items and replace them with a Clear All option, as shown here. Figure 4: Adding and modifying the Edit menu properties. Use the default constant ID_EDIT_CLEAR_ALL, which is assigned by the application framework. A menu prompt automatically appears. Use the dialog editor to modify the IDD_MYMFC15_FORM dialog. Open the AppWizard-generated dialog IDD_MYMFC15_FORM, and add controls as shown below. Be sure that the Styles properties are set exactly as shown in the Dialog Properties dialog (Style = Child; Border = None) and that Visible is unchecked. Figure 5: Modifying the IDD_MYMFC15_FORM dialog and its properties. Use the following IDs for the controls. Figure 6: Modifying the push button properties. Use ClassWizard to add message handlers for CMymfc15View. Select the CMymfc15View class, and then add handlers for the following messages. Accept the default function names. Figure 7: Using ClassWizard to add message handlers for CMymfc15View. Use ClassWizard to add variables for CMymfc15View. Click on the Member Variables tab in the MFC ClassWizard dialog, and then add the following variables. Figure 8: Using ClassWizard to add variables for CMymfc15View.. For m_nGrade, enter a minimum value of 0 and a maximum value of 100. ---------------------------------------------------------------------- Figure 9: Setting the minimum and maximum value for m_nGrade. Notice that ClassWizard generates the code necessary to validate data entered by the user. Listing 2. Add a prototype for the helper function UpdateControlsFromDoc(). In the ClassView window, right-click on CMymfc15View and choose Add Member Function. Fill out the dialog box to add the following function: private: void UpdateControlsFromDoc(); Figure 10: Using ClassView to add a prototype for the helper function UpdateControlsFromDoc(). Edit the file Mymfc15View.cpp. AppWizard generated the skeleton OnInitialUpdate() function and ClassView generated the skeleton UpdateControlsFromDoc() function. UpdateControlsFromDoc() is a private helper member function that transfers data from the document to the CMymfc15View data members and then to the dialog edit controls. Edit the code as shown here: void CMymfc15View::OnInitialUpdate() { // called on startup UpdateControlsFromDoc(); } Listing 3. void CMymfc15View::UpdateControlsFromDoc() { // called from OnInitialUpdate and OnEditClearAll CMymfc15Doc* pDoc = GetDocument(); m_nGrade = pDoc->m_student.m_nGrade; m_strName = pDoc->m_student.m_strName; UpdateData(FALSE); // calls DDX } Listing 4. The OnEnter() function replaces the OnOK() function you'd expect to see in a dialog class. The function transfers data from the edit controls to the view's data members and then to the document. Add the code shown here: void CMymfc15View::OnEnter() { CMymfc15Doc* pDoc = GetDocument(); UpdateData(TRUE); pDoc->m_student.m_nGrade = m_nGrade; pDoc->m_student.m_strName = m_strName; } Listing 5. In a complex multi-view application, the Edit Clear All command would be routed directly to the document. In this simple example, it's routed to the view. The update command UI handler disables the menu item if the document's student object is already blank. Add the following code: void CMymfc15View::OnEditClearAll() { // "blank" student object GetDocument()->m_student = CStudent(); UpdateControlsFromDoc(); } void CMymfc15View::OnUpdateEditClearAll(CCmdUI* pCmdUI) { // blank? pCmdUI->Enable(GetDocument()->m_student != CStudent()); } Listing 6. Edit the MYMFC15 project to add the files for CStudent. Choose Add To Project from the Project menu, choose New from the submenu, and select the C/C++ Header File and type the Student as the file name. Figure 11: Adding new header file to the project for the Student class. Then copy the previous Student.h code into the newly created Student.h file. Repeat the similar steps for Student.cpp file. Select the C++ Source File in this case. Figure 12: Adding new source file to the project for the Student class. Visual C++ will add the files' names to the project's DSP file so that they will be compiled when you build the project. Add a CStudent data member to the CMymfc15Doc class. Use ClassView to add the following data member, and the #include will be added automatically. The CStudent constructor is called when the document object is constructed, and the CStudent destructor is called when the document object is destroyed. Edit the Mymfc15Doc.cpp file. Use the CMymfc15Doc constructor to initialize the student object, as shown here: CMymfc15Doc::CMymfc15Doc() : m_student("The default value", 0) { TRACE("Document object constructed\n"); } Listing 7. We can't tell whether the MYMFC15 program works properly unless we dump the document when the program exits. We'll use the destructor to call the document's Dump() function, which calls the CStudent::Dump function shown here: CMymfc15Doc::~CMymfc15Doc() { #ifdef _DEBUG Dump(afxDump); #endif // _DEBUG } Listing 8. void CMymfc15Doc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); dc << "\n" << m_student << "\n"; } Listing 9. Build and test the MYMFC15 application. Type a name and a grade, and then click Enter. Now exit the application. Figure 14: Building MYMFC15 in debug mode. Figure 15: MYMFC15 program output, testing the functionalities. Does the Debug window show messages similar to those shown here? ... a CMymfc15Doc at $421920 m_strTitle = Untitled m_strPathName = m_bModified = 0 m_pDocTemplate = $421B20 a CStudent at $421974 m_strName = Mr. John Lennon m_nGrade = 99 ... Listing 10. To see these messages, you must compile the application with the Win32 Debug target selected and you must run the program from the debugger..
https://www.tenouk.com/visualcplusmfc/visualcplusmfc10a.html
CC-MAIN-2020-05
refinedweb
888
51.24
On Fri, 15 Feb 2008 08:44:54 -0500, Ignacio Vazquez-Abrams wrote: > On Fri, 2008-02-15 at 13:27 +0000, Kevin Kofler wrote: > > Ignacio Vazquez-Abrams <ivazqueznet <at> gmail.com> writes: > > > So then don't make it a compat-* package. > > > > > > > > > > This distinction you and Michael Schwendt are making between compat packages > > with or without the "compat-" prefix doesn't appear to be shared by all > > maintainers. I see the following packages in Rawhide matching compat-*-devel: > > compat-guichan05-devel-0.5.0-8.fc9.i386.rpm > > compat-guile-16-devel-1.6.7-7.fc8.i386.rpm > > compat-libosip2-devel-2.2.2-15.fc8.i386.rpm > > compat-wxGTK26-devel-2.6.4-2.i386.rpm > > An oversight that will hopefully be corrected. Not worth the hassle, IMO. It would also affect 3rd party packages. And I would not like to see more superfluous rebuilds and updates in all branches as a result of renaming a package. Doing the rename only in rawhide would not be trouble-free either. Among some packagers it has become way to popular to copy even the smalles changes in rawhide to all branches. Renaming BuildRequires would be such a change, and adding Obsoletes/Provides for the compat- namespace would not change the situation at all. In Fedora Extras CVS I would have simply renamed the packages in rawhide and notified the maintainers of dependencies that I would adjust the BR from compat-wxGTK26-devel to wxGTK26-devel. With ACLs and %{?dist}-madness I don't feel good about it. It has complicated some things a lot.
https://www.redhat.com/archives/fedora-devel-list/2008-February/msg01317.html
CC-MAIN-2014-15
refinedweb
264
65.73
Bug #11121closed openssl ext does not handle EWOULDBLOCK Description On Windows, non-blocking IO on sockets seems to return EWOULDBLOCK instead of EAGAIN. The openssl ruby library only handles EAGAIN, which results in EWOULDBLOCK being raised to the caller. This was noticed while using httpclient to send a POST request to an https server via an http proxy on a Windows system: A non-blocking socket operation could not be completed immediately. (Errno::EWOULDBLOCK) C:/Ruby193/lib/ruby/1.9.1/openssl/buffering.rb:53:in `sysread' C:/Ruby193/lib/ruby/1.9.1/openssl/buffering.rb:53:in `sysread' C:/Ruby193/lib/ruby/1.9.1/openssl/buffering.rb:53:in `fill_rbuff' C:/Ruby193/lib/ruby/1.9.1/openssl/buffering.rb:200:in `gets' C:/Ruby193/lib/ruby/gems/1.9.1/gems/httpclient-2.6.0.1/lib/httpclient/session.rb:356:in `gets' C:/Ruby193/lib/ruby/gems/1.9.1/gems/httpclient-2.6.0.1/lib/httpclient/session.rb:876:in `block in parse_header':872:in `parse_header' C:/Ruby193/lib/ruby/gems/1.9.1/gems/httpclient-2.6.0.1/lib/httpclient/session.rb:833:in `connect_ssl_proxy' C:/Ruby193/lib/ruby/gems/1.9.1/gems/httpclient-2.6.0.1/lib/httpclient/session.rb:753:in `block in connect':746:in `connect' C:/Ruby193/lib/ruby/gems/1.9.1/gems/httpclient-2.6.0.1/lib/httpclient/session.rb:612:in `query' C:/Ruby193/lib/ruby/gems/1.9.1/gems/httpclient-2.6.0.1/lib/httpclient/session.rb:164:in `query' ... We could only reproduce it in this environment so far (old version, invoking this particular call, over a proxy) but I believe the same problem can appear at any time with current versions. An example from current trunk (ext/openssl/lib/openssl/buffering.rb): def fill_rbuff begin @rbuffer << self.sysread(BLOCK_SIZE) rescue Errno::EAGAIN retry rescue EOFError @eof = true end end there are multiple references in that file, e.g. Updated by normalperson (Eric Wong) about 7 years ago Which version of OpenSSL is this? I wonder if OpenSSL is not returning SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE properly when it sees EWOULDBLOCK. Assuming OpenSSL returns SSL_ERROR_WANT_* properly, I'm not seeing where we can even raise EAGAIN/EWOULDBLOCK from ext/openssl/ossl_ssl.c Updated by hsbt (Hiroshi SHIBATA) about 7 years ago - Status changed from Open to Feedback Is there this issue on Ruby 2.1 or 2.2? Ruby 1.9.3 is EOL. Updated by pep (Pep Turró Mauri) about 7 years ago Thanks for the feedback and apologies for the delay here - it took a while to do further testing and confirming with the 3rd party who originally hit the problem. We couldn't reproduce this with more recent versions. 3rd party confirmed that they can't reproduce with ruby 2.1.6p336. They hit some unrelated problems installing 2.2 but I think at this point it's safe to say the problem doesn't reproduce in current versions and can be closed. Updated by zzak (Zachary Scott) about 7 years ago - Status changed from Feedback to Third Party's Issue Thanks for following up! Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/11121
CC-MAIN-2022-27
refinedweb
534
51.04
Bazel is one of the most widely used open source build tool these days, the rationale behind using Bazel is aplenty. Let’s say you want to compile Java and Python projects into one build file, then Bazel would be the ideal choice. As a QA company, we use Maven, Gradle, and Grunt to compile & kick-off automated test suites. Bazel is something new for us. In this blog article, you will learn how to run Selenium Scripts using Bazel. Advantages of Bazel 1) Platform Independent: You can run your Selenium scripts on Linux, macOS, Windows. 2) Compiling Large Files: Bazel can handle large files easily. 3) Languages: You can build and test C/C++, Objective-C, Java, Python, and Bourne Shell scripts in one build file. How to run Selenium Scripts using Bazel? Bazel has its own build language. Using Bazel’s predefined test rule, you can set automated test scripts in the build file irrespective of the programming languages used. We, as a test automation company, explore new technologies with the intend to ease automation testing process. Bazel is so programmer friendly, even Selenium developers are using Bazel to test Selenium’s features before deploying. In this blog article, we have used Windows 10 and Python to show the code execution. Let’s start from installation. Prerequisite – Visual C++ Redistributable for Visual Studio 2015 Visual C++ Redistributable for Visual Studio 2015 is a prerequisite if you are installing Bazel on Windows 10. Use the following link to install the package – Visual C++ Redistributable for Visual Studio 2015 Bazel Installation on Windows 10 Step #1 – Download bazel- Step #2 – Rename the downloaded file to bazel.exe Step #3 – Copy and paste the bazel.exe wherever you want. Step #4 – Set the bazel.exe path in PATH environment variable in Windows 10. Step #5 – Restart your PC Create a Python Project Step #1 – Create a Python project Step #2 – Create a directory called ‘scripts’ Step #3 – Create a directory called ‘drivers’ Step #4 – Download and paste the chromedriver.exe in drivers folder Step #5 – Create a python file and name it as test-1.py inside the scripts folder Step #6 – Paste the below snippet inside the test-1.py file from selenium import webdriver from bazel_tools.tools.python.runfiles import runfiles r = runfiles.Create() driver = webdriver.Chrome(executable_path=r.Rlocation("test_suite/drivers/chromedriver.exe")) driver.get("") driver.quit() Note: In line #4, the chromedriver executable path is set using Bazel’s runfiles module. Because all the supporting & testdata files for automated scripts need to be accessed using runfiles module. Maybe in future enhancements we will have a simple workaround instead of calling runfiles. Creating WORKSPACE file Bazel identifies a directory as Bazel Workspace when it contains WORKSPACE file. Step #1 – Create WORKSPACE file without any extension Step #2 – Paste the below line to name the workspace workspace(name = "test_suite") Creating BUILD file Bazel build file is being used to compile and run your test code. We, as a software testing company, use Maven POM.xml files to compile and run test code for Java projects. If you have test code base in different programming languages, then you can opt for Bazel to compile & execute test code of different languages into a single build file. Let’s see how to create a build file. Step #1: Inside the root directory, create a BUILD file without any extension. Step #2: Copy and paste the below snippet in BUILD file. py_binary( name = "test-1", srcs = ["scripts/test-1.py"], srcs_version = "PY2AND3", data = [":drivers/chromedriver.exe"], deps = ["@bazel_tools//tools/python/runfiles"], ) Code Explanation Line #1: py_binary is one of the Bazel’s rules. For Python, Bazel has two more rules – py_library & py_test. Any Python related tasks can be defined using these three rules in the build file. Line #2: You can name your tasks using ‘name’ attribute. Line #3: ‘srcs’ attribute is used to mention source files inside the rule. You can also mention multiple source files. Line #5: To launch the chrome browser, we need chromedriver.exe file. So we are copying the file inside the runfiles folder which can be found in bazel-out folder. Use ‘data’ attribute to copy all the supporting files. Line #6: To access runfiles in Python code, you need runfiles module from bazel_tools. Refer Line#2 in test-1.py file, you can understand why we are mentioning this dependency here. Bazel Run Now it is the time to run the script. You can run the rules from command prompt. Let’s see how to run our test-1 task. Clean – bazel clean Run – bazel run :test-1 That’s it. You can see browser launch after running the above commands. We have uploaded the Python project in Github. Please refer it if you face any issues. Full Code Download Link In Conclusion As a test automation company, we manage and maintain automation test scripts in multiple programming languages. However, managing single build file for compiling test code from different programming languages is a daunting task and eventually a great value add for QA companies. In our subsequent blog articles, we will be publishing more about nuances of Python automation testing. Submit a Comment
https://codoid.com/running-selenium-scripts-using-bazel/
CC-MAIN-2021-31
refinedweb
868
66.74
the syntax in the lesson for super is the following: class Sink: def init(self, basin, nozzle): self.basin = basin self.nozzle = nozzle class KitchenSink(Sink): def init(self, basin, nozzle, trash_compactor=None): super().init(self, basin, nozzle) if trash_compactor: self.trash_compactor = trash_compactor and again points out the syntax again: super().init(self, basin, nozzle) However, I was surprised to see “self” in the super() syntax from other videos I watched about it. When I followed the syntax the error I got was: Did you call super().__init__(potatoes, celery, onions) ? Without the self as a part of it. So is there a reason or is this an error?
https://discuss.codecademy.com/t/lesson-text-used-to-use-self-incorrectly/467232
CC-MAIN-2020-40
refinedweb
109
70.19
std::basic_ostream::swap From cppreference.com Calls basic_ios::swap(rhs) to swap all data members of the base class, except for rdbuf(), between *this and rhs. This swap function is protected: it is called by the swap functions of the swappable output stream classes std::basic_ofstream and std::basic_ostringstream, which know how to correctly swap the associated streambuffers. Parameters Example Run this code #include <sstream> #include <iostream> #include <utility> int main() { std::ostringstream s1("hello"); std::ostringstream s2("bye"); s1.swap(s2); // OK, ostringstream has a public swap() std::swap(s1, s2); // OK, calls s1.swap(s2) // std::cout.swap(s2); // ERROR: swap is a protected member std::cout << s1.str() << '\n'; } Output: hello
http://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_ostream/swap&oldid=49683
CC-MAIN-2014-15
refinedweb
114
58.18
This post is a sequel to a previous post - The TFS Build Definition List<T> OOTB UITypeEditor. In my previous post I showed how easy and cheep it is to use the TFS’s build definition OOTB “List<T>” editor. We even saw that if we use enum’s or Boolean's the “List<T>” editor’s properties grid gives us drop-down editors for them, but what if we want to use more advanced editors; such as the “ServerFileBrowserEditor” to select a project from the source control or the “PlatformConfigurationListEditor” editor to choose in which configurations and platforms I want to compile the project or any other editor? Well it seems to be extremely easy as well. All we need to do is take the same object we were using before: 1: using System.Collections.Generic; 2: using System.ComponentModel; 3: using System.Drawing.Design; 4: using BuildDemosC.Common.Enums; 5: using Microsoft.TeamFoundation.Build.Workflow.Activities; 6: 7: namespace BuildDemosC.CustomTypes 8: { 9: public class DevEnvCompilationItem 10: { 11: [Category("Properties")] 12: public string Project { get; set; } 13: 14: [DisplayName("Compiler Name")] 15: [Category("Properties")] 16: public DevEnvType CompilerName { get; set; } 17: 18: #region Methods 19: 20: public override string ToString() 21: { 22: return string.IsNullOrEmpty(Project) ? "New" : Project + "=>" + CompilerName; 23: } 24: 25: #endregion 26: 27: } 28: } and add the “Editor” attribute with the editor we want to use over the property we want to use it with: 6: 11: [Editor("Microsoft.TeamFoundation.Build.Controls.ServerFileBrowserEditor, Microsoft.TeamFoundation.Build.Controls", typeof(UITypeEditor))] 12: [Category("Properties")] 13: public string Project { get; set; } 14: 15: [DisplayName("Compiler Name")] 16: [Category("Properties")] 17: public DevEnvType CompilerName { get; set; } 18: 19: #region Methods 20: 21: public override string ToString() 22: { 23: return string.IsNullOrEmpty(Project) ? "New" : Project + "=>" + CompilerName; 24: } 25: 26: #endregion 27: 28: } 29: } After we check-in our changes, open a new instance of visual studio (So it will load the new dll files) and go to the build definition this is what will see when we came to edit our object list: Easy, elegant, cheep! :) Pingback from The TFS Build Definition List<T> OOTB UITypeEditor - Oshry Horn Thank you. What type of project is this? Is this a code activity project or a usual library? I'm unable to refer the class from template Also, Can you please attach your code? Hi Kumar, 1) This is a simple class library project. 2) in order to refer to the class from the template you must do the following: Take the project's dll/'s and add it/them to the folder in the source control to which the build controller you're using is referring as its assemblies directory. 3) I have already added the code; it is posted above.
http://blogs.microsoft.co.il/blogs/oshryhorn/archive/2011/07/19/using-microsoft-s-uitypeeditors-with-the-ootb-list-lt-t-gt-editor.aspx
crawl-003
refinedweb
459
51.48
Taking Advantage of Multi-Processor Environments in Node.js Posted on by Rudy Jahchan in Web Node » The “Problem”. Cluster to parallelize the SAME Flow of Execution. Child Process a DIFFERENT Flow of Execution. The Downside.. Feedback Your feedback martypdx March 5, 2014 at 8:26 am Timely write-up for me, thanks Rudy > A final note. In addition to sending an object, the send allows the transmission of handles like TCP servers and sockets between process. It is through this mechanism that the cluster functionality was created. Can you expand on this? At what point in the socket setup are you passing it to the child process and what are you passing? If namespacing, does that happen in the child, or in the parent process? I’m also reading that it can be passed, but also happen “by magic” if requested connection info matches. Rudy Jahchan March 5, 2014 at 10:36 am Thanks for the comment and the question! When you are using child_process alone, you have to yourself pass the sockets from the parent process where the server is to the child via a send. And by “socket” we mean TCP socket or any system IO handles (file reader, etc.) That is why they can be passed between processes. Socket.io websockets are actually higher order objects that can’t be passed; I’ve tried this with no luck. :-/ The only “magic” involved is when you fork via the cluster module. In that case, each worker is written as if they are starting their own server. But when you read the documentation what Node.js is actually doing behind the scenes is checking if any worker process has spun up a server listening on the same port and if they have simply distributes some of the connection events back to it. martypdx March 5, 2014 at 12:40 pm So using socket.io, if I wanted to namespace sockets, io.of(namespace), then using the fork model, each instance would create all of the namespaces. How did you manage the partitioning of games (assuming you used socket.io)? Did you listen on a different port? Canhnm March 14, 2014 at 12:57 pm Errr you said socket, it’s easy to manage them by using subscribe to channel provided! Rudy Jahchan March 16, 2014 at 3:59 pm Sorry for taking a long time to reply. The partitioning of games in the clustering scenario is actually kind of hard, and requires you to make use of Redis and another process(es) to handle the games. Each game’s events those are sent to specific “rooms” where sockets in that game listen to. You can read about it in the previous post about vimtronner: abc March 14, 2014 at 2:24 pm started reading this. then saw it was in coffeescript. waste of time Michael Wynholds March 14, 2014 at 2:29 pm Thank you for spending some of your precious time writing up this helpful comment! Ben May 1, 2015 at 5:10 am just cause you could not copy/paste it ? I can’t see how it changes anything to the topic of this post Alexander May 27, 2015 at 8:50 pm I agree. Coffeescript totally blows. Ashkenas did very well with Underscore and Backbone, but Coffeescript is fucking stupid. But this article is great. Thank you for it. And I have one question. Is there a way to determine at runtime which core a node process is running on? Igor Zelenin March 14, 2014 at 2:40 pm Thank you for the nice text! It’s pleasure to read it! I could also mention, that there is problem with load balancing between workers. In current versions of Node only few workers actually are under load, and other get nearly nothing. It will be solved in Node v0.12 (). And maybe I can promote here 😉 nice guys from russian search engine company Yandex, who develop good alternative for cluster.js which can help to solve this problem. Michael Wynholds March 14, 2014 at 4:09 pm Your first link is 404ing due to an errant right parenthesis. Here’s the page: hayesmaker March 15, 2014 at 7:09 pm Fucking coffeescript, jeez Rudy Jahchan March 16, 2014 at 3:56 pm I know, right? I mean it’s so easy to read and can easily be pre-compiled into Javascript, it must be “the worst”. And let’s not ignore the fact that my using Coffeescript HAS NOTHING TO DO WITH WHAT I AM TALKING ABOUT. Thanks for being a great example of missing the forest for the trees. Ben March 16, 2014 at 6:26 am You should put up the compiled JS code too, to see the kind of monstrosity writing JS like Jeremy Ashkenas did 4 years ago does to your code. Rudy Jahchan March 16, 2014 at 3:51 pm Thanks for showing me the error of my ways in working in a language that is four years old, continually updated, and is part of the Rails stack. Next time I will be sure to write my work up in LiveScript or ClosureScript. 😉 Ben May 1, 2015 at 5:11 am Ahahah this posts ended up in a coffeescript debate. people are crazy,I guess a year later it would not have happened Bradgnar March 18, 2014 at 2:12 pm Rudy is salty about coffeescript comments. Whatever Rudy, I’ve never written coffeescript but can still read your post and tell what is going on, do what you like. Pieter Michels May 20, 2014 at 5:32 am This is one of the best guide regarding the subject. We’ve implemented the technique in an existing game in about an hour. Works like a charm, and all of our cores are in use. Finally Thanks! CarbonMan May 22, 2014 at 1:04 am Never mind the jokers raving about coffeescript, you helped me out a lot. Could have been written in Sanskrit and I still would have gotten the gist of it. Mike Testa July 3, 2014 at 8:26 am Please excuse my ignorance with the following question. Would it possibly be a better design to have all child processes handle all games? Child procs could communicate with each other and the clients via inter proc communication and share the work evenly. Then you wouldn’t be spawning a process per game, but a process per CPU. Adit August 2, 2014 at 10:23 am To all the people complaining about Coffeescript: 1. do yourself a favor, try it! 2. if can’t or don’t have time just convert it on. It will take not more than one second! leegee September 24, 2014 at 9:57 am Grrrr…coffee script… tried your link: it was … pleasant. Easy to read. Probably easy to type. Hm. Toke Voltelen September 16, 2014 at 1:36 am Jeez… A lot of Coffescript haters! Personally I don’t like Coffeescript much but that doesn’t prevent me from finding this article f-ing great! Really good explanations on the concept! Thank you. For me the Coffescript was distracting (at first) but not more than I actually understood the concept and I really feel I can benefit from this article. So +1, like and whatnot from me Guest September 24, 2014 at 9:57 am Grrrrrr! That’s….really easy to read…and probably to type… grrr… Toke Voltelen September 25, 2014 at 7:35 am I wouldn’t use this article to copy paste from. But that is not its purpose either. Again I don’t like Coffescript, but the CONCEPTS described here are great. Besides it is better to write your code yourself so you actually learn from it instead of just copy/pasting stuff. So take it as a challenge rather than bitching about the language chosen her in this article… I know I do… Paul February 26, 2015 at 3:44 pm Fantastic article! Thanks for taking time to clearly explain this interesting topic. Regards Paul Ralph kuntz March 14, 2015 at 4:40 am I am playing with writing a REST server using TypeScript on Node. Your examples in CoffeeScript will be easy to translate. Thanks for nice post. henry hazan April 5, 2015 at 12:03 pm for this use case, erlang seems to be the best solution, this example is very cool flyknit roshe June 30, 2015 at 7:59 pm The greatest devastation occurred in Bhuj, then Ahmadabad, and Anjar, and some other smaller townships. The destruction in Bhuj has been complete for as the reports suggest 90% houses have developed crack, and 10% have crumbled to dust. With these reports we can easily understand the rate of losses and destruction. The horror stricken looks of the people alive looking for their dead in the rubble can hardly be described in words; it can all be just felt. flyknit roshe ClusterFluffer September 13, 2015 at 11:54 pm cluster.fork() Sounds feisty! Gas Creature October 3, 2015 at 9:51 am Great article!
http://blog.carbonfive.com/2014/02/28/taking-advantage-of-multi-processor-environments-in-node-js/
CC-MAIN-2015-48
refinedweb
1,517
72.97
Title: Context Help authoring anywhere/anytime/anyone for .NET application Author: rufei zhao Member ID: 2308266 Language: C# Platform: .NET 1.1+ etc Technology: .NET/C# Level: Beginner, Intermediate, Advanced Description: An article on howto make authoring the context help for UI easier. I started a sourceforge project for this, for detail and progress tracking, please visit The normal way to add context help feature to .NET/Forms, is to add a HelpProvider component to each Form, then edit the help string in the property grid panel for each UI element such as Buttons, RadioButton, CheckBox, ComboBox etc. This is tedious, programmers are not the right one the write the help info for the application, especially for multi-language support applications. In a typical product cycle, changing of the help string/Icon/Color adjustment is always the repeatedly, endless process. And, for such a non-code issues, you as a developer are forced to integrate these resource and rebuild the whole solution. This article introduce a new way for context help authoring. With this method, the help string for multi-language are dynamically load/written for the living applications. The help string are stored in xml file. Everyone running the application has the ability to write down anything about howto use a UI element such as an obscure Button. And, the help written by many peoples can be merged into one, so this is also a distributed context help authoring system. If you like you can also open this feature to the end user, so users of your application have the ability to write down their own idea about what your UI elements does and howto use /or avoid to use it, and share it with others. To use the component, At first add a reference to EasyHelp.dll using Slimzhao; EasyHelpString.AddNonParentUserControl(true, null); EasyHelpString.InitHelpProvider(this); Variable or class names should be wrapped in <code> tags like this. this EasyHelp depend on the fact that Control has a Name property, and Visual Studio IDE will generate a unique name for each control, for developers, it's very little chance for you to notice this property and it's always useless. Here's also comes the drawback of easyhelp: Controls of same parent must specify a unique name, so Visual Studio generated UI, this is not a issue since IDE will generate different name for each UI. For more complicated UI such as dynamical ui, designer will probably to leave the Name property out. Maybe the new version of EasyHelp should depend on the Z-order to identify each control. EasyHelp register the ContextHelp handler, and check the whether the Shift key is pressed when this event is triggered. If so brings up the context help authoring window, and if not just do the old thing which is popup the help string. Microsoft won't allow you combine the minimize box/maximize box/Close box and the "?" help box box/Help box arbitrarily, so if you want to use the context help for forms without "?" box, you need to trigger the event by yourself. But you cannot do it by just send the message. A first thought of mine is to do it in a Button's click handler, such as : private void m_btn_help_Clicked(object sender, System.EventArgs e) { DefWindowProc(this.Handle, WM_SYSCOMMAND, SC_CONTEXTHELP, 0); } private void m_btn_help_Clicked(object sender, System.EventArgs e) { if( m_hlpbtn_timer == null) { m_hlpbtn_timer = new Timer(); m_hlpbtn_timer.Interval = 100; //100 milli-seconds , 1/10 seconds m_hlpbtn_timer.Tick += new EventHandler(m_timer_Tick); } m_hlpbtn_timer.Start(); } private void m_timer_Tick(object sender, EventArgs e) { DefWindowProc(this.Handle, WM_SYSCOMMAND, SC_CONTEXTHELP, 0); m_hlpbtn_timer.Stop(); } This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
http://www.codeproject.com/Articles/21880/Context-Help-authoring-anywhere-anytime-anyone-for
CC-MAIN-2014-52
refinedweb
620
56.05
. > > And yet, I've come across online murky warnings against using > classes as "pseudo-namespaces". Is there some problem that I'm > not seeing with this technique? > > ~K I don't see anything wrong with this, except that I would clean it up in a couple ways. Like other posters, I would give the class a proper class name (Cfg). I also would not assign integers to spam, jambon, or huevos. Instead I would assign each a bare object(). That way you won't get unexpected interactions with other constants outside the class. An object() is equal only to itself. I would also not rule out letting your "pseudo-namespace" grow into a full-fledged class. If you've got a method that makes sense with your class, use it. class Cfg(object): spam = object() jambon = object() huevos = object() def get_animal(self, meat): if meat == self.jambon: return 'pig' elif meat == self.huevos: return 'chicken' elif meat = self.spam: return 'spamalope' Later, perhaps, you might refactor so that each meat type (OK so huevos aren't a meat) gets its own subclass, with a simple, one-line get_animal method. Cheers, Cliff
https://mail.python.org/pipermail/python-list/2010-March/572210.html
CC-MAIN-2016-50
refinedweb
191
75.61
I have a growing workspace with multiple Ext applications, and it feels like we should move some common components to the 'workspace/common/src' directory so they can be reused. I have made an attempt at doing this with one View and its Controller. I've got it working statically but it won't compile, and I am not feeling good about it. Even with the viewing the app without compiling I have couple of console errors. So, I'm approaching this wrong, any advice would be most appreciated! My workspace sencha.cfg includes workspace.classpath=${workspace.dir}/common/src So, in an experimental repo I moved 'workspace/appName/app/controller/HeaderController.js' to 'workspace/common/src/controller/HeaderController.js' I redefined that file from 'AppName.controller.HeaderController' to 'ProductName.controller.HeaderController' I did a similar process with the view. My app.js, having an array of controllers, this one included, didn't like this. So, I put a stub controller back in the app with original definition, but extending the new common controller. I found references in bootstrap.js for both the view and controller definitions and manually modified them. I also modified the Viewport.js requires to include the new view. I think that's the extent of it. I'm getting 2 console errors, one for each file: 'Uncaught SyntaxError: Unexpected Token >' There errors are a result of ext-all-dev.js trying to load the files at paths that don't exist, akin to: I'm not sure why that's happening, but it alerts me that I must be doing this wrong. What is the correct way? Please feel free to ask for more info if I haven't provided enough. Lastly, when I try to compile, I get this error: "failed to find meta class definition for name AppName.view.HeaderView" Which is bizarre to me, because I no longer have this defined anywhere. I changed it to ProductName.view.HeaderView and changed all references in the workspace. The only thing I can think of is that the ProductName.controller.HeaderController lists ['HeaderView'] without specifying namespace and so maybe the controller subclass of that is trying to resolve it to AppName.view. I'm not sure. Thank you kindly!
https://www.sencha.com/forum/showthread.php?257522-Shared-components-in-common-directory-of-workspace&p=943548&viewfull=1
CC-MAIN-2016-36
refinedweb
375
60.72
hi i m doing my project using java desktop application in netbeans.i designed a form to get the user's academic details and on clicking the submit button,it displays all the inputs given by the user.i had a java program for it and accessed it by creating an object for it.my java code is public class submit { JFrame frame; JTextArea text1; void form() { frame=new JFrame("details you have entered are"); JPanel cp=new JPanel(); text1=new JTextArea(); cp.add(text1); frame.add(cp); frame.setSize(450,320); frame.setVisible(true); } } now my next step is i have to take these details and make a file that can be appended each time.how to achieve this in jframe ? can you please post me the code for it ? Thank you, waiting for reply..!! Ads Ads
http://www.roseindia.net/answers/viewqa/Swing-AWT/21438-How-to-create-file-from-input-values-in-Jframe-.html
CC-MAIN-2016-40
refinedweb
138
73.27
What I Am Implement This – I am sure now you understand the concept of drag and drop, this one is trending functionality for any app. Near about all my client wants to implement this functionality in his app for various purposes. That’s why I am going to write a blog on this topic, I am sure you like it, so let’s start the topic. What is react-native drag and drop-board – react-native-drag and drop-board is a third-party npm library for creating drag and drop functionality, it is popular. Introduction – This is a simple React Native library, enabling you to create a scrollable board component with a carousel, sortable columns, and draggable cards for your iOS and Android apps. Are react-native-drag and drop-board popular – The react-native-drag and drop-board receive a total of 123 weekly downloads and 114 stars GitHub. As such, react-native-drag and drop-board popularity were classified as limited but it gets the good star and I like it. So let’s start please follow each step carefully… Step 1 – Installation First, we need to install the third-party npm plugin. npm install react-native-draganddrop-board or yarn add react-native-draganddrop-board Step 2 – Import After installing the npm plugin successfully, now we need to import that plugin into your file. import { BoardRepository } from 'react-native-draganddrop-board' Step 3 – Set up the data Now we are going to create a formate for data, which we show in this box, you can customize it based on your requirements. const data = [ { id: 1, name: 'TO DO', rows: [ { id: '1', name: 'Analyze your audience', description: 'Learn more about the audience to whom you will be speaking' }, { id: '2', name: 'Select a topic', description: 'Select a topic that is of interest to the audience and to you' }, { id: '3', name: 'Define the objective', description: 'Write the objective of the presentation in a single concise statement' } ] }, { id: 2, name: 'IN PROGRESS', rows: [ { id: '4', name: 'Look at drawings', description: 'How did they use line and shape? How did they shade?' }, { id: '5', name: 'Draw from drawings', description: 'Learn from the masters by copying them' }, { id: '6', name: 'Draw from photographs', description: 'For most people, it’s easier to reproduce an image that’s already two-dimensional' } ] }, { id: 3, name: 'DONE', rows: [ { id: '7', name: 'Draw from life', description: 'Do you enjoy coffee? Draw your coffee cup' }, { id: '8', name: 'Take a class', description: 'Check your local university extension' } ] } ] //this is important const boardRepository = new BoardRepository(data); Step 4 – Design the view Now we set up the view for showing the boards. import { Board } from 'react-native-draganddrop-board' <Board boardRepository={boardRepository} open={() => {}} onDragEnd={() => {}} /> Step 5 – Components Step 5 – Run the project Now you can run your project on android or ios and check your view. For more please check – So we completed the react-native drag and drop functionality which is “How To Implement Drag And Drop in React Native“ You can find my next post here. You can find my post on medium as well click here please follow me on medium as well. If have any query or issues, please feel free to ask. Happy Coding Guys.
https://www.itechinsiders.com/how-to-implement-drag-and-drop-fuin-react-native/
CC-MAIN-2022-21
refinedweb
542
52.94
In Excel 2007 it’s possible to add controls, referenced by a qualified ID (idQ attribute), to the Quick Access Toolbar, and in Excel 2010, to add controls to the Quick Acces Toolbar, or the ribbon. Furthermore, it is possible to add and/or position custom controls on or next to the Analysis tab, or groups on the Analysis tab, by using attributes like insertBeforeQ and insertAfterQ. The approaches for configuring the Ribbon are beyond the scope of this article – See here and here for an overview. This article provides a summary of the qualified control IDs (idQ attributes) for the Analysis tab, and the groups on the Analysis tab. They’re qualified by namespace: “SBO”, but you can use a namespace of your own choosing. The Analysis Tab idQ=”SBO:com.sap.ip.bi.analysis.menu” The Analysis Groups Data Source: idQ=”SBO:com.sap.ip.bi.newpioneer.excel.dataconnections” Undo: idQ=”SBO:com.sap.ip.bi.newpioneer.excel.backandforward” Data Analysis: idQ=”SBO:com.sap.ip.bi.newpioneer.excel.dataanalysis” Display: idQ=”SBO:com.sap.ip.bi.newpioneer.excel.display” Insert Component: idQ=”SBO:com.sap.ip.bi.newpioneer.excel.insertGroup” Tools: idQ=”SBO:com.sap.ip.bi.newpioneer.excel.tools” Planning: idQ=”SBO:com.sap.ip.bi.newpioneer.excel.planning” Design Panel: idQ=”SBO:com.sap.ip.bi.newpioneer.excel.Taskpanel” Settings: idQ=”SBO:com.sap.ip.bi.newpioneer.excel.setting” Hi, Andrew, Thank you for a big number of useful tips! If you have also found idQ-s for buttons, I would be very grateful. Ksenia Hi Ksenia, Sorry for the late reply. I’m not sure which buttons you need the idQ-s for? I’ll try to put a more complete list together, but here are 3 of the most commonly used buttons: If you have a need for a particular idQ, please let me know. Refresh All: idQ=com.sap.ip.bi.pioneer.core.command.refresh Prompts: idQ=com.sap.ip.bi.pioneer.core.command.refreshWithPrompt Show/Hide Design Panel: idQ=com.sap.ip.bi.newpioneer.excel.displaytaskpanel Hi, Andrew! Thank you for sharing, that was exactly what I needed 🙂 Hi Andrew, Currently i have a requirement to disable built-in prompts button in data analysis group in Analysis Tab or make all variables displayed in the prompts as Read only. Is any of the above approach is possible? Also i got the idQ of Prompts and Data Analysis from your above reply. Hey Andrew, I’m currently using the UI Editor to add a new tab, which should include different ribbons (own created ones and Analysis specific ones). My coding looks like this: And it displays this: My goal is to use the group “Planning” from the Analysis tab within my own tab “Planning functions”. Am I doing it wrong? Can you help me? Thanks in advance Kind regards Dominik Hi Andrew, thank you for this great article. I have not found another comprehensive list of Analysis controls to be used in a custom ribbon. I would like to use the “Save data” button of the planning group (without the other plannning buttons). Can you provide this ID-Q, too? Any hint is very much aprechiated! Thanks, Leo Hey Leo, I can share some simple VBA solution with you. We have used the UI editor to create a customized ribbon. Afterwards we have assigned Analysis functions via VBA. You can find the required codings in the Analysis for Office User Guide. Our customized buttons look like this: The VBA coding is really simple: Kind regards Dominik Hi Dominik, thanks for your input. This is a good solution. In the meantime, I have found the control id for the “Save data” button: idQ=”com.sap.ip.pioneer.core.command.savePlanValues” It works just like the Button/VBA you implemented, with the difference of being “greyed-out” whenever there is nothing to save. Best regards, Leo
https://blogs.sap.com/2013/10/30/customuiribbon-qualified-ids-for-analysis-tab-and-group-controls/
CC-MAIN-2018-43
refinedweb
652
51.04
As an example, some of the core Kubernetes components like etcd have their corresponding Operators made available by the CoreOs project. Etcd is a distributed key-value store that reflects the running state of the entire Kubernetes cluster at any given instant. Naturally, it is a stateful application and various Kubernetes controllers refer to etcd in order to figure out what their next step is going to be. For example, ReplicaSet controller will look at the number of pods running under a given selector and try to bring the number of running instances equal to the number specified by your ReplicaSet or Deployment YAML. The ReplicaSet refers to etcd which keeps track of the number of running pods and once the number of pods is changed to a desired value the etcd would update its record of it too. But when it comes to Stateful applications, like etcd itself, we can’t spin up more pods across different nodes without some serious intervention. Because all the running instances must have data consistent with one another at all times. This is where Operators come in handy. Prerequisites If you wish to follow along in this tutorial you can start with something small like a Minikube installed on your laptop, or the Kubernetes distribution that comes with Docker for desktop. The important thing is to have an understanding of the basic ideas of Kubernetes to begin with. Etcd Let’s create an Operator that would manage etcd across our Kubernetes cluster. We won’t be installing etcd as a Kubernetes component (that is to say in the kube-system namespace) but as a regular application. Because doing that would put the entire cluster at risk. However, once you are comfortable with Operators you can use them to deploy etcd in the kube-system as you are bootstrapping a new cluster. I will be using Katacoda Playground here, and a closer inspection of the kube-system namespace would show you that we have one pod running etcd for us. But that is not something we will be fiddling with. We will install etcd in default namespace managed by etcd-operator Starting out the default namespace has no pods running, we have a clean slate. No resources found. Now let’s install a new etcd instance in this namespace. We start by cloning the repository followed by a simple kubectl command. $ cd etd-operator Creating Etcd Operator In the repo, there are several examples to operate on, the first would create a simple etcd operator using deployment.yaml file. Before we use that we first need to create a Role for the operator via which is can manage and scale the etcd cluster. You can create that Role using a shell script. $ kubectl create -f ./example/deployment.yaml The operator object will be created by the last command although there will nothing to operate on. We don’t have an etcd cluster yet. So let’s create one. This creates a cluster of etcd pods. You can see them using: NAME READY STATUS RESTARTS AGE etcd-operator-69b559656f-495vg 1/1 Running 0 9m example-etcd-cluster-9bxfh657qq 1/1 Running 0 23s example-etcd-cluster-ntzp4hrw79 1/1 Running 0 8m example-etcd-cluster-xwlpqrzj2q 1/1 Running 0 9m The first one in this list is the operator pod which would ensure that the etcd cluster maintains a certain state, as stated in the yaml files we used earlier. If you try deleting one of the example-etcd-cluster pods, another one will be created to take its place. That’s remarkably similar to what ReplicaSet does but here that pods are stateful! Operators in General As mentioned earlier, Operators are a general framework within which one can deploy and manage complex applications. The framework itself is what makes them useful and the particular examples like etcd operator or Prometheus operator that CoreOS provides are meant to act as a guide for you to develop your own application in a similar manner. A few important aspects of Kubernetes Operators are the SDK used for writing, building and testing your own custom operator, the second is the idea of Operator Life Cycle Manager wherein you can think about all the various stages that your operator as well as the service it offers can go through. The life cycle stages might include various updates, figuring out what operator is running in which namespaces and also updating the operators when a new version comes along. References You can read a lot more about this technology in: - CoreOS’ original post, and - The etcd operator can be explore here
https://linuxhint.com/kubernetes_operator/
CC-MAIN-2019-39
refinedweb
772
59.13
This C# Program Demonstrates Pass by Value Parameter . Here Passing a value-type variable to a method by value means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the argument variable. Here is source code of the C# Program to Demonstrate Pass by Value Parameter . The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below. /* * C# Program to Demonstrate Pass by Value Parameter */ using System; class program { static void Cube(int x) { x = x * x * x; Console.WriteLine("Value Within the Cube method : {0}", x); } static void Main() { int num = 5; Console.WriteLine("Value Before the Method is called : {0}", num); Cube(num); Console.WriteLine("Value After the Method is called : {0}", num); Console.ReadKey(); } } Here is the output of the C# Program: Value Before the Method is called : 5 Value Within the Cube method : 125 Value After the Method is called : 5 Sanfoundry Global Education & Learning Series – 1000 C# Programs. If you wish to look at all C# Programming examples, go to 1000 C# Programs.
https://www.sanfoundry.com/csharp-program-pass-by-value-parameter/
CC-MAIN-2018-26
refinedweb
196
64.2
Ok, My question for this one is a bit more complicated. What I am trying to do is to get the program to first calculate the Basal Metabolic Rate, then the amount of calories needed to maintain the current weight, and lastly convert it. It compiles, but I believe I established my functions wrong because they do not seem to calculate properly. Any suggestions? Code:#include <iostream>#include <cmath> using namespace std; float metabolic_rate; // Returns the metabolic_rate as a floating point value. float digestion_energy; // Returns the digestion_energy as a floating point value. int main () { int P, intensity, minutes, calories, servings; double weight = P; double metabolic_rate = 70 * pow ( P / 2.2 , 0.756 ); double activity = 0.0385 * intensity * P * minutes; double digestion_energy = calories * .01; { cout << "Welcome to the Basal Metabolic Rate program."; cout << endl; cout << "First we need your weight. Please enter your weight: "; cin >> weight; cout << endl; cout << "Please enter the intensity of your workout: "; cin >> intensity; cout << endl; cout << "Please enter the duration (in minutes) that you worked out: "; cin >> minutes; cout << endl; cout << "Please enter the calories you consumed: "; cin >> calories; cout << endl; { cout << "We will first find the ammount of calories to start your Basal Metabolic Rate." <<endl; cout << "Your Basal Metabolic Rate is: "; cout << metabolic_rate << endl; cout << endl; } { cout << "Next we will calculate the calories required for your activity." << endl; cout << "The total ammoount of calories you need is: "; cout << digestion_energy; cout << endl; } { cout << "Lastly we will convert the calories you need into servings."; cout << "You must have a total of: "; cout << servings; cout << " in order to maintain your current weight."; } } return 0; }
http://cboard.cprogramming.com/cplusplus-programming/141364-more-complex-function.html
CC-MAIN-2014-35
refinedweb
267
60.95
Are you sure? This action might not be possible to undo. Are you sure you want to continue? by Willi-Hans Steeb, Gert Cronje and Yorick Hardy International School for Scientific Computing Contents 1 Linux Basics 1.1 Some Basic Commands . . . . . . . . . . . . . 1.2 Working with Files and Directories . . . . . . 1.2.1 Introduction . . . . . . . . . . . . . . . 1.2.2 The Home Directory and Path Names 1.2.3 Important Directories in the Linux File 1.2.4 Basic Files and Directories Commands 1.2.5 File Name Substitution . . . . . . . . . 1.3 Standard Input/Output, and I/O Redirection 1.4 Additional Commands . . . . . . . . . . . . . 2 Advanced Linux 2.1 The Unix File System . . . . 2.2 Mounting and Unmounting . . 2.3 MTools Package . . . . . . . . 2.4 Swap Space and the Loopback 2.5 Network File-System . . . . . 2.6 Linuxconf . . . . . . . . . . . 2.7 Compressed Files . . . . . . . 2.8 The vi and emacs Editors . . 2.8.1 vi Editor . . . . . . . . 2.8.2 emacs Editor . . . . . 2.9 Programming Languages . . . 2.9.1 C and C++ Compiler 2.9.2 Perl . . . . . . . . . . 2.9.3 Lisp . . . . . . . . . . 2.9.4 Java . . . . . . . . . . 3 Linux and Networking 3.1 Introduction . . . . . 3.2 Basic Commands . . 3.3 email . . . . . . . . . 3.4 ftp Commands . . . 3.5 Telnet . . . . . . . . 3.6 Remote Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 9 9 10 12 13 30 34 41 63 63 66 71 72 73 74 75 78 78 86 89 89 91 92 93 95 95 96 106 112 115 117 . . . . . . . . . . . . . . . . . . . . System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i 3.7 3.8 Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 INETD and Socket Programming . . . . . . . . . . . . . . . . . . . . 119 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 . 123 . 127 . 128 . 129 . 130 . 130 . 134 . 137 . 145 . 149 . 154 . 154 . 163 . 167 173 . 173 . 174 . 175 . 177 . 178 . 179 . 180 . 182 . 183 . 187 . 188 . 189 . 190 . 194 . 195 . 196 . 199 . 200 . 201 . 208 . 213 . 220 223 4 Shell Programming 4.1 What is a shell . . . . . . . . . . . . . 4.2 The Shell as a Programming Language 4.2.1 Creating a Script . . . . . . . . 4.2.2 Making a Script executable . . 4.3 Shell Syntax . . . . . . . . . . . . . . . 4.3.1 Variables . . . . . . . . . . . . . 4.3.2 Conditions . . . . . . . . . . . . 4.3.3 Control Structures . . . . . . . 4.3.4 Logical AND and Logical OR . 4.3.5 Functions . . . . . . . . . . . . 4.4 Shell Commands . . . . . . . . . . . . 4.4.1 Builtin Commands . . . . . . . 4.4.2 Command Execution . . . . . . 4.5 Advanced examples . . . . . . . . . . . 5 Perl 5.1 Introduction . . . . . . . . . . 5.2 My First Perl Program . . . . 5.3 Data Types . . . . . . . . . . 5.4 Arithmetic Operation . . . . . 5.5 Standard Input . . . . . . . . 5.6 Basic String Operations . . . 5.7 Conditions . . . . . . . . . . . 5.8 Logical Operators . . . . . . . 5.9 Loops . . . . . . . . . . . . . 5.10 goto Statement . . . . . . . . 5.11 Mathematical Functions . . . 5.12 Bitwise Operations . . . . . . 5.13 List Operations . . . . . . . . 5.14 Associative Arrays Operations 5.15 Pattern Matching . . . . . . . 5.16 Regular Expressions . . . . . 5.17 Map Operator . . . . . . . . . 5.18 Two-Dimensional Arrays . . . 5.19 Subroutines . . . . . . . . . . 5.20 Recursion . . . . . . . . . . . 5.21 File Manipulations . . . . . . 5.22 Networking . . . . . . . . . . Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii Index 223 iii Bell Telephone laboratories and Project MAC at MIT. Standards: Linux implements a superset of the POSIX standard. (e. command1 | command2) – Hierarchical file system.Preface Linux is a Unix-like operating system. – Multiple command interpreters (or shells). the pipe implmentation in DOS does not support simultaneous execution. It is the outcome of years of computer system development: • Multics – 1964-1965 – General Electric. the original author. • Unix – 1969 – Bell Telephone Laboratories. In Unix the programs execute simultaneously. It’s dependent – it contains no code written by Bell Labs or its successors.no licensing fee payable to anybody. (e. Historical Overview Linux did not appear out of thin air. the output form one program is the input for another. – SUID flag. directed by Linus Torvalds.g. It’s free . – A file system for secondary storage. – Input/output redirection.i. iv . It is the result of an international collaboration. The source code comes with the system. – Dynamic libraries. – High level language (PL/I).g. A process started by a executable file takes on the identity and privileges of the owner of the file. The Linux kernel is licensed under Free Software Foundation’s General Public License. Supported architectures: Pentium PentiumPro Amiga PowerPC SUN SPARC DEC Alpha Atari Ports in progress: ARM and MIPS (SGI machines).e. command1 > temp_file) – Pipes . – Security rings. E.H.the X-window system Application Programs for Linux • Motif and the Command Desktop environment • Several commercial X-servers • AplixWare (Office Suite) • CorelDraw (Graphics program) • WordPerfect(Office Suite) • StarOffice (Office Suite . A number of other systems have made contributions which have become an essential part of Linux and current Unix systems. TUNIS. Do not hesistate to throw out clumsy parts and rebuild them. Unix has been described as an operating system kernel with twenty years of nifty add on utilities. – Teach operating systems design. Rather write a new program than complicate old programs by adding new ”features”. Xinu and Minix.Unix Philosophy Unix prescribes a unique philosophy of how system tools should be designed: – Make each program do one thing well. The result of the above is that a typical Unix system has hundreds of obscure programs. – Design and build software to be tried early. commands and tools.Free for non-commercial use) • SymbolicC++ v . Bit mapped display . – Expect the output of any program to become the input of any other program Don’t insist on interactive input. even if we have to detour to build the tools. – Minix prompted the development of Linux also on the Intel 80386.. T. – Use tools to lighten a programming task. Other contributions. These are: – – – – Multi-User Virtual Memory Filename expansion in command lines (globbing or wildcard expansion). – Minix was written for the cheap Intel 8086 platform. Free) • Scilab (Matlab-like.Free) • PV Wave (Visualisation) • Microstation (CAD program) • NexS (Internet enabled spreadsheet) • Netscape (WWW browser) • The GNU Project • SUN Java Developer Kit • Oracle. Excellent for control systems .• Mathematica • Reduce • Maple • Matlab • Octave (Matlab-like package . Program Development Available programming languages include: C ADA C++ APL Objective C Basic Pascal Logo Fortran Smalltalk Forth Perl Simula Postscript Oberon Common Lisp TCL/TK Compatibility Binary compatibility Intel Linux runs several other x86 Unix binaries (for example SCO Unix).Free) • Khoros (Image processing and visualization . vi Scheme Eiffel Modula 2 and 3 Java Prolog Rexx CORC and CUPL INTERCAL . SPARC Linux runs SunOs and some Solaris binaries. za steeb_wh@yahoo.rau. To fix this problem under OS/2. The email addresses of the author is: whs@na.za vii .Networking • Ethernet • Token ring • TCP/IP • IPX (Novell) • SMB (OS/2 Warp server / NT Server / Windows for Workgroups) • Appletalk We note that MS-DOS and OS/2 use different control characters for carriage return and linefeeds that Unix does.rau.za. A well known error is the staircase effect. by which time the library programmers will have upgraded the system software to store dates as 64-bit integers. edit the file under OS/2 and delete and retype the first two characters.rau. which count the seconds since 1970.com The web sites of the author are:. This counter will not overflow until the year 2038.ac. We note that this difference between MS-DOS and Unix may also produce problems when printing. Linux uses libraries that store dates as 32-bit integers. We assume the use of the Bourne shell or a compatible shell. The command prompt is indicated by > in the following. time (24 hour clock. DOS and Windows also have the date command. Under DOS and Windows command line commands are not case-sensitive. The date Command The date command tells the system to print the date and time: > date Tues Jun 27 11:38:37 SAST 2000 > This means date prints the day of the week.1 Some Basic Commands Here we introduce some basic command line commands in LINUX and UNIX. The who Command The who command can be used to get information about all users who are currently logged into the system: > who pat ruth steve > tty29 tty37 tty25 Oct 29 14:40 Oct 29 10:54 Oct 29 15:52 1 . Every UNIX and LINUX command is ended with the pressing of the RETURN (or ENTER) key. month. and year. Finding Out Who’s Logged In. South African Standard Time). day. RETURN (or ENTER) says that we are finished typing things in and are ready for the UNIX system to do its thing. We notice that LINUX and UNIX commands are case-sensitive. Displaying the Date and Time.Chapter 1 Linux Basics 1. 2 CHAPTER 1. LINUX BASICS Here there are three users logged in, pat, ruth, and steve. Along with each user id, is listed the tty number of that user and the day and time that user logged in. The tty number is a unique identification number the UNIX system gives to each terminal. The who command also can be used to get information about yourself > who am i pat tty29 > Oct 29 14:40 who and who am i are actually the same command: who. In the latter case, the am and i are arguments to the who command. Echoing Characters. The echo Command The echo command prints (or echoes) at the terminal whatever else we happen to type on the line. A newline is included by default. > echo this is a test this is a test > echo why not print out a longer line with echo? why not print out a longer line with echo? > echo > echo one two one two three four five > three four five From the last example we see that echo squeezes out extra blanks between words. That is because on a UNIX system, it is the words that are important; the blanks (whitespace with ASCII table number 32) are merely there to separate the words. Generally, the UNIX system ignores extra blanks. Normally echo follows all the output with a newline. The option echo -n suppresses that. Another option is echo -e it enables interpretation of backslashed special characters in the string. \b: backspace, \f: form feed, \n: newline, \r: carriage return, \t: horizontal tab, \\: backslash. The echo command also exists in DOS and Windows. Reporting working directory. The pwd Command The pwd command reports the present working directory. > pwd /root > 1.1. SOME BASIC COMMANDS 3 Reporting the status of currently running processes. The ps command The ps command reports the status of currently running processes. Thus this command gives us information about the processes that are running on the system. ps without any options prints the status of just our processes. If we type in ps at our terminal, we get a few lines back describing the processes we have running: > ps PID 195 1353 1258 > TTY 01 01 01 TIME 0:21 0:00 0:10 COMMAND bash The shell ps The ps command sort The previous sort The ps command prints out four columns of information: PID, the process id; TTY, the terminal number that the process was run from; TIME, the amount of computer time in minutes and seconds that process has used; and COMMAND, the name of the process. The sh process in the above example is the shell that was started when we logged in, and it used 21 seconds of computer time. Until the command is finished, it shows up in the output of the ps command as a running process. Process number 1353 in the above example is the ps command that was typed in, and 1258 is the sort operation. When used with the -f option, ps prints out more information about our processes, including the parent process id (PPID), the time the processes started (STIME), and the command arguments. > ps -f UID steve steve steve PID 195 1360 1258 PPID C 1 0 195 43 195 0 STIME 10:58:29 13:54:48 13:45:04 TTY tty01 tty01 tty01 TIME 0:21 0:01 3:17 COMMAND -sh ps -f sort data > Because processes rapidly progress in their execution path, this report is only a snapshot view of what was happening when we asked. A subsequent invocation of ps may give different results. No options shows a picture of the currently executing processes on our terminal. The following options are available for the ps command. 4 Item Description -l Gives a long listing. -u -j -s -v -m -a -x -S -c -e -w -h -r -n txx CHAPTER 1. LINUX BASICS Prints in user format displaying the user name and start time. Gives output in the jobs format. Gives output in signal format. Displays output in virtual memory format. Displays memory information. Shows processes of other users as well. Displays processes without a controlling terminal. Adds child CPU time and page faults. Lists the command name from the kernel tast_structure. Shows the environment. Displays in wide format. Does not truncate command lines to fit on one line. Does not display a header. Displays running processes only. Provides numeric output for USER and WCHAN. Displays only processes with the controlling tty xx. The -t and -u options are particularly useful for system administrators who have to kill processes for users who have gone astray. The following columns are reported: 1.1. SOME BASIC COMMANDS Column PID PRI NI SIZE RSS Description The process ID. Process priority. 5 The Linux process nice value. A positive value means less CPU time. The virtual image size, calculated as the size of text+data+stack. The resident set size. The number of kilobytes of the program that is currently resident in memory. WCHAN The name of the kernel event that the process is waiting for. STAT The process status. Given by one of the following codes: R Runnable S Sleeping D Uninterruptible sleep T Stopped or traced Z Zombie Q Process has no resident pages The name of the controlling tty (terminal) for the process. The number of page faults that have caused pages to be read from disk. The text resident size. The number of kilobytes on the swap device. TTY PAGEIN TRS SWAP Environment variables. The printenv command The printenv prints the values of all environment variables. These environment variables include the following • USERNAME - our current username (account name). • ENV=/home/gac/.bashrc - default file for setting environment variables for this shell. • HOSTNAME=issc.rau.ac.za - hostname of the computer. • MAIL=/var/spool/mail/gac - where incoming mail is placed. • PATH=/usr/local/bin:/bin - search path for executable files. • IFS - internal field separator. Under LINUX we use the clear command. The clear command Sometimes after filling our terminal screen with information. Clearing Terminal Screen. the command apropos cls is the same as man -k cls. > clear Under DOS. Linux provides help on the ls command. Typing More Than One Command on a Line We can type more than one command on a line provided we separate each command with a semicolon. we want a blank screen. The command man -k cls provides a listing of commands that have the word cls in the help file. including all its parameters. a screen at a time.6 CHAPTER 1. we use the cls command. the following lines must be added to the . For example. > man ls ask for help on the ls command > man pvm_mytid ask for help on the pvm_mytid() function To quit the online help we enter q or CRTL-c. For example PVM (parallel virtual machine) need the following: PVM_DPATH=/usr/local/lib/pvm3/lib PVM_ROOT=/usr/local/lib/pvm3 To set this.bashrc file export PVM_ROOT=/usr/local/lib/pvm3 export PVM_DPATH=$PVM_ROOT/lib There are two ways to access the value of an environment variable: • printenv SHELL • echo $SHELL UNIX and LINUX on-line manual pages. Linux then displays. any information it has on the command. we can type man. Linux also provides an alias for this command called apropos. man then searches through its help files (called man pages) for a topic that contains the keyword. If we are not sure of what command to use. LINUX BASICS A number of programs require certain environment variables to be set. The man command To get on-line help for each of the various Linux commands. If we enter the command man ls. we can try the -k parameter and enter a simple keyword that represents the topic of interest. we can find out the current time and also our current working directory by typing on the date and pwd commands on the same line . maybe a second or two. There are several safe ways to shut down a Linux system: • shutdown . the UNIX and LINUX system automatically displays a number. However. as long as each command is delimited by a semicolon. Sending a Command to the Background Normally. If we type in a command followed by the ampersand character &. called the process id for that command. For all the examples we have seen thus far. we have to wait for the command to finish executing before we can proceed further unless we execute the command in the background. 1258 was the process id assigned by the system. SOME BASIC COMMANDS > date. this waiting time is typically quite short . In the above example. pwd Tues Jun 27 11:41:21 SAST 2000 /usr/pat/bin > 7 We can string out as many commands as we like on the line. Linux is an operating system that has to be told that we want to turn it off. In those cases. If we turn the power off. before writing the information to the disk. it will be as if CTRL-d were typed. we may have to run commands that require many minutes to execute. and we can damage our file-system. The standard output from the command will still be directed to our terminal. This is done with the ps command.1. An immediate system shutdown will be initiated. in most cases the standard input will be dissociated from our terminal. .Type this command while we are logged in as root. we type in a command and then wait for the results of the command to be displayed at the terminal. this information is lost. > sort data > out & send the sort to the background 1258 process id > date terminal is immediately available Tues Jun 27 11:38:37 SAST 2000 > When a command is sent to the background.1. and can be used to obtain status information about the command. then that command will be sent to the background for execution. This means that the command will no longer tie up our terminal and we can then proceed with other work. This process helps to improve system performance and control access to the hardware. in areas called buffers. This number uniquely identifies the command that we sent to the background. If the command does try to read any input from standard input. Shutting down Linux Linux keeps a lot of information about itself and files in memory. However. • halt . to all users. shutdown lets us control when the shutdown takes place. With this option. • CRTL-Alt-Del . . Does a fast reboot. Just sends the warning messages to everybody. Does not really shut down the system. Doesn’t synchronize the disks before rebooting or halting. warning -t n -k -r -h -n -f -c shutdown can only be run by the super user. > shutdown -h now This shuts down the system and halts it immediately. and it notifies the users on a regular basis. halts after shutdown. Cancels an already running shutdown. It also sends the message System rebooting. it is not possible to give the time argument..This key sequence is mapped to the shutdown command. Reboots after shutdown. For example > shutdown -r +15 "System rebooting.The system will shut down and reboot..8 CHAPTER 1. Messages are sent to the users’ terminals at intervals bases on the amount of time left till the shutdown..The system will shut down. LINUX BASICS • reboot . shutdown safely brings the system to a point where the power may be turned off. > shutdown [options] time [warning] Item time Description The time to shut down the system.. This is the easiest way to shut down our LINUX system. but it will not reboot. Wait n seconds between sending processes the warning and the kill signal." This shuts down the system and reboots it 15 minutes from the time the command was entered. A warning message sent out to all users. but we can enter an explanatory message on the command line that is sent to all users. Refer to the man page for a full description of the available time formats. Does not check any file systems on reboot. The filename . A process can create new processes. A path name is the path from the root. Linux consists of two separable parts. A process is a program in execution. The Unix file system is structured as a tree. In normal use. Absolute pathnames start at the root of the file system and are distinguished by a slash at the beginning of the pathname.1. backslash. the kernel and the system programs. The kernel provides the file system. and space. The tree has a root directory. Relative pathnames start at the current directory. but are accessed by the user by the same system calls as other files. As its name implies. program instructions.1 Working with Files and Directories Introduction The LINUX and UNIX system recognizes only three basic types of files: ordinary files. or just about anything else. Linux has both absolute pathnames and relative pathnames. question mark. Hardware devices have names in the file system.and uppercase. . in a directory is a hard link to the directory itself.2. Directories are described later in this chapter. Linux allows filenames to be up to 256 characters long. Directories are themselves files that contain information on how to find other files.. The file name . usually the dash -. text.2. Every file in the system has a unique path name. a special file has a special meaning to the UNIX system. memory management. because these all have meaning to the shell. One bit in each directory entry defines the entry as a file (0) or as a subdirectory (1). each user has a current directory (home directory). directory files. Processes are identified by their identifiers which is an integer. They cannot include reserved metacharacters such as asterisk. and other operating system functions through system calls. and is typically associated with some form of I/O. is a hard link to the parent directory. These device special files are known to the kernel as the device interface. and special files.2 1. . Linux supports multiple processes. WORKING WITH FILES AND DIRECTORIES 9 1. All directories have the same internal format. through all the subdirectories. numbers. All user data files are simply a sequence of bytes. The operating system is mostly written in C. and other characters. The user can create his own subdirectories. A directory (or subdirectory) contains a set of files and/or subdirectories. the underscore _ and the dot . An ordinary file is just that: any file on the system that contains data. to a specified file. These characters can be lower. cpu scheduling. Special system calls are used to create and delete directories. reply Figure 1. Therefore. A special directory known as / (pronounced slash) is shown at the top of the directory tree.A no. If we wish to access a file from another directory. When we log into the system.hire AMG. if we had the directories documents and programs the overall directory structure would actually look something like the figure illustrated in Figure 1.1.JSK dact new.2 The Home Directory and Path Names The UNIX system always associates each user of the system with a particular directory. we are placed automatically into a directory called the home directory. / pat documents memos plan proposals letters wb steve programs collect mon ruth sys. Hierarchical directory structure .1.10 CHAPTER 1. This directory is known as the root. Assume our home directory is called steve and that this directory is actually a subdirectory of a directory called usr. or we can specify the particular file by its path name. the files contained within the directory are immediately accessible. then we can either first issue a command to change to the appropriate directory and then access the particular file.2. LINUX BASICS 1. Whenever we are inside a particular directory (called our current working directory). reply contained along the appropriate directory path. which always refers to the current directory. always references the directory that is one level higher. would reference the documents directory. Another convention is the single period . successive directories along the path are separated by the slash character / . UNIX provides certain notational conveniences. Note that in this case there is usually more than one way to specify a path to a particular file. Similarly.1.. would reference the directory usr.. and . after logging in and being placed into our home directory /usr/steve. WORKING WITH FILES AND DIRECTORIES 11 A path name enables us to uniquely identify a particular file to the UNIX system. the path name /usr/steve/documents references the directory documents as contained in the directory steve under usr. for example. In order to help reduce some of the typing that would otherwise be require. The path is relative to our current working directory.reply identifies the file AMG. . For example./proposals/new. would reference the directory steve.2. As a final example. then the path name . the path name /usr/steve/documents/letters/AMG. the path name /usr/steve identifies the directory steve contained under the directory usr.hire contained in the proposals directory. A path name that begins with a slash is known as a full path name. By convention. . For example. the path name ./. In the specification of a path name.. since it specifies a complete path from the root. Path names that do not begin with a slash character are known as relative path names.hire would reference the file new... So. if we just logged into the system and were placed into our home directory /usr/steve. And if we had issued the appropriate command to change our working directory to documents/letters. the directory name . the relative path name programs/mon could be typed to access the file mon contained inside our programs directory. then we could directly reference the directory documents simply by typing documents.. Similarly. The /dev directories contains devices.12 CHAPTER 1. These files are usually text files and they can be edited to change the systems configuration. For instance if we copy to /dev/fd0 we are actually sending data to the systems floppy disk. Linux treats everything as a file. files that are executable. LINUX BASICS 1. root. spool holds files to be printed. Even the systems memory is a device. Our terminal is one of the /dev/tty files.3 Important Directories in the Linux File System We recall that / is the root directory. bin stands for binaries. The directory /sbin holds files that are usually run automatically by the Linux system. All information sent to /dev/null vanishes . mail holds mail files. These are special files that serve as gateway to physical computer components.2. The directory /home holds users’ home directories.it is thrown in the trash. If we enter the command ls -l we see that we must be the owner. This is sometimes called the bit bucket. It holds the actual Linux program as well as subdirectories. and uucp holds files copied between Linux machines. In other Unix systems this can be /usr or /u directory. The directory /etc and its subdirectory hold many of the Linux configuration files. . to run this commands. The directory /usr holds many other user-oriented directories. In the directory /var/spool we find several subdirectories. The directory /usr/bin holds user-oriented Linux programs. Partitions on the hard disk are of the form /dev/hd0. A famous device is /dev/null. The directory /usr/sbin holds administration files (executable files). The directory /bin holds many of the basic Linux programs. .2. and characters in file(s) or standard input if not supplied Link file1 and file2 Link file(s) into dir cd dir cp file1 file2 cp file(s) dir mv file1 file2 mv file(s) dir mkdir dir(s) rmdir dir(s) rm file(s) cat file(s) wc files(s) ln file1 file2 ln file(s) dir These commands are execute files in the bin directory.4 Basic Files and Directories Commands The UNIX and LINUX system provides many tools that make working with files easy. The commands we describe are ls file(s) ls dir(s) List file(s) List files in dir(s) or in current directory if dir(s) are not specified Change working directory to dir Copy file1 to file2 Copy file(s) into dir Move file1 to file2 Simply rename it if both reference the same directory Move file(s) into directory dir Create directories Remove empty directory dir(s) Remove file(s) Display contents or concatenates files Count the number of lines. WORKING WITH FILES AND DIRECTORIES 13 1.1.2. Here we review many of the basic file manipulation commands. words. the option -l is given to the wc command > wc -l names 5 names > To count just the number of characters in a file. .14 Command Options CHAPTER 1. These options generally follow the same format -letter That is. the -w option can be used to count the number of words contained in the file: > wc -w names 5 names > Some commands require that the options be listed before the file name arguments. LINUX BASICS Most UNIX and LINUX commands allow the specification of options at the time that a command is executed. the -c option is specified > wc -c names 27 names > Finally. For example > sort names -r is acceptable whereas > wc names -l is not. For example. In general the command options should precede file names on the command line. in order to count just the number of lines contained in a file named names. a command option is a minus sign followed immediately by a single letter. cc > 15 This output indicates that three files called READ_ME. and first. We can also use ls to obtain a list of files in other directories by supplying an argument to the command. So.cc are contained in the current directory.2. WORKING WITH FILES AND DIRECTORIES ls [files] . First we get back to our home directory > cd > pwd /usr/steve > Now we look at the files in the current working directory > ls documents programs > If we supply the name of one of these directories to the ls command. we can find out what’s contained in the documents directory simply by typing > ls documents letters memos proposals > to take a look at the subdirectory memos. To see what files we have stored in our directory. Whenever we type the command ls.List the contents of a directory.1. we can type the ls command: > ls READ_ME names first. names. then we can get a list of the contents of that directory. it is the files contained in the current working directory that are listed. we follow a similar procedure > ls documents/memos dact plan > . The first character on each line tells whether the file is a directory. If the character is d. These access modes apply to the file’s owner (the first three characters). then it is a special file. write to the file. among other things. They tell whether the user can read from the file. An l indicates a link. LINUX BASICS If we specify a nondirectory file argument to the ls command. or execute the contents of the file. we obtain > ls -l total 2 drwxr-xr-x drwxr-xr-x > 5 steve 2 steve FP3725 DP3725 80 Jun 25 13:27 documents 96 Jun 25 13:31 programs The first line of the display is a count of the total number of blocks of storage that the listed files use. then it is a directory.cc reverse order list directories .then it is an ordinary file. or p.16 CHAPTER 1. and finally to all other users on the system (the last three characters). we simply get that file name echoed back at the terminal > ls documents/memos/plan documents/memos/plan > There is an option to the ls command that tells us whether a particular file is a directory. other users in the same group as the file’s owner (the next three characters). The -l option provides a more detailed description of the files in a directory.cc -r -d also list hidden files list all file ending in . The next nine characters on the line tell how every user on the system can access the particular file. owner. If we were currently in steve’s home directory. Other command options are ls ls ls ls -a *. This means the ls -l shows file permissions. finally if it is b. size and last modification date. c. if it is . Each successive line displayed by the ls -l command contains detailed information about a file in the directory. since by convention .. This command takes as its argument the name of the directory we wish to change to.. We can verify at the terminal that the working directory has been changed by issuing the pwd command: > pwd /usr/steve/documents > The way to get one level up in a directory is to issue the command > cd . We know that there are two directories directly below steve’s home directory: documents and programs. Note the space (blank) after cd.1. always refers to the directory one level up known as the parent directory. 17 We can change the current working directory by using the cd command. In order to change our current working directory. The command cd. followed by the name of the directory to change to: > cd documents > After executing this command.Change directory. we issue the cd command. Let us assume that we just logged into the system and were placed inside our home directory.2. > pwd /usr/steve > If we want to change to the letters directory. without the space will not work in LINUX. WORKING WITH FILES AND DIRECTORIES cd directory . > cd . we will be placed inside the documents directory. /usr/steve.. we could get there with a single cd command by specifying the relative path documents/letters: .. This can be verified at the terminal by issuing the ls command: > ls documents programs > The ls command lists the two directories documents and programs the same way it listed other ordinary files in previous examples. Typing the command cd without and argument will always place we back into our home directory. The cd . > cd > pwd /usr/steve > The command > cd /tmp change directory to /tmp.18 > cd documents/letters > pwd /usr/steve/documents/letters > CHAPTER 1.. no matter where we are in our directory path.. (without space) in DOS and Windows. LINUX BASICS We can get back up to the home directory with a single cd command as shown: > cd .. > pwd /usr/steve > Or we can get back to the home directory using a full path name instead of a relative one: > cd /usr/steve > pwd /usr/steve > Finally. Note that / is the directory separator and not \ as in DOS. DOS and Windows also provide the cd command.. ./. there is a third way to get back to the home directory that is also the easiest. command in LINUX can be written as cd. . then the command . WORKING WITH FILES AND DIRECTORIES cp source dest or cp source.1. of course).. The command > cp file[0-9] /tmp copies files file0 through file9 to directory /tmp. The cp command can be used to make a copy of a file from one directory into another. then it is necessary to specify only the destination directory as the second argument > cp programs/wb misc > When this command gets executed.2. We can make a copy of the file names and call it saved_names as follows: > cp names saved_names > Execution of this command causes the file named names to be copied into a file named saved_names. The new file is given the same name as the source file. The first argument to the command is the name of the file to be copied known as the source file. 19 In order to make a copy of a file. The command > cp file1 /tmp copies file1 to /tmp/file1. and the second argument is the name of the file to place the copy into (known as the destination file. we can copy the file wb from the programs directory into a file called wbx in the misc directory as follows > cp programs/wb misc/wbx > Since the two files are contained in different directories. The fact that a command prompt was displayed after the cp command was typed indicates that the command executed successfully. directory . For example. the UNIX system recognizes that the second argument is the name of a directory and copies the source file into that directory. If we were currently in the programs directory. the cp command is used. We can copy more than one file into a directory by listing the files to be copied before the name of the destination directory. it is not even necessary that they be given different names > cp programs/wb misc/wb > When the destination file has the same name as the source file (in a different directory.Copy files. collect. To copy a file from another directory into our current one and give it the same name. The above command copies the file collect from the directory . use the fact that the current directory can always be referenced as ’../misc > CHAPTER 1. The copy command in DOS and Windows is copy. LINUX BASICS would copy the three files wb./ programs into the current directory (/usr/steve/misc).20 > cp wb collect mon ./programs/collect > .’ > pwd > /usr/steve/misc > cp .. . and mon into the misc directory under the same names.. 2. for example. WORKING WITH FILES AND DIRECTORIES mv source dest or mv source. We assume we have the proper permission to write to the file. when the two arguments to this command reference different directories. the UNIX system does not care whether the file specified as the second argument already exists. The first argument is the name of the file to be renamed.1. So we would like to move it from the memos directory into the proposals directory. We recall that the mv command can be used to rename a file. For example. then executing the command > cp names old_names would copy the file names to old_names destroying the previous contents of old_names in the process. then the file is acutally moved from the first directory into the second directory. Similarly.. For example. we enter the following command > mv saved_names hold_it > When executing a mv or cp command. Thus to change the name of the file saved_names to hold_it.. if a file called old_names exists. then the contents of the file will be lost. The command > mv file[a-g] /tmp moves file filea through fileg to directory /tmp. The command > mv file1 /tmp moves file1 to /tmp/file1. even if the file old_names existed prior to execution of the command. directory . The arguments to the mv command follow the same format as the cp command.Move or rename files. and the second argument is the new name. However. Thus we apply the command > mv memos/plan proposals/plan > . first change from the home directory to the documents directory > cd documents > Suppose now we decide that the file plan contained in the memos directory is really a proposal and not a memo. the command > mv names old_names would rename names to old_names. If it does. 21 A file can be renamed with the mv command. For example.22 CHAPTER 1. > mv programs bin > ./misc > This would move the three files wb.. > mv memos/plan proposals > Also like the cp command. a group of files can be simultaneously moved into a directory by simply listing all files to be moved before the name of the destination directory > pwd /usr/steve/programs > mv wb collect mon . We can also use the mv command to change the name of a directory. and mon into the directory misc. LINUX BASICS As with the cp command. then only the name of the destination directory need be supplied. collect. if the source file and destination file have the same name. the following will rename the directory programs to bin. . we should get the new directory listed. so "This is a very long filename" is a valid name for a file.1.2. The command > rmdir new_directory deletes the directory we created above. we wish to create a new directory called misc on the same level as the directories documents and program..Delete an empty directory. As an example.. The DOS and Windows command is also rmdir. If we were currently in our home directory.. the mkdir command must be used. The command > mkdir new_directory create a new directory called new_directory. . Note that the directory must be empty. rmdir dir.Create a directory. 23 To create a directory. WORKING WITH FILES AND DIRECTORIES mkdir dir. . Note that there is no practical limit on the length of file or directory names. The argument to this command is simply the name of the directory we want to make. then typing the command mkdir misc would achieve the desired effect > mkdir misc > Now if we execute an ls command. . In DOS and Windows the commands are md and mkdir. . To remove (delete) a file from the system. LINUX BASICS We can remove a directory with the rmdir command. The command > rm -r * deletes all files and directories recursively starting from the current directory. otherwise. it does not have to be empty.Remove files or directories. the above command will work only if no files are contained in the misc directory.24 rm name.. rm will remove the indicated directory and all files (including directories) in it. then we will not be allowed to remove the directory. we can use the -r option to the rm command. the following could be used: > rmdir /usr/steve/misc > Once again. the following would remove the three files wb. The stipulation involved in removing a directory is that no files be contained in the directory. If there are files in the directory when rmdir is executed.. To remove the directory misc that we created earlier. the following will happen: > rmdir /usr/steve/misc rmdir: /usr/steve/misc not empty > If this happens and we still want to remove the misc directory. i. then we would first have to remove all of the files contained in that directory before reissuing the rmdir command. The format is simple > rm -r dir where dir is the name of the directory that we want to remove. We can remove more than one file at a time with the rm command by simply specifying all such files on the command line. Note that there is no undelete command in Unix and Linux.e. For example. and mon > rm wb collect mon > The command > rm -r my_dir deletes directory my_dir recursively. we use the rm command. . CHAPTER 1. collect. The argument to rm is simply the name of the file to be removed > rm hold_it > As an alternate method for removing a directory and the files contained in it. For example. i.1.cc with nothing and sends the output to the screen. . let the file name be names > cat names Susan Jeff Henry Allan Ken > The command > cat file1 file2 > file3 concatenates file1 and file2 and write the result to file3.e. The argument to cat is the name of the file whose contents we wish to examine. For space reasons..cc on the screen.2. The command > cat first.cc prints the contents of file first. WORKING WITH FILES AND DIRECTORIES cat name.let This appends the file signature to letter-to-dat and creates a new file called send. it concatenates first. We can examine the contents of a file by using the cat command. ..let. > cat [options] filelist An output file name must not be the same as any of the input names unless it is a special file. > cat letter-to-dad signature > send. Some of the options for the cat command have both long and short options specifiers. 25 The cat command can be used to display a file or to concatenate files. only the short versions of these options have been listed. The operator > redirects the standard output to the cat command to file3.Concatenate files and print on the standard output. The command > cat longfile | more the standard output of cat is used as the input of the more command. Prints version information on standard output then exits. Numbers all nonblank output lines. Displays a $ after the end of each line. adjacent blank lines with a single blank line. If no files or a hyphen (-) is specified. (displays a $ at the end of each line and control characters). Equivalent to -vT. Displays control characters except for LFD and TAB using ^ notation and precedes characters that have the high bit set with M-. the standard input is read. -b -e -n -s -t -u -v -A -E -T --help --version . Ignored. Prints a usage message and exists with a non-zero status. Numbers all output lines. starting with 1. included for UNIX compatibility. Equivalent to -vE. Equivalent to -vET. LINUX BASICS Description This is an optional list of files to concatenate. Displays TAB characters as ^I. starting with 1.26 Item filelist CHAPTER 1. Replaces multiple. 1.2. WORKING WITH FILES AND DIRECTORIES ln [files] .. - Linking files 27 The ln command creates a link between two files, enabling us to have more than one name to access a file. A directory entry is simply a name to call the file and an inode number. The inode number is an index into the file system’s table. Therefore, it is no big deal to have more than one name to inode reference in the same directory or multiple directories. A benefit of a link over a copy is that only one version of the file exists on the disk; therefore, no additional storage is required. Any file may have multiple links. In simplest terms, the ln command provides an easy way to give more than one name to a file. The drawback of copying a file is that now twice as much disk space is being consumed by the program. ln provides two types of links: hard links and symbolic links. Linux treats hard links just like files. Each hard link is counted as a file entry. This means that the original file will not be deleted until all hard links have been deleted. A symbolic link is treated as a place holder for the file. If a file has symbolic links, and the file is deleted, all symbolic links will be deleted automatically. The syntax is > ln [-s] source-file dest-file For example > ln source dest This enables us to edit either the file source or the file dest and modify both of them at the same time. Now instead of two copies of the file existing, only one exists with two different names: source and dest. The two files have been logically linked by the UNIX system. It appears a though we have two different files. > ls collect mon source dest > Look what happens when we execute an ls -l: > ls -l total 5 -rwxr-cr-x -rwxr-xr-x -rwxr-xr-x -rwxr-xr-x > 1 1 2 2 steve steve steve steve DP3725 DP3725 DP3725 DP3725 358 1219 89 89 Jun Jun Jun Jun 25 25 25 25 13:31 13:31 13:30 13:30 collect mon source dest 28 CHAPTER 1. LINUX BASICS The number right before steve is 1 for collect and mon and 2 for source and dest. This number is the number of links to a file, normally 1 for nonlinked, nondirectory file. Since source and dest are linked, this number is 2 for these files. This implies that we can link to a file more than once. The option -s makes a symbolic link instead of a hard link. We can remove either of the two linked files at any time, and the other will not be removed > rm source > ls -l total 4 -rwxr-xr-x -rwxr-xr-x -rwxr-xr-x > Note that steve is still listed as the owner of dest, even though the listing came from pat’s directory. This makes sense, since really only one copy of the file exists - and it’s owned by steve. The only stipulation on linking files is that the files to be linked together must reside on the same file system. The ln command follows the same general format as cp and mv, meaning that we can link a bunch of files at once into a directory. 1 steve 1 steve 1 steve DP3725 DP3725 DP3725 358 Jun 25 1219 Jun 25 89 Jun 25 13:31 collect 13:31 mon 13:30 dest 1.2. WORKING WITH FILES AND DIRECTORIES wc names - Counting the number of words in a file. 29 With the wc command, we can get a count of the total number of lines, word, and characters of information contained in a file. Once again, the name of the file is needed as the argument to this command > wc names 5 > 5 27 names The wc command lists three numbers followed by the file name. The first number represents the number of lines contained in the file (5), the second the number of words contained in the file (in this case also 5), and the third the number of characters contained in the file (27). The command > wc -c names counts only the number of characters. The command > wc -w names counts only the number of words. Finally the command > wc -l names counts only the number of lines, or more precisely, it counts the number of newline characters encountered. 30 CHAPTER 1. LINUX BASICS 1.2.5 File Name Substitution The bash shell supports three kinds of wildcard: * matches any character and any number of characters ? matches any single character [...] matches any single character contained within the brackets Each of them we discuss now in detail. The Asterisk One very powerful feature of the UNIX system that is actually handled by the shell is file name substitution. Let us say our current directory has these files in it: > ls chap1 chap2 chap3 > Suppose we want to print their contents at the terminal. We could take advantage of the fact that the cat command allows us to specify more than one file name at a time. When this is done, the contents of the files are displayed one after the other. > cat chap1 chap2 chap3 ... > However we can also enter > cat * ... > and get the same results. The shell automatically substitutes the names of all of the files in the current directory for the *. The same substitution occurs if we use * with the echo command: > echo * chap1 chap2 chap3 > Here the * is again replaced with the names of all the files contained in the current directory, and the echo command simply displays them at the terminal. the *p1 specifies all file names that end in the characters p1. . WORKING WITH FILES AND DIRECTORIES 31 Any place that * appears on the command line. It can also be used at the beginning or in the middle as well > echo *p1 chap1 > echo *p* chap1 chap2 chap3 > echo *x *x > In the first echo. all file names containing a p are printed. Therefore. Since there are no files ending wit x. > The cha* matches any file name that begins with cha. we enter > cat chap* . b. . . and c > ls a b c chap1 chap2 chap3 > to display the contents of just the files beginning with chap. For example. the shell performs its substitution > echo * : * chap1 chap2 chap3 : chap1 chap2 chap3 > The * can also be used in combination with other characters to limit the file names that are substituted. no substitution occurs in the last case. All such file names matched are substituted on the command line. the echo command simply display *x. In the second echo. assume that in our current directory we have not only chap1 through chap4 but also files a. The * is not limited to the end of a file name. the first * matches everything up to a p and the second everything after.2. thus.1. but it allows us to choose the characters that will be matched. etc. So cat ? prints all files with one-character names. so that [z-f] is not a valid range specification. It is similar to the ?. or c. . The only restriction in specifying a range of characters is that the first character must be alphabetically less than the last character. We assume that the ls command tells us that the following files in the working directory > ls a aa aax alice b bb c cc report1 report2 report3 Then > echo ? a b c > echo a? aa > echo ?? aa bb cc > echo ??* aa aax alice bb cc report1 report2 report3 > In the last example. [abc] matches one letter a. the ?? matches two characters. xabc. b. x2. meaning that x* will match the file x as well as x1. The question mark ? matches exactly one character. and the * matches zero or more up to the end.32 CHAPTER 1. The Brackets Another way to match a single character is to give a list of the characters to use in the match inside square brackets [ ]. The command cat x? prints all files with two-character names beginning with x. The specification [0-9] matches the characters 0 through 9. For example. The net effect is to match all file names of two or more characters. LINUX BASICS Matching Single Characters the ? The asterisk * matches zero or more characters. If the first character following the [ is a !. For example. ls [a-z]*[!0-9] . File name substitution examples Command echo a* cat *. any character will be matched except those enclosed in the brackets.* ls x* rm * Description Print the names of the files beginning with a print all files ending in . we can perform some very complicated substitutions. WORKING WITH FILES AND DIRECTORIES 33 By mixing and matching ranges and characters in the list.c rm *. [a-np-x]* will match all files that start with the letters a through n or p through z (or more simply stated.1.2.. then the sense of the match is inverted. any lowercase letter but o). and > *[!o] matches any file that does not end with the lowercase letter o. The following table gives a few more examples of filename substitution..c Remove all files containing a period List the names of all files beginning with x Remove all files in the current directory (note: be careful when we use this) Print the names of all files beginning with a and ending with b Copy all files from . echo a*b cp . So > [!a-z] matches any character except a lowercase letter. This means./programs into the current directory List files that begin with a lowercase letter and do not end with a digit./programs/* . LINUX BASICS 1. which is also our terminal by default. At the point. After the fourth name was typed in. When entering data to a command from the terminal. this is our terminal by default. If a sort command is executed without a file name argument. Similarly. More formally. and I/O Redirection Most UNIX system commands take input from our terminal and send the resulting output back to our terminal. Barbara. we use the sort command to sort the following three names: Tony. So the following shows an example of this command used to count the number of lines of text entered from the terminal > wc -l This is text that . which is also the terminal. which happens to be our terminal by default. As with standard output. we enter them directly from the terminal > sort Tony Barbara Harry CTRL-d Barbara Harry Tony > Since no file name was specified to the sort command. the sort command sorted the three names and displayed the results on the standard output device.3 Standard Input/Output. then the command will take its input from standard input. This tells the command that we have finished entering data. the terminal. the input was taken from standard input. We recall that executing the who command results in the display of the currently logged-in users. Instead of first entering the names into a file. As an example. Harry. the CTRL and D keys were pressed to signal the end of the data. A command normally reads its input from a place called standard input. the CTRL and D keys (denoted CTRL-d in this text) must be simultaneously pressed after the last data item has been entered. The wc command is another example of a command that takes its input from standard input if no file name is specified on the command line. a command normally writes its output to standard output. the who command writes a list of the logged-in users to standard output.34 CHAPTER 1. Furthermore. then the data will be lost. then the output of that command will be written to file instead of our terminal > who > users > This command line causes the who command to be executed and its output to be written into the file users. since no file name was specified to the wc command. This is because the output has been redirected from the default standard output device (the terminal) into the specified file > cat users oko tty01 ai tty15 ruth tty21 pat tty24 steve tty25 > Sep Sep Sep Sep Sep 12 12 12 12 12 07:30 13:32 10:10 13:07 13:03 If a command has its output redirected to a file and the file already contains some data. only the count of the number of lines (3) is listed as the output of the command. No output appears at the terminal. STANDARD INPUT/OUTPUT.3.1. Output Redirection The output from a command normally intended for standard output can be diverted to a file instead. For example > echo line 1 > users > cat users line 1 > echo line 2 >> users > cat users line 1 line 2 > . We recall that this command normally prints the name of the file directly after the count. If the notation > file is appended to any command that normally writes its output to standard output. CTRL-d 3 > 35 We note that the CTRL-d that is used to terminate the input is not counted as a separate line by the wc command. AND I/O REDIRECTION is typed on the standard input device. This capability is known as output redirection. If file previously exists. If we type > file not preceded by a command. the shell recognizes a special format of output redirection. This is in file2. > cat file1 file2 This is in file1. By using the redirection append characters >>. zero character length) file for us. > cat file1 file2 > file3 > cat file3 This is in file1. then the shell will create an empty (i.. the previous contents of the file are not lost and the new output simply gets added onto the end. > Redirect it instead Now we can see where the cat command gets its name: when used with more than one file its effect is to concatenate the files together. This is in file2. Incidentally. . then its contents will be lost. LINUX BASICS The second echo command uses a different type of output redirection indicated by the characters >>. > cat file2 This is in file2. > Append file1 to file2 Recall that specifying more than one file name to cat results in the display of the first file followed immediately by the second file. we can use cat to append the contents of one file onto the end of another > cat file1 This is in file1. Therefore. > cat file1 >> file2 > cat file2 This is in file2.36 CHAPTER 1. > cat file2 This is in file2. and so on > cat file1 This is in file1. This character pair causes the standard output from the command to be appended to the specified file. This is in file1.e. we can count the number of lines in the file by redirecting the input of the wc command from the terminal to the file users > wc -l < users 2 > We notice that there is a difference in the output produced by the two forms of the wc command. the less-than character < is used to redirect the input of a command. In order to redirect the input of a command. STANDARD INPUT/OUTPUT. In the second case. the name of the file users is listed with the line count. we type the < character followed by the name of the file that the input is to be read from.1. so can the input of a command be redirected from a file. In the first case wc knows it is reading its input from the file users. This points out the subtle distinction between the execution of the two commands. it is not. only commands that normally take their input from standard input can have their input redirected from a file in this manner. As far as wc is concerned. in the second case. . In the first case. AND I/O REDIRECTION 37 Input Redirection Just as the output of a command can be redirected to a file. So. we can execute the command > wc -l users 2 users > Or. we can easily determine the number of users logged in by simply counting the number of lines in the users file > who > users > wc -l < users 5 > This output would indicate that there were currently five users logged in. to count the number of lines in the file users. it does not know whether its input is coming from the terminal or from a file.3. Of course. The shell redirects the input from the terminal to the file users. Now we have a command sequence we can use whenever we want to know how many users are logged in. it only knows that it is reading its input from standard input. As the greater-than character > is used for output redirection. for example. Since we know that there will be one line in the file for each user logged into the system. Pipes The file users that was created previously contains a list of all the users currently logged into the system. with the output of one program feeding into the input of the next. So to make a pipe between the who and wc -l commands. A pipe can be made between any two programs. since it is piped directly into the wc command. which is placed between the two commands. Note that we never see the output of the who command at the terminal. . The UNIX system allows to connect two commands together. provided the first program writes its output to standard output. Furthermore. the standard output from the first command is connected directly to the standard input of the second command. Consider. It is also possible to form a pipeline consisting of more than two programs. LINUX BASICS There is another approach to determine the number of logged-in users that bypasses the use of a file. we know that if no file name argument is specified to the wc command then it takes its input from standard input. we simply type > who | wc -l 5 > When a pipe is set up between two commands. Suppose we wanted to count the number of files contained in our directory. The sorted file is then piped into the uniq command. We know that the who command writes its list of logged-in users to standard output. the list of logged-in users that is output from the who command automatically becomes the input to the wc command. This connection is known as a pipe. without any options. sorts the input alphabetically by the first field in the input.38 CHAPTER 1. Knowledge of the fact that the ls command displays one line of output per file enables us to see the same type of approach as before > ls | wc -l 10 > The output indicates that the current directory contains 10 files. The uniq command removes any duplicate lines from the input. the contents of the file myfile (the output from the cat command) are fed into the input of the sort command. and it enables us to take the output from one command and feed it directly into the input of another command. the command > cat myfile | sort | uniq Here. A pipe is effected by the character |. Therefore. for example. and the second program reads its input from standard input. The sort command. and cp are not. STANDARD INPUT/OUTPUT. This is where most UNIX commands write their error messages.1. wc is considered a filter. So in the previous pipeline. For example. any redirection does not affect the pipeline). with the output piped through tee which will write the data into filename and to the console. Since the pipe is set up before any redirection.3. . Standard Error In addition to standard input and standard output there is another place known as standard error. we never know the difference between standard output and standard error > ls n* n* not found > List all files beginning with n Here the not found message is actually being written to standard error and not standard output by the ls command. A filter is any program that can be used between two other programs in a pipeline. perform some operation on that input. while who. standard error is associated with our terminal by default. AND I/O REDIRECTION 39 The POSIX standard specifies that (in the Bourne shell) descriptors are assigned to the pipeline before redirection (i. pwd. mv. we could write the same command using the Bourne shell using cat and the redirection and pipeline facilities. And as with the other two standard places. > command | tee filename This command line executes command. and write the results to standard output. cd. ls is not.e. date. In most cases. The command tee can be used to write from its standard input to a file and to standard output. since it does not read its input from standard input. We van verify that this message is not being written to standard output by redirect into the ls command’s output > ls n* > foo n* not found > We still get the message printed out at the terminal. cat and sort are filters. even though we redirected standard output to the file foo. rm. echo. > command > filename | cat Filters The term filter is often used in UNIX terminology to refer to any program that can take input from standard input. 40 CHAPTER 1. similar to the way standard output gets redirected. Any error messages normally intended for standard error will be diverted into the specified file. We can also redirect standard error to a file by using the notation > command 2> file No space is permitted between the 2 and the >. > ls n* 2> errors > cat errors n* not found > . LINUX BASICS The above example shows the raison d’ˆ etre for standard error: so that error messages will still get displayed at the terminal even if standard output is redirected to a file or piped to another command. 1. . Some other commands are in the directory bin. ADDITIONAL COMMANDS 41 1. The commands include more less file find finger grep id kill logname sleep split chkconfig sort tee dd The commands df du free provide information about the disk space usage.4 Additional Commands In this section we describe a number of other important commands in LINUX. The command chkconfig is in the directory sbin.4. our terminal can lock up.42 more display File Contents CHAPTER 1. A disadvantage with more is that we cannot back up to see a screen of information once it passes. we can type the following command > more . LINUX BASICS The more command displays a screenful of a text file.. Like more. . If our terminal does lock up.more. The command > less longfile views file longfile. We enter q to exit. We can look through a text file without invoking an editor. with the less we can page back and forth within the file. less can display a screen of information in a text file. We can press page-up and page-down to scroll through the file.. for example. For example. we could have some unpleasant effects. try pressing either the Ctrl-q or the Ctrl-s keys. view a file The less command is considered as a better more. If we try to pass a binary data file to more. The program’s name is a play on words for the program it’s meant to replace . less name . less displays information a screen at a time on our terminal. printing the file.emacs To quit more we enter q or Crtl-z. or trying to pause the terminal as it displays the file. to display the contents of our emacs configuration file. Unlike more. It is also useful to determine if the file is text based on or not and.cc C++ program text If we compile and link this file we obtain an execute file first. Then > file first. Tells file that the list of files to identify is found in ffile. Intel 80386 version 1. let first. therefore. not stripped . This option causes symbolic links to be followed. Then > file first ELF 32-bit LSB executable. Looks inside a compressed file and tries to figure out its type. The syntax is > file [-c] [-z] [-L] [-f ffile ] [-m mfile] filelist where filelist is a space-separated list of files we want to know the type of. The command file can be used to report the UNIX commands that are and are not scripts. This is used in conjunction with -m to debug a new magic file before installing it. data. dynamically linked. Specifies an alternate file of magic numbers to use for determining file types. ADDITIONAL COMMANDS file determines type of file 43 Determines the type of a file. Many of the UNIX commands are only shell scripts.1. Item -c Description Prints out the parsed form of the magic file. text.4. whether it can be viewed or edited. -z -L -f ffile -m mfile For example. The command file is able to recognize whether the file is executable. This is useful when many files must be identified.cc be a C++ file. and so on. Matches all files whose type. or f (regular file). -perm mode -type x -links n -size n -user user-id -atime n . and execute. is c (meaning) b (block special). creation time. May either be the numeric value or the logname of the user. size. and many more criteria. modification time. s (socket). d (directory). p (named pipe). the file to find is enclosed in quotation marks. For example > find dirlist match-spec where dirlist is space-separated list of the directories where we want to look for a file or set of files and match-spec are the matching specification or description of files we want to find. l (symbolic link).44 find finding files CHAPTER 1. LINUX BASICS The find command traverses the specified directories generating a list of files that match the criteria specified. If preceded by a negative -. Description -name file Tells find what file to search for. All modes must be matched – not just read. Files may be matched by name. x. We can even execute a command on the matched files each time a file is found. write. Matches all files with n number of links Matches all files of size n blocks (512-byte blocks. Matches all files whose mode matches the numeric value of mode. 1K-byte blocks if k follows n) Matches all files whose user ID is user-id. mode take on the meaning of everything without this mode. Wild cards (* and ?) may be used. Matches all files last accesses within the previous n days. For example > find . the full path name is shown on-screen.tex’ finds all Latex files starting in the current directory.cc -print searches the current directory (the . indicates the current directory) and its subdirectories for a file called first. . The command > find . To offer more control over selection. Matches all files that have been modified more recently than the file file. -iname ’*. The command must be terminated by an escaped semicolon (\.1. -newer linux. The parentheses are special to the shell. -newer file The options may be grouped together and combined to limit the search criteria.). ADDITIONAL COMMANDS Description -mtime n -exec cmd 45 Matches all files modified within the previous n days. Here.4. The notation {} is used to signify where the file name should appear in the command executed. This is a NOT operator and negates the expression that follows it. the command ls is executedwith the -d argument and each file is passed to ls at the place where the {} is found. the command cmd is executed. The command > find . they must be escaped. -iname ’*. overriding the default AND assumption. meaning that both criteria must be met. The command > find . When and if find finds it. -name first. This is the OR operator. for example -exec ls -d {}\.tex finds all files that were modified more recently than linux. Multiple flags are assumed to be ANDs. the following table describes other options () -o ! parentheses may be used to group selections.cc.tex’ -exec cp {} /tmp copies all Latex files into directory /tmp.tex. For each file matched.. home phone number. Restricts matching of the user argument to the logon name.plan and . mail status. and office phone number. then additional information about the user is given.project files. . office location. LINUX BASICS The finger command displays information about users on the system. -s Displays the user’s logon name.plan and . The syntax is > finger [options] users Item Description users This is an optional list of user names. Produces a multi-line format displaying all of the information described for the -s option as well as the user’s home directory.project files. idle time. Remote users can be specified by giving the user name and the remote host name as in user@remote. logon shell.46 finger information about users on the system CHAPTER 1. terminal name and write status. -l -p -m If no options ar specified. finger defaults to the multi-line output format as specified by the -l argument.computer. If specified. Prevents the -l option of finger from displaying the contents of the . If no arguments are specified. finger prints an entry for each user currently logged onto the system. and the contents of the user’s . logon time. real name. the standard input is searched. The syntax is > grep > egrep > fgrep Item filelist [option] reg-express filelist [options] reg-express filelist [options] string filelist Description An optional space-separated list of files to search for the given string or reg-expres. Suppresses the display of the name of the file the match was found in (grep and egrep only). Regular expressions are in the form used by ed. See the man page for the definition of regular expressions. Counts the matching lines. The string we want to find in the files. file contains the strings or expressions to search for. ADDITIONAL COMMANDS grep 47 The command grep looks for patterns found in files and reports to us when these patterns are found. If left blank. grep stands for Global Regular Express Printer. Each matching line is displayed along with its relative line number.4.1. The default behavior is to be case-sensitive. The name of the command comes from the use of ”regular expressions” in the ed family of editors. Only the names of the files containing a match are displayed. reg-express string -v -c -l -h -n i -e reg-expres -f file . Causes matching to not be case-sensitive. useful when the regular expression or string starts with a hyphen. The regular expression to search for. List the lines that don’t match string or reg-expres. ? If this trails a regular expression. The command > fgrep "hello > Hello" letter-to-dat does the same thing. The command > grep "[hH]ello" letter-to-dad searches for the word hello or Hello. For example > grep main first. . The command > egrep "([Ss]ome|[Aa]ny)one" letter-to-dad looks for all the words someone.48 CHAPTER 1.cc does the same thing. () May be used to group expressions. it matches 0 or 1 occurrence. The command > fgrep main first. anyone. or Anyone in the file. it matches one or more of that occurrence.cc searches for the word main in the file first. Someone. egrep stands for extended grep and accepts the following enhancements to regular expressions defined by ed: + If this trails a regular expression. | used to denote multiple regular expressions. LINUX BASICS fgrep stands for fast grep and can only search for fixed strings. Multiple strings may be searched for by separating each string by a new line or entering them in the -f file file.cc. Prints the user or group name instead of the ID number.4. Prints version information on the standard output and then exits successfully. user ID number.1. prints a usage message on the standard output and exits successfully. -r -u --help --version For example > id shows the id information. -g. ADDITIONAL COMMANDS id 49 The id command displays our identification to the system. group name. or -G. user or group ID. . and group Id number. or -G. Prints only the supplementary groups. Prints only the user ID. It reports our user name. -g. instead of effective. Requires -u. Requires -u. The syntax is > id [options] Item -g -G -n Description Prints only the group ID. Prints the real. This command is issued to stop the executing process. and SIGKILL. we may have to do some house cleaning after the process terminates.50 kill to kill a process CHAPTER 1. There are instances when even kill -9 can’t kill the process. which is the equivalent of hanging up the phone as if on a modem. The syntax is > kill [-signal] pid > kill -l Item Description signal An optional signal that can be sent. pid The process ID of the process we want to send the specified signal. This is when the process is using a kernel service and can’t receive signals. -l Although kill -9 is the sure kill. A pid is a number used by the system to keep track of the process. The default is SIGTERM. This works if no other signal does. These signals can be caught by the applications and after they receive them. thus the kill name because we use it to kill the process. it is often best to try SIGTERM and SIGHUP first. For example > kill 125 sends the SIGTERM signal to the process 125. The command > kill -9 125 sends signal 9. The messages can be > kill: permission denied We tried to kill a process that we don’t own. Prints a list of the signal names that can be sent with kill. Two other popular ones are SIGHUP. The only way to resolve this is to shut down the system. properly clean up after themselves. Because kill -9 can’t be caught. which is the numeric value for SIGKILL. Periodically processes get locked up in this mode. which cannot be ignored by a process. The default signal is SIGTERM. LINUX BASICS With the kill command we can send a signal to a process that is currently executing. or we are not the super user. . The ps command can be used to report the pid of a process. sleep sleep The sleep command suspends execution for an interval of time. We notice that sleep is not guaranteed to wake up exactly after the amount of time specified.1. The default is measured in seconds. The program runs forever. The syntax is > sleep n Item Description n Specifies the amount of time to sleep. An optional identifier may be used to specify a different time unit.4. These are as follows: s Seconds m Minutes h Hours d Days For example at the command line we enter the code > while : do date pwd sleep 10 done This shows the date and pwd every 10 seconds. ADDITIONAL COMMANDS logname 51 The command logname reads the /etc/utmp file to report what name we used to log onto the system. . To exit the running program we enter CRTL-z. For example > logname reports what name we used to log onto the system. This must be an integer. replaces the x in the previous list.. The syntax is > split -numlines file tagname Item Description -numlines Specifies the number of lines to include in each piece. and so on.52 split breaks up text files CHAPTER 1. myletterab. then xac. . The command > cat myletter* > letter takes all the pieces and puts them back together again into the file letter. thus building the list: tagnameaa. With the command split we can handle the file in individual. more manageable pieces. tagnameab. tagnameac. LINUX BASICS The split command breaks up a text file into smaller pieces. and so on. file The file to split into smaller pieces.is used. . if specified. By default. For examples > split -100 letter myletter breaks up the file letter into 100 line pieces. The output files are myletteraa.. If left blank or . Periodically. then xab. split builds the output pieces by creating the following files: xaa. tagname There must be enough room for two copies of the file in the current file system. files become too large to load into an editor or some other utility. tagname. standard input is read. The message could be > No such file or directory In this case we supplied split with a file name that doesn’t exist. they are created. --del name: Deletes the name service from management. For example > chkconfig --list random gives random 0:off 1:on 2:on 3:on 4:on 5:on 6:off . only information about that service is displayed. If a named service is specified.4. The syntax is > chkconfig --list [name] > chkconfig --add name > chkconfig --del name > chkconfig [--level levels] name <on|off|reset> > chkconfig [--level levels] name Important Flags and Options --add name Adds a new service for management by chkconfig and checks that the necessary start and kill entries exist. --list name: Lists all services that chkconfig knows about and any relevant information about them. If entries are missing. --level levels: Specifies numerically which run level a named service should belong to. ADDITIONAL COMMANDS chkconfig 53 The chkconfig command manipulates or displays settings for system run levels. any links to it are also deleted.1. -d -f -r -t For example > sort Ben Alda Willi Roba <Crtl-d> . digits. data is taken from the standard input and sorted. The resulting sorted data is displayed to the standard output. If no files are indicated. LINUX BASICS The sort command sorts the lines contained in one or more text files and displays the results. and blanks in the sorting process converts lowercase letters to uppercase letters during the sorting process reverses the sort order separator indicates that the specified separator should serve as the field separator for finding sort keys on each line. ignore all characters except letters.54 sort sorting files or standard input CHAPTER 1. No sorting actually takes place. The syntax is > sort filename Important flags are -b -c ignores leading blanks in lines when trying to find sort keys checks whether the input data is sorted and prints an error message if it is not. 4. ADDITIONAL COMMANDS tee duplicating output (pipe fitting) 55 The tee command copies standard input to a file and duplicates the data to standard output. > tee filename The command is useful for logging. For example. when compiling the Linux kernel a lot of information is generated about the process. In general we would like to watch this information for errors. The command name is due to the analogy with the ‘T’ shape pipe connection which creates a fork so that flow (in our case data) can go in two different directions. . So we might use the command > make kernel > /tmp/log and view the log on another console using > tail -f /tmp/log On the other hand we could use the tee command to do this on one console > make kernel | tee /tmp/log which will write the output of make kernel to /tmp/log as well as displaying it to the console. but the information scrolls past very quickly so it would be better to redirect this information to a file.1. ibs input block size. obs output block size.56 dd data/disk/device dump CHAPTER 1. This is useful if your cdrom only supports copying whole sectors (not necessary on Linux systems). count number of blocks to copy. even when there are errors. It is also useful sometimes to specify conv=noerror.iso bs=2048 will copy from a cdrom device with block size 2048 (the sector size for a data cdrom). bs block size. all if not specified.. LINUX BASICS The dd dumps data from one file to another (like a copy) similar to cat except that it allows some conversion to be specified as well as device specific information. skip number of blocks to skip on the input before proceeding with copy. the size of blocks used for reading and writing (bytes). Important parameters are input file name..sync so that a device with errors can be copied as completely as possible.iso to create duplicate cdroms. if . or for a tape drive. of output filename. if not specified it will be the standard output. > dd parameter=value . We can the use the file /tmp/cdrom. conv conversion applied (comma separated list of options) swab: swap pairs of bytes noerror: ignore errors sync: always write the full block. For example > dd if=/dev/cdrom of=/tmp/cdrom. the size of blocks used for writing (bytes). the size of blocks used for reading (bytes). if not specified it will be the standard input. ADDITIONAL COMMANDS 57 To obtain information about disk space usage we use the commands df. If filenames are specified. then the free space for the file system containing each file is displayed. then the free space on all mounted file systems is displayed. then the free space on all mounted file systems is displayed.1. du reports on disk space usage The du command displays free space on one or more mounted disks or partitions. then the free space for the file system containing each file is displayed.] Important Flags and Options t/--type=fstype: Displays information only for the specified type. The du command displays file system block usage for each file argument and each directory in the file hierarchy rooted in each directory argument.4. df free disk space The df command displays free space on one or more mounted disks or partitions... If no files or directories are specified. If no files or directories are specified. If filenames are specified. The syntax is > du [-abcksx] [--all] [--bytes] [--total] [--kilobytes] [--summarize] [--one-file-system] [file .] .. -x/--exclude-type=fstype: Does not report information for file systems of the specified type.. and free. -T/--print-type: Displays the file system type for each file system reported. The syntax is > df [-T] [-t] fstype] [-x fstype] [--all] [--inodes] [--type=fstype] [--exclude-type=fstype] [--print-type] [filename . du. -c/--total: Displays a total usage figure for all. -k: Displays the amount of memory in kilobytes (this is the default). LINUX BASICS -a/--all: Displays usage information for files and directories. skips directories that are not part of the current file system. -s delay: Displays continued reports separated by the specified delay in seconds. For example > du --summarize --bytes gives > 6373155 free reports of free and used memory Displays a report of free and used memory. -x/--one-file-system. -k/--kilobytes: Displays usage informaton in kilobytes. -s/--summarize: Displays a total for each argument and not display individual information for each file or subdirectory inside a directory. -m: Displays the amount of memory in megabytes.58 Important Flags and Options CHAPTER 1. -t: Displays an extra line containing totals. The syntax is > free [-b|-k|-m] [-s delay] Important Flags and Options -b: Displays the amount of memory in bytes. -b/--bytes: Displays usage information in bytes. . When done symbolically. Modes can be specified in two ways: symbolically and numerically. The command checkalias checks the user’s file and then the system alias file in order to see if a specified alias is defined. then only logins to that tty are displayed. The symbol + means that the specified modes should be added to already specified permissions. w for write permission. and x for execute permission. The chown command changes the user and/or group ownership of one or more files or directories.1. The command showkey displays the scancodes and keycodes generated by the keyboard. The batch command schedules commands to be executed at a specified time as long as system load levels permit. The paste command merges corresponding lines from one or more files and prints sequentially corresponding lines on the same line. 59 The at command schedules commands to be executed at a specific time. If a specific tty such as tty0 or tty1 is specified. modes take the form [ugoa][[+-=][rwxXstugo . ADDITIONAL COMMANDS Finally let us summarize other important Linux commands. The command chgrp changes the group ownership of one or more files or directories. .. The symbol r stands for read permission. o = anyone who is not the owner or in the owner group. a = all users). Using the command chmod we can change the access permissions of one or more files or directories. If no file name is provided input is taken from the standard input.. The command kdb_mode displays or sets the keyboard mode and kbdrate sets the repeat rate and delay time for the keyboard. The program remains active for 10 seconds after the last key is pressed. g = all members of the group that owns the file or directory. The command arch displays the architecture on which Linux is running.4. ] The first element [ugoa] represents the users whose permissions are being affected (u = user who owns the file or directory. The user is prompted for the commands or the commands can be provided from a file. Using the last command we can display a history of user logins and logouts based on the contents of /var/log/wtmp.means the specified modes should be removed from existing permissions. separated by a tab with a new line ending the line. the . Using the uname command we can display selected system information. it displays a list of available time zones. Otherwise.ac. unless otherwise specified. The command whereis attempts to locate binary.1 The option -b searches only for binary files. The setclock command sets the computer’s hardware clock to the value of the current system clock. network host name. For example > uname -a provides Linux issc2. it uses the current time as timestamp. the first 10 lines of each file are displayed. When multiple pieces of information are requested. the operating system name is displayed. then the command reads data from the standard input and displays the first section of the data.rau. The head command displays the first part of one or more files. When no options are provided. By default. The top command displays regularly updated reports of processes running on the system.za 2. and man page files for one or more commands. By default. LINUX BASICS The tail command displays the last part of one or more files. The option -c will not create files that do not exist. then the system time zone is changed to the specified time zone.60 CHAPTER 1. and machine type. The touch command changes the timestamp of files without changing their contents. With the command timeconfig we can configure time parameters. If no filenames are provided. the last 10 lines of each file are displayed. The vmstat command reports statistics about virtual memory. For example > whereis ls gives the output ls: /bin/ls /usr/man/man1/ls. the display order is always: operating system. If a time zone is specified. following the same rules as for files. If a file does not exist.34 #1 Fri May 8 16:05:57 EDT 1998 i586 unknown . By default. operating system version. it will be created with size zero. unless otherwise specified.0.source code. operating system release. /banner ls -l cd ls -l vi first. This means that bash keeps track of a certain number of commands that have been entered into the shell.4. For example > history could provide the output 1011 1012 1013 1014 1015 .1.cc . ADDITIONAL COMMANDS 61 bash also supports command history using the history command. 62 CHAPTER 1. LINUX BASICS . We enter at the command prompt $HOME we get the information about the home directory. A hierarchical system is a system organized by graded categorization. When we enter $PATH we find the path. The Unix (and thus Linux) file-system is called a hierarchical file-system. The Unix file-system only has one top level directory (represented by ’/’ and pronounced ”root”). We cannot see them because they have no graphical representation. Files are located in directories. documents are files. it can also write it to the display or sound device (if we really want it to). The file-system consists of files and directories. but IFS has a default value of Space + Tab + Newline. Programs are files. and directories themselves are subdirectories of their parent directories. This means that if a program can write output to a file. IFS is the internal field separator. This concept should be familiar to anyone who has ever used a computer. The newline explains why this variable shows up with a clear line after it in the output of the set command. PATH. The string SHELL identifies the shell to use when a subshell is requested. Anyone who has at one stage added a new hard drive to his system will be familiar with the agony of sorting out a system where drive letters have suddenly changed. This is where our login session starts.Chapter 2 Advanced Linux 2. IFS. and it is the default target of a cd command. 63 . PATH identifies the directories to be searched when we type commands. This string consists of characters that are used to separate fields and records. This differs from other systems such as DOS or OS/2 where we have several root nodes which are assigned drive letters. A key concept in Unix is that everything that is not a directory is a file.1 The Unix File System In this chapter we consider more advanced tools and techniques in LINUX. even the keyboard. device drivers are files. display and mouse are represented as files. HOME is the fullyqualified pathname of the user’s home directory. The shell uses IFS to determine how to break a command line into separate arguments. Under Unix all physical devices are mounted as subdirectories of other directories. Commonly used environment variables are HOME. To change the file ownership we use the commands chown (must be root) and chgrp and to change the permissions we use chmod. The attributes can be listed using the ls -l command. ADVANCED LINUX In general. For example. and the user’s access rights. the file project. The third line indicates that project is a directory (d) owned by user1 and group project1. Some of the attributes include • A single user associated with the file.64 CHAPTER 2. the first being the file type. unix systems implement security with the concepts of users and groups.17 user1 project1 -rw------1 user1 user1 -rw-rw-r-1 user1 project1 1234 May 16 14:36 project 215 May 15 18:12 mbox 10 Apr 20 10:16 project. Lastly. In contrast a group identifies multiple entities for shared access to system resources. the following three . For example a user “netadmin” (which administrates the network) and a user “printadmin” (which administrates the printing devices) may both be in a group “admin” which provides access to common utilities such as file manipulation and access to /etc for configuration. The fourth line indicates that mbox is a normal file (-) owned by user1 and group user1. Although users and groups provide more sophisticated access control. and the group’s access rights. i.status can be read and written by user1 and any user in project1. Both user1 and any user in project1 can read and write (rw) the directory and change to the directory (x). the access is not shared. Only user1 can read or write (rw) the file. mostly control is achieved using file system attributes. while any other user can only read the file.user permissions.for example a “guest” user. Another example is a group “network”.e.group permissions and the final three are other permissions. Each file in a unix file system has attributes. The listing includes 10 characters. On the second line we see that there are 3 files in the directory.status On the first line we typed the command ls -l. All users which require network access should belong to this group. the following three . To find out which groups a user belongs to we use . • The access rights for anyone who is neither the specified user nor in the specified group (other). A user usually refers to a specific person although a group of people may all have access via a single user . A user identifies a single entity for access to system resources. • A single group associated with the file. The files in the project directory may have different permissions. suppose a number of people are working on a project project1 and you (user1) are the project leader. Executing ls -l in your home directory might yield user1@linuxhost:~> ls -l total 3 drwxrwx--. 1. . THE UNIX FILE SYSTEM groups user 65 To add users and groups see the adduser (or useradd) and group manual pages.2. hpfs. ADVANCED LINUX 2. vfat. coherent. and it is mounted as root (’/’). ext. ext2. umsdos. /dev/hdb2 is further mounted below usr as /usr/local. sysv. File-systems are mounted with the mount command. xenix. /dev/hdb3 is the third partition on the second IDE drive. ufs. and it mounted on /usr meaning that the partition will appear to be a subdirectory of / named usr. msdos. nfs. iso9660. xiafs. If the partition is located on a SCSI hard drive the command would be > mount -t ext2 /dev/sdb3 /usr . and a mount point such as /net/applications/linux is easier to remember than a drive letter mapping. At the command line we enter > mount A typical output is /dev/hda1 on / type ext2 (rw) /dev/hdb3 on /usr type ext2 (rw) /dev/hdb2 on /usr/local type ext2 (rw) /dev/hda1 is the first partition on the first IDE hard drive. smbfs.66 CHAPTER 2. affs. proc.2 Mounting and Unmounting A typical Linux system might have the following structure (as given by the mount command). The standard form of the mount command is mount -t type device dir where type is the file-system type of the device. ncpfs. The file system types which are currently supported are minix. device is any block device found in /dev. To mount an ext2 (ext2 stands for ”second extended file-system” and is the native Linux file-system) partition of (IDE) hard drive on /usr we type > mount -t ext2 /dev/hdb3 /usr We must be logged in as root for these commands to work. The option -t specifies the type of the file being mounted. It is a very elegant system. romfs. For example a Sony CDROM will use /dev/cdu31a or /dev/sonycd. A disk in drive B: is mounted with > mount -t msdos /dev/fd1 /mnt/floppy The same procedure as above works for CDROMs. the CDROM will most probably use /dev/hdc as a device file (/dev/hdb if we only have one hard drive). 67 We discuss the mounting of hard drives partitions. and unmounted before the media can be removed from the drive (disk writes are cached. The file system is specified by either its device name. so we rarely need to mount them manually. we must have support for our specific CDROM drive compiled into the system kernel. Other CDROMs use different device files. using the -r option unmount tries to remount the file system in read-only mode. Usually hard drive partitions will be mounted automatically at system startup. IDE CDROMs use device files similar to IDE hard drives. The umount command unmounts a mounted file system. they must be mounted before use. MOUNTING AND UNMOUNTING We can mount our Windows95 partition on /w95 by typing: > mount -t vfat /dev/hda1 /w95 assuming that Windows95 is on the first partition of our first IDE hard drive. its directory name. To amount a DOS format stiffy in what is drive A: under DOS we type > mount -t msdos /dev/fd0 /mnt/floppy where /dev/fd0 is the device file for the first floppy device. Because floppy drives use removable media. but the device file differs for different CDROM types. . or its network path. If unmouning fails. a link is usually made from the specific CDROM device file to /dev/cdrom by typing > ln -s /dev/cdu31a /dev/cdrom The command to mount a CDROM will then be mount /dev/cdrom -t iso9660 /cdrom For any of this to work. Thus if we have two hard drives and a CDROM. cdroms. A Sound-Blaster CDROM will use /dev/sbprocd and so on.2. floppies and network file-systems. so premature removal of the disk from the drive will cause data loss).2. To simplify matters a bit. cc on the Cdrom to the directory cppcourse we use the command $ cp /mnt/first. See what is mounted at the moment we enter: $ mount 3. After we mounted the floppy we can diplay the contents of it by using the command $ ls -l /mnt If we mounted the Cdrom with mount /dev/cdrom /mnt we can display the contents with ls -l /mnt. ADVANCED LINUX Let us assume that the file first./cppcourse/first.68 CHAPTER 2. -w: mounts the file system in readwrite mode. -r: mounts the file system in read-only mode.use the su (”super user” or ”substitute user”) command: $ su Password: <pvm> # 2.cc .cc /mnt 5. See if the file is on the floppy: $ mdir a: Other options for the mount command are: -a: mounts all file systems in \etc\fstab. To copy the file first. Mount # mount -t msdos /dev/fd0 /mnt 4.. The floppy disk must be inserted in the drive (under DOS normally called the A: drive).cc .cc $ cp first. First become the superuser . Copy the file first. Unmount $ umount /mnt 6.cc in on the harddisk and we want to copy it to the floppy (msdos file system). 1. 2. .ro defaults 1 0 1 1 1 0 0 0 0 0 1 0 2 2 2 0 0 0 0 0 The device file. The options nosuid and user gives permission to normal users to mount and unmount devices.user. The option noauto tells the system not to mount this device at system startup. The /etc/fstab file is a repository for parameters for mount points. MOUNTING AND UNMOUNTING 69 The above can become quite tedious after a while. To mount a CDROM we only need to type mount /cdrom. mount point.nosuid.user noauto.2.rw.nosuid. The following listing is the contents of my /etc/fstab file: /dev/hda1 /dev/hdb6 /dev/hdb4 /dev/hdb3 /dev/hdb2 /dev/hdb5 /dev/fd0 /dev/fd0 /dev/hdc none / /os2/os2d /space /usr /usr/local swap /mnt/floppy /mnt/dosfloppy /cdrom /proc ext2 hpfs ext2 ext2 ext2 swap ext2 msdos iso9660 proc defaults defaults defaults defaults defaults defaults noauto noauto. file-system type and mount options are given. -y: assumes an answer yes to all questions. ADVANCED LINUX The command e2fsck checks the state of a Linux second extended file system. The syntax is e2fsck [-cfncpy] [-B blocksize] device Important flags and options are -B blocksize: specifies a specific block size to use in searching for the superblock. -f: -n: opens the file system in read-only state and answers no to all prompts to take action. . if we need to check the root file system or a file system that must be mounted. The device to be checked should be specified using the complete Linux device path such as /dev/hda1 or /dev/sdb3 It is advisable that the file system not be mounted or. that this be done in single-user mode. -c: causes the badblocks program to be run and marks any bad blocks accordingly. forces checking of file systems that outwardly seen clean. This is the default file system used for Linux partitions. -p: forces automatic repairing without prompts.70 CHAPTER 2. Read the Printing-Howto for informations.display contents of an MS-DOS file . This difference between MS-DOS and Unix may also produce problems when printing.3.tests a DOS floppy disk for bad blocks.2. The option for mtype are: -s: removes the high bit from data. . MTOOLS PACKAGE 71 2.mrd .cc from drive A: to the current directory.mbadblocks .mdel .make an MS-DOS subdirectory . The mcopy command provides the switch -t that can be used to translate MS-DOS files to Unix and vice versa.mlabel .move or rename an MS-DOS file or subdirectory . a number of commands are provided to make access of DOS format floppies easier. The most useful of these commands are: . These commands are all easy to use.delete an MS-DOS file .mmove . -t: translates DOS text files to Unix text files before displaying them.cc will copy file1.add an MS-DOS file-system to a low-level formatted floppy disk .mren .mdir .changes the attributes of a file on an MS-DOS file system .mmd .mattrib . A well known error is the staircase effect.display an MS-DOS directory .mformat .mcd .rename an existing MS-DOS file .copy MS-DOS files to/from Unix .make an MS-DOS volume label .3 MTools Package Under Linux.remove an MS-DOS subdirectory .mcopy .mtype .change MS-DOS directory . For example mdir a: will print the directory listing of the disk in drive A: and > mcopy a:file1. These commands all begin with m (for MS-DOS). MS DOS and OS/2 use different control characters for carriage return and line feeds the Linux does. We also use the swapon command to enable the swap space. Using the command swapon -s provides summary information about device usage as swap space. The second parameter is the file we associate with the loopback device. > > > > > dd if=/dev/zero of=/tmp/swapfile bs=102400 count=1024 loconfig /dev/loop0 /tmp/swapfile mkswap /dev/loop0 swapon /dev/loop0 swapon -s /dev/loop0 . The file should not be used while associated with a loopback device as this could lead to inconsistencies. Fortunately Linux can actually use any properly configured device for swap space (you actually use /dev/hda3. The swap space is the space used by the operating system for virtual memory.72 CHAPTER 2. For example. As first parameter we provide the loopback device we wish to configure.4 Swap Space and the Loopback Device Like many unix operating systems Linux uses a partition on a hard disk for swap space. We can prepare a file using the dd command. ADVANCED LINUX 2. Thus we can have a file in our filesystem serve as swap space. The amount of swap space is determined by the filesize. for example /dev/loop0 or /dev/loop1. Unfortunately if you find you need more swap space it involves adding a new hard disk or re-partioning the hard disk and possibly re-installing the operating system. The loconfig command configures the loopback device. /dev/hdb2 or some other device node representing a hard disk partition). suppose we want to add 100MB of swap space to the system using a file. In the mean time another application may use this memory. When memory is not being accessed often it can be moved (copied) to the swap space (hard disk) until it is needed at a later stage when it will be copied back. The following commands set up the swap space. Linux also provides us with a loopback device which can be linked to a file. We use the system command mkswap with the device node we wish to configure for swap space as the first parameter. 100MB is 100*1024*1024 bytes. and are entered into the file /etc/exports. NETWORK FILE-SYSTEM 73 2. These permissions are called exports.5. but it can be restricted to read-only.5 Network File-System NFS (Network File-System) is the Unix standard for sharing file-system over networks. To mount this exported file system we enter > mount Bach:/home/share /mnt/share .rau. First Bach must give Chopin permission to do this.2.ac. Suppose a machine named Chopin wishes to mount the directory /home/share on a machine named Bach as a local directory.za Access is by default read-write. To grant permission for Chopin to mount /home/share the following entry must be added to the /etc/exports file on Bach: /home/share Chopin. 4. initialize services.74 CHAPTER 2. View system files. Add system control priveleges. Add NFS exports. 1. SLIP and PLIP. Change the hostname. 6. 4. reboot. Set date and time. Edit /etc/hosts and /etc/networks. 2. Schedule tasks for the super user. Change passwords. • System configuration. user friendly. interactive configuration of the system. Activate the configuration. Set the DNS server. such as system shutdown priveleges. Schedule tasks for users. • Provides network configuration. 5. 5. delete users. However many newer distributions use their own graphical interfaces for system configuration which may be easier to use. Linuxconf provides th following functionality. 7. 2. 3. • Provides user customization 1. Assign IP numbers to interfaces. • Console based. 3. 1. change default kernel to boot.6 Linuxconf Linuxconf is the program used to configure the linux system. 4. Configure lilo. Shutdown. remove services. ADVANCED LINUX 2. The command we type is linuxconf. edit. 6. 3. Add kernels for booting. . Add. Configure PPP. 2. Add other operating systems to boot menu. Change routing information. For example > uncompress first.7. The file extension is then . we enter /dev/fd0 as the destination. we enter > gunzip filename For the given file we enter > gunzip myfile. To create a tar file. When we install Linux.cc The uncompress the file we use uncompress. we enter > tar cvf <destination> <files/directories> where <files/directory> specifies the files and directories to be archived and destination is where we want the tar file to be created. keeping original file unchanged. This allows more information to be stored. uncompressed file and will have a .cc The option -c writes output to standard output. To uncompress this particular type of file. COMPRESSED FILES 75 2.gz By default.tar. The resulting file generally replaces the original.gz. myfile. it can copy files to floppy disk or to any filename we can specify in the Linux system. Although tar stands for tape archive.gz is a compressed file. To extract a tar file we enter . The compress command compresses files or standard input using Lempel-Ziv compression. For example > compress first. The option -c writes output to standard output. tar files have the extension .7 Compressed Files Most Linux files are stored on the installation CD-RROM in compressed form. For example > gzip file. keeping original file unchanged. This specifies our primary floppy drive.Z. for example. Any file ending with . If we want the destination to be a floppy disk. The tar command is used because it can archive files and directories into a single file and then recreate the files and even the directory structures later.2.gz extension.Z To create an archive file of one or more files or directories we use the tar command. the installation program uncompresses many of the files transferred to our hard drive. The command gzip compresses files using the Lempel-Ziv encoding. gunzip replaces the original compressed files with the uncompressed version of the files. The option -e encrypts the archive after prompting for a password. The zip command creates a ZIP archive from one or more files and directories. The file will simply uncompress into memory and execute. The option -g adds files to an existing archive. including encryption status. The zipinfo command displays details about ZIP archives. The command uudecode decodes ASCII files created by uuencode to recreate the original binary file. The command gzexe creates an executable compressed file. then the standard input is processed. ADVANCED LINUX The command uuencode encodes a binary file into a form that can be used where binary files cannot (such as with some mail software). operating system used to create the archive.76 > tar xvf <tarfile> We can use > tar tvf <filename> to get an index listing of the tar file. If no files are in the archive are specified. If no file is provided the standard input is encoded.gz files). The zmore command displays the contents of compressed text files. allowing searching in much the same way as the more command. then all files in the archive are searched. The option -o specifies an alternate name for the resulting decoded file. CHAPTER 2. The unzip command manipulates and extracts ZIP archives. By default the name of the decoded file will be the original name of the encoded file. then the standard input is decoded. If no files to decode are provided. The znew converts files compressed with compress (. one screen at a time. If we compress a binary file or script with gzexe then we can run it as if it were uncompressed. compression type. . The -t option tests the integrity of files in the archive. leaving the compressed version on our hard drive. The zipgrep command searches for a pattern in one or more files in a ZIP archive using egrep. If no files are specified. The command zgrep searches one or more compressed files for a specified pattern. and more.Z files) into the format used by gzip (. The command zcat uncompresses one or more compressed files and displays the result to the standard output. but slowest compression method. The option -g uses the best. This password is needed to unencrypt files. we will be prompted twice for a password.tgz is a gzipped tar file.tgz | tar xvf . then all files in the current directory are encrypted.tgz we enter > zcat foo.7.2. When we encrypt files. To unpack. COMPRESSED FILES 77 The command cryptdir encryptes all files in a specified directory.crypt extensions added to their names. If no directory is specified. Encrypted files will have the . for example foo. A file with the extension . We use decryptdir to decript all files in a specified directory. Then vi is in command mode.8 2. The cursor is at the leftmost position of the first line.cc we enter > vi first. . For example.cc with vi. waiting for our first command. The ~ is the empty-buffer line flag. We probably see 20 to 22 of the tilde characters at the left of the screen. but it is extremely powerful. > vi If we know the name of the file we want to create or edit. When we see this display we have successfully started vi. we must switch to input mode with the a or i keys. Unlike most word processors. we can issue the vi command with the file name as an argument. we enter > vi first.8. and flexible. Before we start entering text. If that’s not the case. check the value of TERM. People using DOS so far. vi is popular because it is small and is found on virtually all Unix systems.78 CHAPTER 2.1 The vi and emacs Editors vi Editor vi stands for ”Visual Editor”.cc When vi becomes active. we type its name at the shell prompt (command line). ADVANCED LINUX 2. vi starts in command mode. To start the vi editor. to create the file first. find it rather strange and difficult to use.e. i. except for the first.cc To edit a given file for example first. the terminal screen clears and a tilde character ~ appears on the left side of very screen line. substitute. "/". rearrange. . but vi does not. There are many vi commands. At the beginning of the line. Type :help to access the online documentation.save file and exit vi :q! . vi has online help. We can even pass a command to the shell. Most word processors start in input mode. A few of these commands are: :w . "?" or "!". There is also a command line mode. or modify. vi interprets our keystrokes as commands.8. this doesn’t make much difference. vi beeps. In command mode. We must go into input mode by pressing a or i before we start entering text and then explicitly press <Esc> to return to command mode. This mode is used for complex commands such as searching and to save our file or to exit vi. If we enter a character as a command but the character isn’t a command. We enter this mode by typing ":".quit without saving file. move the cursor to various positions in a file.2. press one of the following keys: a i To append text after the cursor To insert text in front of the cursor We use input mode only for entering text. We can use commands to save a file. THE VI AND EMACS EDITORS Looking at vi’s Two Modes 79 The vi editor operates in two modes: command mode and input mode.save file :wq . We can enter text in input mode (also called text-entry mode) by appending after the cursor or inserting before the cursor. or search for text. delete. To go from command mode to input mode. exit vi. 7. Don’t press <Enter>. Start vi. <Enter> int c = a + b.cc appear on the bottom line of the screen (the status line). 4. Press the Esc key. and contains 9 lines. If we run into difficulties.cc and press <Enter>. is a new file. 6. This command saves or writes the buffer to the file first. Add lines of text to the buffer. We do not see the character a on-screen. 2.80 Creating our First vi File CHAPTER 2. See our action confirmed on the status line. Type vi and press <Enter>.cc has been created. and 178 characters. we can quit and start over by pressing Esc. Exit vi. The characters :w first. for example the following small C++ program #include <iostream. We can press Esc more than once without changing modes. 1. We should see the following on the status line: "first. Type :q and press <Enter>. The characters should not appear in the text.cc. Type. Type :w first. 178 characters This statement confirms that the file first.cc. Now we can append characters to the first line. 3. Press the a key. . Save our buffer in a file called first. ADVANCED LINUX This section gives a step-by-step example of how to create a file using vi.cc" [New File] 9 lines. Go into input mode to place characters on the first line. The :w command writes the buffer to the specified file. We hear a beep from our system if we press <Esc> when we are already in command mode. We see the screen full of flush-left tildes. <Enter> } <Enter> We can use the <Backspace> key to correct mistakes on the line we are typing.h> <Enter> <Enter> void main() <Enter> { <Enter> int a = 7. <Enter> int b = 8. <Enter> cout << "c = " << c. Go from input mode to command mode. 5. then type :q! and press <Enter>. • We give commands to vi only when we are in command mode. Go to command mode.8. • To move from command mode to input mode. . however. • We give commands to vi to save a file and can quit only when we are in command mode. Quit vi. we are still in command mode and see these characters on the status line. respectively. press Esc. THE VI AND EMACS EDITORS 81 When we type :q. 3. • To move from input mode to command mode. 5. The following is a synopsis of the steps to follow: 1. Type :w file-name and press <Enter>. Save buffer to file. Go to input mode. Type vi and press <Enter>. When we press <Enter>. Type the text into the buffer. 6. 2.2. press a (to append text) or i (to insert text). Press Esc. Enter the text. 4. • We add text when we are in input mode. Type :q and press <Enter>. vi terminates and we return to the logon shell prompt. Things to Remember about vi • vi starts in command mode. Press a. Start vi. ADVANCED LINUX To edit or look at a file that already exists in our current directory. press Esc. we hear a harmless beep from the terminal. type vi followed by the file name and press <Enter>. tilde characters appear on the far left of empty lines in the buffer. Look at the status line: it contains the name of the file we are editing and the number of lines and characters. We must make our own backup copies of vi files. Remember that we must be in command mode to quit vi. Command :q Action Exits after making no changes to the buffer or exits after the buffer is modified and saved to a file Exits and abandons all changes to the buffer since it was last saved to a file Writes buffer to the working file and then exits Same as :wq Same as :wq :q! :wq :x ZZ vi doesn’t keep backup copies of files. . Next we list the commands we can use to exit vi. For example > vi first. Exiting vi We can exit or quite vi in several ways.cc We see our C++ program on the screen. If we are already in command mode when we press <Esc>. the original files is modified and can’t be restored to its original state.82 Starting vi Using an Existing File CHAPTER 2. To change to command mode. Once we type :wq and press Enter. As before. regardless of cursor position in the line d$ Shift-d dd All these command can be applied to several objects – characters. THE VI AND EMACS EDITORS Commands to Add Text Keystroke a Shift-a i Shift-i o Shift-o Action Appends text after the cursor position Appends text to the end of the current line Inserts text in front of the cursor position Inserts text at the beginning of the current line Opens a line below the current line to add text Opens a line above the current line to add text 83 Commands to Delete Text Keystroke x dw Action Deletes character at the cursor position Deletes from the cursor position in the current word to the beginning of the next word Deletes from the cursor position to the end of the line Same as <d><$>: deletes the remainder of the current line Deletes the entire current line. or lines – by typing a whole number before the command. words. Some examples are as follows: • Press 4x to delete four characters • Press 3dw to delete three words • Press 8dd to delete eight lines .8.2. from the beginning of the word to the character before the cursor position Changes a line. from the cursor position to the end of the line (same as <c><$>) Changes the entire line ce cb c$ Shift-c cc The Search Commands Command /string ?string n Shift-n Action Searches forward through the buffer for string Searches backward through the buffer for string Searches again in the current direction Searches again in the opposite direction .84 The Change and Replace Commands Keystroke r Shift-r cw CHAPTER 2. from the cursor position to the end of the word (same as <c><w>) Changes the current word. ADVANCED LINUX Action Replaces a single character Replaces a sequence of characters Changes the current word. from the cursor position to the end of the line Changes a line. from the cursor position to the end of the word Changes the current word. suspend vi and execute shell command.delete 5 lines 5j .x.open another file for editing. We can enter i a c s o Insert before cursor Append after cursor Replace word Replace character at cursor Open line below cursor I A C S O Insert at beginning of line Append after end of line Replace rest of line Replace whole line Open line above cursor :e filename .2. For example /that/+1 places the cursor on line below the next line that contains the word that.g 5 substitute x by X in the current line and four following lines. THE VI AND EMACS EDITORS A few examples: x . dd . The command :1.delete 5 words 5dd . we must be in insert mode.delete the current word.move down 5 lines 85 As described above to type in text into vi.8.delete the current character. dw . rx .execute shell command and insert output into buffer /search text -search forward for search text. Most commands can be repeated 5x . :!shell command .replace the current character with x. To go from Normal mode to insert mode. s/now/then/g replaces now with then throughout the whole file. we enter i.delete 5 characters 5dw .delete the current line.X. . !!shell command . The command :s. Type emacs and press <Return>. is a new file.86 CHAPTER 2.8. Linux allows us to enter more than eight characters and a three character extension for a file name. Note the number of characters in the file name. integrated computing environment for Linux that provides a wide range of editing. Start emacs. ADVANCED LINUX 2. contains 9 lines and 178 characters. <Enter> <Enter> } We can use the Backspace key to correct mistakes on the line we are typing. <Enter> cout << "c = " << c. 3. Then at the bottom of the screen we enter first. Add lines of text to the buffer. Exit emacs. programming and file management tasks. To save our buffer in a file called first. 2.cc has been created. Notice the mini buffer at the bottom of the screen.cc This statement confirms that the file first. 1. We see the following on the status line: Wrote /root/first. our keystrokes are appearing there because we are typing commands to the emacs editor. 4. 5. Then press <Enter> again. we can quit and start over by pressing Ctrl-x Ctrl-c.cc because it was the specified file. emacs terminates and we return to the logon shell prompt. See our action confirmed on the status line. The following instructions allow us to edit our first emacs file. Press <Ctrl-x><Ctrl-c> and the <Return>. Emacs is an acronym derived from ”Editor MACroS” (although vi worshipers have suggested many other explanations which range from ”Eight Megabyte And Constantly Swapping” through ”Easily Mangles. Aborts.cc we first press Ctrl-x Ctrl-s. <Enter> int b = 8.h> <Enter> <Enter> void main() <Enter> { <Enter> int a = 7.2 emacs Editor Emacs is a powerful. This command saves or writes the buffer to the file first. If we run into difficulties. <Enter> int c = a + b. Crashes and Stupifies” to ”Elsewhere Maybe Alternative Civilizations Survive”). .cc. We enter again our small C++ program #include <iostream. Unlike MS-DOS and Windows. for all our editing tasks. Save buffer to file. There are modes for LaTeX. Type the file name and press <Enter>. Enter the text. Name the file. 4. or variations of them. The macros which give Emacs all its functionality are written in Emacs Lisp. type emacs followed by the file name and press <Enter>. We use these steps. Quit emacs. Type emacs and press <Enter>. . Emacs provides modes that are customized for the type of files you are editing. then press <Enter> . Here is a list of the more frequently used command sequences in Emacs: C-x means type x while holding down the control key. 5.2. Press Ctrl-c Ctrl-s and answer y to the prompt asking to save the file. THE VI AND EMACS EDITORS 87 The following is a synopsis of the steps you followed: 1. Type the text into the buffer. Fortran.cc <Enter> Look at the mini buffer: it contains the name of the file we are editing. Lisp and many more. 2. We do this with our file first. M-x means type x while holding down the alt or Meta key. Start emacs. > emacs first.cc. 3. Java. Starting emacs Using an Existing File To edit or look at a file that already exists in our current directory. C++. Press Ctrl-x Ctrl-c.8. C. We can also send and receive E-Mail from Emacs and read Usenet news. Switch to another buffer C-w .Execute keyboard macro .Convert word to lowercace M-c .Open rectangle r t .Move to beginning of line .Interrupt currently executing command ( .Save a file C-x C-i .copy marked text M-% .Yank (paste) killed text M-w .Interactive search M-q .Interactive search and replace M-$ .Fill text M-u .Set mark C-d .Display online help c-space .String rectangle n command .Insert a file C-x b . We start the Graphics mode by entering > startx At the command prompt in Graphics mode we enter > emacs or > emacs first.Yank rectangle r o .Move to top of file Move to bottom of file .Kill rectangle r y .88 C-x C-f .convert word to uppercase M-l .cc It also allows to insert files and has search facilities. .Move forward one word .Capitalize word C-h .Delete one word In Graphics mode we also have an emacs editor more user friendly than the text based one.Define a keyboard macro ) End macro definition e .Open a file C-x C-s .delete character at cursor position CHAPTER 2. ADVANCED LINUX C-x C-x C-x C-x C-u C-g C-x C-x C-x M-< M-> C-a C-e M-f M-d r k .Kill (cut) marked text C-y .Move to end of line .Repeat command n times .Check spelling of current word C-s . The option -o file places the output in file file in the present example first.cc we could also use . return 0.9./first > myout . cout << "c = " << c.cc #include <iostream> using namespace std. } Instead of the extension .cpp as for other compilers. To compile and link we enter at the command line the command > g++ -o first first. To run this execute file we enter at the command line > .9 2.1 Programming Languages C and C++ Compiler LINUX provides a C and a C++ compiler.cc The file name of the assembler code is first. Consider for example the C++ program // first. int c = a + b. PROGRAMMING LANGUAGES 89 2. To redirect the output into a file myout we enter > .2.s. The assembler code is in AT&T style.9.cc This provides an execute file with the name first. int main(void) { int a = 7. int b = 8./first Obviously the output will be > c = 15 To generate assembler code we enter > g++ -S first. execve.to change to the directory specified by path • int close(int fildes) .to determine if the file descriptor refers to a terminal device • int pipe(int fildes[2]) .the file descriptor for the standard input stream (ANSI C stdin) • STDOUT_FILENO . execv.h is available on all POSIX compliant systems. execlp.to create fildes2 as a duplicate of a file descriptor fildes • execl.to cause a process to sleep (specified in microseconds) More information on these functions can be obtained friom the manual pages.c. .to write to a file identified by the file descriptor • unsigned int sleep(unsigned int seconds) .to create a pipe which can be used for two processes to communicate • ssize_t read(int fildes.to cause a process to sleep (specified in seconds) • int usleep(useconds_t useconds) .the file descriptor for the standard error stream (ANSI C stderr) • int chdir(const char *path) .to execute a program. execvp . ADVANCED LINUX The name of the C compiler is gcc and the file extension for a C file is .to create a duplicate of a file descriptor • int dup2(int fildes. size_t nbyte) . possibly modifying the path or environment • fork() . int fildes2) . void *buf.the file descriptor for the standard output stream (ANSI C stdout) • STDERR_FILENO . It includes standard symbolic constants and types. execle. The header file unistd. Some of the functions defined in the header file are • STDIN_FILENO .90 CHAPTER 2.to create a new process • int isatty(int fildes) . size_t nbyte) .to read from a file identified by the file descriptor • ssize_t write(int fildes. for example type man fork.to close an open file descriptor • int dup(int fildes) . const void *buf. pl. We can also first write a program first.pl $a = 7.pl . To run the program at the command line we enter > perl first. $c = $a + $b. Notice that the extension of a Perl program is .9.2. $b = 8. # first. For example to run a program from the command line that adds the two numbers 7 and 8 we enter > perl $a = 7. print($c). $c = $a + $b. PROGRAMMING LANGUAGES 91 2.9. $b = 8.2 Perl The programming language Perl is part of Linux. To run the program we press CRTL-d under LINUX and CRTL-z under Windows NT.pl and then run it. print($c). lisp Finished loading first.9. (defun double (num) (* num 2)) We can use the load command to load the file first. ADVANCED LINUX 2. We can also load files into CLISP.lisp T > (double 7) 14 where T stands for true. . Consider the Lisp file first. > (load "first. For example > clisp > (car ’(a b)) a > (cdr ’(a b c)) (b c) To leave CLISP we enter > (bye) or (quit) or (exit).92 CHAPTER 2.3 Lisp LINUX also includes CLISP (Common Lisp language interpreter and compiler).lisp with a function called double.lisp and use the function double.lisp") Loading first. Consider for example the Java program // MyFirst.4 Java There are JAVA compilers that run under LINUX. At the command prompt in Graphics mode the compiling and running is the same as above. } } To compile we enter at the command line > javac MyFirst. . This class file is platform independent.class.9. System. int b = 8.2.out. PROGRAMMING LANGUAGES 93 2.java This generates a class file called MyFirst.java public class MyFirst { public static void main(String[] args) { int a = 7.9. drawRect() etc we first have to go to Graphics mode by entering at the text command line > startx The command startx starts X Windows. for example drawLine(). int c = a + b. To run it we type at the command line > java MyFirst If the program contains Graphics with a paint method.println("c = " + c). 94 CHAPTER 2. ADVANCED LINUX . Netscape and Mozilla. featuring a familiar graphical interface and integrated mail and news. Arena. The Internet and Email are almost synonymous these days and Linux is certainly able to handle both efficiently with mail clients such as Kmail.1 Introduction Linux provides all the commands necessary to do networking. though not as flashy as some of the other Internet browsers. Netscape is one of the more common browsers in use under Linux. Spruce. which is similar to the Windows programme.Chapter 3 Linux and Networking 3. is a small fully functional web browser. Another program for those that prefer console applications is BitchX. Internet Relay Chat (IRC) is used in the Linux community as a way of working with others and getting technical assistance. There are also a number of more traditional console mail programs still in use such as Pine and Mutt. Mozilla is a project based on the Netscape source that was released in 1998. 95 . One such IRC client is XChat. LINUX AND NETWORKING 3.96 CHAPTER 3. The commands are ifconfig ping netstat mailto nslookup dnsdomainname route traceroute hostname rlogin rdate .2 Basic Commands Here we summarize all the basic networking commands. The syntax is > ifconfig interface options address where interface specifies the name of the network interface (e.106. To get the IP address of the host machine we enter at the command prompt the command > ifconfig This provides us with the network configuration for the host machine. the current state of all interfaces is displayed. BASIC COMMANDS ifconfig 97 The ifconfig command configures a network interface. If no arguments are provided.255.50.2.60 255.255.106.50.g. eth0 or eth1). or displays its status if no options are provided. For example Ethernet adapter IP address Subnet Mask Default Gateway 152. .240 Under Windows the command is ipconfig.3.0 152. 27 gives the reply Ping statistics for 152.50.106.27: bytes = 32 time = 1ms TTL = Reply from 152.105. Received 4.50. LINUX AND NETWORKING The ping command sends echo request packets to a network host to see if it is accessible on the network.50.106. Lost 0 (0% loss) Approximate round trip i milli-seconds: Minimum = Oms.106.106. Care should be taken when using this option.50. The greater number will be generated.27: bytes = 32 time = 1ms TTL = Reply from 152. For example > ping 152. The syntax is ping [-R] [-c number] [-d] [-i seconds] host Important Flags and Options -c number: Stops sending packets after the specified number of packets have been sent.106. -d: Outputs packets as fast as they come back or 100 times per second.27: bytes = 32 time = 1ms TTL = Reply from 152.98 ping CHAPTER 3. 128 128 128 = 128 . Maximum = 1ms.50.50. Average Oms The ping command also exists in Windows.27 Reply from 152.27: bytes = 32 time < 10 ms TTL Packets: Sent 4. This option can only be used by the root user because it can generate extremely high volumes of network traffic. When no options are provided. -n: Shows numerical addresses instead of their host.rau. For example > netstat An output could be Active Internet Connections (w/o servers) Proto Rec-Q Send-Q Local Address Foreign Address State tcp 0 2 issc2. or user names.ac:netbios-dgm *. a list of active sockets will be displayed.3.rau. -M/--masquerade: Displays a list of masqueraded sessions. -i [interface]/--interface [interface]: Displays information about a specified interface.* udp 0 0 issc2.za mta-v13.ac:netbios-ns *.rau.yahoo.* This command also exists in Windows. .ac.2. port. BASIC COMMANDS netstat 99 The netstat command displays network status information. or all interfaces if none is specified.mail.com:smtp SYN_SENT udp 0 0 issc2. The syntax is > netstat [-Mnrs] [-c] [-i interface] [--interface interface] [--masquerade] [--route] [--statistics] Important Flags and Options -c: Displays the select information every second until Ctrl-C interrupts it. including connections. routing tables. and interface statistics. If no recipients are indicated on the command line. use Ctrl-D or type a ..] Important Flags -a character-set: Specifies and alternate character set.] [-s subject] [recipient . If no standard input is provided. LINUX AND NETWORKING The mailto command sends an e-mail to one or more recipients. such as ISO-8859-8. the user will be prompted for the recipients. The default is US-ASCII.. If the subject is more than one word. -s subject: Specifies the subject line of the message. The syntax is > mailto [-a character-set] [-c address.100 mailto CHAPTER 3. then the user is prompted for the content of the message. To finish composing a message.: Specifies carbon-copy addresses. -c address. . enclose it in quotation marks. alone on a blank line ... If we want to specify a server but not look up a specified host. The syntax is > nslookup [host|-[server]] dnsdomainname The dnsdomainname command displays the system’s DNS domain name based on its fully qualified domain name.in place of the host.ac.3.2. BASIC COMMANDS nslookup 101 The nslookup command queries a DNS nameserver. the DNS server specified in /etc/resolv. It can be run in interactive mode. we must provide a . then the program enters interactive mode. The syntax is > dnsdomainname For example > dnsdomainname rau.za . By default. If no host name is provided.conf is used unless another is specified. del: Indicates that a route is being deleted.0. When no options are provided. the routing table is displayed.106.0 127.0. [def] If: Forces the route to be connected to the specified interface. netmask Nm: Specifies the netmask for the route. The syntax is > route add [-net|-host targetaddress [netmask Nm] [gw Gw] [[dev] If] > route del [-net|-host] targetaddress [gw Gw] [netmask Nm] [[dev] If] Important Flags and Options add: Indicates that a route is being added. For example > route could give the output Kernel IP routing table Destination Gateway Genmask 152.0 The route command also exists in Windows.106. -host: Indicates the target is a host.240 0.102 route CHAPTER 3.0.0 * 255. LINUX AND NETWORKING The route command displays or alters the IP routing table.0.255.0 default 152. Flags U U Ub Metric Ref Use Iface 0 0 1 eth0 0 0 1 lo 0 0 1 eth0 .50. gw Gw: Specifies the gateway for the route.255.50. -net: Indicates the target is a network.0.0.0 * 255. za [152.9. -r: Bypasses normal routing tables and attempts to send directly to an attached host.ac.240] 2 14ms 3ms 5ms 152.50.50.za [152.rau.27] over a minimum of 30 hops 1 3ms 3ms 4ms xylan-40. .2.27] This command is called tracert in Windows.241 3 12ms 26ms 2ms zeus.106.rau. BASIC COMMANDS traceroute 103 The traceroute command displays the route a packet travels to reach a remote host on the network.106.106.ac. This is useful in system with more than one network interface.ac.50.3.rau.27 The output could be Tracing route to zeus.106. The syntax is > traceroute [-r] host Important Flags -i: Specifies a network interface for outgoing packets.106. For example > traceroute -r 152.za [152. The syntax is > hostname [-a] [--alias] [-d] [--domain] [-f] [--fqdn] [-i] [--ip-address] [--long] [-s] [--short] [-y] [--yp] [--nis] Imporloginrtant Flags and Options -a/--alias: Displays the alias name of host if available. -i/--ip-address: Displays the IP address of the host.rau. -d/--domain: Displays the DNS domain name of the host. -s/--short: Displays the host name without the domain name.za . LINUX AND NETWORKING The hostname command displays or sets the system’s host name.104 hostname CHAPTER 3. If no flags or arguments are given. For example > hostname issc2.ac. -y/--yp/--nis: Displays the NIS domain name of the system. then the host name of the system is displayed. -f/--fqdn/--long: Displays the fully qualified domain name of the host. -s: Sets the local system’s time based on the time retrieved from the network. rdate 105 The rdate command retrieves the current time from one or more hosts on the network and displays the returned time.ac. This can only be used by the root user.za connection refused . Important Flags -p: Displays the time returned from the remote system (this is the default behavior).2.. BASIC COMMANDS rlogin The rlogin command logs in to a remote host. The syntax is > rdate [-p] [-s] host .rau. For example > rdate rauteg..3. the system maintains a set of directories and files for mail messages.ac.3 email Unix and Linux have strong support for computer-to-computer communication.rau. enter cat report. To send report. Each user has a file in the system’s mail directory. The computer responds by displaying EOT.za with the subject Hello Willi and the message Give me a call we enter at the command line > mail whs@na.za <Enter> Subject: Hello Willi <Enter> Give me a call <Enter> . To implement electronic mail. the mail command uses the option -s.txt. and the string that serves as the subject heading is surrounded by quotation marks. which means end of transmission. Sending a Prepared Message We may want to use a text editior such as vi to compose a message to be sent by electronic mail. If we use a text editor. There are essentially three ways to send the file. Remember that the Ctrl-d must be on a line by itself just as the period must be on a line by itself.com. Here are the three methods we can use to send mail using a prepared message file called report.ac.com<Enter> . As new mail arrives it is added to the file for the recipient and the user is informed of its arrival. The mail system is implemented by the mail program.txt | mail -s "Sales Report" steeb_wh@yahoo. In the examples in the following list. Thus messages are stored on disk in mailbox files.rau. It doesn’t matter what program we use to create the text as long as we end up with a text or ASCII file. LINUX AND NETWORKING 3. • Use a pipe. as shown in the following list.106 CHAPTER 3.<Enter> (to send message) We can also end the message with Ctrl-d instead of a period.txt and that the recipient’s address is steeb_wh@yahoo. Assume we want to send mail to the following address whs@na. we have the tools to do things such as format the text and check our spelling.txt with the mail command. Suppose that the file we want to send is named report. the message we have read are kept either in our systems mailbox.3. "/var/spool/mail/imgood": 5 message 2 new 1 unread 1 sarah -Wed Jan 5 09:17 15/363 2 croster@turn. the e-mail program marks a message as read.green. enter these commands: mail steeb_wh@yahoo. EMAIL 107 • Redirect input. As we read our mail. Suppose that our logon name is imgood: we see a display similar to this: mail<Enter> mail Type ? for help. Depending on what commands we use and how we quit the e-mail program. enter mail -s "Sales Report" steeb_wh@yahoo. It’s up to us to read and act on it.txt<Enter> • Use ~r to include a file in a message.3.com < report.com<Enter> Subject: Sales Report<Enter> ~r report. We can use either mail or another e-mail program to read any mail we have. To send report.com -Sat Jan 8 13:21 76/3103 Excerpt from GREAT new UNI ? Here are some things to note about the display: . type mail and press <Enter>. To use mail to send the file (using the default Subject: prompt).<Enter> EOT Reading our Mail Most Linux systems notify us when we log on that we have e-mail.txt with the mail command and the -s option. Using mail to Read Mail To read our mail with mail.com -Thu Jan 6 10:18 26/657 Meeting on Friday U 3 wjones -Fri Jan 7 08:09 32/900 Framistan Order > N 4 chendric -Fri Jan 7 13:22 35/1277 Draft Report N 5 colcom!kackerma@ps.txt<Enter> ~. /var/spool/mail/SLOGNAME or in our logon directory in the file named mbox. green.com an address that indicates the message came to our machine from a network (mail from a local user is marked with just the user’s logon ID).108 CHAPTER 3. The subject is ”Meeting on Friday. . Each line holds a message number.com Thu Jan 6 10:18 26/657 Meeting on Friday This line indicates the message numbered 2 is from croster@turn.mail we didn’t know about before.green. • A message line without either N or U is mail we have read and save in our system mailbox. • A message line starting with U indicates unread mail – mail that we know about but haven’t read. We see the shell prompt again. at 10:18. Quitting and Saving Changes To quit the mail program and save the changes that occur. Consider the following line: 2 croster@turn. the date the message was sent. January 6. • A greater-than character (>) on a message line marks the current message the message we act on next. and two messages have already been read.” • A message line starting with N indicates new mail . messages we read but didn’t delete are saved in a file named mbox in our home directory. • The question mark (?) on the last line is the command prompt from mail. the number of lines and characters in the message. and the subject (if one was given). LINUX AND NETWORKING • The first line identifies the program and says to type a question mark for help. Two have arrived since we last checked our mail. press q and <Enter> when we see the ? prompt. the address of the sender. it consists of 26 lines and 657 characters. When we quit mail this way. Ignore the first few characters for now. /var/spool/mail/imgood and that we have five messages. • The five lines give information about our mail. The message was sent on Thursday. • The second line indicates that mail is reading our system mailbox. one appeared previously but we have not yet read it. Shall I create the directory . If this is the first time we have used elm. 7 = help .4 PL23] N 1 Nov 11 Jack Tackett Linux book N 2 Nov 11 Jack Tackett more ideas You can use any of the following commands by pressing the first character. Since elm is easy to use. we only touch on the highlights of using it. Shall I create the directory /home/gunter/Mail for you (y/n/q)? y<Return> Great! I’ll do it now. r)eply or f)orward mail. It provides a set of interactive menu prompts and is extermely easy to use.3. Here is what we see as we start elm for the first time: $ elm<Enter> Notice: This version of ELM requires the use of a . Notice: ELM requires the use of a folders directory to store your mail folders in. Starting elm To start a mail session with elm.elm directory in your home directory to store your elmrc and alias files.3. d)elete or u)ndelete mail. After elm creates its directory and mbox file. EMAIL The elm Mailer 109 There are several different mail programs available for Linux. Command: k = move up. Our screen clears and the following is displayed Mailbox is ’/var/spool/mail/gunter’ with 2 messages [ELM 2. m)ail a message. This is a full-screen-oriented mailer. We can find more in-depth information by using elm’s online help or by reading the man page. it will prompt for permission to set up a configuration directory in our account and create an mbox mail file if one does not exist. it runs the main mail program.elm for you and set it up (y/n/q)? y<Return> Great! I’ll do it now. press <return>. Virtually everything that we can do with mail can be done under elm. One mail reader that comes with the Slackware distribution of Linux is the elm mailer. Each has its own advantages and disadvantages. j = move down. q)uit To read a message. This mail program is a screen-oriented mailer rather than a line-oriented one. we enter elm at the command prompt. rau. and what version of elm we are running. and the subject. <Right> Display next index page -. The Command: prompt at the bottom of the screen tells us to press a command key for elm to do something. elm tells us where our system mail box is located. reply to a message.ps we enter the following command > elm -s testing whs@na. Other elm commands are summerized in the following table.ps To display the current message we use <Enter> or <Spacebar>. <Left> Displays previous index page = Sets current message to first message * Sets current message to last message <Number><Return> Set current message to <Number> . we can delete or undelete mail. It places the letter N before each new message. Command Summary for elm Command Description | Pipes current messsage or tagged message to a system command ! Shell escape $ Resynchronizes folder ? Displays online help +. The current message is highlighted in the list. Help is available by pressing the ? key. or quit. As we can see in this example. how many messages are in it.ac.za < qc.rau.110 CHAPTER 3. Our display may vary slightly depending on our version of elm. Pressing the j key moves the message selection to the previous message. The summary line for each message tells us if the message is new. just like the mail program. mail a message.ac. the k key moves it to the next message. the sender. To send a file to whs@na.za named qc. elm then lists one line for each message in our mailbox. forward mail. LINUX AND NETWORKING At the top of the screen. the message date. At the bottom of the screen is a command summary that tells us what commands we have available for the current screen. displaying current. storing. ask permission if folder changed X Exits leaving folder untouched. <Ctrl-q> Exists leaving folder untouched. <Up-Arrow> Advances to previous undeleted message l limits messages by specified criteria <Ctrl-l> Redraws screen m Mails a message n Next message.3. then increment o Changes elm options p Prints current message or tagged messages q Quits. <Down-Arrow> Advances to next undeleted message K Decrements current message by one k. maybe prompting for deleting. changes to ’alias’ mode b Bounces (remail) current message C Copies current message or tagged messages to a folder c Changes to another folder d Deletes current message <Ctrl-d> Deletes messages with a specified pattern e Edits current folder f Forwards current message g Groups (all recipients) reply to current message h Displays header with message J Increments current message by one j. EMAIL Command Description / Searches subjects for pattern // Searches entire message texts for pattern > Saves current message or tagged messages to a folder < Scans current message for calendar entries a Alias. and keeping messages Q Quick quit-no prompting r Replies to current message s Saves current message or tagged messages to a folder t Tags current message for futher operatons T Tags current message and go to next message <Ctrl-t> Tags messages with a specified pattern u Undeletes current message <Ctrl-u> Undeletes messages with a specified pattern x.3. unconditionally 111 . 150 Opening ASCII mode data connection for /bin/ls. The ftp server will ask you for your login name. $ ftp eng. Nov 3 14:43 bnc-2.2. bin dev etc lib pub welcome. It provides access to public databases without the need for an account on the system.112 CHAPTER 3. We use ftp as follows. ftp> ls 200 PORT command successful.msg 4.0. We can transfer text and binary files to and from remote sytems of any supported type. ftp> .rau. Nov 18 15:38 . ftp> cd pub 250 CWD command successful. total 8 drwxr-x--7 ftp ftp 1024 Oct 31 18:00 drwxr-x--7 ftp ftp 1024 Oct 31 18:00 d--x--x--x 2 root root 1024 Oct 22 11:07 drwxr-xr-x 2 root root 1024 Aug 7 1996 d--x--x--x 2 root root 1024 Aug 7 1996 drwxr-xr-x 2 root root 1024 Aug 7 1996 dr-xr-xr-x 5 root root 1024 Apr 15 1997 -rw-r--r-1 root root 505 Feb 19 1997 226 Transfer complete. Type anonymous and enter your email address as password (or just pvm@).ac.. Aug 26 1996 .gz .4 ftp Commands The ftp application is an interface program for the ARPAnet standard file-transfer protocol. 3. 1. where the data resides. Type ls to get a file listing: ftp> ls 200 PORT command successful. Anonymous FTP is a popular use of this application. and get a new listing. Now lets see what is available on the ftp site. Change into the /pub directory by using the cd command. Start ftp by typing the command ftp and the ftp-host at the prompt.za 2. LINUX AND NETWORKING 3. .tar.. 150 Opening ASCII mode data connection total 564 dr-xr-sr-x 5 root ftp 1024 drwxr-xr-x 9 root root 1024 -rw-rw-r-1 501 501 3562 for /bin/ls. To disconnect from the server type bye: ftp> bye 221 Goodbye $ . dr-xr-sr-x 5 root ftp 1024 Nov 18 15:38 .tar.4.zip 18 15:38 tear 17 1997 uml 113 5. We use the get command. ftp> 6. 226 Transfer complete.10.. 66 bytes received in 0. FTP COMMANDS drwxr-xr-x drwxrwsr-x -rw-r--r--rwxr-xr-x drwxrwsr-x 226 Transfer ftp> 2 ftp 3 root 1 root 2 root 2 root complete. Always switch to binary mode before downloading a file. total 2382 drwxrwsr-x 3 root ftp 1024 Nov 25 11:47 . root ftp ftp ftp ftp 1024 1024 555437 7399 1024 Jun Nov Oct Nov Feb 5 1996 irc 18 07:36 linux 16 14:12 sdc51. drwxrwsr-x 2 root ftp 1024 Mar 26 1997 MuPAD -rw-r--r-1 root ftp 22824 Nov 18 07:36 freefont-0. 150 Opening ASCII mode data connection for /bin/ls. Lets see what is the linux directory: ftp> cd linux 250 CWD command successful. 150 Opening BINARY mode data connection for please_download_me (66 bytes).gz -rw-r--r-1 root ftp 66 Nov 25 11:47 please_download_me 226 Transfer complete. ftp> bin 200 Type set to I. ftp> ls 200 PORT command successful.3. Now we wish to download the file please_download_me. ftp> get please_download_me local: please_download_me remote: please_download_me 200 PORT command successful.00399 secs (16 Kbytes/sec) ftp> 7. LINUX AND NETWORKING Let us summarize the main commands for CHAPTER 3. ascii sets the file transfer type to network ASCII bell sounds the bell after each file transfer binary sets the file transfer to binary mode bye terminates the FTP session with the remote server cd remote-directory changes the working directory on the remote machine cdup goes to the parent chmod mode file-name changes the permission modes of the file close terminates the FTP session with the remote server delete remote-file deletes the remote file on the remote machine get remote-file retrieves the remote file and stores it on the local machine ls lists the contents of the remote directory open host [port] establishes a connection to the specified host FTP server put local-file stores a local file on the remote machine pwd prints the name of the current working directory quit same as bye rmdir directory-name deletes a directory on the remote machine . cc pvm slave1. We can call any remote system that is accessible on the network.cc slave2.dat add.64. In telnet we can log in either in one of two modes: character-by-character or line-by-line.cc subcourse test.student iofile pow.3.s gnu. > telnet hostname [port] where hostname is the host we want to connect to and port indicates a port number. Let us look at a telnet session. We do this if we want to send commands directly to the telnet program and not to our remote computer session. We can connect to another port.2 Kernel 2.cc add file_to_sort master.cc new.50. In the character-by-character mode... To start a telnet session we simply enter the command name at the command line.c Hewey:~/course$ exit $ product. In line-by-line mode all text is echoed locally and only completed lines are sent to the remoe host.cc hosts pmx.5 Telnet The telnet application is a user interface program for remote system access.106.cc The default port to which telnet connects in 23. Connect to hewey.cc test12. for example port 80 which is the port on which the www server listens: .za. School for Scientific Computing RedHat Linux 4.30 on an i586 login: pvm Password: Last login: Tue Nov 25 13:11:22 on tty1 Hewey: ~$ cd course Hewey:~/course$ ls Makefile file2. TELNET 115 3. This puts us in the telnet command interpreter. When we connected to a remote host.cc first. we can enter the telnet command mode by typing Ctrl ]. $ telnet hewey Trying 152.cc add.5.rau. but we need an account on the remote system.ac.cc names.student iofile. most tect typed is immediately sent to the remote host for processing.tex file1. Escape characters is ’^]’.cc ex2m.0. If a port number is not specified the default telnet port is used. 27. Which gives us another way to read www pages (if we can decipher HTML).50. .0 200 OK Server: Microsoft-PWS/3.0 Date: Tue.0 CHAPTER 3. Connected to zeus.ac...za Escape character is ’^]’.. 25 Nov 1997 11:55:45 GMT Content-Type: text/html Accept-Ranges: bytes Last-Modified: Mon.106.. GET ? HTTP/1.rau. 01 Sep 1997 10:21:46 GMT Content-Length: 2207 <head><title> Home Page: Prof Willi Hans Steeb </title></head> . LINUX AND NETWORKING HTTP/1.116 $ telnet zeus 80 Trying 152. cc pvm slave1.cc ex2m.19s 0. This is contolled by the . 0.cc names.cc add.cc subcourse test.cc hosts file1.student iofile Hewey:~/course$ from Atilla iofile.cc Our system is set up so that rsh does not ask for a password (for pvm to work properly).6.cc pmx.cc slave2. REMOTE SHELL 117 3.6 Remote Shell The rsh command (remote shell) allows us to start a ”remote shell” on a Unix machine on the network. we can copy a file to as list of computers: Hewey:~/course$ for name in dewey louie atilla > do > rcp foo $name:~/course > done Hewey:~/course$ . 0. For example Chopin:~$ rsh hewey Last login: Tue Nov 25 14:31:24 Hewey:~$ cd course Hewey: ~/course$ ls Makefile file2. 1 user.08s -bash The command rcp (remote copy) is useful for distributing files over the network: Hewey:~/course$ echo "This text is going to do some travelin" > foo Hewey:~/course$ rcp foo dewey:~/course By combining rcp with an interactive shell script.cc first.tex posix pow.cc test13.cc master.00.cc product.00 LOGIN@ IDLE JCPU PCPU WHAT 4:07pm 46:15 0. USER TTY FROM pvm tty1 Hewey:~S load average: 0.dat new.00.s gnu. The rsh command can be used to start a program other that shell Hewey:~$ rsh atilla exec w 4:54pm up 3:37.3.student add file_to_sort add.rhosts file in the /home/pvm directory. Opensource graphical web browser derived from publicly released source code from the Netscape browser. It is very fast since it does not render any graphics. Lynx supports the use of cookies. A popular console (text) based web browser. • Links.7 Web Netscape provides a Web browser for Linux including HTML and JavaScript. The only option for some advanced websites (also see Mozilla below).118 CHAPTER 3. No support for scripting (javascript. This browser is becoming very popular but is still weak with respect to Java and javascript support. CGI forms and SSL. A popular graphical web browser. The graphical web browser which comes with the KDE package. . javascript and XML. Also used for reading KDE help files. with support for the newest standards including Java. We list some of them here.) or Java. All the latest web browser features are available. Similar to lynx but can also display frames and tables. It is possible to browse websites with frames although this is somewhat less intuitive. A good and stable browser for simple browsing of the internet. vbscript etc. • Lynx. Another console (text) based web browser. • Netscape. • Mozilla. tends to be an ‘experimental’ browser. Also available for windows. • Konqueror. LINUX AND NETWORKING 3. There is a wealth of web browsers available for Linux. depending on the needs of the user. ps ax | grep inetd to determine the process id (inetdpid ) of inetd 2. INETD AND SOCKET PROGRAMMING 119 3. To select a port to use. Inetd provides the following. kill -HUP inetdpid to reload inetd. inetd starts the program associated with the port according to the contents of inetd.conf installed on the system. • The server program reads from stdin and writes to stdout to communicate with the client. The port must be specified by a name from . this port is not used. By default.conf.conf: 1. without knowing much about the underlying network programming. When a connection is made.8 INETD and Socket Programming Inetd is a daemon which listens on specified network ports for network connections. We can use any port number from 0 up to and including 65535.conf). Alternatively you could modify /etc/services and add an unused port and name for use on your system only. • Inetd listens on a number of specified ports (see inetd. • To reload inetd. The following is an example of /etc/inetd. Type in the process id number of inetd in place of inetpid.sh ftpd -l telnetd comsat rshell.conf. When a client connects to one of these ports inetd starts a server program with it’s standard input and output redirected to use then network connection.sh We use the port aol since it is unlikely the system will ever need to use this. See the services(5) man page. • Inetd redirects the standard input and output descriptors to use the socket for the connection. Thus inetd can be used to write simple network server programs.3.conf. • Allows programs to act as servers without implementing any network programming.8. examine the file /etc/services for an unused service and use that one. ftp telnet comsat aol stream stream dgram stream tcp tcp udp tcp nowait nowait wait nowait root root tty:tty root /usr/libexec/ftpd /usr/libexec/telnetd /usr/libexec/comsat /usr/local/bin/rshell. For example we could add the line rshell 60000/tcp to /etc/services. Usually we would add the last line to the existing /etc/inetd. fd_set fselect.c). The shell expects all commands to end with a linefeed code. we can write our own client using sockets. This is done in the following program (rshell_client.h> <netinet/in. LINUX AND NETWORKING /etc/services.h> <stdlib. telnet localhost aol Testing this will show that every command entered fails. This is because telnet sends a carriage return and linefeed code whenever you press the enter key.char *argv[]) { struct hostent *host.h> <sys/types. struct sockaddr_in sin. and the command will not be recognised.h> /* */ /* for select */ /* */ /* for sockaddr_in */ /* for gethostbyname and others */ #define BUFSIZE 4096 int main(int argc. We could test a server using the telnet command. The following is the contents of /usr/local/bin/rshell.h> <unistd. int s. To illustrate the flexibility of the inetd system we use a Bourne shell script for the server.h> <netdb. Do not use this script when connected to a network since the service provides full access to the machine. We can overcome this by removing the carriage return from the command in the shell script.sh. do echo Enter command: read command $command done The script asks for a command and then executes it. #!/bin/sh echo "Remote shell" date while true. Thus the carriage return is used as part of the command. Alternatively. struct servent *sp. .h> <sys/socket.120 CHAPTER 3. #include #include #include #include #include #include #include #include <stdio.h> <sys/time. sin_port=sp->s_port. } sp=getservbyname(argv[2].(const struct sockaddr*)&sin. } skt=fdopen(s.sizeof(sin))==-1) { close(s). FD_SET(s. if (s==-1) { printf("Socket open failed. sin. char buffer[BUFSIZE]. } s=socket(host->h_addrtype.\n"). exit(EXIT_FAILURE). if (host==NULL) { printf("Host lookup failed. exit(EXIT_FAILURE). exit(EXIT_FAILURE).\n"). } FD_SET(STDIN_FILENO. sin. getprotobyname(sp->s_proto)->p_proto).\n"). } host=gethostbyname(argv[1]).\n").&fselect). if (argc<3) { printf("Host and service expected.sin_family=host->h_addrtype.&fselect). if (connect(s.3. 121 .sin_addr=*((struct in_addr*)(host->h_addr_list[0])).SOCK_STREAM.8. sin.\n")."r+").(char*)0). printf("Socket connect failed. INETD AND SOCKET PROGRAMMING FILE *skt. exit(EXIT_FAILURE). if (sp==NULL) { printf("Service lookup failed. exit(EXIT_FAILURE). &fselect).&fselect)) { fgets(buffer.stdin). } close(s). fputs(buffer.&fselect. FD_SET(s.NULL.skt). fflush(skt).NULL)>0) &&!feof(stdin)&&!feof(skt)) { if (FD_ISSET(s. } if (FD_ISSET(STDIN_FILENO. fflush(stdout). LINUX AND NETWORKING while ((select(s+1. fputs(buffer.skt). } FD_SET(STDIN_FILENO.&fselect).BUFSIZE. } .BUFSIZE.NULL.122 CHAPTER 3.&fselect)) { fgets(buffer.stdout). 1. 5. 4. Once we have typed our password. it starts up a program called login to finish the process of loging in. In most cases it will be /bin/sh (or /bin/bash on Linux machines). among other things. The point is that absolutely any program can be started when a specific user logs in. it checks for the name of the program to execute. login proceeds to verify it against the encrypted entry in the /etc/passwd file. and program to start up when that user logs in. and then waits for us to type our password. As soon as someone types some characters followed by RETURN. we review the sequence of events that happen when we log into a Unix system. or a terminal emulator such as a xterm window) connected to certain ports on the Unix machine. To understand what the shell is.1 What is a shell The shell is a program used to interface between the user and the Linux kernel. The shell just happens to be the one most often selected. home directory. This file contains one line for each user on the system. a program called init automatically starts up a getty program on each terminal port. When login begins execution. password. 123 . 3. displays the message Login: at its assigned terminal and then just waits for someone to type something in. Whenever we enter a command it is interpreted by the Linux shell. and what it actually does. getty determines things such as the baud rate. it displays the string Password: at the terminal.Chapter 4 Shell Programming 4. the login name. or some custom-designed application. After login checks the password. the getty program disappears. On a Unix system. We normally access a Unix system through a terminal (be it an old fashioned serial terminal. The shell is a command line interpreter. It also gives login the characters we typed in at the terminal – characters that presumably represent our login name. 2. That line specifies. but before it goes away. meaning that anyone with the capability and the devotion can create their own shell program. Program execution The shell is responsible for the execution of all programs that you request from our terminal. The kernel copies the specified program into memory and begins to execute it. Each time we type in a command and press the Enter key. If the program writes output to the standard output. It is important to realize that the shell is just a program. If we ask it to execute a program. the shell proceeds to search the disk for that program. the Korn shell ksh. When we log off. This program is called a process . developed by David Korn and the C shell csh. but has several additional features not offered by the standard Bourne shell. the shell analyses the line we have typed and then proceeds to carry out our request. control once again returns to the shell which awaits your next command. This cycle continues as long as we are logged in. Similarly. it displays a command prompt – typically a dollar $ sign or > sign – at our terminal and then waits for us to type some commands. developed by Stephen Bourne. . and then “goes to sleep” until the program has finished. Once found. This shell is compatible with the Bourne shell. including the standard Bourne Shell sh. The shell scans this command line and determines the name of the program to be executed and what arguments to pass to the program. SHELL PROGRAMMING When the shell starts up. in this way the distinction is made between a program that resides in a file on disk and a process that is in memory doing things. As far as the shell is concerned. developed by the GNU project of the Free Software Foundation. execution of the shell terminates and the Unix system starts up a new getty at the terminal that waits for someone else to log in. if the program read from standard input. When the command has finished. the shell analyses the line and then determines what to do. it will wait for you to type something at your terminal. The shell found on most Linux systems is the Bourne-again-shell bash. unless input is redirected or piped in from a file or command. This is in fact the reason why various flavours of the shell exist today. The shell has several responsibilities namely: 1. the shell asks the kernel to initiate the programs execution. it will appear on our terminal unless redirected or piped into a file or another command. each line follows the same basic format: program-name arguments The line that is typed to the shell is known more formally as the command line. developed by Bill Joy. It has no special privileges on the system. Each time we type in a line to the shell.124 CHAPTER 4. Variable and File name substitution Like any other programming language. The shell also performs name substitution on the command line..cc outbox the shell scans the command line and takes everything from the start of the line to the first whitespace character as the name of the command to execute: mv.c The echo command can be used to illustrate file name substitution: $ echo * template.cc worm.cc test test.ps thread thread.cc test test.1.cc template_trouble.cc thread. We note that multiple occurences of whitespace is ignored.cc vector.cc worm.cc template_trouble. ?. preceded by an dollar sign. or [.o varargs varargs. and are the space character. WHAT IS A SHELL 125 The shell uses special characters to determine where the program name starts and ends. When we type the command $ mv progs/wonderprog.cc vector. We have to remember that the filename substitution is done by the shell before the arguments are passed to the program.o varargs varargs. and the end-of-line (or newline) character. The shell scans the command line looking for name substitution characters *.cc vector.cc test.] before determining the name of the program and its arguments to execute. 3. the horizontal tab character. How many arguments were passed to the echo command? The correct answer is 15. These characters are collectively called whitespace characters. Suppose your current directory contains the files: $ ls template. Standard Input/Output and I/O redirection It is the shells’ responsibility to take care of input and output redirection on the command line. > or >>.h virtual virtual.cc test.4.ps thread thread.cc vector. When we type the command: $ echo This is some text that is redirected into a file > text . the shell substitues the value that was assigned to the variable at that point.. The next set of characters is the first argument to the program and so forth. the shell allows you to assign values to variables.cc thread.h virtual virtual. 2. It scans the command line for the occurrence of the special redirection characters <. Whenever we specify one of these variables on the command line.c Question. The second case. however. So wc opens the file users. when we enter $ who | wc -l the shell connects the standard output of the command who (which generates a list of all users currently logged into the system) and connects it to the standard input of the command wc -l. it also scans for the pipe character |. the shell start the wc program with only the one argument -l. Seeing that it was called with only one argument. and will in effect count the number of currently logged in users. and then prints the count together with the file name at the terminal. the shell analyses the command line and determines that the name of the program to execute is wc (a program that counts the number of lines. The shell spots the redirection character < when it scans the command line. The first argument tell it to only count the number of lines. and the second argument is the file whose lines have to be counted. it is overwritten.126 CHAPTER 4. It again prints the final count. SHELL PROGRAMMING The shell recognizes the redirection character > and uses the next word on the line as the name of the file to which the input stream is to be redirected. and redirects its standard input from the file users. it connects the standard output from the program preceding the | to the standard input of the program following the |. Use the >> operator to append to the file. So. The word that follows is the name of the file input is to be redirected from. Having “gobbled up” the < users from the command line. Consider the following nearly identical commands: $ wc -l users 5 users $ wc -l < users 5 In the first case. operates entirely differently. If the file already exists. For each such character it finds. wc knows it has to read input from standard input. . but without a filename. it redirects the standard output of the program to the indicated file. It then initiates execution of both commands. because it wasn’t given one. Pipes Just as the shell scans the command line for redirection characters. The program is never aware of the fact that its output is being redirected. word and bytes in a file) and that it is to be passed two arguments namely -l and users. 4. The two commands execute simultaneously. Before the shell starts the execution of the desired program. counts its lines. 2.2 The Shell as a Programming Language There are two ways of writing shell programs. Then we could enter at the command line $ > > > $ if [ -f first. Interactive programs Typing in the script on the command line is a quick and easy way of trying out small code fragments.cc ] then echo "file exists" fi If the file exists. and execute the script immediately. THE SHELL AS A PROGRAMMING LANGUAGE 127 4. The following interactive script shows how to do mathematics (addition. The solution is to store the commands in a file.cc exists in the present directory. The shell will decide when we have finished. or we can store those commands in a file which we can then invoke as a program. the system displays file exists. Note how the shell prompt $ changes to a > when we type in shell commands. Suppose we want to find out whether the file first. typing in a script every time we need it is too much trouble. Thus division is integer division. The shell can only do integer arithmetic. At the command line we enter > count=1 > count=$((count+1)) > echo $count 2 > count=$((count+2)) > echo $count 4 > count=$((count*5)) > echo $count 20 > count=$((count/7)) 2 > . division) using the shell. However.4. conventionally refered to as a shell script. We can type in a sequence of commands and allow the shell to execute them initeractively. multiplication. Having made such a sweeping statement.128 CHAPTER 4. SHELL PROGRAMMING 4.2. Conventionally. and then prints those files to the standard output.1 Creating a Script First. Since the script as it stands can’t detect any failures. the #! characters tell the system that the one argumant that follows on the line is the program to be used to execute this file. In this case /bin/sh is the default shell program. though.sh #!/bin/sh # # # # first. Call the file first. for file in * do if grep -l POSIX $file then more $file fi done exit 0 Comments start with # and continue to the end of a line. Even if we never intend to allow our script to be invoked from another. . This is rarely checked when commands are run interactively.sh This program looks through all the files in the current directory for the string POSIX. # is usually kept in the first column. but if we want to invoke this script from another script and check whether it succeeded. we should still exit with a reasonable code. we create a file containing the commands we have just typed. we always return success. #!/bin/sh. The exit command ensures that the script returns a sensible exit code. is a special form of comment. A zero denotes success in shell programming. returning an appropriate exit code is very important. using any text editor. we next note that the first line. but it would be much better if we could simply invoke the script by typing its name. thus $ /bin/sh first.2.2 Making a Script executable Now that we have our script file.sh This should work. giving it the respectability of other Unix commands.2. we can run it in two ways.4. THE SHELL AS A PROGRAMMING LANGUAGE 129 4. We do this by changing the file mode to make the file executable for all users using the chmod command $ chmod +x first./first. .sh We note that it is necessary to type the .sh We then execute the script using the command $ ./ because for security reasons our current directory should never be in our PATH (especially not if we are logged in as root). The simpler way is to invoke the shell with the name of the script file as a parameter. not least because it is easy to test small program fragments interactively before combining them into bigger scripts.130 CHAPTER 4. Instead we create them when we first use them. we can set various values of the variable message: $ message=hello $ echo $message hello $ message="Hello. a tab. Also note that there may be no spaces on either side of the equals sign. for example. The shell is an easy programming language to learn. Normally. World" $ echo $message Hello. namely the use of quoting.1 Variables Unlike C we don’t declare variables in the shell before we use them. or a newline character. . Within the shell. and foo to be different. except when an assignment is being made to the variable. Unix is a case sensitive system and considers the variables Foo. Whenever we use them. The read command takes one argument namely the name of the variable. FOO. we have to quote the parameter. even when they are assigned numerical values. it is now time to look in more depth at the programming power of the shell. 4. The shell and some utilities will convert ’numeric strings’ to their values before operating on them. parameters are separated by whitespace characters. If we want a parameter to contain one or more whitespace characters. By default. when we pass an initial value to them. and waits for the user to type in some text and press the return key. all variables are considered and stored as strings. SHELL PROGRAMMING 4. we can get at the contents of a variable by preceding its name with a $ character and outputting its contents with the echo command. we need to give variables a preceding $. On the command line.e. We can use the modern Unix shell to write large structured programs.3. World $ message=7+11 $ echo $message 7+11 Note how a string has to be delimeted by quotation marks if it contains spaces. i. a space.3 Shell Syntax Having seen an example of a simple shell program. We can assign user input to a variable by using the read command. Quoting Before we move on we have to clear about one feature of the shell. The variables created will depend on our personal configuration. Normally strings are enclosed in double quotes. but allows $ expansion to take place. If we enclose it in single qoutes. These are normally capitalized to distinguish them from user-defined (shell) variables in scripts. while single quotes and the backslash do. Many are listed in the manual pages. SHELL SYNTAX 131 The behaviour of parameters such as $message inside quotes depends on the type of quotes we use. We can also remove the special meaning of the $ symbol by prefacing it with a backslash \. some variables are initialized from values in the environment. but the principle ones are . it’s replaced with its value when the line is executed.4.3. The following script illustrates shell variables and quoting #!/bin/bash myvar="Hi there" echo echo echo echo $myvar "$myvar" ’$myvar’ \$myvar echo Enter some text read myvar echo ’$myvar’ now equals $myvar exit 0 This gives the output: Hi there Hi there $myvar $myvar Enter some text Foo $myvar now equals Foo We see that the double quotes doesn’t affect the substitution of the variable. which are conventionally lowercase. no substitution takes place. which protects variables from being seperated by whitespace. We also use the read command to get a string from the user. If we enclose a $ variable expression in double quotes. Environment Variables When a shell script starts. A colon-seperated list of directories to search for commands. or by a space if IFS is unset. usually >. separated by the character in environment variable IFS . $* The parameters given to the script. The name of the shell script. that doesn’t use the IFS environment variable. The number of parameters passed. . $2. A command prompt. SHELL PROGRAMMING The home directory of the current user. the environment variable $# listed above does still exist.. in a single variable. which isn’t equivalent to unsetting it. $@ When the parameter expansion occurs within a double-quoted string. For example . for example /tmp/junk $$. usually space. A list of all the parameters. some additional variables are created. Even if no parameters are passed.the input field separator character. A list of characters that are used to separate words when the shell is reading input. $@ expands the positional parameters as separate fields regardless of the IFS value. tab and newline characters. but has a value of 0. The process id of the shell script. The parameter variables are $1. A subtle variation on $*. $* expands to a single field with the value of each parameter separated by the first character of the IFS variable. usually $.132 $HOME $PATH $PS1 $PS2 $IFS CHAPTER 4. the parameter values will be concatenated. $$0 $# $$ Parameter Variables If our script is invoked with parameters. often used inside a script for generating unique temporary filesnames. If IFS is set to a null string. For example: $ IFS=’’ $ set foo bar goo $ echo "$@" foo bar goo $ echo "$*" foobargoo $ unset IFS $ echo "$*" foo bar goo Within the double quotes. An input field separator. . A secondary prompt. used when prompting for additional input. /try_variable foo bar goo we get the output: Hello The program .sh modulus() { echo $(($1%$2)) } At the command prompt we enter $ ./try_variable is now running The second parameter was bar The first parameter was foo The parameter list was foo bar goo The users’s home directory is /home/gac Please enter a new greeting My leige My leige The script is now complete 133 We also can write a shell program which only contains a function and then using $1. mod. . $2.3.4. etc to pass parameters to this function. SHELL SYNTAX #!/bin/sh salutation="Hello" echo $salutation echo "The program $0 is now running" echo "The second parameter was $2" echo "The first parameter was $1" echo "The parameter list was $*" echo "The users’s home directory is $HOME" echo "Please enter a new greeting" read salutation echo $salutation echo "The script is now complete" exit 0 If we run the script with $ . The output will be 2.sh $ modulus 20 3 Then $1 will be assigned to 20 and $2 to 3. For example given the shell program # mod. /test To introduce the test command. the shell’s Boolean check. most scripts make extensive use of the [ ] or test command.cc ] then echo "file exists" else echo "file does not exist" fi The test command’s exit code (whether the condition is satisfied) determines whether the conditional code is run. many users who have never written a shell script try to write a simple programs and call them test.2 Conditions Fundamental to all programming languages is the ability to test conditions and perform different actions based on those decisions. Having a command [ ] might seem a little odd. A shell script can test the exit code of any command that can be invoked from the command line. The command for this is test -f <filename>. One way to avoid this problem is by specifying the complete path to our executable when calling it. as in . In older Unix systems. so within a script we can write: if test -f first. . but in most modern Unix systems these commands are built into the shell.3. It helps to think of the opening brace as a command that takes the condition and the end brace as arguments. within the code it does make the syntax neat and more like other programming languages. The test or [ ] Command In practice. Since the test command is infrequently used outside of shell scripts. On most systems these commands are synonymous. That is why it is important to always include an exit command at the end of any scripts that we write. the test and [ ] commands used to call an external command /bin/test or /usr/bin/test. We have to put spaces between the [ ] and the condition being checked. including scripts that we have written ourself. If such a program doesn’t work.cc then echo "file exists" else echo "file does not exist" fi We can also write it like this: if [ -f first. we use it to test for the existence of a file. but actually.134 CHAPTER 4. SHELL PROGRAMMING 4. it’s probably conflicting with the builtin test command. True if expr1 is less than expr2.4.cc ]. True if expr1 is greater than expr2. True if expr1 is greater than or equal to expr2. True if the string is null (an empty string). SHELL SYNTAX 135 If we prefer to put the then on the same line as the if. then echo "strings are the same" else echo "strings are not the same" fi strings are not the same True if the string is not an empty string True if the strings are the same. Arithmetic Comparison: expr1 expr1 expr1 expr1 -eq -ne -gt -ge expr2 expr2 expr2 expr2 True if the expressions are equal. True if the string is not null. True if the strings are not equal. and vice versa. we must add a semicolon to separate the test from the then: if [ -f first. expr1 -lt expr2 expr1 -le expr2 ! expr . The ! negates the expression and returns true if the expression is false. then echo "file exists" else echo "file does not exist" fi The condition types that we can use with the test command fall into three categories: String Comparison: string string1 = string2 string1 != string2 -n string -z string For example $ $ $ > > > > string1="hallo" string2="hallooo" if [ $string1 = $string2 ] . True if the expressions are not equal. True if expr1 is less than or equal to expr2.3. then echo "$number1 is greater than $number2" else echo "$number1 is less than $number2" fi The output is 10 is less than 12 File Conditional: -d -e -f -g -r -s -u -w -x file file file file file file file file file True True True True True True True True True if if if if if if if if if the file is a directory. set-group-id is set on the file. or help test). set-user-id is set on the file. See the bash manual page for a complete list (type man bash. the file is readable. the file exists. the file has non-zero size. We note that before any of the file conditionals can be true test looks whether the file exists. .136 For example $ $ $ > > > > CHAPTER 4. the file is writable. the file is executable. This is only a partial list of options to the test command. the file is a regular file. SHELL PROGRAMMING number1=10 number2=12 if [ $number1 -gt $number2 ] . which then allows different line of code to be executed. Others are just subtle syntax changes. if Command The if statement is very simple. For some structures (like the case statement). The result of this is evaluated by the if command.3. It tests the result of a command and then conditionally executes a group of statements: if condition then statements else statements fi Example.3 Control Structures The shell has a number of control structures. . and then to make a decision based on the answer: #!/bin/bash echo "Is it morning? Please answer yes or no" read timeofday if [ $timeofday = "yes" ]. and once again they are very similar to other programming languages. In the following sections. the shell offers more power. SHELL SYNTAX 137 4. then echo "Good morning" else echo "Good afternoon" fi exit 0 This would give the following output: Is it morning? Please answer yes or no yes Good morning $ The script used the [ ] command to test the contents of the variable timeofday.4. A common use for the if statement is to ask a question. the statements are the series of commands that are to be performed when/while/until the condition is fulfilled.3. SHELL PROGRAMMING elif Command There are several problems with this very simple script. Enter yes or no" exit 1 fi exit 0 This is quite similar to the last example. If neither of the tests are successful. but a more subtle problem is lurking. then echo "Good morning" elif [ $timeofday = "no" ]. so the if clause looks like. but now uses the elif command which tests the variable again if the first if command was not true. if [ = "yes" ] which isn’t a valid condition.138 CHAPTER 4. When the variable timeofday was tested. if [ "$timeofday" = "yes" ]. If we execute this new script. This fixes the most obvious defect. which allows us to add a second condition to be checked when the else portion of the if is executed. We do this by replacing the else with an elif. To avoid this problem. Example. we just press <Return>. then so an empty string gives us a valid test: if [ "" = "yes" ] . it consisted of a blank string. an error message is printed and the script exits with the value 1. but instead of answering the question. It will take any answer except yes as meaning no. we have to put quotes around the variable. We can prevent this using the elif contruct. and adding another condition. we get the following error message: [: =: unary operator expected The problem is in the first if clause. which the caller can use in a calling program to check if the script was successful. $timeofday not recognized. then echo "Good afternoon" else echo "Sorry. #!/bin/bash echo "Is it morning? Please answer yes or no" read timeofday if [ $timeofday = "yes" ]. We can modify our previous script so that we report an error mesage if the user types in anything other than yes or no. The first example shows the use of for with fixed strings. chap4.txt). more commonly.4.txt. This script will send the files called chap3. They could simply be listed in the program or. SHELL SYNTAX 139 for Command We use the for construct to loop through a range of values. The parameter list for the for command is provided by the output of the command enclosed in the $() sequence. the result of a shell expansion of filenames. #!/bin/bash for count in one two three four do echo $count done exit 0 The output is: one two three four Example.txt and chap5. . #!/bin/bash for file in $(ls chap[345].txt to the default system printer via the lpr command. The next example uses the for construct with wild card expansion. do lpr $file done This script also illustrates the use of the $(command) syntax. which can be any set of strings. which will be reviewed in more detail later. The syntax is: for variable in values do statements done Example.3. This is less cumbersome than the for loop we used earlier.140 CHAPTER 4. #!/bin/bash foo=1 while [ "$foo" -le 20 ] do echo "Here we go again" foo=$(($foo+1)) done exit 0 This script uses the [ ] command to test the value of foo against the value 20 and executes the while loop if it’s smaller or equal. which has the following syntax: while condition do statements done Example. SHELL PROGRAMMING while Command Since all shell variables is considered to be strings. . By combining the while construct with arithmetic substitution. It can become tedious if we want to use for to repeat a command say twenty times #!/bin/bash for foo in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 do echo "Here we go again" done exit 0 Even with wild card expansion. In that case we can use a while loop. the for loop is good for looping through a series of strings. Inside the while loop the syntax $(($foo+1)) is used to perform arithmetic evaluation of the expression inside the braces. but a little awkward to use when we wish to execute a command a fixed number of times. so foo is incremented by one each time around the loop. we can execute a command a fixed number of times. we might be in a situation where we just don’t know how many times we need to loop. not while the condition is true. As an example.4. > > > > > > > > > > > > > > outer=1 while [ $outer -le $1 ] do inner=1 while [ $inner -le $outer ] do echo -n "*" inner=$(($inner+1)) done echo outer=$(($outer+1)) done exit 0 From the command line we pass the number of lines of asterisks we want to display.3. until Command The until statement has the syntax: until condition do statements done This is very similar to the while loop. Often the until statement adds clarity. In other words. we can set up an alarm which goes off when another user logs in: #!/bin/bash until who | grep "$1" > /dev/null do sleep 10 done # ring the bell and announce the users’ presence . Example. but the condition test is reversed. the loop continues until the condition becomes true. It also fits naturally when we want to loop forever until something happens. SHELL SYNTAX 141 In the next program we use two nested while loops to display a triangle of asterisks on the screen. 142 CHAPTER 4... #!/bin/bash echo "Is it morning? Please answer yes or no" read timeofday case "$timeofday" in . esac statements. and then allows execution of different statements. The case construct allows us to match the contents of a variable against patterns in quite a sophisticated way......) .) pattern [ | pattern] . Example. SHELL PROGRAMMING echo -e \\a echo "$1 has just logged in!!!" exit 0 The -e option to echo enable interpretation of the following backslash-escaped characters in the strings: \a \b \c \f \n \r \t \v \\ \nnn alert (bell) backspace suppress trailing newline form feed new line carriage return horizontal tab vertical tab backslash the character whose ASCII code is nnn (octal) case Command The case statement is a little more complex than the other structures we have discussed up to now.. We present a version of our input testing script that uses case. Its syntax is: case variable in values pattern [ | pattern] . statements. This ability to match multiple patterns and execute multiple statements makes the case construct a good way of dealing with user input. depending on which pattern was matched. . 143 When the case statement is executing.. * ) echo "Sorry. "Good Afternoon"... Example. To make the script reusable. "Good Afternoon"... answer not recognized". The asterisk * is used as the default action to be performed if no other pattern is satisfied. so that the * is a wild card that will match any string. it compares the contents of timeofday to each string in turn. By putting patterns with the same actions together we can make a much cleaner version: #!/bin/bash echo "Is it morning? Please answer yes or no" read timeofday case "$timeofday" in "yes" | "y" | "Yes" | "YES" ) echo "Good Morning".3. we have to change it to return an error code when the default pattern had to be used. To do this we need to execute more than one statement when a certain case was matched: #!/bin/bash echo "Is it morning? Please answer yes or no" read timeofday case "$timeofday" in "yes" | "y" | "Yes" | "YES" ) echo "Good Morning" . SHELL SYNTAX "yes") "no" ) "y" ) "n" ) * ) esac exit 0 echo echo echo echo echo "Good Morning". "n*" | "N" ) echo "Good Afternoon".. "Sorry. The case command performs normal expansion.4. and executes the statements following the first pattern that matches. "Good Morning". esac exit 0 Example. answer not recognized".. 144 . *) echo echo exit . we have changed the ‘no’ pattern to ‘[nN]*’ which is read as “an ‘n’ or an ‘N’ followed by anything”. SHELL PROGRAMMING "Good Afternoon" "Sorry.. answer not recognized" "Please answer yes or no" 1 To show a different way of matching multiple patterns. .. "[nN]*") echo . esac exit 0 CHAPTER 4.. 3. The shell has a special pair of constructs for dealing with lists of commands: the AND list and the OR list. The syntax is: statement1 && statement1 && statement1 && . For instance. or when no more statements in the list are executed.4. the results are awkward. then if [ -f the_other_file]. if it returns true. Each statement is executed independently. each statement is executed and. we may want several different conditions to be met before we execute a statement. The && tests the condition of the preceding command. then foo="True" elif [ -f that_file]. SHELL SYNTAX 145 4... then echo "One of the files exists" fi Although these can be implemented using multiple if statements. The AND list as a whole succeeds (true) if all . The AND List The AND list construct allows us to execute a series of commands. allowing us to mix many different commands in a single list.3. then echo "All files are present and correct" fi fi fi or we may want at least one of a series of conditions to be met: if [ -f this_file]. This continues until a statement returns false. for example: if [ -f this_file]. Starting at the left.4 Logical AND and Logical OR Sometimes we want to connect commands together in a series. the next statement to the right is executed. then if [ -f that_file]. C++ and Java. then foo="True" else foo="False" fi if [ "$foo" = "True"]. executing the next commnd only if all of the preceding commands have succeeded. We notice that && is the logical AND in languages such as C. then foo="True" elif [ -f the_other_file]. [ -f file two ] fails since we have just erased file two. the AND list as a whole returns false and the statement in the else condition is executed. Then the AND list tests for the existence of each of the files and echoes some text in between #!/bin/bash touch file_one rm -f file_two if [ -f file_one ] && echo "hello" && [ -f file_two ] && echo " there" then echo "in if" else echo "in else" fi exit 0 The script gives the output: hello in else The touch and rm commands ensure that the files are in a known state. and it fails (false) otherwise. . The echo command always returns true. therefore the last statement echo "there" is not executed. The && list then executes the [ -f file one ] statement. The third test. Example. the echo command is called. The touch command changes the access and modification times of a file. we use the command touch file_one which checks whether the file exists and create it if it does not. In the following script. Then we remove file two. which succeeds because we have just made sure that the file existed. or creates a new file with specified times. Since one of the commands in the AND list failed. Since the previous statement succeeded. This also succeeds. SHELL PROGRAMMING commands are executed successfully.146 CHAPTER 4. If it returns false. This continues until a statement returns true. the synax is: statement1 || statement1 || statement1 || .. Starting at the left. SHELL SYNTAX The OR list 147 The OR list construct allows us to execute a series of commands until one succeeds. and the echo command has to executed. The if succeeds because one of the commands in the OR list was true. the next statement to the right is executed. #!/bin/bash rm -f file_one if [ -f file_one ] || echo "hello" || echo " there" then echo "in if" else echo "in else" fi exit 0 This will give you the output: hello in if The first test [ -f file one ] fails. each statement is executed.4.. or when no more statements are executed. . echo returns true and no more statements in the OR list is executed.3. . n | no ) return 1. For example #!/bin/bash tempfile=temp_$$ yes_or_no() { while true do echo "Enter yes or no" read x case "$x" in y | yes ) return 0.148 Statement blocks CHAPTER 4.. * ) echo "answer yes or no" esac done } yes_or_no && { who > $tempfile grep "secret" $tempfile } Depending on the return value of the function yes_or_no the following block of statements will be executed. we can do so by enclosing them in braces { } to make a statement block. SHELL PROGRAMMING If we want to use multiple statements in a place where only one is allowed.. such as in an AND or an OR list. and if we are going to write any large scripts. When it finds the foo() { construct. It stores the fact foo refers to a function and continues executing after the matching }.4. The syntax is function_name() { statements } For example #! /bin/bash foo() { echo "Function foo is executing" } echo "script is starting" foo echo "script ended" exit 0 Running the script will show: script is starting Function foo is executing script ended As always.5 Functions The shell provides functions. We must always define a function before it can be executed. This isn’t a problem in the shell. SHELL SYNTAX 149 4. the shell now knows to execute the previously defined function.3. we simply write its name. execution resumes at the line after the call to foo. To define a shell function. it is a good idea to use functions to structure our code. When this function completes. since all scripts start executing at the top.3. it knows that a function called foo is being defined. . Thus we put all the functions before the first call of any function. followed by empty () parentheses and enclose the statements in { } braces. the script starts executing at the top. When the single line foo is executed. the positional parameters to the script. $@. $*. $2 and so on are replaced by the parameters to the function. they are restored to their previous values. That is how you read parameters passed to the function.150 Function Arguments CHAPTER 4. $#. SHELL PROGRAMMING When a function is invoked. For example #! /bin/bash foo() { echo "The argument to the function is $1 $2" } foo "bar" "willi" exit 0 The script will give the output: The argument to the function is bar willi For example #! /bin/bash foo() { echo "The argument to the function is $@" } foo "bar" "willi" "olla" exit 0 The script will give the output The argument to the function is bar willi olla . $1. When the function exits. 4. SHELL SYNTAX Returning Values 151 Shell functions can only return numeric values with the return command.3./function4. * ) echo "answer yes or no" esac done } echo "original parameters are $*" if yes_or_no "Is your name $1" then echo "Hi $1" else echo "Never mind" fi exit 0 Running the program with $ .sh John and Ben gives original parameters are John and Ben Parameters are Is your name John Enter yes or no dunno answer yes or no .. For example #! /bin/bash yes_or_no() { echo "Parameters are $*" while true do echo "Enter yes or no" read x case "$x" in y | yes ) return 0. The only way to return string values is to store them in a global variable.. n | no ) return 1. which can then be used after the function finishes. Otherwise. For example #! /bin/bash text="global variable" foo() { local text="local variable" echo "Function foo is executing" echo $text } echo "script is starting" echo $text foo echo "script ended" echo $text exit 0 The output is global local global . If a local variable has the same name as a global variable. the function can access the other shell variables which are essentially global in scope. SHELL PROGRAMMING Local variables can be declared inside shell function by using the local keyword.152 Enter yes or no yes Hi John $ Local variables CHAPTER 4. it shadows that variable but only within the function. The variable is then only in scope within the function. . then the status returned is that of the last command executed. If omitted. For example x=0 foo() { if [ $1 -eq 0 ] then x=7 return 0. whose format is return n The value n is used as the return status of the function. SHELL SYNTAX 153 If we execute an exit command from inside a function. else x=9 return 1. fi } Calling the function foo with foo 5 echo $x echo $? provides the output 9 and 1. The value of its return status we can access with $?.3. its effect is not only to terminate execution of the function. Calling the function foo with foo 0 echo $x echo $? provides the output 7 and 0.4. but also of the shell program that called the function. If we instead would like to just terminate execution of the function. we can use the return command. 154 CHAPTER 4. SHELL PROGRAMMING 4.4 4.4.1 Shell Commands Builtin Commands We can execute two types of commands from shell scripts. There are the ‘normal’ commands that we could also execute from the command prompt and there are the ‘builtin’ commands that we mentioned earlier. These builtin commands are implemented internally to the shell and can not be invoked as external programs. Most internal commands are, however, also provided as stand-alone programs–it’s part of the POSIX specification. It generally does not matter whether the command is external or internal, except that the internal commands execute more efficiently. break Command We use this command for escaping from an enclosing for, while or until loop before the controlling condition has been met. For example #! /bin/bash rm -rf fred* echo > fred1 echo > fred2 mkdir fred3 echo > fred4 for file in fred* do if [ -d "$file" ]; then break fi done echo first directory starting with fred was $file exit 0 The output is $ fred3 We recall that the option -d tests whether the file is a directory. We recall that the command echo > fred1 creates the file fred1. The size of the file is 1 byte. Explain why? 4.4. SHELL COMMANDS 155 “:” Command The colon command is a null command. It’s occasionally useful to simplify the logic of conditions, being an alias for true. Since it is a builtin command, it runs faster than true. We may see it used as a condition for while loops: while : implements an infinite loop, in place of the more conventional while true. continue Command Rather like the C keyword of the same name, this command make the enclosing for, while or until loop continue at the next iteration, with the loop variable taking the next value in the list. For example #! /bin/bash rm -rf fred* echo > fred1 echo > fred2 mkdir fred3 echo > fred4 for i in fred* do if [ -d "$i" ]; then continue fi echo i is $i done exit 0 We run the program with $ ./continue.sh The output is: i is fred1 i is fred2 i is fred4 $ 156 CHAPTER 4. SHELL PROGRAMMING “.” Command The dot command executes the command in the current shell. The syntax is . shell script Normally when a script executes an external command or script, a new shell (a sub shell) is spawned, the command is executed in the sub shell and the sub shell is then discarded, apart from the exit code which is returned to the parent shell. The external source and the internal dot command run the commands in the same shell that called the script. Usually any changes to environment variables that take place in a script is lost when the script finishes. The dot command, however, allows the executed command to change the current environment. This is often useful when we use a script as a wrapper to set up our environment for the later execution of some command. In shell scripts, the dot command works like the #include directive in C or C++. Though it doesn’t literally include the script, it does execute the script in the current context, so we can use it to incorporate variable and function definitions into a script. echo Command The echo is also a builtin command. We have been using it throughout, so it won’t be discussed further. The X/Open standard has introduced the printf command in newer shells, and it should rather be used for outputting strings. exec Command The exec command has two different uses. It is normally used to replace the current shell with a different program. For example exec wall "Thanks for all the fish" in a script will replace the current shell with the wall command. No lines in the script after the exec will be processed, because the shell that was executing the script no longer exists. The second use of exec is to modify the current file descriptors. exec 3 < afile This causes file descriptor three to be opened for reading from file afile. It is rarely used. 4.4. SHELL COMMANDS 157 exit n Command The exit command causes the script to exit with exit code n. If we use it at the command prompt of any interactive shell, it will log us out. If we allow the script to exit without specifying the exit status, the status of the last command execute in the script will be used as the return value. In shell programming, exit code 0 is success, codes 1 through 125 inclusive are error codes that can be used by scripts. The remaining values have reserved meanings. export Command The export command makes the variable being exported visible to sub shells. By default variables created in a shell are not available in further sub shells invoked from that shell. The export command creates an environment variable from its parameter which can be seen by other scripts and programs invoked from the current program. expr Command The expr command evaluates its arguments as an expression. It is most commonly used for simple arithmetic. expr can perform many expression evaluations: Expression For example a=1 a=‘expr $a + 1‘ echo $a The output is 2. Note that in newer scripts, expr is normally replaced with the more efficient $((...)) syntax. Description expr1 if expr1 is non-zero, otherwise expr2. Zero if either expression is zero, otherwise expr1 Equal Greater than. Greater than or equal to. Less than. Less than or equal to. Not equal. Addition. Subtraction. Multiplication. Integer division. Integer modulo. . . \f Form feed character. printf Command The printf command is only available in more recent shells. \ooo The single character with actual value ooo . All characters in the format string. . The syntax is: printf "format string" parameter1 parameter2 . The format string very similar to that used in C or C++. \n Newline character. appear literally in the output. All arithmetic in the shell is performed as integers. Floating point arithmetic is not supported. SHELL PROGRAMMING eval Command eval [arg . \t Tab character. \r Carriage return. For example #!/bin/bash command="ls" files="*.158 CHAPTER 4. If there are no args.sh" eval $command $files exit 0 The output displays all the files with the extension . with some restrictions.. escape sequences and conversion specifiers.sh. This command is then read and executed by the shell. eval returns true. \a Alert (rings the bell or beep). other than % and \. and its exit status is returned as the value of the eval command. The following escape sequences are supported: Escape Sequence Description \\ Backslash character.] The args are read and concatenated together into a single command. or only null arguments. The format string consists of any combination of literal characters. \b Backspace character. \v Vertical tab character. Output the % character.. SHELL COMMANDS 159 The conversion specifier is quite complex. More details can be found in the manual. Output a character.. Enter man bash at the command prompt. The output set x y z echo $2 is y. For example. y to $2 and z to $3. set and unset Commands The set command sets the parameter values for the shell.4. Output a string. but we need to separate it from the other fields. which gives the date in a format that contains the name of the month as a string. Without any argument set gives in alphabetical order the list of all of the variables that exists in our envirement. The system provides a date command. The conversion specifier consists of a % character. so we list only the commonly used ones here. The principal conversions are: Conversion Specifier d c s % Description Output a decimal number.4. followed by a conversion character.) construct to execute the date command and return the result and the set command. We can do this using a combination of the $(. It can be a useful way of setting fields in commands that output space-separated values. For example $ printf "%s\n" hello hello $ printf "%s %d\t%s" "Hi there" 15 people Hi there 15 people Note how we have to use " " to protect the Hi there string and make it a single parameter. The format string is then used to interpret the remaining parameters and output the result. set x y z assigns x to $1. Suppose we want to use the name of the current month in a shell script. The date command output has the month string as its second parameter #! /bin/bash echo the date is $(date) set $(date) echo The month is $2 exit 0 . The variables $*.160 The script output is CHAPTER 4. do echo "$1" shift done exit 0 If we run the script with > ./shell1. followed by the signal name (or names) to trap on. The shift command is often useful for scanning through parameters.sh while [ "$1" != "" ]. while $0 retmains unchanged. For example #!/bin/bash # shell1. so $2 becomes $1.sh willi hans steeb the output is willi hans steeb trap Command The trap command is used for specifying the actions to take on receipt of a signal. The . The unset command is used to remove a variable from the environment. The previous value of $1 is discarded. SHELL PROGRAMMING the date is Thu Nov 13 23:16:33 SAT 1997 The month is Nov We can also use the set command to control the way the shell executes. The trap command is passed the action to take. $3 becomes $2. It cannot do this to read-only variables (such as USER or PWD). and if we write a script that takes ten or more parameters. $@ and $# are also modified to reflect the new arrangement of parameter variables. we have no choice but to use the shift command. and so on. The most commonly used is set -x which makes a script display a trace of its currently executing command. by passing it parameters. If a numerical argument is specified the parameters will move that many spaces. A common use is to tidy up a a script when it is interrupted. shift Command The shift command moves all the parameter variables down by one. " while [ -f /tmp/my_tmp_file_$$ ]. usually sent when a terminal goes offline. Interrupt. Remember that scripts are normally interpreted from ‘top’ to ‘bottom’ so we have to specify the trap command before the part of the script we wish to protect. " while [ -f /tmp/my_tmp_file_$$ ]. do . Alarm. usually sent by pressing <Ctrl-\>. The following table lists the more important signals covered by the X/Open standard that can be caught: Signal(number ) HUP (1) INT (2) QUIT(3) ABRT(6) ALRM(14) TERM(15) Description Hang up.. A trap command with no parameters prints out the current list of traps and actions.. To ignore a signal. usually sent on some serious execution error. do echo File exists sleep 1 done echo The file no longer exists trap . Terminate.4. For example.. usually sent by pressing <Ctrl-C>. #! /bin/bash trap ’rm -f /tmp/my_tmp_file_$$’ INT echo creating file /tmp/my_tmp_file_$$ date > /tmp/my_tmp_file_$$ echo "press interrupt (CRTL-C) to interrupt .. Abort. simply specify the action as -. To reset a trap condition to the default.INT echo creating file /tmp/my_tmp_file_$$ date > /tmp/my_tmp_file_$$ echo "press interrupt (CRTL-C) to interrupt . usually used for handling time-outs. usually sent by the system when it’s shutting down. in the following program the process id number of the program being executed. set the action to the empty string ’’. Quit. or a user logs out. SHELL COMMANDS trap command signal 161 command will be executed whenever any of the signals specified by signal is received.4. Since the script terminates immediately. since the file has now been removed. there is no handler installed for the signal. It then recreates the file and loops inside the second while construct. the statement rm -f /tmp/my_tmp_file_$$ is executed. the final echo and exit statements are never executed. the first while loop terminates normally. The script then enters a while loop which continues while the file exists. File exists File exists The file no longer exists creating file /tmp/my_tmp_file_1010 press interrupt (CRTL-C) to interrupt .162 echo File exists sleep 1 done echo We never get here exit 0 To run the script we enter > . When the user presses <Ctrl-C> this time. so the default behavior occurs. When the user presses <Ctrl-C>.. . which is to immediately terminate the script.. then the while loop resumes./trap..sh The output from this script is CHAPTER 4.. this time to specify that no command is to be executed when an INT signal occurs. SHELL PROGRAMMING creating file /tmp/my_tmp_file_1010 press interrupt (CRTL-C) to interrupt . The script then uses the trap command again. File exists File exists [1]+ Terminated ./trap.sh This script uses the trap command to arrange for the command rm -f /tmp/my_tmp_file_$$ to be executed when an INT (interrupt) signal occurs. we want to execute a command and put the output of the command in a variable. it must be escaped with a \ character.e. but the string output. SHELL COMMANDS 163 4.. since a new shell is invoked to process the expr command.‘ construct. does need this construct if it is to be available to the script.)).. By enclosing the expression we wish to evaluate in $((.2 Command Execution When we are writing scripts. The result of who. There is also an older form. Note that this is not the return status of the command..)) expansion.4. For example #! /bin/bash echo "The current working directory is $PWD" echo "The current users are $(who)" exit 0 Because the current directory is a shell environment variable. We do this by using the $(command) syntax. however. The result of the $(command) is simply the output from the command. ‘command‘.) form. we can perform simple arithmetic much more efficiently.. A newer and better alternative is $((.4.. i. For example #! /bin/bash x=0 while [ "$x" -ne 10 ]. ‘ and \ inside the back quoted command.. A problem sometimes arises when the command we want to invoke outputs some whitespace before the text we want. do echo $x x=$(($x+1)) done exit 0 . If a back quote is used inside the ‘. the first line doesn’t need to use this command execution construct. as it make it easy to use existing commands in scripts and capture their output. Arithmetic Expansion We have already used the expr command. In such cases we can use the set command as we have already shown. The concept of putting the result of a command into a script variable is very powerful. but this is quite slow to execute. which was introduced to avoid some rather complex rules covering the use of the characters $.. we often need to capture the output from a command’s execution for use in the script.. or more output than we actually require. All new script should use the $(. which allows simple arithmetic commands to be processed. which is still in common usage.4. Often. We could try: #!/bin/bash for i in 1 2 3 do cat $i_temp done But on each loop. We can perform many parameter substitutions in the shell. these provide an elegant solution to many parameter processing problems. 2_temp and 3_temp. SHELL PROGRAMMING We have seen the simplest form of parameter assignment and expansion. Suppose we want to write a script to process files called 1_temp. which doesn’t exist. we get the error message too few arguments What went wrong? The problem is that the shell tried to substitute the value of the variable $i temp. where we write: foo=fred echo $foo A problem occurs when we want to append extra characters to the end of a variable. to give the actual file names.164 Parameter Expansion CHAPTER 4. The common ones are: . To protect the expansion of the $i part of the variable. we need to enclose the i in {} like this: #!/bin/bash for i in 1 2 3 do cat ${i}_temp done On each loop. the value of i is substituted for ${i}. ${param%%word} From the end. ${param#word} From the beginning. removes the smallest part of param that matches word and returns the rest. ${#param} Gives the length of param. removes the longest part of param that matches word and returns the rest.4. For example #! /bin/bash unset foo echo ${foo:-bar} foo=fud echo ${foo:-bar} foo=/usr/bin/X11R6/startx echo ${foo#*/} echo ${foo##*/} bar=/usr/local/etc/local/networks echo ${bar%local*} echo ${bar%%local*} exit 0 This gives the output: bar fud usr/bin/X11R6/startx startx /usr/local/etc/ /usr/ . as the example below shows. ${param##word} From the beginning.4. removes the smallest part of param that matches word and returns the rest. The last four that remove parts of strings are especially useful for processing filenames and paths. set it to the value of default. removes the longest part of param that matches word and returns the rest. SHELL COMMANDS Parameter Expansion Description ${param:-default} If param is null. 165 These substitutions are often useful when we are working with strings. ${param%word} From the end. jpg Sometimes. We can type the following: $ cjpeg image. we want to perform this type of operation on a large number of files.gif do cjpeg $image > ${image%%gif}jpg done .gif > image. For example we want to convert a gif file into a jpeg file using the cjpeg filter available with most Linux distributions.166 CHAPTER 4. however. the result of one operation must often be redirected manually. The following script will automate this process: #!/bin/bash for image in *. SHELL PROGRAMMING Since Unix is based around filters. sh newar. ADVANCED EXAMPLES 167 4.shar which uses tar to extract the archive.shar echo "EOF" >> newar.4. . Consider self extracting archives (common in the Windows environment).gz some_directory cat shar. The quotes around ‘EOF’ indicate to the shell that lines should not be interpreted (shell variables should not be expanded) Now the following commands construct a self extracting archive. The tar archive for example leads to the idea of a shar or shell archive./newar. This can easily be implemented using shell scripts. i.sh #!/bin/sh tar xvfz << "EOF" The redirection << "EOF" is for the so called “HERE” document.5.shar To extract the shell archive we simply use the command > .5 Advanced examples Shell programming can be quite flexible.tgz > newar.shar chmod +x newar.e. Consider the shell script shar. Thus the shell script and the archive are contained in the same file. We could use any word we want to end the redirection. the file used for redirection follows this line and ends when EOF appears at the beginning of a line on its own. > > > > tar cfz newar.tar. i.. When each ftp has downloaded at least chunksize bytes we stop the ftp session. We use the reget command of ftp. SHELL PROGRAMMING We describe a way to use ftp to do a parallel download. given n the number of ftp processes to use we download a file in n pieces of equal size using n ftp processes running simultaneously. Suppose we know the size (use the size command in ftp). Then we execute for i = 0.e.i bs=chunksize count=1 skip=i >> filename to obtain the desired file filename. The following script automates the process. We divide the file into n chunks of equal size. #!/bin/sh #Assume $1=n processes $2=host $3=user $4=password $5=filename n="$1" host="$2" ftpuser="$3" ftppass="$4" filename="$5" file=$(basename "$filename") #obtain the filesize name=$(\ { echo user "$ftpuser" \’"$ftppass"\’ echo bin echo size "$filename" echo quit } | ftp -n "\$host" | \ { while [ "$name" != "$filename" ] do read name filesize .n For each of the n files (at the same time). i = 1. For each chunk we > dd if=/dev/zero of=filename.. .168 CHAPTER 4.n count=n bs=chunksize We start ftp and use the command > reget filename filename.. i=n−1 > dd if=filename. 5.$i bs=$chunksize count=$i \ > /dev/null 2> /dev/null fi rm -f $file 2> /dev/null { echo user "$ftpuser" \’"$ftppass"\’ echo bin echo reget $filename ${file}.\$i ] then dd if=/dev/zero of=${file}. ADVANCED EXAMPLES echo -n $name $filesize done }) set -set $name filesize=$2 chunksize=$(($n-1)) chunksize=$(($filesize/$chunksize)) if [ "$chunksize" -eq 0 ] then chunksize=$filesize n=1 fi i=0 set -#start the ftp processes while [ $i -lt $n ] do if [ ! -e \$\{file\}.4.$i echo quit } | ftp -nv \$host > /dev/null & # a list of process ids for the ftp processes set $* $! i=$(($i+1)) done i=0 for j in $* do csize=0 k=$(($i+1)) k=$(($k*$chunksize)) 169 . $i) csize=$5 printf "$csize / $filesize of $file \r" sleep 1 done kill $j > /dev/null 2> /dev/null dd if=${file}.170 CHAPTER 4.$i" i=$(($i+1)) done echo #only do this at the end so that an interrupted # download can continue rm $rmfiles . SHELL PROGRAMMING while [ "$csize" -le "$k" ] \&\& [ "$csize" -lt $filesize ] do set -.$(ls -l ${file}.$i bs=$chunksize skip=$i count=1 >> $file 2> /dev/null rmfiles="$rmfiles ${file}. 4. fi . It is an option to include normal files in the tree. ADVANCED EXAMPLES 171 We give a shell script which. displays a tree of the directory structure (similar to the DOS tree command). given directory names as arguments.5. #!/bin/sh topmost=YES normalfiles=NO dirlist() { local tabbing="$1" local oldtopmost="$topmost" shift for i in "$@" do if [ -e $i ] then if [ -d $i ] || [ "$normalfiles" = YES ] then if [ "$topmost" = YES ] then printf "${tabbing\}\-\-%s\\n" $i else printf "${tabbing\}\-\-%s\\n" $(basename $i) fi fi fi topmost=NO if [ -d $i ] then dirlist "$tabbing |" ${i}/* fi done topmost="$oldtopmost" } if [ $# -gt 0 ] && [ "$1" = ’-n’ ] then normalfiles=YES shift fi if [ $# -gt 0 ] then dirlist ’’ "$@" else dirlist ’’ . SHELL PROGRAMMING .172 CHAPTER 4. a backup of the original is made as file myfile. Perl has powerful text-manipulation functions. OS/2. loops.html This command. For example. file maintenance. i. for example myfile. awk. or sed comands from shell programming. we could simple give the command perl -e ’s/gopher/World Wide Web/gi’ -p -i.html needs changing. indicated by /gi. Instead of editing each possible file or constructing some cryptic find. VMS.bak *.html in the current directory. Macintosh. executes the short Perl program specified in single quotes.e. arrays. and other operating systems. databases and users. string manipulations. Linux. If any file. This program consists of one perl operation.1 Introduction Perl is a Pratical Extraction and Report Language freely available for Unix. and for Common Gateway Interface Web applications (CGI programming). it substitutes for the original word gopher the string World Wide Web. Amiga.bak. We can program in Perl for data manipulation. The remainder of the Linux command indicates that the perl program should run for each file ending in . packaging or interfacing system facilities. if we want to change the same text in many files we can use Perl. subroutines and input and output.Chapter 5 Perl 5. In Perl we can do all the fundamental programming constructs such as variables. Perl has enjoyed recent popularity for programming World Wide Web electronic forms and generally as glue and gateway between systems.html. issued at the Linux prompt. MVS. 173 . MS/DOS. This is done globally and ignoring case. Under Linux we press Ctrl-d to run the program. . To run the file myfirst. print($c). for example myfirst. $c = $a + $b.bat file.2 My First Perl Program We can run Perl from the command line.pl we enter at the command line perl myfirst. $b = 4.pl To use Perl on a Linux and Unix system we first have to know where Perl is installed. $b = 4.pl $a = 5. Thus at the beginning of the program we add the line #!/usr/bin/perl -w for the one Perl is localized.174 CHAPTER 5. After we have entered and saved the program we must make the file executable by using the command chmod u+x filename at the Linux prompt. PERL 5. print($c). We can also write a program. $c = $a + $b. For example > perl <Enter> $a = 5.pl. Often it is installed in /usr/bin/perl or /usr/local/bin/perl. Under Windows we put the Perl binary in our path. For example we include set path=C:\perl5\bin in the autoexec. # myfirst. Under Windows we press Ctrl-z to run the program. # indexed arrays @arr1 = (3. # accessing element no 2 in array => 5 print("\n").23.pl # scalars $a = 7. 4. 25. -1. print("\n"). Carl. print("\n"). print($c). $b = 1. "Carl". 14. 14. $c = ’A’.23. Arrays start with a @. # returns 2 The keys are Willi. .3 Data Types Perl has three data types. # returns 25 print("\n"). "Otto". print($id_numbers{"Willi"}). Perl also allows to use of hex numbers. 5. 2. for example $x = 0xffa3. print($d). # newline print($b). print($a). # associative arrays %id_numbers = ("Willi". Associative arrays (also called hashes) contains keys and associated values. print("\n"). DATA TYPES 175 5. print("\n"). $d = "willi". Scalars can be numeric or characters or strings as determined by context.3. "egoli"). print(@arr1). # perl1. Scalars start with $.5. print($id_numbers{"Otto"}). print("\n"). 2. Otto and the associated values are 2. 25). print("$e\n"). $e = false. Arrays of scalars are sequentially arranged scalars. 1. arrays (also called lists) and associative arrays (also called hashes). print($arr1[2]). ’a’. namely scalars. Associative arrays start with an %. $b = $_ + $a. # acts on $_ print("$_\n"). PERL The most commonly used global scalar variable is the $_.pl $_ = 4. # => 11 # => willi # in the following code block # we replace the substring the by the string xxx $_ = " the cat is in the house". # => xxx cat is in xxx house . $search = "the". $a = 7. print("b = " + $b). print("\n"). s/$search/xxx/g.176 CHAPTER 5. $_ = "willi". print($_). For example # global. . $b = 13. # post-increment ++$a. /. # returns 1 $a++. print("The division yields: $f\n"). print("$a\n"). %. # perl2. print("The difference is: $d\n"). ** Division is floating point division. $y = 3. # returns 6 $b--. # pre-decrement print("$b\n").4.4 Arithmetic Operation The arithmetic operations are +. $c = $a + $b.5.6. -.pl $a = 4. $z = $x ** $y. $e = $a*$b. # pre-increment. print("The sum is: $c\n"). print("The product is: $e\n"). $f = $b/$a. $d = $a . ++. # remainder print("The remainder is: $g\n").5. # returns 3. print("z = $z\n"). # returns 11 # exponentiation operator is ** $x = 2.25 $g = $b%$a. # post-decrement --$b.$b. *. ARITHMETIC OPERATION 177 5. --. chop($dist).pl print("Enter the distance in kilometers: ").6214. $dist = <STDIN>. # perl3. The library function chop gets rid of the closing newline character that is part of the input line we entered. PERL 5.178 CHAPTER 5. $dist = <STDIN>. " miles = ". print($dist. " kilometers\n"). chop($dist). $miles. " miles\n"). $kilometers = $dist * 1. print($dist. " kilometers = ". $kilometers.609. . print("Enter the distance in miles: ").5 Standard Input The Perl program is referencing the file handle STDIN which represents the standard input file. The < and > on either side of STDIN tell the Perl interpreter to read a line of input from the standard input file. $miles = $dist * 0. print "\n". print($z). To compare two strings we use the cmp operator. print "\n". The operator cmp is case-sensitive. $a = "Egoli-". $name2 = "willi". $result = $name1 cmp $name2. $w = $u cmp $v. $d. print "$a$b". $z = $x cmp $y. print($result).6 Basic String Operations To concatenate two strings we can use the . # returns Egoli-Gauteng # concatenate $c and $d # the concatenate operators is the . $c = "alpha-". print("\n"). If the strings are identical the function cmp returns 0. print("\n"). $name1 = "willi". # returns apples and pears # comparing strings with cmp $x = "egoli". print($w).6. $e = $c . BASIC STRING OPERATIONS 179 5. operator. print "$str1 and $str2".5. # returns alpha-3 print "\n". $u = "X". # interpolation $str1 = "apples". print $e. $str2 = "pears". $y = "gauteng". print("w = "). $b = "Gauteng". . $v = "x". $d = "3". 180 CHAPTER 5. PERL 5.7 Conditions Numeric Version < <= > >= == != <=> String Version lt le gt ge eq ne cmp The comparison operators in Perl are Operation less than less than or equal to greater than greater than or equal to equal to not equal to compare The if statement is the simplest conditional statement used in Perl. It executes when a specified condition is true. The statement if-else chooses between two alternatives. The statement if-elsif-else chooses among more than two alternatives. The statements while and until repeat a group of statements of specified number of times. Perl also has other conditional statements we discuss later. # testing.pl $a = 1; $b = 7; if($a == $b) { print "numbers } else { print "numbers } # $c = 7.3; $d = 7.3; if($c == $d) { print "numbers } else { print "numbers } # are equal\n"; are not equal\n"; are equal\n"; are not equal\n"; 5.7. CONDITIONS $char1 = ’a’; $char2 = ’A’; if($char1 eq $char2) { print "characters are equal" } else { print "characters are not equal"; } print "\n"; # $string1 = "willi"; $string2 = "willI"; if($string1 ne $string2) { print "string1 is not the same as string2\n"; } else { print "strings 1 and string2 are the same\n"; } 181 182 CHAPTER 5. PERL 5.8 && || xor ! Logical Operators AND OR XOR NOT The logical operators are logical logical logical logical xor is the logical xor operator: true if either a or b is nonzero, but not both. # logical.pl $x = 8; if(($x > 0) && (($x%2) == 0)) { print "integer number is positive and even"; } else { print "number is either not positive or not even"; } print "\n"; $y = 0; if(!($y)) { print "number is zero"; } else { print "number is nonzero"; } print("\n"); $u = 6; $v = 5; if(($u > 0) xor ($v > 0)) { print("abba"); } else { print("baab"); } # what happens if you change to: # $v = -5; ? 5.9. LOOPS 183 5.9 Loops Perl provides a for loop, a while loop, a until loop, and a foreach loop. The next program shows how the for loop is used. # forloop.pl # $sum = 0; for($i=0; $i<10; ++$i) { $sum = $sum + $i; } print "$sum"; print "\n"; $product = 1; for($i=1; $i<12; ++$i) { $product *= $i; } print "$product"; print "\n"; The following program shows how the standard input can be used within a for loop. The program reads four input lines and writes three of them to the screen. # forloop1.pl # for($line = <STDIN>, $count = 1; $count <= 3; $line = <STDIN>, $count++) { print($line); } # remove the newline at end while($a ne "willi") { print "sorry.pl # # $x ne $y Is $x string unequal to $y ? # print "Password? ". try again\n". print("\n"). } print "you did it". chop $a. PERL # while.184 The next program shows the use of the while loop. $a = <STDIN>. chop $a. . $a = <STDIN>. print "Password? ". CHAPTER 5. 5.pl print("What is 27 plus 26?\n"). LOOPS 185 The until statement is similar to the while statement. The until statement loops until its conditional expression is true. $correct_answer = 53. This means it loops as long as its conditional expression is false. $input_answer = <STDIN>. chop($input_answer). # until. chop($input_answer). $input_answer = <STDIN>. The while statement loops while its conditional expression is true. } print("You go it!\n"). . until($input_answer == $correct_answer) { print("wrong! keep trying!\n"). but it works in a different way.9. foreach $x (@numbers) { if($x == "3") { ++$count. The first time the loop is executed. "3".pl # @wordlist = ("Good". The local variable $word is only defined for the duration of the foreach statement. "3". "15".186 CHAPTER 5. $count = 0. "3"). the value stored in $word is the string Good. foreach $word (@wordlist) { print("$word\n"). the value stored in $word is Morning. # => 4 . The second time the loop is executed. print "\n". } @numbers = ("3". # foreach. "7". The loop defined by the foreach statement terminates after all of the words in the list have been assigned to $word. PERL In the following example the foreach statement assigns a word from @worldlist to the local variable $word. "Morning". } } print $count. "12". "Egoli"). 10.5. } print("You got it!\n"). L1: print("Let’s give up\n"). $input_answer = <STDIN>. # goto. . L2: print("end of session"). goto L2.pl print("What is 20 + 36?\n"). chop($input_answer). } $count++. chop($input_answer). $correct_answer = 56. $count = 0. if($count == 5) { goto L1. GOTO STATEMENT 187 5. In the following program L1 and L2 are labels. until($input_answer == $correct_answer) { print("wrong! keep trying!\n").10 goto Statement Like C and C++ Perl has a goto statement. $input_answer = <STDIN>. 0. $y = sin($x). $w = exp($v). print("s = $s\n").5). PERL 5. # log base e print("r = $r\n").188 CHAPTER 5. $s = abs(-3. # in the range -pi to pi $u = atan2(1. $z = cos($y).pl $x = 3. print("z = $z\n").4. # atan2 function calculates and returns # the argument of one value divided by another.5).11 Mathematical Functions Perl has a large number of built-in mathematical functions. $r = log(4. print("v = $v\n").0). print("u = $u\n"). print("y = $y\n"). print("w = $w\n"). .0). Perl includes all standard mathematical functions For example # math. $v = sqrt(6.14159. XOR ^ (exclusive OR). # => 1 # => 15 # => 14 # => 4294967286 . # two complement $z = -45. $e = $a ^ $b.5. $c = $a & $b. Any integer can be written in binary representation. $z = ~$z. print(" $e\n"). $z++. print(" $z\n"). For example 9 = 1 × 23 + 0 × 22 + 0 × 21 + 1 × 20 Thus the bitstring is 1001. BITWISE OPERATIONS 189 5. OR | (inclusive OR). If we assume we store the bitstring in 32 bits we have 00000000 00000000 00000000 00001001 The one’s complement of this bitstring is 11111111 11111111 11111111 11110110 The bitwise operations are & | ^ ~ is is is is the the the the bitwise AND bitwise inclusive OR bitwise exclusive OR NOT operator (one’s complement) # bitwise. print(" $f\n").pl $a = 9. $f = ~$a. $d = $a | $b. print(" $d\n").12 Bitwise Operations Perl allows the bitwise operation AND &. $b = 7. print(" $c\n").12. and the NOT operator (one’s complement) ~. 23. The first element in the list has the index 0. Thus in the following list @myarray = (7.23. In the first program we count the number of elements in the list. 9.23e-10). "Egoli". we have myarray[0] = 7.23e-10). myarray[1] = "Egoli". } . 1. "Egoli". while($count <= 5) { print("element $count is $myarray[$count]\n"). # mylist. The operator [ ] is used to access the elements in the list. "\"Having fun?\"".190 CHAPTER 5. $count = 0. and so on. $count++.pl # @myarray = (7.13 List Operations The next four programs show how to use list operations. 1. PERL 5. 9. "\"Having fun?\"". print("\n"). "Cape Town ". } ($x. print $difference. "banana "). LIST OPERATIONS 191 # array operations # array.13. "15"). $z) = @cities.5. } else { $difference = $numbers[2] . $y. "12". print "\n". @numbers = ("4". if($numbers[2] != $numbers[4]) { $sum = $numbers[2] + $numbers[4]. print "\n". print $x. # => Durban print "\n". print $cities[2]. @cities = ("Egoli ". print "\n". "Durban ".$numbers[4]. # => Egoli # => Durban . "pears ".pl # @fruit = ("apples ". # => 24 print($sum). print @fruit. "7". print "\n". "9". "Pretoria "). print $z. print "\n". print "\n". @morecities). "Cape Town ". "Bloemfontain"). print @fruit. "peach ". print "\n". To remove the last item from a list and return it we use the pop function. "Grahamstown"). PERL In the following program we show how the push and pop operator can be used.192 CHAPTER 5. "plums "). @fruit = ("apples ". push(@fruit. "Pretoria "). push(@cities. push(@cities. . $mycity = pop(@cities). "pears ". print @cities. @cities = ("Egoli ". "banana "). "strawberries ". @morecities = ("George". "Durban ". print $mycity. "Johannesburg"). print $myarray[2]. To split a character string into separate items we call the function split. LIST OPERATIONS 193 The next program show the use of the split and join function. carl. ludwig. print("$concatstring"). @names). The split function puts the string into an array./. "Gauteng ". @myarray = split(/.pl # splitting a string into a list # $string = "otto. # mysplit. To create a single string from a list use the function join. $string). print "@myarray\n". print("\n").5. . $concatstring = join("". # => otto carl ludwig berlin:postdam print("\n").13. # => ludwig @names = ("Egoli-". berlin:postdam". # adding an element $ages{"Henry VIII"} = 1654. "Dan Smithlone". PERL 5. @valuearray = values(%ages). @myarray = keys(%ages). print %ages. print $ages{"Jane Coppersmith"}. # => 40 print("\n"). 21. } # !! curly brackets # => only the names . print("\n"). print $ages{"Ludwig Otto"}. 32.pl %ages = ( "Ludwig Otto". print(" "). # assoc. print($value). print("@valuearray"). $value) = each(%ages)) { print($name). 67). print("\n"). # => 21 print("\n"). "Jane Coppersmith". print("\n").14 Associative Arrays Operations Perl defines associate arrays which enable us to access array variables using any scalar value we like. # => only the values print("\n\n"). Associative arrays are also called hashes. # deleting an element delete($ages{"Franz Karl"}). print("\n").194 CHAPTER 5. print @myarray. print %ages. while(($name. 40. "Franz Karl". } . if($question =~ /please/) { print("Thank you for being polite!"). This operator binds the pattern to the string for testing whether a pattern (substring) is matched.pl print("Ask me a question politely:\n").15. } else { print("That was not very polite!\n").5.15 =~ Pattern Matching Matching involves use of patterns called regular expressions. $question = <STDIN>. The following shows how this is applied. # matching. PATTERN MATCHING 195 5. The operator performs pattern matching and substitution. print("$_"). The syntax for the substitution operator is s/pattern/replacement/ options for the substitution operator g i e m o s x change all occurence of the pattern ignore case in pattern evaluate replacement string as expression treat string to be matched as multiple lines evaluate only once treat string to be matched as single line ignore white space in pattern In our first program we replace the substring 123 by 4567.16 Regular Expressions Regular expressions are patterns used to match character combinations in strings. # => abc4567def In our second example we use the global variable $_. Regular expressions also exist in JavaScript. For example. to search for all occurences of the in a string. s/([a-z])/\1+/g.pl $_ = "Egoli Gauteng". # acts on global scalar variable $_ print("$_"). print("\n"). $string =~ s/123/4567/. s/([A-Z])/+\1+/g. # => +E+goli +G+auteng print("\n").pl $string = "abc123def". we create a pattern consisting of the to search for its match in a string.196 CHAPTER 5. # regexp1. print("$string\n"). # => +E+g+o+l+i+ +G+a+u+t+e+n+g+ . # replace1. PERL 5. If any exist. } print("Formatted text:\n"). $input[$count] =~ s/[ \t]+\n$/\n/. $count++. $count = 0. REGULAR EXPRESSIONS The next program is a white-space clean up program. ^ $ * + ? any single character except a newline the beginning of the line or string the end of the line or string zero or more of the last character one or more of the last character zero or one of the last character . # # # # # # # # # # # # the line $input[$count] =~ s/^[ \t]+//. the line $input[$count] =~ s/[ \t]+\n$/\n/. they are removed. while($input[$count] ne "") { $input[$count] =~ s/^[ \t]+//.pl @input = <STDIN>. checks whether there are any spaces or tabs at the end of the line (before the trailing newline character). print(@input). If any exist.16. 197 Here are some special regular epression characters and their meaning . they are removed.5. the line $input[$count] =~ s/[ \t]+/ /g uses a global substitution to remove extra spaces and tabs between words. # replace2. $input[$count] =~ s/[ \t]+/ /g. checks whether there are any spaces or tabs at the beginning of the line. $word =~ tr/a-z/A-Z/. In the second part of the following program the search pattern and the replacement pattern are the same. $string =~ tr/oi/uo/. PERL where sourcelist is the list of characters to replace. the number of characters translated is equivalent to the length of the sentence. This length is assigned to the scalar variable length. $length = tr/a-zA-Z /a-zA-Z /. . # the muun os rosong $word = "egoli-Gauteng". print("$word\n"). Every character is being translated. # EGOLI-GAUTENG $sentence = "here is a sentence".pl $string = " the moon is rising ". print("$string"). print("the sentence is $length characters long\n").198 The syntax for the trace function (translation) is: tr/sourcelist/replacelist/ CHAPTER 5. and replacelist is the list of characters to replaced it with. $_ = $sentence. # trace. First all elements in the array are multiplied by 3 and then we add 2 to each element. in turn.5. 3). "234").17 Map Operator The map function enables us to use each of the elements of a list.@numbers)). -1. 2. as an operand in expression. # 5811 . @charres = map($_ . @result = map($_+2.pl @numbers = (1. @charlist). # 403 @charlist = ( "aba".list). # mymap. # 103 242 403 2 237 print("$result[2]\n"). # abaxxx celxxx We can also chain the map operator together. 239. In the second example we concatenate xxx to all elements in the list.map($_*3. @result = map($_+3. 400. print @result.pl @numberlist = (100. print("@result\n"). The following program gives two examples. # mapchain. xxx. In the first example we add 3 to all elements in the list. The following example shows this.17. "cel" ). @numberlist). MAP OPERATOR 199 5. The syntax is resultlist = map(expr. print("@charres\n"). $s2.pl $myarray = [ [ 4. $s2 = $stringarray -> [1][0].0]]. ["hulopi". $a2 = [[6.[4.-9].18 Two-Dimensional Arrays The operator -> is used to de-reference the reference that has been created to point to the array of arrays. $j < 2. $j++) { $a3 -> [$i][$j] = $a1 -> [$i][$j] + $a2 -> [$i][$j]. $stringarray = [[ "yuli". $j < 2. " = ".19]]. "][". "]". # => -9 print("\n"). ($a3 -> [$i][$j])). "fulipok"]].200 CHAPTER 5. $j++) { print("a3[". } } .0]. print($a). print($myarray -> [1][1]).3]. $i++) { for($j=0. $s1 = $stringarray -> [0][1].-10]].[2. } } # display the result of the matrix addition for($i=0. print("$s3\n"). $j. $i. PERL 5. -9]]. # => 5 print("\n"). # => uilopihulopi # addition of two 2 x 2 matrices $a1 = [[2. print("\n"). $a3 = [[0. [ 6. $a = $myarray -> [0][1]. $i < 2. # twodim. "uilopi"]. for($i=0. $i++) { for($j=0. $i < 2. 5 ]. $s3 = $s1 .[0. sub myrand { rand(10. srand(). print("res1 is: $res1\n"). The keyword sub tells the interpreter that this is a subroutine definition.19 Subroutines In Perl a subroutine is a separate body of code designed to perform a particular task. print("res3 is: $res3\n"). The variable $c can be seen globally. # subrand. print("c = $c\n"). $z = 0. SUBROUTINES 201 5. } The function add adds two numbers.pl $res1 = &myrand. print("res2 is: $res2\n"). The function srand() sets a seed for the random number generator. $b = 5. print("z = $z\n"). Subroutines are referenced with an initial &. sub add { $c = $a + $b.19.pl $a = 7. $res2 = &myrand.0).5. $res3 = &myrand. } $z = &add. # add. # => 12 # => 12 . # inverse. print("largest number = $result\n"). } else { if($_[1] > $_[2]) { $_[1].202 CHAPTER 5.pl sub inverse { -$_[0]. # => -37 # => -88 print("default scalar variable = "). print $_[0].9. print("r1 = $r1\n"). $_[0] = 88.7). We recall that $_ is the default scalar variable. PERL The subroutine inverse in the next example finds the inverse of a scalar variable. $r2 = &inverse. . # => 88 The subroutine maximum finds the largest of three numbers.pl sub maximum { if(($_[0] > $_[1]) && ($_[0] > $_[2])) { $_[0]. print("r2 = $r2\n"). } } } # end sub maximum $result = &maximum(2. } else { $_[2]. # largest. } $r1 = &inverse(37). # subrout2. $r = 12. 203 The subroutine even_odd finds out whether a given integer number is even or odd. print $st. print("="). $st = even_odd(14).pl sub even_odd { my $num = $_[0]. return "even" if(($num % 2) eq 0). # subrout1.19. } $st = even_odd(7). print $st. print("\n").0. return "odd" if(($num % 2) eq 1). print $area. print $num. print("\n"). print("\n"). . SUBROUTINES In the following program we calculate the area of a circle.pl sub calc { $pi = 3.5. } $area = calc. $calc = $pi*($r*$r).14159. 90. $sum = 0.204 CHAPTER 5.8.5.pl sub sum { my $sum = 0. &addlist(@otherlist). } print("The sum is: $sum\n"). "24". } @otherlist = ( 1.6. foreach $item(@list) { $sum += $item. } return $sum. The following example demonstrates this. PERL Using the @_ operator we can pass arrays to a subroutine. # passarray1.5.1. -34. foreach $num(@_) { $sum += $num. 4.6 ).17).13. "-45" ). A slightly modified version is given in the next example.pl @mylist = ( "14".9. } $total = sum(3. print $total. sub addlist { my(@list) = @_.23. &addlist(@mylist). 7. # passarray2. . The output is egoli 123Johannesburg begin 3.5.pl sub pass { my ($name. ’1’. print @rest. ’2’.56. } pass("egoli". SUBROUTINES 205 The subroutine pass splits the list into a scalar (first item) and the rest which is again a list. 4.19.7. "Johannesburg").4. 3. @rest) = @_.5. print("\n").44.7end . # passarray3. print("\n"). "end"). print $name. pass("begin". 6. ’3’. # subsplit. Then it is splitted into numbers. $line =~ s/^\s+|\s*\n$//g. foreach $numbers(@numbers) { $sum += $numbers. @numbers = &getnumbers.$line). } print("The sum is: $sum\n"). split(/\s+/. This is the return value. We recall that \s stands for any whitespace.0. PERL In the following program the subroutine getnumbers reads a line of input from the standard input file and then removes the leading whitespace (including the trailing newline) from the input line. } .pl $sum = 0. sub getnumbers { $line = <STDIN>.206 CHAPTER 5. The following two programs demonstrate this. $value = 50. # local1. } print return_value.pl $value = 100. # => 50 # => 50 # => 100 # => 50 . } print return_value. The my statement defines variables that exist only inside a subroutine. print $value. print $value. we have to make the variables local in scope. SUBROUTINES 207 If variables are only used inside a subroutine and not to be seen outside. # global variable sub return_value { $value = 50.pl $value = 100. return $value. # local2. return $value.5.19. # global variable sub return_value { my $value. return $temp. In our first example we find n! := 1 × 2 × . . } $temp = $_[0]*&fac($_[0]-1). PERL 5. } # end subroutine fac print("enter value = "). print("Factorial of $n is $f\n").20 Recursion Perl also allows recursion. $f = &fac($n). $n = <STDIN>. # Recur1. × n using recursion. chop($n)..208 CHAPTER 5.pl sub fac { my $temp.. if($_[0] == 1) { return 1. print("Fibonacci number of $n is $fibo\n"). f1 = 1 209 .pl sub fib { my $temp. } $temp = &fib($_[0]-1) + &fib($_[0]-2). chop($n). return $temp. } if($_[0] == 1) { return 1. # Recur2. $fibo = &fib($n).5.20. $n = <STDIN>. f0 = 0. } # end subroutine fib print("enter value = "). if($_[0] == 0) { return 0. RECURSION As a second example we consider the Fibonacci numbers which are defined by fn+2 = fn+1 + fn . For example. } else . # recur3.210 CHAPTER 5. @list = split(/\s+/. For example + 100 / -5 + 15 -16 is 100 + (−5)/(15 − 16) which evaluates to 105. my ($result. $result = &rightcalc(0).98 * 4 + 12 11 into the list given above. sub rightcalc { my ($index) = @_. Then the subroutine rightcalc(0) starts with the first element of the list. -. print("The result is $result\n"). . the first operand.$inputline). "+".pl $inputline = <STDIN>. "12". 98. The first three lines in the program put the input from the keyboard .$op2). PERL In the following example we evaluate recursively a mathematical expression from right-to-left with the operator as prefix.$op1. and a sublist (the rest of the list). For our first example we get the list ("-". if($index+3 == @list) { $op2 = $list[$index+2].98 * 4 + 12 11 is in standard notation 98 − 4 ∗ (12 + 11) which evaluates to 6. "11") which can be split into three parts: the first operator. "4". "98". "*". } } 211 A slightly simpler version with support for command line values is given below.20. my $node=pop. } elsif($list[$index] eq "-") { $result = $op1 . # recursion } $op1 = $list[$index+1]. if($list[$index] eq "+") { $result = $op1 + $op2. $op1=&postfix. } elsif($list[$index] eq "*") { $result = $op1 * $op2. return $op1*$op2.e. return $op1-$op2. $op1=&postfix. } if("\$node" eq "-") { $op2=&postfix. return $op1+$op2. Thus &postfix refers to the sub postfix without explicitly giving parameters. if("$node" eq "+") { $op2=&postfix. $op1=&postfix.$op2).5. also &postfix works on @ directly (it does not get its own copy). } if("\$node" eq "/") . my ($op1. } else { $result = $op1 / $op2.$op2. We use &postfix so that PERL will use @ as the parameters. we consume parameters from the list @ . sub postfix { #For prefix expression evaluation use #my $node=shift. RECURSION { $op2 = &rightcalc($index+2). #!/usr/bin/perl #Assume all postfix expressions are valid. i. } if("\$node" eq "*") { $op2=&postfix. 212 CHAPTER 5.$line)). print "\n". } if(@ARGV > 0) { foreach $i (@ARGV) { print postfix(split(’ ’. return $op1/$op2. } return $node. $op1=&postfix. print "\n".$i)). PERL { $op2=&postfix. } } . print postfix(split(’ ’. } } else { while($line=<STDIN>) { chop($line). txt.and the code inside the if statement is executed.">$file").21 The line File Manipulations open(MYFILE.21. The next lines print the contents of file1. open(INFO. } } The open command allows different options open(INFO. The sample output shown here assumes that file1."file1.5. open(INFO.txt") is assumed to be true. The file handle MYFILE is associated with the file1."file1. file1.$file).txt")) { $line = <MYFILE>. If the call to open returns a nonzero value. FILE MANIPULATIONS 213 5. $line = <MYFILE>.txt") opens the file file1. while($line ne "") { print($line).txt in read mode."<$file").txt.txt contains the following three lines: Good morning Egoli.txt is assumed to be in the current working directory. the conditional expression open(MYFILE. How are you ? Good night Egoli! # file1."file1. open open open also for input for output for appending open for input . which means that the file is to be made available for reading.">>$file"). open(INFO.p1 if(open(MYFILE. $line = <HANDLE>.214 CHAPTER 5.txt")) { die("cannot open input file file1. PERL # # # # # file2. the file was # opened successfully $line = <HANDLE>.txt\n"). } .pl terminating a program using the die function unless(open(HANDLE. while($line ne "") { print($line). "file1. } # if the program gets so far. $line = <INFILE>.txt indicates that the file # is opened in write mode. $line = <INFILE>. } unless(open(OUTFILE. .5. FILE MANIPULATIONS 215 # file3. writes the contents of the scalar variable $line on the file specified by OUTFILE. } # the > in >file2.txt\n")."file1.txt")) { die("cannot open input file file1. } # # # # # the line print OUTFILE ($line).txt\n").txt")) { die("cannot open output file file2.pl # # writing to a file unless(open(INFILE.21. while($line ne "") { print OUTFILE ($line).">file2. print @lines. close(INFO). $file).dat". PERL .dat contains # 20 3 1960 CHAPTER 5.216 # file4. open(INFO. @lines = <INFO>. print("\n"). # file willi.pl # closing a file $file = "willi. open(FILE.5. # file5.pl FOO The output is: This line equals: 6 This line equals: -8 This line equals: 12 217 The result is stored in the file FOO. ">$ARGV[$count]"). $count++. } . FILE MANIPULATIONS Let us assume that the file named FOO contains the text This line equals: 3 This line equals: -4 This line equals: 6 At the command line run: perl file5. $linenum++. print FILE (@file). Thus we multiply every integer in a file by 2. close(FILE). while($ARGV[$count] ne "") { open(FILE. @file = <FILE>. } close(FILE). while($file[$linenum] ne "") { $file[$linenum] =~ s/\d+/$& * 2/eg. The pattern \d+ matches a sequence of one or more digits.21. $linenum = 0. "$ARGV[$count]").pl $count = 0. $single = &countName($line). close(INFILE). @narray = split(/ /.218 CHAPTER 5.txt").txt")) { die("cannot open smith.pl unless(open(INFILE. $nbSmith += $single. } $line = <INFILE>. PERL In the following program we count how often the name Smith (case-sensitive) is in the file smith.$_[0]). } print("Number of Smith in file smith. } .txt. sub countName { $i = 0. foreach $x (@narray) { if($x =~ /Smith/) { $i++. while($line ne "") { print("$line ")."smith. $line = <INFILE>. # findSmith. $nbSmith = 0. $single = 0.txt = $nbSmith \n"). } } return $i. print("$single \n"). } if ( @ARGV > 0 ) { dirlist("". } } ."$curdir$i") or print("Failed to open directory $curdir$i. dirlist("$tabbing |". #!/usr/bin/perl $normalfiles=NO.$curdir."".@dir)=@_.5.21. shift @newdir.@newdir). my @newdir=readdir(DIRHANDLE).".\n"). } } if ( -d "$curdir$i" ) { opendir(DIRHANDLE."$curdir$i/". } else { dirlist("". FILE MANIPULATIONS 219 In this program we made extensive use of man perlop perlfunc perlipc./"). foreach $i (@dir) { if ( -e "$curdir$i" ) { if (( -d "$curdir$i" ) || ( "$normalfiles" eq YES )) { print "$tabbing\-\-$i\n"."". closedir(DIRHANDLE). shift @newdir. shift @ARGV. sub dirlist { my ($tabbing. } } } if (( @ARGV > 0 ) \&\& ( "\$ARGV[0]" eq "-n" )) { $normalfiles=YES.@ARGV). The program draws a tree structure of a given directory. $altnames). # these three lines convert the address into # a four-byte packed integer $machine =~ s/^\s+|\s+$//g. @altlist = split(/\s+/. $addrtype. @bytes = split(/\.pl networking the gethostbyaddr function searches the hostname for a given network address. $packaddr = pack("C4". @bytes).106. } } # if we enter: # 152. $len. $altnames.22 # # # # # Networking net1.rau. print("enter an Internet address:\n"). if($altnames ne "") { print("alternative names:\n").\n").ac. $i < @altlist. PERL 5. @addrlist) = gethostbyaddr($packaddr.50. } print("principal name: $name\n").220 CHAPTER 5. $i++) { print("\t$altlist[$i]\n"). $machine = <STDIN>.60 # we get # principal name: whs. if(!(($name. $machine). for($i=0.2))) { die ("Address $machine not found.za ./. pl networking the gethostbyname function searches for an entry that matches a specified machine name or Internet site name. print("\t$realaddr\n"). @addrlist) = gethostbyname ($machine))) { die ("Machine name $machine not found.5. $machine = <STDIN>.". for($i=0.50. print("enter a machine name or Internet sie name:\n").ac. NETWORKING 221 # # # # # net2.22.rau. @addrbytes).za # we get # 152. print $machine. } # if we enter: # whs.106. $altnames. # machine name prepared $machine =~ s/^\s+|\s+$//g. print("\n"). $addrlist[$i]).\n"). $addrtype. $i < @addrlist. $i++) { @addrbytes = unpack("C4".60 . } print("equivalent addresses:\n"). if(!(($name. $len. $realaddr = join (". if($childpid=fork()) { while( $toprint=<SOCKET> ) { print STDOUT "$toprint". connect(SOCKET.$addr) || die("Failed to connect.$childpid). } kill(TERM. use Socket. socket(SOCKET.\n"). #!/usr/bin/perl use IO::Handle. $addr=sockaddr_in($port. CHAPTER 5. $proto=getprotobyname("tcp")||die("getprotobyname failed. print "Connection established. $port=shift||"telnet".\n"). PERL $server=shift||"localhost".\n").PF_INET.\n"). . $port=getservbyname($port. STDIN->autoflush(1).$addr)||die("sockaddr_in failed. SOCKET->autoflush(1).222 In the following program we create a minimal telnet client.SOCK_STREAM.\n")."tcp")||die("getservbyname failed.\n".\n").$proto) || die("Failed to open socket. } else { while(($tosend=<STDIN>) && (print SOCKET "$tosend")) {} } close(SOCKET). $addr=gethostbyname($server)||die("gethostbyname failed. Beginning Java 2. Java 1. 1996 [4] McComb Gordon. 1998 [3] Johnson Marc. Macmillan Computer Publishing. 1996 [5] Tan Kiat Shi. USA. Birmingham. London. Macmillan Computer Publishing. WROX Press. 2nd edition Springer-Verlag. JavaScript Sourcebook. JavaScript Manual of Style. 2000 223 . New York. Willi-Hans Steeb and Yorick Hardy. Wiley Computer Publishing.2 Unleashed. USA. SAMS NET. SymbolicC++: An Introduction to Computer Algebra Using Object-Oriented Programming. UK. 1999 [2] Jaworski Jamie.Bibliography [1] Horton Ivor. 6 cmp. 59 kill. 60 uname. 47 id. 129 chown. 59 clear. 43 find. 2 read. 51 man. 59 chkconfig. 57 du. 52 sub. 192 printenv. 199 more. 1 df. 60 whereis. 131 sleep. 39 One’s complement. 46 grep. 49 kdb_mode. 192 pwd. 51 split. 10 224 . 44 finger. 60 who. 1 Filter. 60 touch. 179 date. 42 local. 57 echo. 38 Root. 91 Pipe. 152 logname.Index arch. 53 chmod. 6 map. 5 ps. 3 push. 50 less. 201 tail. 2 file. 42 mount. 66 pop. 60 top. 189 Perl.
https://www.scribd.com/doc/165281666/6917186-LINUX
CC-MAIN-2017-39
refinedweb
44,699
68.97
Closed Bug 450581 Opened 14 years ago Closed 14 years ago Address Book lists in dialogs may become unsorted Categories (MailNews Core :: Address Book, defect, P2) Tracking (Not tracked) Thunderbird 3.0a3 People (Reporter: standard8, Assigned: neil) References Details Attachments (1 file, 4 obsolete files) In Bug 449260 Neil suggested: > Ideally you'd keep the array of directories as a member and then you can a) use > it to validate the notifications and b) use it to sort a new entry into the > correct position (speaking of which, shouldn't renaming an entry re-sort it?) I agree this would be an improvement. Neil said he'd be happy to do it, so assigning to him. Flags: blocking-thunderbird3+ Not blocking, but definitely wanted. Flags: blocking-thunderbird3+ → wanted-thunderbird3+ Priority: -- → P2 Summary: In addrbookWidgets.xml store the directories in an array and use for validation and re-sorting → Address Book lists in dialogs may become unsorted Stealing: I decided that I needed the array implementation for being able to provide an alternative value for the menuitems (i.e. dirPrefId as opposed to URI). This patch changes over to the array implementation and fixes some bugs in the onItemAdded routine (as well as avoiding teardown and rebuilding). I think the only other thing I need to fix now is re-sorting the list in onItemPropertyChanged. Assignee: neil → bugzilla Status: NEW → ASSIGNED Comment on attachment 334085 [details] [diff] [review] WIP Patch Isn't the node for this._books[i] always going to be this.childNodes[i]? Also the code may be unreadable but I hope you get the idea ;-) (In reply to comment #4) > Created an attachment (id=334173) [details] > untested > > Also the code may be unreadable but I hope you get the idea ;-) > This looks better than my version. When I tried it just now, it didn't seem to work too well. Initially renames and deletes weren't working. I then restarted and trying adding an ab (and that worked), but then renaming, partially worked but was throwing errors. Assignee: bugzilla → neil Status: ASSIGNED → NEW OK, so I had to switch from indexOf to a for loop because indexOf requires strict equality which we don't get for xpconnect objects. (This isn't a problem when deleting/renaming a new directory because we already have a strictly equal xpconnect object to compare against.) I also fixed a typo which prevented renames from working (passing _compare() instead of _compare to sort). Attachment #334173 - Attachment is obsolete: true Keeping wanted‑thunderbird3+. Whiteboard: [needs sr:dmose] Target Milestone: --- → mozilla1.9.1a2 Target Milestone: mozilla1.9.1a2 → Thunderbird 3.0b1 I added an extra entry in the array to track the menuitem as that seems to be simpler than adjusting the offsets depending on whether the menuitem exists. Attachment #334259 - Attachment is obsolete: true Attachment #335034 - Flags: superreview?(dmose) Attachment #335034 - Flags: review?(bugzilla) Comment on attachment 335034 [details] [diff] [review] Added > <implementation implements="nsIAbListener"> >+ <field name="_directories">[]</field> >+ >+ <field name="_value">this.getAttribute("value") || "URI"</field> It's not clear to me what the point of "URI" is above. Can you add a comment explaining? >+ if (this.hasAttribute("none")) { >+ this._directories.unshift(null); >+ menulist.insertItemAt(0, this.getAttribute("none"), ""); >+ } Please document how the "none" attribute works, who sets it, etc. >+ if (index != -1) >+ if (this.parentNode.selectedItem == >+ this.removeChild(this.childNodes[index])) >+ if (this.hasChildNodes()) >+ this.firstChild.doCommand(); >+ else >+ this.parentNode.selectedItem = null; The above code could use at least a comment, and might make sense to break up for readability. >+ <method name="_contains"> >+ <parameter name="ab"/> This method needs some commentary explaining the exact semantics of what it's doing. I'm not totally convinced that _contains is the right name: it's used in building up the array, when it's got nothing to do with what the widget actually contains at that time, but rather what it should contain, inferred from the various attributes on the widget. I'm not really sure what the best name would be, _shouldContain might be a little better, but that's not great either. > <body><![CDATA[ >+ const nsIAbDirectory = Components.interfaces.nsIAbDirectory; >+ return (ab.isRemote ? this.getAttribute("localonly") != "true" >+ : this.getAttribute("remoteonly") != "true") && >+ (ab.supportsMailingLists || >+ this.getAttribute("supportsmaillists") != "true") && >+ ((ab.operations & nsIAbDirectory.opWrite) || >+ this.getAttribute("writeable") != "true"); I know this code was just moved from what was here previously, but it's really a pain to read, which makes it hard to review as well as fragile to maintain. I suspect this wants to be split up into multiple statements with local variables. The various different attributes also want to be documented, I think. One thing that was nice about the old code is that most non-trivial clauses had comments explaining what they were trying to do. This made it much easier to follow the code flow as well as meant that there was an english expression describing what the code was supposed to be doing that the reviewer/reader can audit the actual code behavior against. Please give the code a once-over and do this, if you would; then I'll take another pass. Attachment #335034 - Flags: superreview?(dmose) → superreview- I changed "_contains" to "_matches" to indicate what it does. I also gave the method alternative body which you might prefer. I hope I added sufficient comments for you to understand the code. Attachment #335034 - Attachment is obsolete: true Attachment #337279 - Flags: superreview?(dmose) Attachment #337279 - Flags: review+ Comment on attachment 337279 [details] [diff] [review] Updated for review comments (!) Code is definitely more approachable & maintainable; thank you! >+ <!-- Represents the nsIAbDirectory attribute used as the value of the >+ parent menulist. Defaults to URI but can be e.g. dirPrefId --> >+ <field name="_value">this.getAttribute("value") || "URI"</field> Clever. >+ // Attempt to select the persisted or otherwise first directory. >+ menulist.value = menulist.value; Why write to .value rather than .selectedItem? >+ /* This code was vetoed by dmose, but I can't think why... Heh. You don't really _have_ to keep this comment in there, but you're welcome to if you wish. :-) Don't forget to add yourself to the license boilerplate. sr=dmose . Pushed changeset 3776ea557ca4 to comm-central. Status: NEW → RESOLVED Closed: 14 years ago Resolution: --- → FIXED Whiteboard: [needs sr:dmose] (In reply to comment #12) > . That's what the getter half of the statement does, not the setter half. But why assign it the returned value to .value rather than assigning it to .selectedItem? No, the value getter simply reads the menulist's value attribute. menulists have three properties identifying the current selection: 1. selectedItem - the actual node in the current DOM 2. selectedIndex - the (numeric) index in childNodes of selectedItem 3. value - a (string) abstract representation stored as an attribute Setting any one of the properties will update the other two. So when you write menulist.value = menulist.value; you're taking the persisted attribute and asking the menulist to convert it to a DOM node and child index.
https://bugzilla.mozilla.org/show_bug.cgi?id=450581
CC-MAIN-2022-33
refinedweb
1,158
57.16
RationalWiki:Constructive dialogue We here at RationalWiki always welcome those who disagree with points of view presented here to discuss their disagreement with us in a rational way. There are primarily three ways of doing this: - Discuss a particular article's content on its talk page. - Start a debate in the debate namespace. - Write an essay explaining your perspective. If you choose to travel down path 3, we expect you to be willing to defend your essay on its talkpage, and you are strongly encouraged to take on board the comments made there and consider changes if you feel any are necessary. We have no edit limit, and 100% of your edits can be talk and debate. We would rather you explain why you disagree rather than make disparaging or unhelpful comments on the articles. If you can show why you are correct the articles will be updated to reflect this new information. However, if you just spout off randomly without any sources (we prefer raw data, or at least some decent links), or if your argument is based on sexism, racism, or other hateful world views, you may find your welcome a little icy. You will find more information on editing in our newcomers' guide and Community Standards.
https://rationalwiki.org/wiki/RationalWiki:Constructive_dialogue
CC-MAIN-2019-13
refinedweb
209
58.92
Hello all ... I'm experiencing a very curious compiler error... I have a lot of variables defined in the following fashion static StringBuffer logstr_area = new StringBuffer() ; static StringBuffer message_area = new StingBuffer() ; .....etc..... when I compile the source code the first error message I get is: ..Found java.lang.string ...required java.lang.stringbuffer or words to that effect and from that I get about 98 compiler errors from all the references to stringbuffers I've defined ... invalid type is part of the error message. I tried an explicit import...i.e. import java.lang.* ; but i still get the same error messages I'm running IBM's SDK 6 (java 1.6 ??) any ideas and/or suggestions are welcomed Thanks Guy Topic SystemAdmin 110000D4XK 757 Posts Pinned topic Compiler Error 2011-04-22T00:04:21Z | Updated on 2012-06-11T20:02:04Z at 2012-06-11T20:02:04Z by TatianaHriplivii - SystemAdmin 110000D4XK757 Posts Re: Compiler Error2011-04-22T15:49:58Z This is the accepted answer. This is the accepted answer.more on this compiler error this is one of the many error messages I get src\LU62XnsCvr.java:265: incompatible types found : java.lang.String required: java.lang.StringBuffer message_data = "LU62XCE0513: Request File I/O Exception =" ; the rest are exactly like this one ... My question is WHY does the java compiler make such a distinction ?? Now it's my understanding that a stringbuffer can change size dynamically. and simple string variables are "fixed" in size. SO why does it matter if one is copying a string of fixed size into a stringbuffer that starts out with an initial size of 16 bytes and can extend its length to accomodate the data it's receiving... I could understand incompatble types IF I was trying to put integer data into a "display" field. This however makes no sense BOTH are strings .. Re: Compiler Error2011-11-22T16:20:04Z This is the accepted answer. This is the accepted answer.at first you need to post your code snippet here, usually the java code tell you which line has the error. anyway, what i am guessing is that you are assigning an instance of StingBuffer directly to a string, like this: String a = stingBufferInstance; what you should do is: String a = stingBufferInstance.toString(); hope that this can be helpful. Acoolme is an Online Marketing Software Platform And Social Community Re: Compiler Error2011-11-22T16:24:56Z This is the accepted answer. This is the accepted answer. you might be assign a string directly to string buffer, like this StringBuffer sb = "asdfasdfasdfa'; you should do it like this: sb.append("adsfasdfafasd"; Acoolme is an Online Marketing Software Platform And Social Community - TatianaHriplivii 270005DVGD1 Post Re: Compiler Error2012-06-11T20:02:04Z This is the accepted answer. This is the accepted answer.onceI wrote everything ok, and the teacher checked: it was written right, but I made copy-paste from a text and the complier didn't "understant" what was there. I made delede and wrote by myself - and then it worked.
https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014609411
CC-MAIN-2016-07
refinedweb
506
65.32
Hi All Scenario: I need to fetch content of Winscp log files( from specific location) and compare the data of logs using SOAP UI by hitting another service . Currently I am doing this manually Is there any way I can automate this process Or, any groovy script I can run to automate the whole process Solved! Go to Solution. Hey @Nikita I've never used it, but i think you can use the 'File Wait' test step. The file contents get loaded into a property. I've had to compare stuff before..... @nmrao developed a groovy script that compared the contents of 2 properties against each other a while back for me. the groovy is as follows: /** * all work courtesy of Rao * This groovy script compares the specified property values of two property steps and report the error if any * For more details: **/ //Define the property names as defined in the property steps //Say, Name in Property Step 1 : Name in Property Step 2 //This way, it is possible to compare even if property names do not match in two Property Steps //Add or remove as per your need def map = ['id1': 'id2', 'name':'name'] //Modify the names of the Property Test step if needed. Here two property steps with given names are defined in the test case. def p1 = context.testCase.testSteps["Properties1"].properties def p2 = context.testCase.testSteps["Properties2"].properties def result = [] def assertPropertyValue = { p1key, p2key -> def temp = p1[p1key].value == p2[p2key].value log.info("Comparing $p1key, and $p2key values respectively ${p1[p1key].value} == ${p2[p2key].value} ? $temp") temp } map.each { result << assertPropertyValue(it.key, it.value) } assert result.every{it == true}, 'Comparison failed, check log' You could grab the FileWait content and pass to a Properties step, extract the detail from the Request's response and pass it to another Properties step and then run the groovy to compare the two. This is how I'd do this - although there's probably other groovy options available. so if you use something like the following test step hierarchy with the above you can probably compare the contents of the log files against any detail transferred to a properties step via your Request step FileWaitStep (log contents are saved to step PropertiesStep1)PropertiesStep1 (holds the content of the FileWaitStep) RequestStep(generates response, grab response detail and pass to PropertiesStep2) PropertiesStep2 (holds the properties from RequestStep) GroovyScriptStep (compares the contents of the PropertiesStep1 to PropertiesStep2) hope this helps, rich Hi all, Thanks for the reply and for sharing the script Rao created! @Nikita, was your question answered?
https://community.smartbear.com/t5/SoapUI-Pro/WinScp-and-ReadyApI/m-p/187910
CC-MAIN-2019-35
refinedweb
428
59.84
Things related to the Rock Ridge Interchange Protocol (RRIP) More... #include <cdio/types.h> Go to the source code of this file. Things related to the Rock Ridge Interchange Protocol (RRIP) Applications will probably not include this directly but via the iso9660.h header. Enforced file locking (shared w/set group ID) Child link. See Section 4.1.5.1 Parent link. See Section 4.1.5.2 POSIX device number, PN. A PN is mandatory if the file type recorded in the "PX" File Mode field for a Directory Record indicates a character or block device (ISO_ROCK_ISCHR | ISO_ROCK_ISBLK). This entry is ignored for other (non-Direcotry) file types. No more than one "PN" is recorded in the System Use Area of a Directory Record. See Rock Ridge Section 4.1.2 POSIX file attributes, PX. See Rock Ridge Section 4.1.2 File data in sparse format. See Rock Ridge Section 4.1.7 Symbolic link. See Rock Ridge Section 4.1.3 Time stamp(s) for a file. See Rock Ridge Section 4.1.6 system-use extension record The next two structs are used by the system-use-sharing protocol (SUSP), in which the Rock Ridge extensions are embedded. It is quite possible that other extensions are present on the disk, and this is fine as long as they all use SUSP. system-use-sharing protocol An enumeration for some of the ISO_ROCK_* #defines below. This isn't really an enumeration one would really use in a program it is to be helpful in debuggers where wants just to refer to the ISO_ROCK_* names and get something. Alternate name. See Rock Ridge Section 4.1.4 These are the bits and their meanings for flags in the NM structure. These are the bits and their meanings for flags in the SL structure. These are the bits and their meanings for flags in the TF structure. return length of name field; 0: not found, -1: to be ignored Returns POSIX mode bitstring for a given file. Returns a string which interpreting the POSIX mode st_mode. For example: drwxrws--- -rw---Sr-- lrwxrwxrwx A description of the characters in the string follows The 1st character is either "d" if the entry is a directory, "l" is a symbolic link or "-" if neither. The 2nd to 4th characters refer to permissions for a user while the the 5th to 7th characters refer to permissions for a group while, and the 8th to 10h characters refer to permissions for everyone. In each of these triplets the first character (2, 5, 8) is "r" if the entry is allowed to be read. The second character of a triplet (3, 6, 9) is "w" if the entry is allowed to be written. The third character of a triplet (4, 7, 10) is "x" if the entry is executable but not user (for character 4) or group (for characters 6) settable and "s" if the item has the corresponding user/group set. For a directory having an executable property on ("x" or "s") means the directory is allowed to be listed or "searched". If the execute property is not allowed for a group or user but the corresponding group/user is set "S" indicates this. If none of these properties holds the "-" indicates this. These variables are not used, but are defined to facilatate debugging by letting us use enumerations values (which also correspond to #define's inside a debugged program.
http://www.gnu.org/software/libcdio/doxygen/rock_8h.html
CC-MAIN-2014-42
refinedweb
576
74.29
The idea for this is based on. The article discusses how binary search can be done on a predicate. If the predicate p is monotonic, i.e. it satisfies the property: If p is true for x, then it is true for all values > x then we can use binary search to find the smallest true value. This can be applied to the current problem. Recall that the median of an array divides it into two equal parts. Similarly, to find the median of two arrays, we are trying to find k, l that cut the arrays into two parts such that k + l = (m + n) // 2 and left_part | right_part A[0], A[1], ..., A[k-1] | A[k], A[k+1], ..., A[m-1] B[0], B[1], ..., B[l-1] | B[l], B[l+1], ..., B[n-1] (diagram copied from the current solution, but variables changed) where the left part <= the right part. In other words we would like a[k-1], b[l-1] <= a[k], b[l] (eqn 1) As noted in other solutions, we can use binary search to find the location of the cut. An important note is that we do binary search on the shorter array. Suppose that b is the shorter array. Then, we can binary search the indices 0 .. n-1 in b for the location of the cut. To solve this problem, we can find the smallest l such that a[k-1] < b[l] (<- the predicate). Note that this predicate is monotonic. (Think of k as a function of l.) So, this approach can be done with predicate binary search. Why does this work? Once such an l is found, we also know that a[k] >= b[l-1], else the found l is not the smallest. Therefore equation (1) is satisfied, so l is actually the desired cut! Handling edge cases: Several edge cases are handled by the way we implement predicate binary search. Note that the cut can pass before the start of b, between two elements of b, or after the end of b. - If the predicate is true for all of b, the whole bis in the right part, and predicate binary search naturally returns 0. - If the predicate is false for all of b, the whole bis in the left part. In this case we make predicate binary search return n. So most of the pieces of the solution are here, and the idea is: - Do predicate binary search to find the appropriate cut. - Find the most extreme values of the left and right parts. - If l = 0, the cut passes before the start of b, so all of bis on the right. - If l = n, the cut passes after the end of b, so all of bis on the left. - If the # of #s is even, return avg(max(left part), min(right part)). Else, return min(right part). Since we use binary search, the desired O(log(m + n)) runtime is achieved. # Python 3 class Solution: def predicate_binary_search(self, lo, hi, p): """ Return the smallest index for which the predicate is true. The predicate p must have a breakpoint; it is false for all values up to a certain value, after which it is true for all values. In other words, p satisfies "if p is true for x, p is true for all values > x". If p is false for the whole range, return hi + 1. """ # lo, hi contains smallest i such that p(i) is true. while lo < hi: mid = (lo + hi) // 2 if p(mid): hi = mid else: lo = mid + 1 if p(lo) == False: return hi + 1 # p(x) is false for all x in S! return lo # lo is the least x for which p(x) is true def findMedianSortedArrays(self, a, b): if len(a) == len(b) == 0: raise IndexError # Assume b is shorter if len(b) > len(a): a, b = b, a m = len(a) n = len(b) # Find cut if n == 0: # Since b is empty, we consider the cut to be before the start of b # So 0 works l = 0 else: # It is left as an exercise for the reader why the index into a is # always in bounds l = self.predicate_binary_search( 0, n - 1, lambda l: a[(m+n)//2 - l - 1] < b[l]) # Get contenders for max elts on the left and min elts on the right if l == 0: # Use this slightly awkward syntax to add elements, since some of them # may have index out of bounds left = [a[(m+n)//2 - 1]] if (m+n)//2 - 1 >= 0 else [] right = (([a[(m+n)//2]] if (m+n)//2 < len(a) else []) + ([b[0]] if len(b) > 0 else []) ) elif l == n: left = (([a[(m-n)//2 - 1]] if (m-n)//2 - 1 >= 0 else []) + ([b[n-1]] if len(b) > 0 else []) ) right = [a[(m-n)//2]] # Must exist since a is the longer array else: # n >= 2 k = (m + n) // 2 - l left = [a[k-1], b[l-1]] right = [a[k], b[l]] # Depending on whether the # of #s is even or odd, just return the min of # the right half or average of the two halves if (m + n) % 2 == 0: return (max(left) + min(right)) / 2 else: return min(right)
https://discuss.leetcode.com/topic/115316/python-o-log-min-m-n-solution-using-predicate-binary-search
CC-MAIN-2018-05
refinedweb
887
77.98
/* Detect stack overflow (when getrlimit and sigaction or sigvec are available) Copyright (C) 1993, 1994, 2006 Free Software Foundation, Inc. Jim Avera <jima@netcom.com>, October */ /* Compiled only when USE_STACKOVF is defined, which itself requires getrlimit with the RLIMIT_STACK option, and support for alternate signal stacks using either SVR4 or BSD interfaces. This should compile on ANY system which supports either sigaltstack() or sigstack(), with or without <siginfo.h> or another way to determine the fault address. There is no completely portable way to determine if a SIGSEGV signal indicates a stack overflow. The fault address can be used to infer this. However, the fault address is passed to the signal handler in different ways on various systems. One of three methods are used to determine the fault address: 1. The siginfo parameter (with siginfo.h, i.e., SVR4). 2. 4th "addr" parameter (assumed if struct sigcontext is defined, i.e., SunOS 4.x/BSD). 3. None (if no method is available). This case just prints a message before aborting with a core dump. That way the user at least knows that it *might* be a recursion problem. Jim Avera <jima@netcom.com> writes, on Tue, 5 Oct 93 19:27 PDT: "I got interested finding out how a program could catch and diagnose its own stack overflow, and ended up modifying m4 to do this. Now it prints a nice error message and exits. How it works: SIGSEGV is caught using a separate signal stack. The signal handler declares a stack overflow if the fault address is near the end of the stack region, or if the maximum VM address space limit has been reached. Otherwise, it returns to re-execute the instruction with SIG_DFL set, so that any real bugs cause a core dump as usual." Jim Avera <jima@netcom.com> writes, on Fri, 24 Jun 94 12:14 PDT: "The stack-overflow detection code would still be needed to avoid a SIGSEGV abort if swap space was exhausted at the moment the stack tried to grow. This is probably unlikely to occur with the explicit nesting limit option of GNU m4." Jim Avera <jima@netcom.com> writes, on Wed, 6 Jul 1994 14:41 PDT: "When a stack overflow occurs, a SIGSEGV signal is sent, which by default aborts the process with a core dump. The code in stackovf.c catches SIGSEGV using a separate signal stack. The signal handler determines whether or not the SIGSEGV arose from a stack overflow. If it is a stack overflow, an external function is called (which, in m4, prints a message an exits). Otherwise the SIGSEGV represents an m4 bug, and the signal is re-raised with SIG_DFL set, which results in an abort and core dump in the usual way. It seems important (to me) that internal m4 bugs not be reported as user recursion errors, or vice-versa." */ #include "m4.h" /* stdlib.h, xmalloc() */ #include <assert.h> #include <sys/time.h> #include <sys/resource.h> #include <signal.h> #if HAVE_SIGINFO_H # include <siginfo.h> #endif #ifndef SA_RESETHAND # define SA_RESETHAND 0 #endif #ifndef SA_SIGINFO # define SA_SIGINFO 0 #endif #ifndef SIGSTKSZ # define SIGSTKSZ 8192 #endif /* If the trap address is within STACKOVF_DETECT bytes of the calculated stack limit, we diagnose a stack overflow. This must be large enough to cover errors in our estimatation of the limit address, and to account for the maximum size of local variables (the amount the trapping reference might exceed the stack limit). Also, some machines may report an arbitrary address within the same page frame. If the value is too large, we might call some other SIGSEGV a stack overflow, masking a bug. */ #ifndef STACKOVF_DETECT # define STACKOVF_DETECT 16384 #endif typedef void (*handler_t) (void); static const char *stackbot; static const char *stackend; static const char *arg0; static handler_t stackovf_handler; /* The following OS-independent procedure is called from the SIGSEGV signal handler. The signal handler obtains information about the trap in an OS-dependent manner, and passes a parameter with the meanings as explained below. If the OS explicitly identifies a stack overflow trap, either pass PARAM_STACKOVF if a stack overflow, or pass PARAM_NOSTACKOVF if not (id est, it is a random bounds violation). Otherwise, if the fault address is available, pass the fault address. Otherwise (if no information is available), pass NULL. Not given an explicit indication, we compare the fault address with the estimated stack limit, and test to see if overall VM space is exhausted. If a stack overflow is identified, then the external *stackovf_handler function is called, which should print an error message and exit. If it is NOT a stack overflow, then we silently abort with a core dump by returning to re-raise the SIGSEGV with SIG_DFL set. If indeterminate, then we do not call *stackovf_handler, but instead print an ambiguous message and abort with a core dump. This only occurs on systems which provide no information, but is better than nothing. */ #define PARAM_STACKOVF ((const char *) (1 + STACKOVF_DETECT)) #define PARAM_NOSTACKOVF ((const char *) (2 + STACKOVF_DETECT)) static void process_sigsegv (int signo, const char *p) { long diff; diff = (p - stackend); #ifdef DEBUG_STKOVF { char buf[140]; sprintf (buf, "process_sigsegv: p=%#lx stackend=%#lx diff=%ld bot=%#lx\n", (long) p, (long) stackend, (long) diff, (long) stackbot); write (2, buf, strlen (buf)); } #endif if (p != PARAM_NOSTACKOVF) { if ((long) sbrk (8192) == (long) -1) { /* sbrk failed. Assume the RLIMIT_VMEM prevents expansion even if the stack limit has not been reached. */ write (2, "VMEM limit exceeded?\n", 21); p = PARAM_STACKOVF; } if (diff >= -STACKOVF_DETECT && diff <= STACKOVF_DETECT) { /* The fault address is "sufficiently close" to the stack lim. */ p = PARAM_STACKOVF; } if (p == PARAM_STACKOVF) { /* We have determined that this is indeed a stack overflow. */ (*stackovf_handler) (); /* should call exit() */ } } if (p == NULL) { const char *cp; cp = "\ Memory bounds violation detected (SIGSEGV). Either a stack overflow\n\ occurred, or there is a bug in "; write (2, cp, strlen (cp)); write (2, arg0, strlen (arg0)); cp = ". Check for possible infinite recursion.\n"; write (2, cp, strlen (cp)); } /* Return to re-execute the instruction which caused the trap with SIGSEGV set to SIG_DFL. An abort with core dump should occur. */ signal (signo, SIG_DFL); } #if HAVE_STRUCT_SIGACTION_SA_SIGACTION /* POSIX. */ static void sigsegv_handler (int signo, siginfo_t *ip, void *context) { process_sigsegv (signo, (ip != NULL && ip->si_signo == SIGSEGV ? (char *) ip->si_addr : NULL)); } #elif HAVE_SIGINFO_T /* SVR4. */ static void sigsegv_handler (int signo, siginfo_t *ip) { process_sigsegv (signo, (ip != NULL && ip->si_signo == SIGSEGV ? (char *) ip->si_addr : NULL)); } #elif HAVE_SIGCONTEXT /* SunOS 4.x (and BSD?). (not tested) */ static void sigsegv_handler (int signo, int code, struct sigcontext *scp, char *addr) { process_sigsegv (signo, addr); } #else /* not HAVE_SIGCONTEXT */ /* OS provides no information. */ static void sigsegv_handler (int signo) { process_sigsegv (signo, NULL); } #endif /* not HAVE_SIGCONTEXT */ /* Arrange to trap a stack-overflow and call a specified handler. The call is on a dedicated signal stack. argv and envp are as passed to main(). If a stack overflow is not detected, then the SIGSEGV is re-raised with action set to SIG_DFL, causing an abort and coredump in the usual way. Detection of a stack overflow depends on the trap address being near the stack limit address. The stack limit can not be directly determined in a portable way, but we make an estimate based on the address of the argv and environment vectors, their contents, and the maximum stack size obtained using getrlimit. */ void setup_stackovf_trap (char *const *argv, char *const *envp, handler_t handler) { struct rlimit rl; rlim_t stack_len; int grows_upward; register char *const *v; register char *p; #if HAVE_SIGACTION && defined SA_ONSTACK struct sigaction act; #elif HAVE_SIGVEC && defined SV_ONSTACK struct sigvec vec; #else Error - Do not know how to set up stack-ovf trap handler... #endif arg0 = argv[0]; stackovf_handler = handler; /* Calculate the approximate expected addr for a stack-ovf trap. */ if (getrlimit (RLIMIT_STACK, &rl) < 0) error (EXIT_FAILURE, errno, "getrlimit"); stack_len = (rl.rlim_cur < rl.rlim_max ? rl.rlim_cur : rl.rlim_max); stackbot = (char *) argv; grows_upward = ((char *) &stack_len > stackbot); if (grows_upward) { /* Grows toward increasing; } else { /* The stack grows "downward" (toward decreasing; } /* Allocate a separate signal-handler stack. */ #if HAVE_SIGALTSTACK && (HAVE_SIGINFO_T || ! HAVE_SIGSTACK) /* Use sigaltstack only if siginfo_t is available, unless there is no choice. */ { stack_t ss; ss.ss_size = SIGSTKSZ; ss.ss_sp = xmalloc ((unsigned) ss.ss_size); ss.ss_flags = 0; if (sigaltstack (&ss, NULL) < 0) { /* Oops - sigaltstack exists but doesn't work. We can't install the overflow detector, but should gracefully treat it as though sigaltstack doesn't exist. For example, this happens when compiled with Linux 2.1 headers but run against Linux 2.0 kernel. */ free (ss.ss_sp); if (errno == ENOSYS) return; error (EXIT_FAILURE, errno, "sigaltstack"); } } #elif HAVE_SIGSTACK { struct sigstack ss; char *stackbuf = xmalloc (2 * SIGSTKSZ); ss.ss_sp = stackbuf + SIGSTKSZ; ss.ss_onstack = 0; if (sigstack (&ss, NULL) < 0) { /* Oops - sigstack exists but doesn't work. We can't install the overflow detector, but should gracefully treat it as though sigstack doesn't exist. For example, this happens when compiled with Linux 2.1 headers but run against Linux 2.0 kernel. */ free (stackbuf); if (errno == ENOSYS) return; error (EXIT_FAILURE, errno, "sigstack"); } } #else /* not HAVE_SIGSTACK */ Error - Do not know how to set up stack-ovf trap handler... #endif /* not HAVE_SIGSTACK */ /* Arm the SIGSEGV signal handler. */ #if HAVE_SIGACTION && defined SA_ONSTACK sigaction (SIGSEGV, NULL, &act); # if HAVE_STRUCT_SIGACTION_SA_SIGACTION act.sa_sigaction = sigsegv_handler; # else /* ! HAVE_STRUCT_SIGACTION_SA_SIGACTION */ act.sa_handler = (RETSIGTYPE (*) (int)) sigsegv_handler; # endif /* ! HAVE_STRUCT_SIGACTION_SA_SIGACTION */ sigemptyset (&act.sa_mask); act.sa_flags = (SA_ONSTACK | SA_RESETHAND | SA_SIGINFO); if (sigaction (SIGSEGV, &act, NULL) < 0) error (EXIT_FAILURE, errno, "sigaction"); #else /* ! HAVE_SIGACTION */ vec.sv_handler = (RETSIGTYPE (*) (int)) sigsegv_handler; vec.sv_mask = 0; vec.sv_flags = (SV_ONSTACK | SV_RESETHAND); if (sigvec (SIGSEGV, &vec, NULL) < 0) error (EXIT_FAILURE, errno, "sigvec"); #endif /* ! HAVE_SIGACTION */ }
http://opensource.apple.com/source/gm4/gm4-13/m4/src/stackovf.c
CC-MAIN-2016-30
refinedweb
1,572
57.06
How to: Notify an Application When an Item Is Removed from the Cache In most cache scenarios, when an item is removed from the cache, you do not have to be notified when it has been removed. The typical development pattern is to always check the cache for the item before using it. If the item is in the cache, you use it. If it is not in the cache, you retrieve the item again and add it back to the cache. However, in some cases it is useful for your application to be notified when an item is removed from the cache. For example, you might want to track when and why items are removed from the cache in order to tune cache settings. To enable notification of items being removed from the cache, ASP.NET provides the CacheItemRemovedCallback delegate. The delegate defines the signature for an event handler to call when an item is removed from the cache. Typically, you implement the callback by creating a handler in a business object that manages the cache data. To notify an application after an item is removed from the cache In a business class (not in a page or user control class), create a method that handles the callback when a cache item is removed. The method must have the same signature as the CacheItemRemovedCallback delegate. You must make sure that this method is available when the cache item is deleted. Using a static class is one way to accomplish this. Note that in a static class, all static methods must be thread-safe. Because the methods that add items to the cache and get items from the cache do not have to be available when the cache item is removed, it is common to put them in a separate class from the one that contains the callback handler. In the callback method, add logic that will run when the item is removed from the cache. The following example shows a class named ReportManager. The GetReport method of this class creates a report that consists of the string "Report Text". The method saves this report in the cache, and on subsequent calls it retrieves the report from the cache. If more than 15 seconds elapses between calls to GetReport, ASP.NET removes the report from the cache. When that event occurs, the ReportRemovedCallback method of the ReportManager class is called. This method sets a private member variable to "Re-created [date and time]", where [date and time] is the current date and time. The next time that GetReport is called after the cache item has expired, the method re-creates the report and appends the value of the variable that was set by the ReportRemovedCallback method to the report. The ShowReport.aspx page displays the report string that GetReport returns, which includes the date and time that the report was last re-created. To see this behavior, load the page, wait more than 15 seconds, and then reload the page in the browser. You will see the date and time added to the report text. using System; using System.Text; using System.Web; using System.Web.Caching; public static class ReportManager { private static string _lastRemoved = ""; public static String GetReport() { string report = HttpRuntime.Cache["MyReport"] as string; if (report == null) { report = GenerateAndCacheReport(); } return report; } private static string GenerateAndCacheReport() { string report = "Report Text. " + _lastRemoved.ToString(); HttpRuntime.Cache.Insert( "MyReport", report, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 15), CacheItemPriority.Default, new CacheItemRemovedCallback(ReportRemovedCallback)); return report; } public static void ReportRemovedCallback(String key, object value, CacheItemRemovedReason removedReason) { _lastRemoved = "Recreated " + DateTime.Now.ToString(); } } <%@ Page <html xmlns=""> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <%=ReportManager.GetReport() %> </div> </form> </body> </html>
https://msdn.microsoft.com/en-us/library/7kxdx246(v=vs.90).aspx
CC-MAIN-2016-50
refinedweb
620
64.1
Recently I had the privilege of writing an article for Java Tech Journal about using HTML5 Server Sent Events in a JSF 2 User Interface. I've made that article available here.: import javax.inject.Inject; .... @ManagedBean @SessionScoped public class UserNumberBean implements Serializable { @Inject private Count count; ... public String getCount() { if (null != count) { return count.getCount(); } else { return ""; } } ... } Cheers... My slides for "Exploring HTML5 With JavaServer Faces 2.0" slides are available at Slideshare: Available at:. All you need to do is fire up a browser and visit: . With this, you'll see a nice breakdown of the features that are available in the current browser version. It will also tell you, the strengh of support for each feature. For example, for the current version of Firefox I'm using (3.6.3), it says it has a total score of 101 out of 160. Here's a breakdown for each of the current browsers I'm using: Of course if you really like an HTML5 feaure that is not available in your favorite browser, you can always check the "development" versions for the browser - as HTML5 support is still a work in progress.. The application just prompts for a user name / pasword, and pressing the submit button sends those values to a servlet. First, let's take a look at some of the supporting code for the application: This is just one example of Web Bean injection into a servlet. There are more areas in the JavaEE6 platform that can be used as Web Bean injection points - topics that will certainly be covered in future posts. The sample for this blog can be found under the glassfish-samples project. You can check out the code following these instructions. Once the workspace is checked out, you can find this sample under glassfish-samples/ws/javaee6/webbeans/webbeans-servlet. You can find documentation for the sample under glassfish-samples/ws/javaee6/webbeans/webbeans-servlet/docs. As with all the Web Beans samples now, you should run with GlassFish V3 - any build after September 2 2009.. Everything on this page is really just standard JSF 2.0 view markup. I've emphasized the Expression Language (EL) portions of the view, especially game because it refers to a contextual bean instance also known as a Web Bean. As you can see, in JSF, binding to a Web Bean is no different than binding to a typical managed bean. Let's take a look at some of the utility classes for the application, namely the classes that are used to generate a random number and some of the supporting annotations. The JSR 330 @Qualifier annotation is used to make Random a binding type. This will allow us to inject a random number into the application. Likewise, the @Qualifier annotation is used to make MaxNumber a binding type that will allow us to inject the maximum number allowed (for a guess) in the application. Now that we have are utility classes and annotations in place, we can use them in our Web Bean. I've color coded the areas of interest in this class. The blue areas are JSR 299 (Web Beans) implementation details. The red areas are JSR 330 (Dependency Injection For Java) areas. The purple areas are the binding types.. The session will explore the variety of JSF Ajax frameworks available today. Then you will get a preview of the Ajax work that is being standardized in the JSF 2.0 specification.. We're definitely exploring new territory here, as this is the first time that a public JavaScript API has been introduced with JavaServer Faces to the JCP. It may be the first time a public JavaScript API has been introduced to the JCP, period.
https://community.oracle.com/blogs/rogerk
CC-MAIN-2016-07
refinedweb
623
64.51
As more and more repositories start to incorporate MyBinder / repo2docker build specifications, more and more building blocks start to appear for how to get particular things running in MyBinder. For example, I have several ouseful-template-repos with various building blocks for getting different databases running in MyBinder, and occasionally require an environment that also loads in a Jupyter-server-proxied application, such as OpenRefine. Other times, I might want to pull in the config for a partculalry ast install, or merge configs someone else has developed to run different sets of notbooks in the same Binderised repo. But: a problem arises if you want to combine multiple Binder specifications from various repos into a single Binder setup in a single repo – how do you do it? One way might be for repo2docker to itereate through multiple build steps, one for each Binder specification. There may be clashes, of course, such as conflicting package versions from different specifications, but it would then fall to the user to try to resolve the issue. Which is fine, if Binder is making a best attempt rather than guaranteeing to work. Assuming that such a facility does not exist, it would require updates to repo2docker, so that’s not something we can easily hack around with ourselves. So how about something where we try to combine the contents of multiple binder/ setup directories ourselves. This is something we can start to do easily enough ourselves, and as a personal tool doesn’t necessarily have to work “properly” and “for everything”: for starters, it only has to work with what we want it to work with. And if it only works so far, getting 80% of the way to a working combined configuration that’s fine too. So what would we need to do? Simple list files like apt.txt and requirements.txt could be simply concatenated together, leaving it up to pip to do whatever it does with any clashes in pinned package numbers, for example (though we may want to report possible clashes, perhaps via a comment in the file, to help the user debug things). In a shell script, something like the following would concatenate files in directories binder_1, binder_2, etc.: for i in $(ls -d binder_*) do echo >> binder/apt.txt echo "# $i" >> binder/apt.txt cat "$i/requirements.txt" >> binder/apt.txt done In Python, something like: import os with open('binder/requirements.txt', 'w') as outfile: for d in [d for d in os.listdir() if d.startswith('binder_') and os.path.isdir(d)]: # Should test: if 'requirements.txt' in os.listdir(d) with open(os.path.join(d, 'requirements.txt')) as infile: outfile.write(f'\n#{d}\n') outfile.write(infile.read()) Merging environment.yml files is a little trickier — the structure within the file is hierarchical — but a package like hiyapyco can help us with that: import hiyapyco import fnmatch _envs = [os.path.join(d, e) for e in [d for d in os.listdir() if d.startswith('binder_') and os.path.isdir(d)] if fnmatch.fnmatch(e, '*.y*ml')] merged = hiyapyco.load(_envs, method=hiyapyco.METHOD_MERGE, interpolate=True) with open('binder/environment.yml', 'w') as f: f.write(hiyapyco.dump(merged)) There is an issue with environments where we have both environment.yml and requirements.txt files because the environments.yml trumps requirements.txt: the former will run but the latter won’t. A workaround I have used in the past for installing from both is to call install from the requirements.txt file by using a directive in the postBuild file to handle the requirements.txt installation. I’ve also had to use a related trick to install a really dependent Python package explicitly via postBuild and then install from a renamed requirements.txt also via postBuild: the pip installer installs packages in whatever order it wants, and doesn’t necessarily follow any order “specified” in the requirements.txt file. This means that on certain occasions, a build can fail becuase one Python package is relying on another which is specified in the requirements.txt file but hasn’t been installed yet. Another approach might be to grab any requirements from a (merged) requirements.txt file into an environment.yml file. For example, we can create a “dummy” _environment.yml file that will install elements from our requirements file, and then merge that into an existing environments.yml file. (We’d probbaly guard this with a check that both environment.y*ml and requirements.txt are in binder/): _yaml = '''dependencies: - pip - pip: ''' # if 'requirements.txt' in os.listdir() and 'environment.yml' in os.listdir(): with open('binder/requirements.txt') as f: for item in f.readlines(): if item and not item.startswith('#'): _yaml = f'{_yaml} - {item.strip()}\n' with open('binder/_environment.yml', 'w') as f: f.write(_yaml) merged = hiyapyco.load('binder/environment.yml', 'binder/_environment.yml', method=hiyapyco.METHOD_MERGE, interpolate=True) with open('binder/environment.yml', 'w') as f: f.write(hiyapyco.dump(merged)) # Maybe also now delete requirements.txt? For postBuild elements, different postBuild files may well operate in different shells (for example, we may have one that executes bash code, another that contains Python code). Perhaps the simplest way of “merging” this is to just copy over the separate postBuild files and generate a new one that calls each of them in turn. import shutil postBuild = '' for d in [d for d in os.listdir() if d.startswith('binder_') and os.path.isdir(d)]: if 'postBuild' in os.listdir(d) and os.path.isfile(os.path.join(d, 'postBuild')): _from = os.path.join(d, 'postBuild') _to = os.path.join('binder', f'postBuild_{d}') shutil.copyfile(_from, _to) postBuild = f'{postBuild}\n./{_to}\n' with open('binder/postBuild', 'w') as outfile: outfile.write(postBuild) I’m guessing we could do the same for start? If you want to have a play, the beginnings of a test file can be found here (for some reason, WordPress craps all over it and deletes half of it if I try to embed it in the sourcecode block etc. (I really should move to a blogging platform that does what I need…)
https://blog.ouseful.info/tag/repo2docker/
CC-MAIN-2021-21
refinedweb
1,026
60.72
While learning C++, sooner or later you will run into the this pointer. This article explains its use on three groups of examples, namely: To illustrate the concept of the this pointer we are going to use a class called Account. For the moment the class has only one member variable 'amount'. Apart from the standard get and set method, notice an extra method in the header called getAddress(), which returns the this pointer. #ifndef ACCOUNT_H #define ACCOUNT_H class Account { public: void setAmount(double amount); double getAmount() const {return this->amount;} Account* getAddress() {return this;} private: double amount; }; #endif // ACCOUNT_H #include "account.h" void Account::setAmount(double a){ amount = a; } To show you the meaning of this pointer, I am going to instantiate one Account object with the use of the default constructor and call its getAddress() method, as illustrated in the main.cpp: #include <iostream> #include "account.h" int main() { Account ac; std::cout << ac.getAddress() << '\n'; return 0; } You can see the output of the program below. 0x28ff38 The program outputs an address (most probably you are going to get a different address than me, since you are using a different computer). This pointer gives us an address of an instantiated object! It gives us a way to refer to the instantiated object itself. Note: this pointer gives you an address of an object, while *this gives you the object residing at the address this. Now that we shed a bit of light on the 'this' pointer, we are going to look at its first use, i.e. to distinguish between member variables and method parameters. We are going to do that with the help of the method setAmount(double). Notice the current implementation of the setAmount() method. To distinguish between the method parameter and the member variable, we are using the name 'a' for the method parameter and the name 'amount' for the member variable. void Account::setAmount(double a){ amount = a; } Since we now know a bit more about the 'this' pointer, we are going to write the setAmount() method in a different way. In this new approach, we are going to rename the method parameter 'a' to 'amount'. Of course, now we have a problem because the method parameter has the same name as the member variable. How are we going to solve this? We are going to use the pointer this to distinguish between them. The new 'name' of the member variable is this->amount. You can see the new method below: void Account::setAmount(double amount){ this->amount = amount; } How useful! As a result, we do not have to come up with different names for method parameters and member variables for set methods. To show you the next use of the this pointer we are going to introduce an extra member variable called the interest rate and the corresponding set method. We are also going to add a method called addAnnualInterest(). The method increases the value of the current amount by the annual interest according to the following formula: amount = amount * (1 + interest rate) The header and the source file are shown below. Notice that the addAnnualInterest() method returns a reference to the modified Account object, hence the line 'return *this'. #ifndef ACCOUNT_H #define ACCOUNT_H class Account { public: void setAmount(double amount); double getAmount() const {return this->amount;} void setInterestRate(double interestRate); Account& addAnnualInterest(); private: double amount; double interestRate; }; #endif // ACCOUNT_H #include "account.h" void Account::setAmount(double amount){ this->amount = amount; } void Account::setInterestRate(double interestRate){ this->interestRate = interestRate; } Account& Account::addAnnualInterest(){ this->amount = this->amount*(1 + this->interestRate); return *this; } Why do we return a reference to the modified Account object, when we could have simply declared the addAnnualInterest() method as void, increased the amount and returned nothing at all? The reply is because by returning a reference we have the possibility of method chaining. You can see the example of method chaining in the main.cpp below. Because the method addAnnualInterest() returns a reference to the modified object, we can now call the same method multiple times in a chain and modify the object by the amount of interest after several years (in this case three method calls = three years). If we had declared the method as void, we would not have been able to perform method chaining. #include <iostream> #include "account.h" int main() { Account ac; ac.setAmount(1000.0); ac.setInterestRate(0.1); ac.addAnnualInterest().addAnnualInterest().addAnnualInterest(); std::cout << ac.getAmount() << '\n'; return 0; } The output of this program is 1331, which was internally computed in the following way: amount1 = 1000*(1+0.1) = 1100 amount2 = 1100*(1+0.1) = 1210 amount3 = 1210*(1+0.1) = 1331 The last use of the 'this' pointer that we are going to look at is operator overloading. Just like with method chaining, our aim is to increase the amount on the account after several years by the amount of annual interest. However, unlike in the case of method chaining, we are not going to introduce addAnnualInterest() method, but rather overload the operator *= to accomplish the same thing. Notice the header and source file below. As we are going to use a general multiplier, we removed the member variable interest rate, Moreover, we added operator*=(double multiplier) that takes the current amount, multiplies it and returns a reference to the modified object (return *this). This is performed in a similar manner to the addAnnualInterest() method. The multiplier is simply: multiplier = 1 + interest rate #ifndef ACCOUNT_H #define ACCOUNT_H class Account { public: void setAmount(double amount); double getAmount() const {return this->amount;} Account& operator*=(double multiplier); private: double amount; }; #endif // ACCOUNT_H #include "account.h" void Account::setAmount(double amount){ this->amount = amount; } Account& Account::operator*=(double multiplier){ this->amount = this->amount * multiplier; return *this; } The main.cpp below illustrates the use of the operator*=. #include <iostream> #include "account.h" int main() { Account ac; ac.setAmount(1000.0); ac*=1.1; ac*=1.1; ac*=1.1; //((ac*=1.1)*=1.1)*=1.1; std::cout << ac.getAmount() << '\n'; return 0; } Similarly to the method chaining example the output of the program is 1331 (amount with interest after three years), which we got in the following way: amount1 = 1000*1.1 = 1100 amount2 = 1100*1.1 = 1210 amount3 = 1210*1.1 = 1331 The commented section shows that it is also possible to do this in one row, however we shall not forget the parentheses.
http://walletfox.com/course/thispointer.php
CC-MAIN-2017-39
refinedweb
1,069
54.32
I just released the latest Antipasto Arduino for Windows, Linux, and Mac OS X x86. The IDE is available for download on illuminatolabs. Along with a number of code "housekeeping" updates, there were a couple larger changes: - Fixes for Gadget File loads and board switches (issue #3, issue #4 , issue #7) Thanks Joao! - New TouchShield TButton library and ButtonDialog example sketch for that library Chris added the TButton library after several people asked about projects that use the TouchShield Slide as a menu system. Writing code for custom touchscreen buttons was part of what made the TouchShield so useful (instead of having real buttons), and it was actually something that came up quite some time ago. Actually, Matt and I remixed the original BitDJ code to create a TouchShield app to make breakfast. Here’s the simple ButtonDialog example I’ve included: And this is the code: #include <TButton.h> TButton ok = TButton("Ok",20,80); TButton cancel = TButton("Cancel",80,80); void setup() { ok.Paint(); cancel.Paint(); } void loop() { if (ok.GetTouch()) { stroke(255); fill(0); text("Pressed 'Ok' ", 10, 30); } if (cancel.GetTouch()) { stroke(255); fill(0); text("Pressed 'Cancel'", 10, 30); } } Of course, TButton is just a basic library to make it easier to get started with menus. I think the next step is to make it easier to crop and upload images as buttons, much like Alain’s ArdTouch project that mimics an iPhone interface. I’d love to check out other cool Slide menu projects and code too – jhuynh at gmail 6 comments: whoa i love those icons... Great... I have written quite a bit or code, first in processing, still waiting for my slide to be delivered. Its ported overto the Arduino enviroment, but not tested yet although it worked well inside processing. Basicly its a kind of menu/tool bar system menu disapears after 5 seconds of non use and gives its space up to the current selected screen. I've made a spread sheet widget which can display data in simple xls spreadsheet style(scroll bars clicking on cells etc). A keyboard based upon a phone that you can hit keys a few times and they alternate between numbers and text etc. Also a charting app for drawing line (etc) charts... it shars data with the table so you can switch between the two and see how things change. If anyone is interested to see the code already they are welcome... I've not yet tried it on the sheild but it compiles and did work nicly under processing. Anyone want a try it in processing I can share the sketch. Neil @ndudman ... um, i'd definitely like to try it out on my slide too... inthebitz at gmail. how'd you do the line charting? Hi Justin! Thanks for the article ! I just precise that all the code (for arduino, TouchShield, and Windows) is here (same site). I'll resume working on the ardTouch when I have finished a current project and post you with latest updates. Cheeers! I'm having problems uploading code to Mega using the new Lunux build mentioned in this blog. I get [exec] avrdude: stk500_recv(): programmer is not responding [exec] avrdude: stk500_2_ReceiveMessage(): timeout [exec] avrdude: stk500_2_ReceiveMessage(): timeout ... Using normal Arduino 017 I can upload ok to Mega. I've tried with the slide connected and disconnected, both the same. The board.txt is the same for working 17 and the latest Antipasto... any ideas on what to try ? @Matt Heres a video of it working on processing... I'm afraid I havn't got it working yet with TouchSlide... but can email you the processing stuff to look at.
http://antipastohw.blogspot.com/2010/01/antipasto-arduino-0838-released-with.html?showComment=1263035371567
CC-MAIN-2017-13
refinedweb
613
72.87
Sharing the goodness… Beth Massi is a Senior Program Manager on the Visual Studio team at Microsoft and a community champion for .NET developers. Learn more about Beth. More videos » NOTE: This is the Visual Studio 2012 version of the popular Beginning LightSwitch article series. For other versions see: Welcome to Part 6 of the Beginning LightSwitch in Visual Studio 2012 series! In parts 1 thru 5 we built an Address Book application and learned all about the major building blocks of a Visual Studio LightSwitch application -- entities, relationships, screens, queries and user permissions. If you missed them: In this post I want to talk about extensions. Extensions allow you to do more with LightSwitch than what’s “in the box”. There are all kinds of extensions for doing all kinds of stuff. There are additional themes and shells you can download for changing the colors, fonts and styles of all the visual elements in the user interface. There are also fancy controls you can use for visualizing your data, additional business types to add to your entity designer, and there are even extensions that help you work with documents, design client-side reports, and even automate Microsoft Office. These extensions are provided by trusted component vendors as well as the global community, most are free, some are pay. You can browse through the LightSwitch extensions online on the Visual Studio Gallery. What makes this possible is LightSwitch provides an entire extensibility framework so that professional developers can write extensions to enhance the LightSwitch development experience. If you are a code-savvy, professional .NET developer. then you can create your own extensions. For more information on creating extensions see the Extensibility section of the LightSwitch Developer Center. Keep in mind that extensions are Visual Studio version specific so if an extension doesn’t support a certain version of Visual Studio, then it will notify you when you try to install it. Luckily, you don’t need to be a hardcore programmer to use extensions. They are easy to find and install. Just open “Extensions and Updates…” from the Tools menu. A window will come up and display all your installed extensions. Select the “Online Gallery” tab to choose from all the extensions from the Visual Studio Gallery. Enter “LightSwitch” in the filter to see just the LightSwitch extensions. You can also download these extensions directly from the Visual Studio Gallery. Select the extension you want and click the download button to install. For our Address Book application I’d like to add the ability to import contacts from Excel spreadsheets. LightSwitch has built-in functionality to export all data in grids to Excel but it lacks an import feature. Luckily the Office Integration Pack is a free extension that has this feature. If you sort by popularity you will see it near the top. I highly recommend this extension for working with Office. After you download and install any extension, you need to enable them on a per-project basis in LightSwitch. Open the project properties by right-clicking on the project in the Solution Explorer and select “Properties”. Then select the “Extensions” tab to enable the extension. For our Address Book application, enable the Office Integration Pack extension. Also notice that there is the “Microsoft LightSwitch Extensions” also in this list which is always enabled and used in new projects. This is an extension that is included with the LightSwitch install and contains the business types Email Address, Phone Number, Percent, Web Address, Money and Image that you can use when defining your data entities like we did in Part 1. You should never have to disable these. There is also the Cosmo theme and shell that we’ve been using in this series that enables that look-and-feel for new projects. Depending on what your extension does, there are different ways to use them. You’ll need to refer to the specific documentation for the extension. Some controls you can literally drop right in and use them without having to write any code. The Office Integration Pack makes it super-easy to automate Office but we need to write a line of code to get the import feature to work. (See the documentation on all the things you can do with it.) In order to allow uploading contacts from an Excel spreadsheet, create a new screen like we did in Part 3 and select the Editable Grid Screen template. Then select the Contacts as the screen data. In the Screen Designer, expand the Screen Command Bar and add a new button. Call it “ImportContacts” and click OK Now right-click on the button and select “Edit Execute Code”. Then write this one line of code (in bold) into the method stub. VB: Namespace LightSwitchApplication Public Class EditableContactsGrid Private Sub ImportContacts_Execute() ' Write your code here. OfficeIntegration.Excel.Import(Me.Contacts) End Sub End Class End Namespace C#: namespace LightSwitchApplication { public partial class EditableContactsGrid { partial void ImportContacts_Execute() { // Write your code here. OfficeIntegration.Excel.Import(this.Contacts); } } } Next make sure you have the permission to add Contacts into the system. Remember in Part 5 we set up a permission to check for this. Go into the project properties and on the Access Control tab make sure you have granted the CanAddContacts permission for debug. (You can also disable the import button if the user does not have permission to add contacts by adding a permission check to the button’s CanExecute method.) Now run it by hitting F5. Open the screen and click the Import Contacts button. The Office Integration Pack will prompt you for a spreadsheet and ask you how you want to map the columns it finds inside to the properties on your Contact entity. Pretty slick for just one line of code. As you can see it’s easy to download and enable LightSwitch extensions in Visual Studio 2012 in order to do all sorts of things that aren’t available right out of the box. LightSwitch provides an entire extensibility model that allows the community to create all kinds of extensions that enhance the LightSwitch development experience that you can take advantage of. If you’re a code-savvy developer that wants to create your own extensions, head to the LightSwitch Extensibility section of the Visual Studio Developer Center to get set up and then read the Extensibility documentation. You can also download the competed sample application we built in this article series. Well that wraps up what I planned for the Beginning LightSwitch in Visual Studio 2012 Series! I hope you enjoyed it and I hope it has helped you get started building your own LightSwitch applications with Visual Studio 2012. For more LightSwitch training please see the LightSwitch section of the Visual Studio Developer Center. In particular, I recommend going through my “How Do I” videos next. Enjoy! Very explanatory Beth. I get a warning when adding the OfficeIntegration Import method to a button. It relates the runtime error is "Unable to cast object of type 'LightSwitchApplication.TableEntity' to type 'Microsoft.LightSwitch.Client.IVisualCollection'. Any ideas? Great job with the article and look forward to more. Hi Beth thanks for spending your valuable time to share this technology with us. its crystal clear and easy to follow Great job. Hi Beth, what if i want to show a combobox for a EntityFramework6 enum Type property? I think this is a widespread question among newbies like me. I needed to exit VS and restart to see the extension in the Project Properties/Extensions panel Thanks for your great job! However,this method is only work for single table without any relations, How can I import my data via excel in multi-relation tables? Thanks a lot!!!
http://blogs.msdn.com/b/bethmassi/archive/2012/08/15/beginning-lightswitch-in-vs-2012-part-6-go-beyond-the-box-customizing-lightswitch-apps-with-extensions.aspx
CC-MAIN-2015-35
refinedweb
1,291
63.59
Simple SSAO - A 1-class solution for SSAO. Description To have SSAO in OGRE usually you need tons of code and shaders, well nullsquared posted a demo that avoided that, and it provided a pretty decent quality, so this is his code, converted into 1 easy to use class, which can provide your application with SSAO with only 1 line of code (2 including the header "include" statement). See MOGRE Simple SSAO for Mogre source code. Download You can find the full pre-compiled demo + source here. Usage Instructions 1. Add the sub-directories in the 'data/ssao/materials' directory to your resource locations. 2. Derive all your materials from diffuse_template like so: import diffuse_template from "diffuse.material" material sibenik/poplocenje : diffuse_template { technique { pass { ambient 0 0 0 1 diffuse 0.65098 0.647059 0.596078 1 texture_unit { texture KAMEN320x240.jpg } } } } The above example uses one of sibenik's (the "church" in the Deferred Shading Demo) materials. (You need to do this for all of the materials you wish to be affected by the SSAO compositor.) 3. Add this to your code: PFXSSAO* mSSAO = new PFXSSAO(mWindow, mCamera); Assuming that mWindow is the render window, and mCamera is of course - the camera. (And they're initialized) That's it! After that, you've got SSAO on your scene. Screenshots Credits and related Forum topics SimpleSSAO - 1 Line SSAO SSAO (Screen Space Ambient Occlusion) Demo + Source SSAO Compositor See Also Implementing SSAO in Mogre
https://wiki.ogre3d.org/Simple+SSAO
CC-MAIN-2022-21
refinedweb
243
56.15
#. The components required to develop basic CLR database objects are installed with SQL Server 2005. CLR integration functionality is exposed in an assembly called system.data.dll, which is part of the .NET Framework. This assembly can be found in the Global Assembly Cache (GAC) as well as in the .NET Framework directory. A reference to this assembly is typically added automatically by both command line tools and Microsoft Visual Studio, so there is no need to add it manually. The system.data.dll assembly contains the following namespaces, which are required for compiling CLR database objects: System.Data System.Data.Sql Microsoft.SqlServer.Server System.Data.SqlTypes Copy and paste the following Visual C# or Microsoft Visual Basic modify your path variable to point to the directory containing csc.exe or vbc.exe. The following is the default installation path of the .NET Framework. sample database). The ability to execute common language runtime (CLR) code is set to OFF by default in SQL Server 2005. The CLR code can be enabled by using the sp_configure system stored procedure. For more information, see Enabling CLR Integration. We will need to create the assembly so we can access the stored procedure. For this example, we will assume that you have created the helloworld.dll assembly in the C:\ directory. Add the following Transact-SQL statement to your query..
http://msdn.microsoft.com/en-US/library/ms131052(v=sql.90).aspx
CC-MAIN-2014-15
refinedweb
227
50.33
You can view these four specifications at the W3C Web site (.) XLink is part of the XML standard that currently defines the linking components of XML. XLink is similar to the functionality of the <a> tag in HTML in that XLink allows elements to be inserted into XML documents to create links between resources. XLink also has additional features. XPath is a language that views the XML document as a tree with nodes. Using XPath, you can locate any node in the XML document tree. XPointer provides a way to address the internal structure of an XML document. XPointer extends XPath by allowing you to address points and ranges in addition to nodes, locate information by string matching, and use addressing expressions in URI-references as fragment identifiers. XLink works with either XPath or XPointer. The XPath or XPointer language is used to define where you want to link in an XML document, and XLink will provide the actual link to that point in the document. Namespaces are also an important part of the XML specification. When creating DTDs or schemas from multiple documents, you need a way to define where each definition originated. This is especially important if two external documents use the same name for an element, but each is defining a different element. For example, title could refer to Mr., Mrs., and Miss in one DTD and to the title of the document in another DTD. If you merged these two DTDs, you would have a name conflict. Namespaces prevent this conflict from happening. In this tutorial, we'll begin by looking at namespaces and then move on to the XPath, XPointer, and XLink languages. NOTE At the time of this writing, the specifications for XLink and XPointer are still being reviewed, and it's possible that some of the syntax will change. The overall structure of XPointer, XPath, and XLink should not change.
https://www.brainbell.com/tutors/XML/XML_Book_B/XML_Namespace_XPath_XPointer_and_XLink.htm
CC-MAIN-2019-18
refinedweb
317
64
I 02:43 PM 5/12/2001 -0500, Ian Bicking wrote: >Here's pertinant parts of the Classes.csv file: > >Class,Attribute,Type,isRequired,Min,Max,Extras, >Portfolio,,,,,,, >,pieces,list of Piece,0,,,, >,representativePiece,Piece,0,,,, >Piece,name,string,1,1,30,, >,portfolio,Portfolio,1,,,, > >The important part is that Pieces are contained in Portfolios, but >each Portfolio has a representative Piece (which will be used for the >Portfolio's icon). I feel like MK is inferring the relation between >the objects incorrectly in this case -- there just isn't enough >information in this description for MK to figure out what's going on, >really. I'm getting a weird bug as a result, which in itself probably >isn't interesting or helpful. So how should I deal with this? Should >I have representativePiece be an int, and do the lookup myself? This will be fixed in general when I (or Geoff) rehash MK's list policies and code. In the current MK, Piece.portfolio is seen as a back reference to Portfolio for the purposes of the pieces list. If you don't need a back ref from the representativePiece to the Portfolio that owns it, then you can create those rep pieces without a Portfolio ref and everything should be fine. Does that get you by for now? -Chuck At 08:38 PM 5/9/2001 -0500, Ian Bicking wrote: >Instead of deleting objects, I'm marking them as hidden. So I'm >creating special thumbnails whenever the hidden attributes of a MK >object is changed. I'm doing something like this: > >class Piece(GenPiece): > [...] > def setHidden(self, hidden): > if self.hidden() != hidden: > [create or delete thumbnail] > GenPiece.setHidden(self, hidden) > >But it seems like this is happening maybe everytime the object is >created -- like the store sets the hidden attribute via setHidden, >instead of directly writing the attribute. Is this the case? > >If so, is there some way I can tell if the object is being changed, >rather than just constructed? Yes it does use setFoo() to set foo upon reading. In the future I would like to use readFoo() first and then setFoo() if the "read" is not available. That way you could customize unarchiving behavior vs. ordinary use behavior. In the mean time, you can check self.__mk_initing to see if you are being created. Let me know if that works fo ryou. -Chuck At 09:02 PM 3/11/2001 +0000, Stephan Diehl wrote: >1. Since Webware has a session management, it might happen, that one is >visiting the same url twice, but in different contexts (maybe one has an >application, that collects different data and in the end one goes to an >url "myApp?action=save". Anyway, if the Browser has caching enabled, >chances are, that the browser won't even try to connect to the server >since he already "knows" the url. . My first impression is that you would be better off using one the expires: or cache: type HTTP headers. Otherwise, browsers and proxy servers will attempt to cache all these pages that really shouldn't be cached. And this technique still allows you to keep clean URLs. -Chuck Sorry, I forgot: Probably of interest: My config file. Probably an important detail: If I run the app using the app servers an WebKit, I first have to delete the session file. Otherwise I get the *same* error. After having deleted it, the app runs fine with the servers. Regards Franz { 'AdminPassword': 'webware', #Change This! 'PrintConfigAtStartUp': 1, 'DirectoryFile': ['index', 'Main'], 'ExtensionsToIgnore': ['.pyc', '.pyo', '.py~', '.psp~', '.html~','.bak'], 'LogActivity': 1, 'ActivityLogFilename': 'Logs/Activity.csv', 'ActivityLogColumns': ['request.remoteAddress', 'request.method', 'request.uri', 'response.size', 'servlet.name', 'request.timeStamp', 'transaction.duration', 'transaction.errorOccurred'], 'Contexts': {'default': 'Examples', 'Admin': 'Admin', 'Examples': 'Examples', 'Docs': 'Docs', 'Testing': 'Testing', 'SellIt': 'SellIt', }, 'SessionStore': 'Dynamic', # can be File or Dynamic or Memory 'SessionTimeout': 60, # minutes 'MaxDynamicMemorySessions': 10000, # maximum sessions in memory 'DynamicSessionTimeout': 15, # minutes, specifies when to move sessions from memory to disk 'IgnoreInvalidSession': 0, 'ExtraPathInfo' : 0, # set to 1 to allow extra path info to be attached to URLs 'CacheServletClasses': 1, # set to 0 for debugging 'CacheServletInstances': 1, # set to 0 for debugging # Error handling 'ShowDebugInfoOnErrors': 1, 'UserErrorMessage': 'The site is having technical difficulties with this page. An error has been logged, and the problem will be fixed as soon as possible. Sorry!', 'ErrorLogFilename': 'Logs/Errors.csv', 'SaveErrorMessages': 1, 'ErrorMessagesDir': 'ErrorMsgs', 'EmailErrors': 0, # be sure to review the following settings when enabling error e-mails 'ErrorEmailServer': 'mail.-.com', 'ErrorEmailHeaders': { 'From': '-@...', 'To': ['-@...'], 'Reply-to': '-@...', 'Content-type': 'text/html', 'Subject': 'Error', }, 'UnknownFileTypes': { 'ReuseServlets': 1, # Technique choices: # serveContent, redirectSansAdapter 'Technique': 'serveContent', # If serving content: 'CacheContent': 1, # set to 0 to reduce memory use 'CheckDate': 1, }, } Hi everybody, I try to write a small shopping app, where I can add items to a Cart. When I want to view the Cart I get: C:\Inetpub\wwwroot\SellIt\PageCart.py Traceback (most recent call last): File "D:\Webware\WebKit\Application.py", line 303, in dispatchRequest elif self.isSessionIdProblematic(request): File "D:\Webware\WebKit\Application.py", line 378, in isSessionIdProblematic if (time()-request.session().lastAccessTime()) >= self.setting('SessionTimeout')*60: File "D:\Webware\WebKit\HTTPRequest.py", line 165, in session return self._transaction.session() File "D:\Webware\WebKit\Transaction.py", line 56, in session self._session = self._application.createSessionForTransaction(self) File "D:\Webware\WebKit\Application.py", line 659, in createSessionForTransaction session = self.session(sessId) File "D:\Webware\WebKit\Application.py", line 503, in session return self._sessions[sessionId] File "D:\Webware\WebKit\SessionDynamicStore.py", line 61, in __getitem__ self.MovetoMemory(key) File "D:\Webware\WebKit\SessionDynamicStore.py", line 92, in MovetoMemory self._memoryStore[key] = self._fileStore[key] File "D:\Webware\WebKit\SessionFileStore.py", line 48, in __getitem__ item = self.decoder()(file) ImportError: No module named Cart In other files I did a "import Cart", which I had to change to "from Cart import Cart" to make them work. But the error shown above I cannot get rid of. To be honest, I'm a bit helpless in spotting this down, so any hint is appreciated. What I found out so far ist, that the session file is there. The line causing the error is: item = self.decoder()(file) which I find in __getitem__ of class SessionFileStore. It is called, when the line self._memoryStore[key] = self._fileStore[key] in MovetoMemory() of class SessionStore is executed: def MovetoMemory(self, key): global debug if debug: print ">> Moving %s to Memory" % key self._memoryStore[key] = self._fileStore[key] del self._fileStore[key] The key is 2001051317021315940, the file is D:\Webware\WebKit\Sessions\2001051317021315940.ses. All my app files and therefore Cart.py are in D:\Webware\WebKit\SellIt. If I run WebKit everything's running fine, but if I run OneShot things seem to be different (e.g. the current dir is WebKit instead of Webware). I'm using Webware 0.5.1.rc#3 on NT4. OneShot.exe is a renamed PythonLauncher.exe and OneShot.py is a renamed OneShot.cgi. Best regards Franz GEIGER
http://sourceforge.net/p/webware/mailman/webware-discuss/?viewmonth=200105&viewday=13
CC-MAIN-2014-10
refinedweb
1,166
50.94
Hi everybody, i got 4 sensors connected to my Arduino Mega (Slave) and i want to transmit their values over I2C. My current Arduino code looks like this: #include <Wire.h> int SLAVE_ADDRESS = 0x08; int analogPin1 = A0; int analogPin2 = A1; int analogPin3 = A2; int analogPin4 = A3; void setup(){ Wire.begin(SLAVE_ADDRESS); Wire.onRequest(sendAnalogReading); } void loop(){ } void sendAnalogReading(){ int reading1 = analogRead(analogPin1); int reading2 = analogRead(analogPin2); int reading3 = analogRead(analogPin3); int reading4 = analogRead(analogPin4); Wire.write(reading1); Wire.write(reading2); Wire.write(reading3); Wire.write(reading4); } The Code on my Raspberry looks like this: import smbus import time bus = smbus.SMBus(1) SLAVE_ADDRESS = 0x08 def requestreading(): block = bus.read_i2c_block_data((SLAVE_ADDRESS), 0, 4) print(block) while True: var = input("Press any key for reading: ") requestreading() First Problem is that i only get values from 0 - 255 and not the whole range to 1023. Is this because of the script on my Arduino and the fact that the analogreadings have been defined as int? For the Master script: i would like to be able to start and stop the transmission via the press of a button and the log the values into a csv file. I would very much appreciate if anybody had suggestions. Thanks
https://forum.arduino.cc/t/i2c-raspi-master-arduino-slave-analog-values-transmission-for-csv-file/572167
CC-MAIN-2022-27
refinedweb
203
61.67
WSCEnableNSProvider function The WSCEnableNSProvider function changes the state of a given namespace provider. It is intended to give the end-user the ability to change the state of the namespace providers. Syntax Parameters - lpProviderId [in] A pointer to a globally unique identifier (GUID) for the namespace provider. - fEnable [in] A Boolean value that, if TRUE, the provider is set to the active state. If FALSE, the provider is disabled and will not be available for query operations or service registration. Return value If no error occurs, the WSCEnableNSProvider function returns NO_ERROR (zero). Otherwise, it returns SOCKET_ERROR if the function fails, and you must retrieve the appropriate error code using the WSAGetLastError function. Remarks The WSCEnableNSProvider function is intended to be used to change the state of the namespace providers. An independent software vendor (ISV) should not normally de-activate another ISV namespace provider in order to activate its own. The choice should be left to the user. The WSCEnableNSProvider function does not affect applications that are already running. Newly installed namespace providers will not be visible to applications nor will the changes in a namespace provider's activation state be visible. Applications launched after the call to WSCEnableNSProvider will see the changes. The WSCEnableNSProvider function can only be called by a user logged on as a member of the Administrators group. If WSCEnableNSProvider is called by a user that is not a member of the Administrators group, the function call will fail.. Requirements See also
https://msdn.microsoft.com/en-us/library/ms742233(v=vs.85).aspx
CC-MAIN-2015-22
refinedweb
245
56.15
MPI_Comm_get_nameReturn the print name from the communicator int MPI_Comm_get_name( MPI_Comm comm, char *comm_name, int *resultlen ); int MPI_Comm_get_name( MPI_Comm comm, wchar_t *comm_name, int *resultlen ); Parameters - comm - [in] Communicator to get name of (handle) - comm_name - [out] On output, contains the name of the communicator. It must be an array of size at least MPI_MAX_OBJECT_NAME. - resultlen - [out] Number of characters in name Remarks MPI_COMM_GET_NAME returns the last name which has previously been associated with the given communicator. The name may be set and got from any language. The same name will be returned independent of the language used. name should be allocated so that it can hold a resulting string of length MPI_MAX_OBJECT_NAME characters. MPI_COMM_GET_NAME returns a copy of the set name in. Because MPI specifies that null objects (e.g., MPI_COMM_NULL) are invalid as input to MPI routines unless otherwise specified, using MPI_COMM_NULL as input to this routine is an error. Rationale.. We provide separate functions for setting and getting the name of a communicator, rather than simply providing a predefined attribute key for the following reasons: - It is not, in general, possible to store a string as an attribute from Fortran. - It is not easy to set up the delete function for a string attribute unless it is known to have been allocated from the heap. - To make the attribute key useful additional code to call strdup is necessary. If this is not standardized then users have to write it. This is extra unneeded work which we can easily eliminate. - The Fortran binding is not trivial to write (it will depend on details of the Fortran compilation system), and will not be portable. Therefore it should be in the library rather than in user code. Advice to users. The above definition means that it is safe simply to print the string returned by MPI_COMM_GET_NAME, as it is always a valid string even if there was no name._get_name.#include "mpi.h" #include <stdio.h> #include <stdlib.h> int main( int argc, char *argv[] ) { MPI_Comm comm; int rlen; char name[MPI_MAX_OBJECT_NAME], nameout[MPI_MAX_OBJECT_NAME]; MPI_Init( &argc, &argv ); nameout[0] = 0; MPI_Comm_get_name( MPI_COMM_WORLD, nameout, &rlen ); if (strcmp(nameout,"MPI_COMM_WORLD")) { printf( "Name of comm world is %s, should be MPI_COMM_WORLD\n", nameout );fflush(stdout); } nameout[0] = 0; MPI_Comm_get_name( MPI_COMM_SELF, nameout, &rlen ); if (strcmp(nameout,"MPI_COMM_SELF")) { printf( "Name of comm self is %s, should be MPI_COMM_SELF\n", nameout );fflush(stdout); } MPI_Finalize(); return 0; }
http://mpi.deino.net/mpi_functions/MPI_Comm_get_name.html
CC-MAIN-2017-47
refinedweb
397
53.21
Nitpick shield: Games don’t “need” a language, but such a thing would be useful. I’m not complaining about the person who titled this article. I had the same problem yesterday when I said GTA V was “Banned” instead of more correctly stating it was “un-stocked from certain retailers in one country in response to an internet petition”. It’s really hard to cram complex ideas into pithy article titles. I’m okay with a bit of conceptual slop as long as it still conveys the basic idea. The only downside is the prevalence of people who argue with article titles without reading the article. Those people make me sad. ANYWAY. My column this week talks about the fact that we use C++ for making AAA games, and why that’s strange and un-optimal. The conversation stems from this video: That’s a two-hour talk by developer Jon Blow. My column attempts to explain the mess we’re in and how we got here, and is aimed at non-technical people who can’t follow what Blow has to say. I have a half-written post where I go over Blow’s video point-by-point, annotating it for non-coders. I’ll finish it one of these days. And finally, I’m going to start taking reader questions in my columns. I’m looking for questions about programming. Stuff like, “Why do we have to keep updating our drivers for existing graphics cards?” or “Why do consoles still use checkpoint saves?” or “Why do Skyrim and Minecraft have thousands of mods, but most games have none?” Note that these questions are for the Escapist audience, so try to keep questions relevant to that. Don’t ask about stuff like Good Robot, because most of them have never heard of it. Don’t ask overly technical stuff (“What do you think of how C++ handles exceptions?”) because that’s going to be too big and complex a discussion for The Escapist. You can ask about non-programming stuff, but it should probably be focused on videogames in some way. If you’ve got a question for the column, you can send it to [email protected] If you send it anywhere else I won’t know it’s for the column and I’ll probably put it in the Diecast pile. Please bear with me, this job is confusing. Shamus Plays WOW Ever wondered what's in all those quest boxes you've never bothered to read? Get ready: They're more insane than you might expect. The Best of 2011 My picks for what was important, awesome, or worth talking about in 2011. The Witch Watch My first REAL published book, about a guy who comes back from the dead due to a misunderstanding. PC Hardware is Toast This is why shopping for graphics cards is so stupid and miserable. Do It Again, Stupid One of the highest-rated games of all time has some of the least interesting gameplay. 178 thoughts on “Experienced Points: Why Video Games Need Their Own Programming Language” Dear Shamus, How do you type with boxing gloves on? kol,gfhtcsxd n olktg frtgthbnZAfrrd hbzsaedrdsx,l medrsaqwll;thyg. Trs;;u??? P Yjpohjy oy esd ,ptr ;olr yjod… Poorly. It’s tricky, but possible if you take your time and backspace a lot. It took me like two minutes to type that sentence. (I took off the gloves for the subsequent ones.) Oh heck, it’s really easy so long as you have the gloves! …Wait, do you mean type WELL? Nice. That was worth of Zucker Abrams Zucker FYI, Civilization 4 was written mostly in Python. The core game engine was written mostly in c++. There was however a lot of scripting exposed to the players which used python. ( And if I recall correctly they eventually released the SDK which exposed a fair amount of C++ code to players to so they could pay around with some of the game dlls.) But the main game code was absolutely not written in python. Indeed. Python is very cool , but I doubt you could make a AAA game using only Python. Nor should one try to. There is nothing wrong with letting each language shine where its strengths are, and I think it’s really cool to see how nowadays you can see routinely big projects that integrate code in several languages. Back when I was a lad, games were written in assembly language! Challenge Accepted The primary issue is that Python, as an interpreted language, is very, VERY slow compared to a compiled language. Especially a relatively low-level language like C. And AAA games are largely defined by their high-end requirements– great graphics, large environments, et cetera. Lots of things that will put a strain on a computer’s ability to maintain solid framerates or avoid horrendous loading times. Python is primarily useful when you’re doing things where what matters is the amount of time it takes to produce a program, not how much time it takes to run it, because it’s a lot easier to write code in Python than it is in C or C++. As an example, let’s say that you need a program that can search your company’s database for something and cross-reference it with something else. If it’s a check that needs to be done once a day, it really doesn’t matter if the program takes ten seconds instead of a tenth of a second, and if your programmer can write the Python script in half the time, you’ve probably saved money. But if you’re writing a game engine, there are lots of things that would need to calculated every frame, which generally means somewhere between 30 and 60 times per second. At that point, speed starts to matter a LOT. Having a per-frame process that takes .5 seconds instead of .05 will cut your framerate by a factor of ten. I could not have said it better. :-) There’s one aspect missing: Python is used in scientific computing a lot, and there are entire projects using just that … and a bunch of libraries containing properly optimised code for everything that approaches heavy lifting. You could probably create a finite element code in python these days. As long as you took care to use the existing libraries for matrix and vector maths, you wouldn’t do half bad. In a game context, this means you could probably really put all the draing, screen-updating, physics-simulating stuff in proper, highly optimized C++-libraries but the organisational stuff (level layout, mission goals, event triggers, when to spawn new enemies, when to level up …) into Python. That’d make it super-easy to rearrange maps, scripted events, probably quite a few more things. Heck, massively parallelvisualisation software for immense datasets has been written mostly in Python, and that’s all about dealing with limited RAM and CPU/GPU cycles in the face of gigantic datasets. The trick is singling the really performance-critical bits out and move them into libraries. Wait, challenge accepted for writing a game in Python or in Assembler? I still remember the times of tzping program listings from magayines into a hex editor, even learned the basics of assembler once but really… on today’s PCs with variable hardware, drivers, whathaveyou … you you’d probabably die trying just to figure out what the hardware is let alone adressing it. … then again, for a small and well-determined system like a RasPi — that might actually work, though it’d be still a lot more complicated than back in the day. Uhhh, I really don’t like Python. I always feel like I have to know the entire implementation of a function to know whether it will accept a certain object as an input. And the enforced whitespace and lack of {} just messes with my perception of control flow. I suppose that’s just a matter of getting used to it, but I seriously can’t fathom how anyone can deal with duck typing. Look, I just want to know exactly what functions the object has to support to be compatible with this function, that’s all. In Java, I’d just look at it and say “Oh, it’s the interface XYZ. So, if I want the function to work with my class, I have to implement functions f and g and if I forget that, I’m gonna get an error at compilation time.” and I know all I need to know just from looking at the documentation of that one function instead of having to read through the entire freaking page. Oh yeah, that’s another thing that baffles me. Who the hell thought that just cramming all classes that are vaguely similar on one page was a good idea, easily readable or simple to understand? Every time I look at the Python documentation, I get slightly miffed. I don’t understand why everybody loves this language and says that it’s so easy to learn and that it’s documentation is so great. Obvious XKCD reference: …that’s why. Seriously, there are things that are just stupidly easy to do in Python that I’d have no idea how to accomplish in other languages. Removing variable declarations and brackets around code blocks just speeds up writing code, and is visually cleaner. One of the goals was to speed up programming and improve readability, so that’s accomplished. With great power comes great responsibility, so there are a number of hacks that are possible but very risky. I learned to code on C64 BASIC, then turbopascal, later Fortran and bits of (non-object) C. Going from there to Python was a huge step but once you’ve got the habits that allow you to breathe in this world, you never want to go back. At least I don’t. …then of course it’s a question of using the right tool. So me doing proper computing with a light GUI is just fine since there are loads of libraries for everything I need. It completely replaced Matlab for me, and for most other people I know. For other things there may not be the same infrastructure, though I’m still impressed any time I start looking for some Python libraries that could help me out in some way… oh, and if you want to have declared data types, you can always use numpy arrays with typed fields. The types ans size of an array are immutable and you can even give them names. So you could basically replace a dictionary with an np.array. Also, vector maths is super easy (it’ll even use your CPU’s SIMD commands), and you can feed most formulas an array of numbers instead of a single number, and it’ll give you the array of results. Doing any faster in C or Java will require you to write LOADS of code, and know very well what you’re doing. I love Blow’s games, especially Myst, although I’m still not clear why he changed the name for the upcoming re-release. (I’ll stop telling the joke when Blow proves it’s unfair. He’s failed to do so for 4 years now.) Shot in the dark, but… Are you Alan Broad? Nope. (I have a feeling I may be missing something here. I have no idea who Alan Board is.) I admit, I don’t get the joke. Explain? Blow’s new game, The Witness (currently seems to be in that last 10% of the work which takes up the other 90% of the time) is being billed as a spiritual successor to Myst. They look really similar. Blow is hyping The Witness as innovative, but to this point everything he has described or shown looks like Myst, or at least RealMyst. The main difference that I can see is that The Witness uses a consistent puzzle language. In Myst, the puzzles within an Age usually followed a theme, but aside from a few minor details there was never a unifying language. In The Witness, every single puzzle is interacted with by messing about with mazes, which admittedly sounds dull. Still, you know how Portal begins by teaching you the very basic rules of portals and then expands it into physics-defying glory? Best-case scenario is that The Witness begins by teaching you “start at entrance, find exit” and then will expand it into mind-puzzling beauty. One of the advantages of C is that it’s the programming language just about every other programming language can (relatively) easily interface (link) with. So if you want to write a nifty new library that as many people as possible can use, C is a pretty good choice. Of course, if all of your libraries are in C, why mess around with another language when you could just stick with C or C++ and eliminate the hassle of integrating with another language? I think there is a lot to be said for embedding a second language for non-CPU intensive work. Lua seems to be popular, as it’s relatively small and easy to embed. People who find programming languages interesting might be interested in Inform 7. It’s a programming language designed to write text adventures in. It’s really well tuned to that specific problem space. I wonder what a programming language tuned to 1st and 3rd person shooters would look like. wouldn’t it just look a lot like Unrealscript? Even if you don’t have much interest in programming languages, if you liked text-adventure games, Inform 7 is worth a look. It’s a ton of fun! There is one big downside to having a language designed and used for games programming: you create a barrier between games coders and everyone else. If you know C, C++ or java ( and is not that hard to be competent in all three), and you are at some kind of senior level then you’re not going to find out so easy to switch into games when you have no experience of . And vice versa, experienced games programmers will be ghettoised and harder to employ in any other jobs. This is bad for flexible career prospects, and I suspect particularly bad for games programmer salaries, which are already significantly below the levels of the rest of the industry. I imagine a lot of programmers would still want to code games in C++ if only to keep their career options open. On the other hand, it’s probably easier to learn than full-on programming, and it’d still likely be a stepping stone for a full programming education anyways. This might sound arrogant and might be a bit controversial, but I have to disagree with your notion that the experienced programmers would be newbies, if you switched to a new programming language. A good programmer should be able to learn a new language in a couple of weeks. Especially an experienced one. First of all, programming languages are fairly similar in both syntax and semantic (discounting functional languages like Haskell, or esoteric languages like Arnold C). Secondly, a programmer doesn’t so much write Code, he implements algorithms. And these algorithms are independent of language. Rewriting existing libraries are a real hassle, though… When you need to make an optimal implementation of an algorithm, that is not nearly so independent of language. As long as the language is still imperative(So not a corner case like Haskell), and doesn’t hide a lot of complexity from the programmer(which you really don’t want if you’re that worried about performance), I’d say most of the relevant skills should still translate. I’m not saying people will be up to speed after messing with a new language within a weeked, but I think we’re talking weeks or months to use it proficiently in the relevant domain, rather than years and years. There are interesting corner cases when you switch between almost-similar languages (say C++ and Java, two languages I am somewhat familiar with) where things that are perfectly fine in one will have a high chance of performing atrociously in the other. If we look at C++ vs Java, the cost of heap-allocating and then rapidly deallocating data is bordering on expensive in C++, but is essentially free in Java. On the other hand, stack-allocations followed by deallocations in C++ are essentially free. But knowing how to recognize and build an optimal implementation is language-independent. That’s design work. That’s writing. That’s not plugging together prewritten chunks and fiddling with the API to make it work. Because if the latter is what’s (and you do end up then having a language dependence) then it doesn’t matter if chunks you’re pasting are in your head, or coming from the team’s code library or being cribbed from a web page somewhere. The only reason they’re “optimal” is because someone told you they were, and maybe you tested a couple in a particular set of circumstances that may have no bearing on what’s actually fast. It’s bordering on cargo-cult programming. And frankly, it shouldn’t be in your head because you want to build the right kind of thing into the language in the first place. Because it’s a waste of time to know that “Oh, I have this kind of data so a selectsort will be faster than quicksort most of the time” and implement it instead of just calling a built-in selectsort feature. Two things. Firstly, yes an experienced programmer who has learned more than one language in the past will likely pick up the basics of a new language pretty quickly. But to really be an expert in a language – to be a team or project lead – you have to know a language better than that. I know c++ pretty well. I managed to get stuff to compile and run in java with no prior knowledge of the language in a trivial amount of time. Which is fine for simple projects. But the hidden problem is that I am designing java code as though it were c++. Different languages have different philosophies, subtly different expectations of how to do things. Unless you understand those, you will probably find yourself fighting against the language by doing something the ‘wrong’ way at some point. (And all the C++ experience in the world isn’t going to be much use if you get the job of writing php for the web interface to the game dumped on you instead…) Secondly, and more practically, the first pass of filtering in the job application process often involved brain-dead comparison of bullet-point skills lists on a CV (or resume if you are American) versus the bullet-point list of job requirements by someone who has no understanding of how significant the differences are. Particularly when employment agencies get in on the business. That creates a wall of stupidity separating programmers experienced in different languages. An artificial wall to be sure, but even artifical walls reduce the movement between groups. Which would be fine if all groups were equally in demand – but games programmers are pretty poorly paid already because there is an excess of supply for them compared to other programming jobs. Learning a new language: 1-2 weeks Learning the idioms, the ins and outs of the libraries, all the little gotchas where two pieces of code that seem to do the same thing have different performance characteristics, etc: years. When I went from being a Perl5 programmer to a Java programmer, it was really easy to pick up the syntax and write basic code. That doesn’t mean any of it was *good* and 5 years later I wanted to hit myself for all the things I did wrong when I started using Java. When I started using PHP and Javascript for my latest job, same thing: the code was there and it worked, but I want to fire me-from-7-years-ago for gross incompetence. I wrote functions for things that I now know are in the libraries. I used some Java-like structures that I now know had better ways to be written in PHP. I worried about the memory or speed costs of things that were slow or hoggish in Java, and not at all about the costs of things that were efficient in Java but slow or hoggish in PHP or Javascript. I avoided callback functions because the reflection library in Java made them painful to write in 2001, but they are easy to write in Javascript. When I found a library function that did what I wanted, I was happy, even if it was annoying to use, and then later I’d find there was an even better fit library function I should’ve used instead. I used some Design Patterns that only exist in C++ and Java because they are so strongly typed, and are quickly replaced by arrays in PHP and Javascript. The list goes on, but basically: it was trivial to learn the languages, but experience really does make you a better programmer in a particular language. Plus there is what happens when you need to read someone else’s code in a new language. If their code works, it can be fairly straightforward, but if it doesn’t, and you have to figure out why… Well, what I can say is: debugging time goes down dramatically with experience in the particular language you’re using. What might take a few hours to debug when you have the “1-2 weeks of exposure” can take you a minute or two when you have years of experience with that particular language. PHP is such a strange creature. I’ve been using it for years and I still think of myself as a novice. I think part of the problem is that you can’t tell of well you’re doing. Is this code fast? Am I using a lot of memory? I have no idea. I can’t tell. Which means that once code gives good output I’m done working on it, because I have no way to measure further improvements. PHP is such a byzantine mess of a language that I seriously doubt anybody actually knows it. /r/lolphp on Reddit can provide some pretty great laughs. There’s some amazing bugs like: >>> 0x0 +2 4 >>> 0x0 +3.5 6.5 >>> 0x0 +2e1 757 or: define() has an optional third argument that specifies if the constant should be case-insensitive; it has the undocumented side-effect of allowing constants to be redefined, but only if they have at least one capital letter. But if you’re a little lost and want a thorough breakdown, I liked and was terrified by this article: Just tried the examples you noted above, and either youre wrong, or you are referring to an older version of PHP, because: php > echo 0*0+2; 2 php > echo 0*0 +3.5; 3.5 php > echo 0*0 +2e1; 20 You’ve intentionally replaced the “x” characters, which are SUPPOSED to make PHP treat the number as hexadecimal, but doesn’t always. This is where the weirdness comes from. Yeah, except: php > echo 0X0 +2e1; 20 php > echo 0X0 +3.5; 3.5 php > echo 0X0 +2; 2 he mentioned in that article that the spacing matters: php > echo 0x0+2; 4 php > echo 0x0+ 2; 2 php > echo 0x0 +2; 4 php > echo 0x0 + 2; 2 I would’ve never found this bug in my day to day life, because I always use the 4th form (spaces are your friend – they make reading easier). But in theory the spaces should not matter, and they do :/ I’m not up to date, so maybe it was fixed later, too. $ php –version PHP 5.3.3-1ubuntu9.10 with Suhosin-Patch (cli) (built: Feb 11 2012 06:21:15) Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies The x has to be lower-case. The hexadecimal notation is always case-sensitive. Yup. Admittedly, this is a really niche-case example – essentially nobody ever deals with hexadecimal in PHP, and even fewer would choose to format it in a weird way. But it’s a nice demonstration of PHP’s general weirdness – either these tests should resolve to an unambiguously correct answer, or PHP’s syntax should be way less permissive to prevent this nonsense ever making it to runtime. Ah, good, you linked to the Fractal of Bad Design page. I was enlightened by it recently and feel it’s my solemn duty to mention it any time PHP is brought up ;) I learned a little PHP in my course on Database theory in college. Didn’t relly get into it beyond making SQL queries, but it didn’t seem too horrible. I started reading that list in the article. I quickly went from “wait, what?” on some of the issues he brings up to “oh, you have GOT to be kidding!” And then the list kept going…and going…. and going… Isn’t a large portion of the internet running on PHP? How the hell did that happen? I was thinking the same thing. It’s amazing. I never run into these issues, but then I’m always doing really simple stuff. PHP was someone’s compilers 101 homework that inexplicably got popular. It’s not surprising it’s almost impossible to know whether you’re doing the right thing, it’s such a bizarre and amateurish language in general. I remember right up to the end of the PHP 4 era, being constantly annoyed assignment expressions weren’t rvalues, except of course in the special case of the prefix and postfix increments. I can’t even imagine what the grammar for the language looks like at that point. That’s not even mentioning the half-arsed modules that come with it. I remember the OpenSSL module being some ultra-thin wrappers around a random assortment of crypto functions. No attempt had been made to make the calls more “PHP like”, and of course being anywhere near complete was out of the question. Quality control was non-existent. Worse, the half-arsed attitude filters down to projects written in it. Consider mediawiki, the only web application so completely broken that the managed to make it CPU bound. Every attempt they’ve ever made to fix what they laughingly describe as a parser has been abandoned and instead they rely on ever more byzantine caching architectures to mask the problem. And this thing runs one of the most popular sites on the internet. Insanity. If they just devoted some of their constant begging drive money to fixing the thing, maybe they could scrap like 80% of the CPUs they need to run the fucking thing. I catch myself all the time, I dig through some old code (sometimes posted on the net) and I see how archaic the way I did it is. The way I code has evolved as I do evolve. I’ve slanted towards always predefining things, set things up as much as possible before entering a loop, I’m not afraid to use extra memory at startup if it means I can re-use it later (instead of wasteful allocate/free calls all the time). When I close my program I only close handles the OS documentation state I should close the rest I do not, my programs takes less than a second to start and less than a second to quit. The GUI is in it’s own thread so interacting with it will not halt the program otherwise. Checking if a new version is available is in it’s own thread that way waiting for a slow server won’t halt the program. My code looks tighter and shorter, and I often find myself tweaking improving it all the time. Instead of relying on the OS version I now feature test, instead of just assuming libraries are available I dynamically load them which means I can actually show a useful error to the user if something is wrong. For example by doing few simple changes I managed to make compiling WebP library in such a way that it can be used n Windows 2000 and later possible (instead of just Windows XP SP3 and later), the upcoming v0.4.3 of WebP should have a “legacy” option available. I hate bloat, but I’m not afraid to use some disk space or memory if it speeds up performance. I’m also a huge hypocrite, I cringe all the time when I see my old code as I broke pretty much all my current “rules” when coding. My mantra for coding these days are “Tight, Simple, Efficient.” I’m sure a few years from now I’ll think the me of today sucks. If you can “read” C like syntax then you can read most languages. I first started with Basic on 64 and Atari XE, later AmigaE and C a sliver of ASM on Amiga and HTML then later PureBasic and C and a dash of ASM on PC and PHP, HTML/CSS/Javascript. ASM and variants Basic have familiarities, C/CSS/Javascript/PHP have familiarities. I’m usually able to do a pretty good implementation even in languages I do not understand well because I enjoy striping code/functions down to their core functionality. If code is hidden in a class somewhere I prefer to just get it and break it down into the parts I need. That’s how I learn and understand the code used. I’ve ended up having to cram Ruby, Erlang and Haskell to the point where I could judge if the code I was given by an interview candidate was close to or far from a correct implementation of the interview question. It’s not that much of a problem, as it turns out. And, yes, if you (generic you, here) ever end up having a coding interview with me, I’ll choose a problem guided towards showing mastery of whatever of “C”, “Python”, “Go” or “Common Lisp” that you’ve said is your prime language, but leave the actual choice of language up to you. Seems like a fair test as the person would most likely prefer or feel more comfortable with one of them in particular. I might however (if interviewing) ask to see the example ion both the language(s) Id’ be hiring for and the preferred language of the interviewee. That way I could gauge how much “catching up” they need (if any) for the language they’ll be working with. It would be odd though if one is hiring for a C coder and they prefer Python. But I guess you could send a memo to HR and say you got this guy that’s shitty at C but amazing at Python and hopefully a Python project is ongoing that might benefit from such a person. Now if the job allows some leeway in what language a project is coded. (heck it might be using dll’s (Window) or so (Linux) in which case C and other languages can be intermixed with no issues (with some care). I’ve written C++, Go, Python and bash for work (and some JavaScript) and all of it has been peer-reviewed before being checked in. I think I mostly wrote ksh and C during my interview process, but it’s been a while. We typically take the approach that with a few weeks, style guides and extensive peer reviewing, the syntax, semantics and idiosyncrasies of a language can be rapidly acquired. Yes, having a mentor with a ton of experience can speed up the acquisition process, but I still maintain that learning a new language, and learning it WELL are different matters and the latter takes a lot more time. Even with mentoring, it’s possible to get into traps of “good knowledge acquired badly” – where you know A is preferable to B, but can’t tell anyone why. If you just tell your shop, “and today we’re using Java,” they will be greatly slowed down and write terrible code – maybe if you hire an expert, provided that expert has the right personality to get along with your team dynamics, you can reduce the time and make better code… Overall, my point is that the sentiment that “any good programmer can write in any language” has a lot of caveats of the kind management doesn’t usually take into account. My other point would be that experience matters. Young me might reply “you just want to feel like the time investment was worthwhile,” but older me knows young me was a fool. Experience makes a lot of difference. Even in the mentoring example, it works because the mentors have experience. Yep, mentoring and guidance are the key points here. Normally, we tend towards being generous with “this works, but Y would be more readable/efficient/idiomatic” and as long as someone can motivate why what they wrote is better than anything else, I’m happy to let it pass (last was “this is a new file, while all functionality is trivial, I’d like to see either ‘unit tests’ or ‘a short essay on why this will never need unit tests'”, and I would genuinely had been happy with either). Because once you have another file, it WILL acquire more functionality, building on what’s already there, so you probably do want to have some tests. This is unrelated to the column, but the other week I wrote a question for this column, directed at one of your other contact mail addresses(the one listed at your “author” page). I just wonder if mails sent there are still considered/read through for the Experienced Points column? In your column, you mention that one of the things that makes C still very useful to videogames is the demand for more high-powered graphics. It seems that there are so many things in the videogame industry that all go back to the graphics arms-race, but whenever I look back at what games look the best, great art design/direction still beats technical graphical proficiency every time. There are still games coming out new that don’t look as good as the best games that came out a decade earlier. There’s been a surge of indy games that maintain more “retro” aesthetics recently in order to make dealing with graphics easier so they can focus on art design, why haven’t any AAA games tried scaling back on technical aspects in order to focus on design? I can answer this one. The answer is that Marketing doesn’t ever care about design. I’m not just being cynical here: the way the companies are structured is that Marketing makes decisions for Marketing reasons and if someone in Marketing has a background in design, only then does a decision get made partly for design reasons. This is, for example, the reason behind the awful state of Final Fantasy XIII. Final Fantasy XII is a great game to play. Huge playable world, better cities than Skyrim (You bet your ass I mean it.), wonderful combat system that ties into simplified custom AI programming, great class system where you build your own classes, and an unfinished story. So yeah, Final Fantasy XII has exactly two flaws: the stupid hidden treasure chest thing that keeps you from getting one of the best weapons, and the fact that the story ends around the equivalent of the second third of a trilogy. That last part of a story was made into a game, but you need a DS to play it. So Marketing decided that for XIII, they needed to rework the milestones so that telling a complete story was the highest priority and all of the game parts would be secondary concerns. That is the reason why Final Fantasy XIII is such an atrocious game. Because of Marketing not caring about how to make a good Final Fantasy game. FF12 may not be a complete story, but it’s still a much, much, much better game than XIII. Squeenix have learned their lesson, but the lesson they learned is that their market doesn’t want that specific terrible idea, not that they should think of things from a design standpoint to see if a good marketing idea is a terrible design idea. Because then they made XIII-2 and XIII-3, which are not nearly as awful as XIII but still pale in comparison to XII’s gameplay, world design, and accessibility. And all of them have wonderful graphics, sound, and music. AAA publishers take design for granted and will always take design for granted. Because they are AAA publishers. Final Fantasy XIII is the best Final Fantasy game. Reason that C is so popular is because there is so many examples, books, sites about it and you’d be hard pressed to find a computing platform that does not have some form of C compiler for it (by C I mean “C” and not “C++”). The “C syntax” will probably stick around forever. > (by C I mean “C” and not “C++”) Honestly I’m hard pressed to think of a >=32-bit architecture which lacks a C++ implementation. There are even a few 16-bit processors with good C++ support. So in the gaming space it’s probably safe to assume that C++ is available. But yes, there are working C compilers for almost everything. The embedded space will keep C alive for a long time yet. much ado is made about other languages… but guess what language their compilers/interpreters/environments are written in? if your guess sounds like the ocean, you’d win most of the time, and you’d understand the language’s real staying power The first three Jak and Daxter game engines were written in Common LISP. When the guy who wrote the engine left the company, he was the only person who knew LISP, so they dropped everything he had been working on and started working in C++ like everyone else. This fact is particularly impressive because I still don’t know how the heck he wrote something in Allegro CL that compiled to work on the PS2. I really wish more was written on this. IIRC, it was actually a custom language called GOAL(Game Oriented Assembly Lisp), which compiled to playstation assembly. The compiler for this language was written in Common Lisp. Edit, found the link: That’s insane. I have to look that up. Okay, having looked it up, it isn’t actually done in LISP – it’s done in some variation of LISP they developed that functions as an imperative language. That’s infinitely more sane than actual LISP. Still pretty interesting, though. There’s nothing about Lisp that stops you from being imperative… It’s actually easier to write obnoxiously imperative code in Common Lisp than it is in C++, bu no one ever does, because why would you want to (the thing to look up, should you want, is “tagbody”, which is an essentially pure imperative subset with goto). That game engine was also used for the first three Ratchet & Clank games. Thanks for the vid link, I have friends going through game dev right now who’ll likely find it compelling. The “Ask-a-Shamus” sounds like a neat idea. I wonder where the line is before a technical question becomes too complex. For instance, is it too much to ask something like, “Why is it so difficult for PC games to be relatively bug free and stable at least across the same operating system” or, “What is it about peoples’ PC hardware that make games difficult to function in the exact same way for all people, where bugs and bug fixes will affect different setups differently”? Bug related questions are probably going to be popular based on recent releases like Ass C: Unity This covers things like how hardware interacts with software, drivers, compatibility, OS updates and so on. Tangentially related, I’ve been reading this book and enjoying it a ton so far: Game Programming Patterns. So far I’ve read the first third of the book, where he goes over several programming patterns from the GoF, and explains them in the context of game development. I haven’t started writing a game yet, but they gave me a good understanding of the patterns, and in a way more interesting way than the dry theoretical text of the original book. The author is a good writer. I’m reading the chapter on finite state machines right now. Would definitely recommend. Woah, he finally finished it. The portion that I read years ago was really good – I’ll have to come back to it and check it out. So, cpu cycles and memory are plentiful, and C is overly geared towards conserving those. Yet, games require terrifyingly powerful PCs and still run slow as molasses. How do you reconcile these two points? By “plentiful” I mean by the standards of when C was designed. The memory saved by manual string management is completely trivial today and doesn’t help us meet our current performance needs. (And yes, you don’t need to do manual string manipulation these days, but I didn’t want to get into the C vs. C++ business.) It’s not that C is OVERLY geared towards performance, it’s that a lot of its quirks are due to design decisions that made more sense in 1972 than 2014. The actual memory space saved by C-style strings isn’t much, that’s true. But memory allocations from the heap are still expensive: especially in multithreaded stuff. (You’re pretty much guaranteed a cache miss and some kind of mutex lock/unlock or some other overhead to stop two threads allocating the same memory at the same time to different things.) C-style strings allow programmers to allocate from the stack instead and allows them to tightly control the number of heap allocations. That is their real advantage these days. Actually, you *do* need to do manual string manipulation. See the recent discussion on [email protected] where the Chrome browser is doing tens of thousands of std::string allocations and deallocations for every character you type in the search box. This has a real, serious performance impact. (At least, we think so – just measuring the performance of a 10-million-line-of-code interactive program is pushing the state of the art.) There’s no such thing as too many CPU cycles to use them all up. But if you have a language that shaves a couple bytes off each object and objects are kilobytes in size, that’s not a terribly important issue. The other side of the coin is that if your language is too complicated, your code might take twice as long or even asymptotically longer than it should and you simply never notice. And C opens up the possibility of various bizarre errors from manipulating memory directly. You can add a letter to a number and not have the compiler tell you you’re an idiot, if you muck up your pointers. Which is sometimes good but is bad when you don’t want to do that. “f you have a language that shaves a couple bytes off each object and objects are kilobytes in size, that's not a terribly important issue” Actually the effect is cumulative. A modern game has potentially millions of objects (by objects I do not mean 2D object, but anything, like a decimal number or a yes no state flag), and if a few bytes are wasted here and there and CPU cycles are gobbled up yonder and beyonder then that translates to not reaching 60FPS or to blasting past 4GB in memory use. If a object is no longer used it is usually freed (garbage collector/routine to free up resources), if a object is created and freed several times per second then that has an impact. You can’t add memory resource to a object oriented language, you can do such to a game engine though. Personally I’d like to see something like C but way more strict/restricting, maybe a subset. As to the issue of games running like crap. That’s because you got objects and classes calling other classes or methods and you got wrappers for other wrappers and. And most games use frameworks, some of them made to work with the game engines others hacked to work. Some use old game engines with a graphical “spruce up” but the engine itself is otherwise old and dated and barely holding together. Some people look down on re-factoring (redoing the whole thing from scratch) but me I see it as needed because over time, regardless of how well meaning or strict one are, cruft tends to stick to it and create a real mess. You can only add so many layers of paint before you need to consider stripping off all the old paint and sand the darn thing. See, I’m a java native and we call those guys primitives. You really shouldn’t touch memory allocation for those directly; everything expects them to be certain sizes and dealing with variable size ones is going to introduce a whole host of problems. Objects are generally variably sized (an instance may be fixed size but you can have different ones of different sizes) and tend to be much larger. If there’s a way to dependably reduce their overhead without changing their performance, that sounds like a job for the compiler. Sure, you might be able to shave off some more space doing things by hand when you know things the compiler can’t see, but getting that working takes time away from other things you could be doing, and it’s likely that making sure the algorithms are correct and efficient will be more useful. Overlook a single instance of non-tail recursion because you’re saving on per-object overhead and you can probably wave all of those memory savings goodbye. Granted, I’m assuming the compiler is good enough that it won’t pointlessly waste memory. Also incidentally Java doesn’t optimize tail recursion because it breaks Java’s exception handling, which involves proceeding back up the call stack and obviously doesn’t work so well if frames get reallocated. Actually the reason Java doesn’t have tail-call optimization is that certain security related code was counting stack frames to know what to allow. This has recently been removed and while that’s not a promise of TCO, the big block against it is now gone. Also, for Java 10 there are plans for value objects, user defined objects that behave like primitives, good memory layout in arrays, not pointer jumps. Unfortunately Java 10 is planned for 2018, which feels pretty far away right now. As programs get ever larger and more complex (and they are vastly more complex than they used to be), trying to keep your code relatively bug free becomes harder and harder. Heavily optimised code tends to be an unmaintainable disaster area. It’s fine (more or less) if you can write it once and forget about it, but in the real world that is very rarely an option. (Plus it takes a very long time to really optimise code, and the cost-benefit analysis rarely favours it except for serious performance bottlenecks). In practice, writing code that can be understood quickly by the other 15 people who might have to fiddle with it, that can be adpated to changing requirements or rewritten to fix some tangentially related bug is much more important. Actually optimising code properly basically means locking down any further changes and then spending a few months on it (and hoping that the bugs you introduce doing this aren’t life threatening). If you’ve noticed, most games tend to be released these days when they still have pretty obvious bugs in them; the idea of persuading marketing / publishers to wait a few more weeks while the critical bugs are fixed, then a few more months for the other significant bugs, and then a few more months again to work on the performance is a bit of a non-starter these days. With the exception of CD Projekt Red, the guys making The Witcher 3 which was postponed since the devs wanted more time. I’m pretty sure the money guy (and to some extent the marketing guy) over there is shedding a few tears, but damn, respect for doing it right guys. I call this the Deus Ex school (the devs of the original Deus Ex was said to have reached gold, the game was finished and ready for release, then “Hey! Why don’t we spend 6 more months polishing it?” and they did so. Now Deus Ex was not bug free or without issues, but these 6 extra months probably turned that game into the landmark it is due to that extra time. Also, The Witcher 3 is the last in a trilogy, and my guess is that the devs want to make sure that it ends in a way (or ways rather) that they and the players will be happy with. Interestingly enough the moved release will move The Witcher 3 away from the GTA V PC release, something I’m sure Rockstar don’t mind. Rockstar (at least for their GTA games) seem to take their time when working on games too, I’m kind of glad they aren’t rushing the PC release of GTA V. Shamus a language (or should i say languages) for making games has existed for decades. But for various reasons they’ve been ignored. Either because they are proprietary or the industry ignored them or saw them as “toy” languages. For 2D (and later 3D) there was AMOS and Blitz Basic. Both was BASIC familiar languages with a strong focus on multimedia and games, you could make a game with just a few lines of code. They where marketed towards the consumer that wanted to make games rather than the professional, though there where quite a few games made professionally using them. For 1D (aka Text Adventure / Interactive Fiction) games there are many languages, TADS, Inform, ADRIFT, Quest, ALAN, and plenty more. The issue is that at a certain point you end up at a cross road, a generic game programming language is just too… generic, there is a reason why game engines exists as these are custom game languages if you will. Some even have WYSIWYG (What You See is What You Get) editors allowing you to manipulate the game world in realtime in 3D. Instead of writing a game in a programming language you are programming a game engine. I suggested to AMD many years ago that they should look into putting a game engine in hardware (or parts of a engine) allowing a game to essentially “upload” the gameworld to the hardware, this was many years ago and I see no signs that they are working on anything close to that yet (hence me stating it in public now, it’s not like I’m ruining any secret plans). My suggestion to fix the issue of complexity in making games is the following. A industry standard open source game engine, royalty and license fee free. (MIT / BSD license?) The project is guided by industry experts and any improvement to DirectX and OpenGL andMantle and whatever Intel, AMD, Nvidia and Microsoft and the rest come up with are included in it. This engine will serve as a “reference” engine, and developers/companies using it are encourage to share the improvements with the project. The way the whole thing is financed are by donation/sponsorship by hardware manufacturer (build it and they shall come principle) so there exist a reference implementation of an engine that makes use of their hardware features. In addition those working on the project could do consultancy (for a fee) for companies that need coding help to implement/do certain things (several Open Source based companies do this today). Learning curve would drop too when getting developer jobs as many other engines would be based on the reference one so there would be familiarity. The reference engine would also be multi-platform. I think this would work better than a game programming language (which has been done but abandoned/ignored in the past by the industry), I can not recall ever hearing of a reference game engine though. Those examples are all languages specifically trying to solve very high-level problems, which are all different for different types of games. How do I make a text adventure? How do I make a platformer?. Also of note, is that the examples you give, solve problems which are difficult for non-programmers, and part of your daily job if you’re a programmer. I’m not trying to bash them, or sound condescending there. They’re really great tools for teaching, or for getting people interested in programming. However, once you have learned/made yourself a programmer, there’s better tools to use, which solve the bigger problems you now face. .” A subset of C/C++ is all that is needed. Heck you could probably use a C compiler of sorts (Clang?) Just apply a pre-processors that ensures the C subset is followed (and spits out an error if not). The issue is your statement “common to nearly every game”, if you think just FPS games then a game engine is ideal (Unreal, Cryengine, etc), for Point and click games something like Wintermute is ideal. What is needed is a pre-processor and a standard library (kind of like a std clib) where you can just add sub-libs with the functionality you need. Ironically a opensource game engine in some ways. But the type of games that exists are so wast that you’d need a generic language to cater to them all. There are also frameworks (SDL) that are sort of a generic game engine. The issue with C/C++ is that it’s been added to and changed over decades, the ideal is if there was only one way to do things. By enforcing a subset of C any debugging is much easier, heck if you combine a subset of C/C++ with a gameengine framework then that is the ideal. You will never be able to create a programming language that makes it easy to make games without also restricting the flexibility in the type of games you can make, and as soon as a developer need to start doing game code in another language just because the main language is unable to do certain things then you got a whole new mess on your hands. A lot of the junk in C/C++ is in the standard library of C, sure there is some cruft in the compiler itself and the actual language but there is a lot defined in the standard library (C89, C99, C++08 C++10 or is it C++11? and upcoming C++14) and so on. These try to fix things by adding/removing/changing things related to the standard library. Another issue though is the definition of a game. A RISK like game is mostly just a map and a database the disconnect codewise between something like that an say Call Of Duty is huge. You do not need dynamic music in a RISK game nor worry about LOD and Occlusion or shadows and shading or lighting. Also note that EPIC and Mozilla (I think, can’t recall) managed to get Unreal engine running in a web browser using Javascript and HTML5 stuff. Ideally a game developer should not have to worry about memory and file access and controller support and things like that. The game engine developer on the other hand do have to worry about stuff like that. A game develeoper should only worry about creating and piecing the content together. If you want the cost of making games go down then you must have a game engine, and if it’s modular so you can add/remove pieces you need or don’t need then that is ideal. If you need to code the game from scratch using a “game language” then that is going to cost a lot and the development time is going to be huge. Now if a game language is used to create a game engine, then game devs will not be using the game language but instead the game engine, the engine may have semantics that go in a different direction from the language it’s written in. At which point the language is irrelevant just like today. A opensource modular game engine would allow development time and costs to plummet compared to today. C/C++ would be just convenient for such an engine as would any other common language that is available on most platforms. A modular game engine / C game library can abstract away file and memory access and provide ready made solutions for common problems. It also does not help that you have Mantle/DirectX/OpenGL to choose between. Ideally there should only be one and that would automatically map to whatever is considered the native graphics API on the platform. Same with audio with DirectSound/OpenAL-Soft (the original OpenAL is dead in the water). Frameworks like SDL mitigate some of it but you still have to faff around with graphics and audio calls and memory and other things anyway. A “game programming language” will not automatically allow you to do plug’n’play programming of games (there are actual clik’n’program game developer software out there and the games you can make are rather limited). A open source modular game engine could be designed such that you could “swap” out the 3D graphics engine with a 2D one (figuratively speaking) a 3D audio engine with the 2D audio engine and so on. For example I got some local code here that allows me to just swap a .dll and I’ll be able to support Xbox 360 compatible controller, PS4 controller or WASD, all of it is abstracted away, the player just choose their controller/layout and the only thing the game sees is that “forward” has the value 1.0 (but that value may originate from a button, analog stick, trigger a foot pedal or the “W” key on a keyboard). Stuff like this belongs in a library or game engine not in the programming language itself. If you thought C was “slow” to compile image when the compiler has to juggle all this stuff for ALL games. Want to compile a Solitaire game? Sure just wait while the compiles compiles the game world. The player only sees a green screen and some cards but underneath is a full blown 3D engine? Now if you say that a game language should not have the engine included then we are no longer talking about a game language at all, just a generic programming language. Better attempts at better generic programming languages happen all the time. C, C++, Pascal, Fortran, Cobol, Delphi, BASIC (and the umpteen inspired ones that are the same but not really), AmigaE, PureBasic, Python, Javascript, PHP, all this was designed because anther language did not suit whatever design was needed. And sometimes a language was made because making your own compiler is kind of cool. Another issue is that a lot of games usea a server client model and you can see this even in single player games. I’ve actually had a game fail because the “client” could not talk to the “server”. I’ve seen rubberbanding/lag cause my character to be warped back a few steps just like in a MMO….but in a single player game. Should this server client model be part of a game programming language? At the core a programming language is just IF THEN ELSE and a few other keywords. Start adding things like keyboard input, file I/O, networking etc and it’s a language with a standard library or modules. Add a huge amount of these together and you got a full engine. Sorry, I should have clarified this earlier. Blow’s hypothetical language is made for game engine developers, not game developers, to use your words. They’re the ones doing all the resource-heavy programming*, who need a new language. Scripting languages and libraries already exist for the higher-level stuff, which is generally resource-light. * Graphics engines, AI engines, etc Another thing is that, for reasons I can’t grasp, C/C++ are virtually the only languages that can compile to an actual binary. Every other major language like Java, C#, Python, or Ruby requires the user to have some runtime engine installed. Not to mention languages that can only create programs for a certain platform (C#) or needs to be made with commercial tools (whatever Adobe is selling for Flash and Flash’s descendants). This actually makes me upset. When writing apps I don’t want my users to have to install any additional crap to get my software to run, but C is bare bones to a fault while C++ is an ugly, ugly language. Porting issues, mostly. There’s lots of fiddly stuff you may have to mess with to get things to compile for a given OS. Meanwhile, Java’s runtime environment means your code should work just fine on any computer with no changes whatsoever. Technically speaking, C++ programs do require the C++ runtime to run. The important bit being, the C++ runtime is tiny compared to Java’s runtime. For programs built with Visual Studio, for example, the computer that runs it would need the appropriate Visual C++ Redistributable Runtime. Programs built with gcc or clang will also have their own versions, which generally are already installed in the system. And version issues are generally easier to solve (as opposed to Java that only has a single version easily available). But since all the C++ runtime does is set up the environment before handing execution to the main function, it feels as if there was no runtime at all. You sure you’re not confusing C++ with C#? Last time I checked, C++ was definitely compiled before-hand into machine code. A reference would be nice. :) C# is compiled into an intermediate language, and then compiled just-in-time into the native machine language, by the interpreter, which is distributed by Microsoft. References: Of note: “VC++ Redistributable Packages: The Microsoft Visual C++ 2013 Redistributable Package installs runtime components of Visual C++ Libraries required to run applications developed with Visual C++ 2013 on a computer that does not have Visual C++ 2013 installed.” If you are on Windows, go to “Add or Remove Programs” (it called “Programs and Features” in Win7) and scroll to “Microsoft Visual C++” and you’ll find every version of the Visual C++ runtime that your system has installed. Even though C++ is compiled to machine language (eventually), you still need the runtime. It’s just that the runtime is more of a primer than a running environment the way Java or .Net are. That’s the difference between managed and unmanaged. Which is why I clarified that this is technically speaking, but that in common parlance there is no runtime. If you hand someone a C++ executable, however, and they don’t have the runtime installed, the executable alone can’t run. The C++ Runtimes are simply a set of libraries that contain the code which every single C++ program on a given platform needs, and common functions that most of them do. They include the ‘boilerplate’ code like memory allocators, library loaders, the core functionality needed to talk to the operating system, the C++ standard library etc. The MS Visual C++ ones also have manifest checks to ensure the right version gets loaded etc (Side-by-side assemblies) The whole lot really could be statically-linked inside your binary if you wanted – however, this is usually only done for embedded systems because on ‘normal’ systems it simply makes your binaries larger for no benefit. (I’m currently working on 32-bit ARM system where I’m compiling the entire (RT)OS into my code.) The Visual C++ ones also allow Microsoft to patch your program when they find faults in the implementation of the Visual C++ standard libraries. – If you take a look in Add/Remove you’ll see a variety of patches to the VC++ runtimes you have installed. The theory is that all programs need those functions so there’s no point in a given PC having more than one copy. In practice a lot of installers just drop them in the program’s folder so you have many copies, but it’s worth a try. Microsoft Visual C++ is C++ written in an IDE, whose compiler didn’t finish compiling. That’s Microsoft’s choice, and not inherent in the language. C++ itself is a compiled language. :) GCC in linux does the same thing. You need libstdc++ to run C++ programs compiled with it: clang also has it’s own libc++ So, if the three major C++ compilers, on the three major platforms, all have runtime libraries C++ programs need to link against to run, I think it’s fair to say that C++ has a runtime. It’s a small, minimal runtime, basically a bunch of functions that are too large to inline and standard setup code to get your program up and running. Otherwise, I’d like to hear what you think a runtime is and why what all the compilers call a runtime is not a runtime. Well crap. I thought gcc compiled and linked everything into one file, which could execute on its own, without anything else needed. (Except if you were relying on DLLs in your program.) Now I need to check its docs for a flag to do such a thing. :P You can tell gcc to link statically. Although there are some technical issues you have to be aware of. For example, you might have issues with your dlls if they link to a dynamic version of the library. “C” does not technically need a c runtime. If you are thinking of msvcrt.dll then that is not really needed. It’s got functions like malloc and so on in it for portability/compatibility of originally Windows own system code. Those are just wrappers for HeapAlloc and similar OS APIs. Every process on windows automatically have kernel32.dll loaded. The minimum you need in a C program is the ability to call GetModuleHandle on kernel32.dll then use GetProcAdress to do feature testing, no other dependencies needed. From there you can simply get to all the APIs and stuff you could possibly need or dream of. Also note that C does not compile directly to binary (machine code I assume you mean), it goes through a assembler first. Some language > Assembler > Machine Code, or in some cases: Some language > C > Assembler > Machine Code which is kind of weird when you think about it for too long. Oh and the main() function, you can totally make your own and tell the linker to point to that directly, the argv and argc stuff is again a holdover from portability, Windows API got special calls to retrieve that stuff so you do not need argv and argc (most likely they are just empty anyway). A “C” exe can get freakishly small this way, a few KB in size and no dependencies at all. To be clear, I’ve been speaking about the C++ runtime, not C’s. C also has a runtime, but it’s even tinier than C++ and often linked into the executable directly. Yes, the runtime is super simple stuff. I said this. But that doesn’t make it not a runtime. It’s not a managed byte-code interpreter, but “technically speaking”, that is, using the correct technical terms, it is a runtime. Which is why the dll is called “MicroSoft Visual C RunTime”. WTF! I was supposed to reply to Kian here on the C runtime stuff but something went wonky. C and C++ are probably the most well-known ones, but there are many other languages that compile down to native code. Many of the more popular functional languages are generally compiled (such as SML, OCaml, Haskell, and Common Lisp) and various languages which want to function in the same space as C and C++ do as well (such as Go, D, and Rust.) None of these are quite as popular is C or Python, but they are all languages that are used in production in various places, so they’re not ENTIRELY obscure. It’s the difference between static linking and dynamic linking, plus DLL Hell. Java, C#, etc. runtimes include both the core libraries you’d need and the runtime that everything works on. The runtime is generally not particularly big, but it still does a fair amount of work. C and C++ do indeed have a runtime (Ever heard of MVCRT?), but it’s so small it typically comes shipped with Windows or with the game itself. Then all the libraries the game depends on come bundled with the game as separate DLLs (dynamic linking) or as part of the executable itself (static linking). This is a valid way to do things, but it leads to the famous DLL Hell problem in the former case and makes it impossible to update libraries without releasing a new version of the executable, in the latter case. Fundamentally the difference is that C#, Java, etc. try to be platform-independent, so you need a translation layer between their bytecode and the machine. This is the runtime. My point was that if I release something written in, say, Java, everyone will have to download the Java Runtime Engine before they can use my software. This is not something that’s needed for a compiled language like C and C++. Though I have noticed that Steam launches the Visual C++ installer a lot whenever I start a game for the first time… But if you hand that C/C++ Windows compiled executable to someone using a Mac it won’t do anything. Interpreted languages (which Java is) were specifically designed to solve portability problems by adding a middle layer to the process. It’s very much done for a reason. You’d have to port and compile your code to have different executables for different platforms. It’s a burden on the developer, but not on the user like asking the user to install a third party engine would be. Well that’s an important decision to make when choosing the language and tools to use on a project. Sometimes it’s better to burden the user than the developer and sometimes it’s vice-versa. Depending on the size and scope of the project it might be prohibitively expensive (in either time and/or money) to port your code for another compiler, but it’s trivial and easy for a user to install the machine specific interpreter. If the application is fairly small porting your code is much more manageable and you can have the luxury of creating custom executables for all the desired target Operating Systems. Things get even more complicated when you get into web hosted solutions. Those that have an interpreted language backend allows you a lot of flexibility in what server configurations you can use. Depending on your product that could be very important. What you seem to really be pointing out to me is that developers should insure they use the right tool for the job. It’s still an issue on numerous levels. First, it’s much more convenient for everyone if you only have to distribute one executable. Would you want to have to make sure you’re buying the Mac disk instead of the windows disk? And it would mean the developers have to compile it on numerous different platforms, which in turn requires that they have them, which can be an issue for smaller developers. And that’s assuming the compiler handles everything for them. If they have to directly interact with system functionality to get a display window and such, they’ll have to actually rewrite and retest the code for every platform, which can rapidly get expensive. Or they can write everything in Java and never deal with any of that. And then the user goes and gets a third party engine once and they can run everything written in Java just fine. The downside is basically that the JRE has to do all the platform-dependent stuff on the fly, so it is slower. They have various fancy tricks to speed it up, but it’s still never going to match compiling it into the platform machine code ahead of time. This statement is puzzling. You do know the languages, so you should know that you can totally write code that looks like C in C++, while still using features like RAII instead of manual resource handling. The only real thing C is missing, besides clean memory management, are standard libraries for collections. C++ has those libraries, but you have to employ the ugliest syntax possible if you ever want to use lists. I don’t think I saw an answer to your complaint, why you need a runtime environment installed in languages such as Java or C#. There are a number of reasons. Essentially, these languages offer complex facilities. For garbage collection to work, for example, the runtime needs to be aware of what your program is doing. Garbage collection is an entire other program that runs under your program and is updating references and moving your memory around for you. To give you network services, the runtime needs to talk to the OS on your behalf and implement the entire network stack. To create windows it has to have an entire rendering component that handles that. So say you wanted to have a stand-alone executable. Every program written in that language would have to duplicate all those facilities, and then compete for the resources. A simple “Hello World!” would have to load all sorts of things that you don’t really need but that the language establishes should be there. You could cut back on some of that by doing static analysis, but that makes the compilation longer and more complex. By having a common runtime for all the applications, you cut down on the size of the executables, simplify compilation (or remove it altogether), and you can take advantage of economies of scale on shared resources. For example, if you have many Java programs running on a single machine, the garbage collector can probably manage the lot more effectively than if each one had it’s own independent garbage collection. Those are some of the reasons I imagine you need to have a runtime in managed languages. How do you tell a C++ programmer and a C programmer apart? If they don’t make any distinction between C and C++, they’re a C++ programmer! C++ is C with everything Stroustrup has ever heard of bolted onto it. Source. C# – the new Java! :P I’m happy at least, that Python is still around. Death to unnecessary syntax! Long live languages which respect the programmer’s time! :D C# is Java without the dumb. :V And it’s only for Windows… (Mono doesn’t count.) Mono may not count, but that won’t matter for much longer. MS open-sourcing and Linux-porting C# Open-source of C# compiler Analysis of C# open sourcing I thought writing the game engine in C and then using a higher-level scripting language on top was the rule rather than the exception these days, although that could well be mistaken. WoW has Lua, EVE uses a Python variant, and so on. I think my favourite scripting language I’ve seen recently is Limit Theory’s LTSL (unfortunately the forums seem to be down at the moment, but it’s easily google-able). It’s a LISP variant, but where parentheses can be replaced with indentation, so it ends up looking a lot cleaner and easier to read than LISP while still being easy to parse and interpret. It looks like he’s using it to write shader-like programs, so I assume it’s relatively fast. C (or C++) executables/libraries and LUA to handle the scripting is probably one of the most common combos. Now I have no actually done any LUA scripting yet but if I was to recommend anything I’d recommend a C and LUA combo. Though some seem to prefer Python over LUA so you may see that with some game engines. Both C and LUA has a huge amount of books/references/examples on the net so as a programmer you are rarely stuck if you should sit there without a mentor. This is my understanding as well. This is even what Unity does: they give you their monstrous engine written in C++, and you script all your own code in a .NET language. Until they release their new compiler (whatever the fancy name is), the performance of scripting isn’t particularly great, however. Moving transforms around has a surprising overhead. The main problem is that Unity is still using an incredibly old version of the Mono compiler, due to licensing issues. It’s missing a million and one features, bugfixes and optimizations that both Microsoft’s official .NET compiler+runtime and Mono’s own have had for ages. “I thought writing the game engine in C and then using a higher-level scripting language on top was the rule rather than the exception these days, although that could well be mistaken. WoW has Lua, EVE uses a Python variant, and so on.” WoW and EVE are PC games though – if you go onto consoles, the higher-level scripting components are probably re-written, or used with a Lua/Python compiler that compiles down to C/C++, to then compile down to machine code for the console. I mean, that’s my immediate guess – after all, IIRC, Minecraft on XBox was re-written to C#, IIRC – in part because you can use C# there. Or in other words, the reason you use C/C++ as a backbone is because it’s the one part you’re probably going to need to do the least amount of work to get up and running, before even doing platform-specific changes to get the non-working parts up and going fine. I think the issue is that the various components of a game — or any major piece of software, for that matter — have different purposes and so have different requirements, and if you try to make one language that can fulfill all of those requirements you end up with a language that won’t do any of them all that well. The biggest problem is that software projects all focus on having one language doing everything, and it’s often the coolest one that wins, or the one that most people know that wins. But that usually means that the language does some things really, really well, and some things really poorly. I’ve worked on multiple projects that heavily used different languages for different parts of it. I had one with a Java GUI, a C legacy GUI, and C/C++ servers. I had another one with a Javascript/HTML front end and a C++ back end. One of the big gripes about some other projects was that they insisted on using one language — again, usually the new and cool one — for everything, and it couldn’t do everything well. One advantage that C/C++ has is through various libraries and mechanisms it can generally do pretty much everything reasonably well … even interact with other languages (Java might be better at that than C/C++ though). So writing one language for gaming won’t work because USING only one language for gaming is probably a bad idea. What you want are multiple languages all used in their appropriate places in the software. Couldn’t agree more. And nothing is worse than seeing the wrong language used for something (or heck, the wrong game engine used for a game), or worse a language or engine is used without the developers having enough time to learn/understand it. Nothing is worse than seeing XML used as a scripting language. Nothing. I think I know (seen) what you mean, I agree, horrible. Shamus, re: the following tweet: “These Victorias Secret ads make me wonder if somewhere out there, someone is working on some kinda “real-time photoshopping” for live video.” People have been working on this sort of thing for a while. Here’s a video from 4 years ago. Make you wonder what tech is capable now 4 years later. That video evidence in court “The court can clearly see the accused is not as fat as the man in the video”. Odd that CSI or one of the other cop shows haven’t touched on “photoshopped” video yet as a episode plot. They are certainly good at catching faked audio. “See if I isolate these frequencies, there’s a cut/change in the background noise here”. Really now? You can download room noise recordings on the net, then simply filter out the room noise in the original and replace it with the fake room noise, voila any “splice” will sound seamless. Unless… they got a database of room typical noise in their lab computer…shit I think I gave the writers an idea now. But yeah, that Baywatch muscle boost was creepy. That being said it was not high fidelity video, but with improve algorithms and modern hardware I doubt that is an issue now. Is the new Terminator movie going to use some tech similar to this for Arnold’s T-800, i wonder?! I’m mostly tired of the elitism I see where people are like, “Java!?!?!? Have you lost your mind? If you really want to make a game, you should be using C++.” Not to mention that practically every game job posting wants a load of C++ experience. So, boo C++ out personal spite. The main problem is that Java was made for line of business applications. It’s very heavy and cumbersome for gaming applications. It’s why Minecraft uses so many resources. I’ve talked to a few programmers from Ubisoft when they visited my university. They develop all their engines in C (maybe C++, not sure) but they have an inhouse scripting language on top of that. The scripting language isn’t interpreted though, it’s not C# to Unity’s C++ engine, it’s probably much more efficient. Seems like the way to go. Note that C# is not interpreted, it’s JIT-compiled. More importantly, I wouldn’t trust any homebrewed solutions to be more efficient than dedicated counterparts. Ubisoft makes games, not compilers or interpreters, after all. Full disclosure: I’m a bit of a C++ fanboy. It’s my job and it’s my hobby. So take what I say with a pinch of salt. I don’t agree that video games need a special language just for them, and I think it makes sense to use C++ for them. More so than some newer, hotter languages. Although game companies need to leverage the strengths of C++ properly to be able to take advantage of it to the fullest. First of all, video games are complex. As Carmack put it, video game programming is more complex than rocket science. In your typical AAA game you have a real time simulation of the player plus several AI, using many complex systems (weapons, vehicles, animations, etc), in huge areas that can be explored in three dimensions, feeding data to a real time rendering engine with photo-realistic graphics and surround sound, which has to page in and out gigs of data from storage, while communicating over the net to synchronize with a server that’s trying to keep dozens of other machines up to date. And all this has to run in uncountable combinations of processor, motherboard, memory, hard disk, audio, video and network components of varying quality. Complex problems require complex solutions. Simplifying the problem often comes down to creating higher level abstractions, and abstractions by their very nature are “leaky”. That is, they don’t apply everywhere all the time. They have edge cases and exceptions. An abstraction that perfectly models the underlying problem would be just as complex as the underlying problem itself. The way abstractions work is that you sacrifice flexibility for ease of use, and live with the fact that solving corner cases will expose all that complexity that you wanted to hide. And you better hope those corner cases aren’t right in the middle of your program’s domain, because your abstraction hobbled you for dealing with that kind of problem. And considering the breadth of domains that a modern game has to tackle (networking, processing, AI, rendering, etc), you don’t have a lot of room for abstraction. What works for networking is not going to work for rendering. And this is exactly why I think C++ is so good (and in particular, perfectly suited to game programming). C++ is meant to help you create abstractions. Instead of having a language that tries to abstract making games, deciding your trade-offs for you and making it impossible to do anything about it, you have the tool to create the abstractions you need, for each domain you have to tackle. All of which can talk to each other in a single system. Another way this is often put is that C++ is meant to write libraries (which is in essence what being a systems language means). Which exposes another strength of C++. C++ is meant to be easy for the user. The way it does that is that it loads the complexity on the library implementer. This is the typical example of “Hello world” in C++: #include <iostream> int main() { std::cout << "Hello world!"; return 0; } This is pretty easy to follow, right? I think even someone that isn’t a programmer can tell that “std::cout <<" prints things to the console. And yet "std::cout <<" is an example of a specialized template of an overloaded operator. There are a few more qualifiers that apply and I can't remember. And yet, while the person that wrote "std::cout" had to think of all that and what all those words mean, the user can simply use it. Of course, this requires that libraries be clearly designed and that they have consistent and clear interfaces. C++ enables you to write clear interfaces, but it doesn't prevent you from writing terrible interfaces. But the same can be said of any language, you can write ugly code in any language. Which leads to one of the trade-offs C++ had to do, which has earned it it's reputation for being so complex and overloaded, but that should also help game development. C++ is meant to be backwards compatible. This means that code written in the 90's (nearly twenty five years ago) can still compile, or at most require some trivial clean up to work with a more recent standard. This is a great win for companies, because it means that all their legacy code will still work and compile with new tools. And game companies should have a lot of library code that they depend on (back-end code shouldn't be rewritten every other year, for example, and even game engines benefit more from incremental improvements over rewrites). One downside of backwards compatibility is that you have to live with your mistakes. And there have been some of those. Keep in mind, C++ was a pioneer in many language features that were later picked up and polished by newer languages. They didn't always get things right the first time. And when you've made a commitment to backwards compatibility, the first time is the only go you get. Breaking changes have to be really worth it. This includes mistakes that C made, so that they kept compatibility with it. The other downside is cruft. As you come up with new ways of doing things, you have to still support the old way of doing things. Which makes the language seem overloaded and complex. After all, it's the new language, plus the previous iteration, plus the one before that. In conclusion, C++ is awesome, and Shamus is a slanderer and a liar! (just kidding). I’m not really sure how that is an advantage of C++. Pretty much all languages let you create abstractions, and at least Blow’s proposed language is not one with a bunch of game-specific abstractions built in. I’d need you to clear up what “that” refers to specifically. I’m guessing the use of abstractions? To clarify, saying that something is an advantage of the language does not mean that no other language shares that advantage, it highlights that not all do. That said, C++ is good at it because of two main reasons I can think of right now: It allows the implementer access down from individual bits and memory locations up to complex high level structures, and it allows the implementer to hide all that complexity behind a clear interface so the user doesn’t need to worry about it. Few other languages give you that kind of flexibility. Anecdote time: a guy that interviewed prospects for Facebook described how a common trend among Java programmers was that when asked to implement a list (single or double linked) in a language of their choice, they were usually stumped. There are a number of reasons why this may be so, and I don’t have experience with Java to say why exactly, but it may have to do with Java being too high level and hiding memory management. In exchange, you get a lot of work already done for you. Making a network service from scratch in Java is trivial, you just use the extensive network facilities already included in the language. In C++, there is no language support for networking. You need to use a library (either third party or whatever your host OS provides), or build it from scratch yourself. Which reminds me of a quote by Sagan: “If you wish to make an apple pie from scratch, you must first invent the universe”. C++ is a bit like that. But if you need a network service that behaves differently from how the protocols Java provides you do, you’re going to have to do a lot of weird things to wrangle the system to perform as you need it to. In C++, you have access to the guts already. Another advantage I just remembered that C++ has (over C in this instance) is that it is much more expressive, thanks to templates. Generic programming, being able to create forms that apply to different types in a type-safe manner, is huge for making powerful abstractions. Actually, it’s probably because java.util.LinkedList already exists. Making your own in Java is actually pretty easy. Basically, Java has primitives and objects. int, double, boolean, char, and such are primitives. They get allocated on the stack, and when you pass them as parameters their values are copied over. Objects have a reference allocated on the stack and their contents allocated on the heap, and when you pass them as parameters the references are copied over. You can’t interact with the referenced data except by calling methods of that object. This lets you do a linked list pretty trivially by making a class that can hold a reference to objects of the same class, then storing a reference to the head of the list, with something to change that reference if you’re inserting or removing at the head. Add insert, remove, and traverse methods, and you’re done. Java will allocate appropriately-sized chunks of memory and do garbage collection for you. Since what you’re actually passing are just references, any change to the data will change it everywhere it’s referenced. Why yes, this does sometimes end very badly. But it’s also pretty handy. “I think even someone that isn't a programmer can tell that “std::cout <<" prints things to the console." Just for the record, I wouldn't have guessed that in a million years. For all I know it defines a new sexually transmitted disease. I mean, you might make a case that C++ hello world is a little simpler than the Java version, because of the required object-orientation stuff. But if you think that it’s simpler or easier for “even a non-programmer” to understand than a Python (or Ruby or similar) hello world, you’re blinded by your language preference. I’m not making a point about “Hello world” being simpler than in other languages. That’s a silly and pointless argument to have. What I hoped to highlight is that even though many people dislike C++ because it is “overly complicated”, there is thought put into how that complexity is allocated. In the case of C++, it falls on the implementer of a class or library, not on the user. “Hello world” is an example of this principle. The std::cout “<<" operator would be complex to write: You'd need to know about overloading, templates, streams, locales, inheritance and a bunch of other things. But despite all the complexity behind it, using it is so simple that it's one of the first things you learn. And not only that, you can even extend its functionality for your own types without needing to know about all that stuff. What this means is that on a large project, you need only a handful of people that are "experts", and the rest can use the abstractions the experts create to be productive. I watched that video months ago and within a day could think of heaps of instances of code I’d written in my past 7 years in the industry, that would’ve been quicker and simpler with some of those changes. I can’t remember the exact points from the video, but I wrote a list of other things I’d like to see improved upon (or at least discussed too). Things such as: alloca() actually being properly supported instead of kinda sorta supported on most platforms by using funky assembly under the hood. Better support for platform specific implementations of files, currently I have to go through a bunch of visual studio property pages and flag files I don’t want to compile on particular configurations and adding new platforms is a massive pain. There has to be a better way of doing this. Have an interface keyword that works similar to virtual but works at compile time in a manner similar to templates so that we don’t need vtable lookups. (I can’t think exactly how to work it under the hood, but I’m sure with some time that someone could think of a decent way to do it). Make function pointer and data member pointer syntax nicer, I know a lot of experienced programmers who still have to look it up every time they use them. Adding functionality to define initial values of data members at declaration rather than in each of the constructors (which can lead to lots of code duplication and the odd error when someone hasn’t NULL initialised a pointer they thought they had). Multiple return values from functions. It’s a lot clearer than having a single return then a bunch of out arguments. And obviously everything he said about being able to tell the compiler which members to automatically delete or ref count would make things easier to read and cut down on unnoticed memory leaks and such. People could even discuss whether or not we need certain entrenched standards like case sensitivity. I’ve seen functions that had both a ‘filename’ and a ‘fileName’ variable declared at different points and only had one updated when someone changed stuff later and so on. I figure case sensitivity was probably originally for compiler speed but I think the difference now would be so negligable that it’d be worth trying to not have it and see if it was a problem. Ultimately I agree with the premise that we could build a better general purpose language that simplifies things games programmers do every day, and that people should definitely keep the conversation going. I tend to pass structures to a function and return a error code (any changed/data returned is done to the structure), that way all functions return a success (0 zero) or failure (a non-zero value/error code). And in cases where speed is a issue I don't use a function at all and instead inline the code that would be in the function. But yeah calling conventions was odd especially for a while. On x86 Windows you have STDCALL, FASTCALL and CDECL. Luckily with x64 there is only FASTCALL, so linking with dynamic libraries or calling other code won't be a minefield (I.e: Why the heck does this keep crashing.). Just wanted to chime in that C++ can return multiple values from a function, of any types you want. You can either return a struct, which can be a little annoying, or you can return a tuple (which are in essence ad-hoc structs). And to avoid the annoyance of having to write the template definition to declare the variable at the calling site, you have the auto keyword. So you declare the functions like so: std::tuple<double, char, std::string> get_student(int id); And use it like this: auto student = get_student(0); And now student is a variable of type std::tuple<double, char, std::string>, only without all the typing. Tuple reference: As someone who predominately works with SQL the case sensitivity thing always screws me up for a bit when I switch back to some front end coding for a bit. Case sensitivity can be nice. For instance it lets you declare List list and suchlike. But yes, if you’re using case sensitivity to distinguish between two things and it is possible to compile a program when you mix them up in a scenario where that changes functionality you have a problem. It’s not an issue in Java for the specific scenario I described because either you’re calling a static method (which will behave identically in either case) or it won’t compile if you use List. The first part is asking for a better IDE, or possibly something better than make/nmake. And I’d agree, Microsoft Visual Studio is a poor IDE for multi-platform programming – this isn’t a surprise though, because it was originally written to encourage people to program on and for the Windows platform – and only the Windows platform. The realisation that “Ah, now there are several Microsoft platforms” came later, and is part of the Visual Studio technical debt. There are other IDEs that handle multiplatform better and will happily use the MSVC++ compiler (and GCC, Clang et al) if you want, as well as replacements for make/nmake that have an entirely different set of limitations. My personal take on Blow’s video was that he was too quick to dismiss Rust. Rust is a new language being developed at Mozilla which is focused on being a modern C or C++ equivalent, so it compiles to native code, requires no runtime, and does not have garbage collection. It also makes it very easy to call C from Rust and vice versa. Rust also has an unusual but quite powerful system where all memory management is determined by the compiler according to simple rules, so errors like segfaults or memory leaks are impossible. The mechanism used takes a bit of learning, but it’s not really complicated””just unusual. (There is an ‘escape hatch’ by which you can violate these rules, which might be necessary in some low-level code, but it’s designed as a last resort.) Blow mentions Rust but dislikes it because it’s a “big-idea language” and also has too strong an emphasis on safety and correctness, which he suspects would be too strong an impedance mismatch. I would nevertheless argue that it’s one of the more promising languages for future game development. Blow’s argument against Rust was that segfaults and memory leaks weren’t a big deal so protecting against them just puts unnecessary constraints on the rest of the language/program. He argued that memory leaks aren’t a big deal? I’m no programmer, but every damn time I hear about an update in some open source application I’m interested in, there’s talk about how they fixed a bunch of memory leaks. Every time I hear complaints about how some program is a hog that slows down your system, the allegation is that there’s a bunch of memory leaks. How can memory leaks not be a big deal, especially in programs like huge hastily-written games? My biggest fear if any new language might come up is that it likely will be garbage-collected and not support RAII. Yes, automatic garbage collection is a good thing except for the cases where you want to couple certain functionality with a clearly defined lifetime of an object. (For the record, I consider RAII the single most important feature that C++ brought to the table.) (I’d also settle for reference counting as a substitute as you can use it like RAII when you never hand out a reference or pointed to anything outside the scope to which you want to tie a resource.) I think it’s fair to argue that control over the GC is one of the features that would be necessary in any new language intended for game development. IIRC, it’s amongst the reasons presented by Blow for rejecting the existing C++ “successors”. I don’t think garbage collection is good, frankly. RAII is hands down the superior alternative. To repeat a point I heard in a talk by Stroustrup, garbage collection only manages memory. RAII is a general method for handling any kind of resource, be it memory, file handles, or whatever else your system needs to handle. He doesn’t argue for GC but in his video what Jonathan Blow uses to argue against RAII is that other resources occupy a very small part of development while the vast majority is about memory, thus a generalized tool for a generic resource is less useful than specific methods for handling memory. I’ll have to listen to it when I can. Still, RAII is amazing and if he argues against it, then I can’t help but think he is wrong. What RAII basically means is that when you acquire a resource, you have to assign the responsibility of cleaning it up to someone. And whoever you assigned that responsibility to will clear the resource when it’s done with it (if you chose a shared responsibility with reference counting, the last one to use it will clean up, etc). This is a design phase issue, and in fact it helps write clearer code because it means you had to put some thought into it before you start typing. It also provides deterministic handling of resources, which helps debug performance issues and make guarantees about the behavior of the program. Which is very useful when you need to make sure your frame is done within 1/60th of a second to avoid stuttering. I’ll have to listen to why he dislikes RAII. I’ve never heard of anyone that argued against it, and I can’t think of a reason why anyone would dislike it. The only problem scenario for RAII that I can think of (working from high level knowledge of the concepts versus knowing how they are implemented) is if you really need to manage your memory footprint very precisely inside a limited scope. Having finer control over when the memory is taken and given back could be important if you are struggling to stay within some size constraint. RAII could make that sort of process unintuitive if you needed to do it, but it would depend how the RAII works under the hood which I will again admit I have absolutely no idea to the specifics of. I would think GC is probably an even bigger problem if you were working inside such constraints. If you have really tight constraints, RAII can also help you manage your resources effectively. You just engineer the solution differently. RAII gives you absolute control over when you grab it and when you release it. It’s up to the implementer to make the right choice given the appropriate tools. If you are working in such a system, I think its reasonable to expect the implementer to be an expert in the field and you have tools like emplace new and custom allocators to manage your memory however you want to. RAII is an approach to solving a kind of problems, not a fixed solution itself. And if it really doesn’t fit, that’s cool. You can fall back to pure C-style at no cost from within the language and not use it, and if you need to be even more specific you can fall back to assembly directly. Although the realm of people that need to do these things should be vanishingly small. I’m not using C++ so I don’t know much about it, but his argument seemed to be that there’s not much need for it at all. Using non-memory resources is such a small part of his programs, and one that doesn’t cause a lot of problems, so what’s the point of having some specific feature for handling those? The only resource he cares about handling is memory. Not that these aren’t my argument but what I’ve heard form Blow’s videos. Files are probably the most commonly accessed resource right after memory. What would you rather do, put a std::fstream in your function scope or design the entire function around the fact that you must, at all times, call a function to close it before returning from the function. Exception safety and handle leaks become a serious risk without RAII. Being the second most common doesn’t matter much if the second is way behind the first. I don’t really see much problem with having to manually close. Sure it’s nice not to, but it’s not a major issue. Especially if you’re in a language without exceptions. There are interesting corner cases where the C++ allocation/deallocation model simply doesn’t work (which pushes you back into manual new/delete or not-sufficiently-intelligent reference counting (these cases tend towards being where having circularity in your data structures is useful and falling back on weak references really isn’t a solution, since that can end up with parts of your data being deallocated before it’s actually out of use)). In, say, Common Lisp, the “with-” idiom is frequently used for resources that need to be finished off somehow, in a predictable way, at a predictable time. So if you need to open a file (and ensure it’s closed once the code block is done), you do something like: (with-open-file (the-file “and the name goes here”) ;; Insert code here ) And when the execution passes back out of the block, the file will be flushed and closed. There’s, now, a similar thing in Python (although implemented in a completely different way). Also, I thought the basic idea behind RAII was that you should never “first allocate, then initialize” but rather you should do both at once. The dealocation of the allocated object is (again as far as I understand it) completely orthogonal to RAII. What you described about Common Lisp is literally what C++ has always done. RAII stresses initialization with allocation because in C++ deallocation can then happen automatically without further issue. Match the lifetime of the resource to the lifetime of the object and you know exactly when it is acquired and when it is freed. A more detailed description is here: but to summarize: C++ objects (classes, structs) have what are called Constructors and Destructors. You can specify what they each do. When you declare a variable of some type, the constructor for that variable is called. When that variable goes out of scope, the destructor is called. This is guaranteed to ALWAYS happen, even if you throw an exception. The stack unwinds, and destructors get called along the way, freeing your resources. Your lisp example, in C++, looks like this: #include <fstream> void SomeFunction() { std::fstream theFile ("filename"); // We open a file named "filename" theFile << "Let's stick some text into the file."; } // Bam, theFile goes out of scope, destructor is called, file is flushed and handle released. This is the proper way to handle resources in C++. Exception safe, automatic, clean. At least, it’s this way for automatic storage. When you need something that has to leave the scope, you should use smart pointers. The greatest feature that C++11 brought is “move semantics”, which enabled the language to have effective smart pointers. But explaining that wouldn’t really fit in a short explanation. You know, I actually know C++ and I still find the allocation/deallocation of C++ less than ideal. Give me predictable GC every day and let me have a construct that closes/deallocates things early if that makes semantic sense. But, then, I’m used to being able to return a closure closing over local variables and in C++ that requires quite a dance (or an intermediate object). I’m not sure what you mean by “a construct that closes/deallocates things early if that makes semantic sense.” If you want to limit the lifetime of an object, you can use an enclosed scope: #include <fstream> void SomeFunction() { int someVariable = 0; // Do some work { // Open scope, someVariable is visible here std::fstream theFile ("filename"); // Declare a variable // in the enclosed scope // Do stuff with it } // Exited the scope, theFile destructor is called // Do whatever else you need // theFile doesn't exist here, someVariable does. } Or give the class a method that cleans up the resources if you need it done early. For example, you can call std::fstream::close() at any time to close the file. I don’t see how you could ever have a predictable GC. As far as I understand, that’s impossible by definition. On the other hand, reference counted pointers behave kind of like that. That random extra scope is very misleading, knowing it’s function in this case relies on an inference of some possibly non-standard underlying rules. Until this discussion it never occurred to me to use scope like that. I would categorize it as clumsy, but at least it’s fairly simple. How is it misleading? That is the whole point of using a block within an enclosing scope. Automatic variables have scoped lifetime, and you can create scopes within scopes to handle that lifetime as your needs dictate. It’s part of the fundamental syntax of the language. As far as I know, scope rules have always been part of the language. The behavior is clear and well defined according to the language specification. It’s an example of using a language feature for the exact purpose it was defined for. We’re not even talking about an obscure language feature. Scope rules are as fundamental as knowing you have to declare a variable before using it. Things only exist within the curly braces they were declared in, whether those curly braces belong to a function, an if clause, a while or for loop, etc. It might be not that the people argue with the title but rather simply don’t like when title is not in line with reality or the points in the article itself. Because these practices are mainly used by bad journalists as means to draw attention to otherwise standard text (particularly popular in tabloids). ;-) Anyway good article and thank you for the video link. I’ll take a look. The problem with Blow’s video is that he makes it abundantly clear in the first few slides that he has not done his research. D fills his requirements to the dot (RAII, optional GC, modern syntax, fast compilation, great performance), and then has a few super useful features on top of that such as easy compatibility with C and C++ libraries, powerful meta-programming and a good community. But he ignores all that, sprout some nonsense about how D is “too similar to C++” without ever specifying what that’s supposed to mean, and then goes on and creates a language without the least care in the world for important problems. That’s how Javascript was made, and look how horrible that turned out. The only things bad about D are that it isn’t finished (but more so than his abomination), and that it’s quite annoying to google for “D”. I don’t know what his requirements are but in his videos he’s made it clear that he’s against both RAII and GC even if optional. Javascript horrible? Javascript is a wonderful language. JavaScript is a plague. Anyone who says otherwise is a scoundrel and a blackguard. So might it be useful to do some work in Vala or something like that? Vala seems like a nice compromise in that it’s apparently a relatively easy-to-work-with kind of language, but then it generates C code (which in turn then gets compiled). So like, if you wanted to do some tweaks that can only be done in actual C, you could mess with the generated code or write pieces directly in C. But most of the work could be done in the easier Vala language. You could write weeks of columns on mods and mod support and I’d read them. Looking forward to this. I’m a web developer who can’t even credibly say he understands javascript* (so much time fiddling with making things work in Sharepoint) JQuery makes me lazy. *Mainly its all the browser specific stuff I don’t get though I’ll admit I haven’t found a use for creating my own objects yet which I know means I’m doing something wrong given the complexity of my projects. Relevant and topical: a talk by a Ubisoft Montreal C++ developer at CppCon 2014 a bit before Unity came out. One of the slides: “Big Games * Assassin’s Creed Unity: – 6.5 M C++ LOC for entire team code. – 9 M more C++ LOC from outside project. – 5 M C# LOC.” LOC = Lines Of Code Missing from the slide: * No faces. The thing is that there’s nothing wrong with C++ being old, per se – it’s not as if it hasn’t been maintained for years, it’s still getting updates and improvements. I haven’t really gotten into the new standards yet but there’s all sorts of nice pointer types baked-in now that you used to need Boost for. And there’s new C and C++ libraries to do Cool Stuff popping up every day. I think the only “problem” with it, very generally speaking, is that as a compiled language you need to build a different binary for each platform you’re targeting, which can be a bit problematic in today’s world of various mobile devices with various differing architectures. It’s also its strength that you can come up with machine code for that specific platform, but intermediate bytecode languages can get pretty decent speeds these days without going all the way down to the metal, without sacrificing portability. But yeah, my point is, C++ is old and wise, not old and frail. I know several programming languages, mostly from both hobbyist games programming and also the science work that I do. I also have done assembly language programming for Z80, 6502, 68000 (Atari ST) and the 8086. I use mostly C++ for most of the stuff I do these days and have written games in it, but it’s got serious issues for games programming. I did think that a cleaner language like C# would be a better choice of language coupled with good support libraries and a lightweight scripting language such as Lua for mods. I’ve recently been looking into cross-platform programming for gaming using HaXe and the support libraries OpenFL and Flixel which takes the hard work out of maintaining multi-platform codebase. It’s not there yet as there are various issues with the platform support having incompatibility with modern versions of the platform tools and libraries. Unity does the same job but it’s Windows only and most of my machines are Linux based. If you could write the basic engine in a cross-platform language and then apply platform specific changes as required, this would remove the need to keep rewriting the same code in different languages for different platforms. One factor that is also important (and missed out from the discussion) is support libraries – ideally, you’d have one API that you would write code in and this would translate to the various platform libraries in sound or graphics (such as either OpenGL or DirectX). If a new graphics standard came out, you’d add support to the library for it and alter the API should it be required, hopefully without breaking existing code (too much). I think this is the future myself. I don’t think the major issue having the perfect games programming language but a integrated system that allows you to realize any game you want that runs on any platform that you might want to support. Duuuuude! You can’t just drop all those questions without answering them! I suspect they are planned for future articles at least? Sheesh. 1. People make better drivers that do more things and then new games use the better drivers. Also they may do the same thing better and then new games are designed to the performance constraints of the better drivers. 2. I assume it’s easier to program. Unless you’re going to dump the entire game state to hard drive (do not do this, very soon your saves will be bigger than the executable) you need to decide what to store and what to throw away. If you have a checkpoint, you don’t need to store nearly as much world information, because it can be determined from the checkpoint used. Also, if they’re well-positioned, stuff like enemy locations and health can be thrown away without too much trouble. Remember that hilarious Skyrim shopkeeper exploit? That’s because something didn’t get saved that should have. 3. They have very flexible and powerful toolsets available to users. Most other games don’t. I’m not trying to be mean here but I really need sub-titles for this guy. thub-titles. So I went and made a bit of time to listen to this guy, and so far (45 minutes in) I’m not impressed. I don’t share many of his opinions, but I think there are two in particular that are terrible (and he himself calls the more important part of his presentation). His view on RAII and exceptions. 33:20 “No such thing as a resource” – I don’t know what to say about this. It’s just so wrong. But I kind of see why he thinks so, he’s too used to thinking at a low level. He can’t abstract away the computer running the software. He doesn’t see a programming language as a tool to describe a complex system, he sees it as a way to tell a computer what to do. So he doesn’t understand why RAII is so useful. He thinks the program’s job is to fill memory, he doesn’t understand that memory is merely a tool we need to represent more abstract ideas. That you have to build on abstractions to make more powerful, more useful abstractions. Sure, your program allocates memory, but that memory, while being a resource itself, can also represent resources that themselves have to be opened, used, and closed. For example, perhaps you have a “Treasure Chest” in your game. That chest is a resource, because you want it to be opened, only allow the player to interact with it while it’s open, and then close it, and not allow the player to use it after it’s closed. But if you only think in terms of the computer, you might not realize that that chest is a resource. So you think, “I don’t have many resources, I have three”. 34:16 “There’s a big misunderstanding here” – Yeah, we agree on that ;) 39:00 “RAII exists because of exceptions” – Oh, and he’s against exceptions now! “Exceptions are silly”. I’m sorry, but every thing he says is just so full of wrong and bad. But at least this is a common complaint. So, let’s address it. It’s an unfortunate fact of life that computers exist in the real world and not in an ideal state free of limitations or imperfections. Memory is finite, processing power is finite, disk space is finite, etc. So sometimes, when you attempt an operation of some type, that operation doesn’t do what you wanted it to do. An example: you try to ask for more memory but you are out. There are two main ways you can handle these situations. One, you report the error to the function that asked for the operation. “Sorry, no more memory”. It’s then up to the caller to handle what to do about it at that point. Two, you throw an exception, and basically fall back to wherever it is determined what to do about it. If you didn’t set any handler for it, your program dies. Oh noes. The irony is that the same people that complain about how any line of code could throw, will blithely ignore error codes anyway and just assume that every operation succeeded. It takes just as much effort to ignore exceptions as it does to ignore errors, and it’s better for your program to die cleanly when an exception shows up than to keep on trucking after finding an error, messing up things until you run into a crashing fault. Handling error codes properly, however, takes a lot more effort than it does to handle exceptions properly. Because that same line that could result in an exception would otherwise have called an operation that failed, so you need to check if it did, and then think if you can handle that error yourself, or if you need to cancel everything you were doing and return the error back to your caller, and so on down the stack. With exceptions, however, you only need to think about error handling at the point where you can actually do something about it. With exceptions, you can write code with the assumption that everything is peachy, and trust that if a line of code is reached, every assumption up to that point is true. With error codes, that is only true if you and everyone else involved in your project was careful about checking for and handling errors properly. So which one really frees you up to think about the problem at hand, and which one just appears to do so? Define programming language, I’m pretty sure this site was written in one. Its like saying the English language is becoming too obfuscated lets chop it in two. Game developers NEED a language. Assuming all interpreted/JIT languages are not used for gaming because they suck for it, a language that will be JIT/interpreted and that is good for gaming NEED to be made. When some game developer make a game X, they want that people play their game X (or at least try it), don’t specifically want that people use an operational system A B or C. They didn’t made operational system A, B or C, so they wont care if people will use it, its not their work/product. Said that using a interpreted language is good to make sure people use whateaver the hell they want and not whateaver the hell YOU sort of want. You dont>
http://www.shamusyoung.com/twentysidedtale/?p=25303&replytocom=879891
CC-MAIN-2019-39
refinedweb
21,031
68.2
Given. Examples: Input : n = 54, k = 3 Output : 2, 3, 9 Note that 2, 3 and 9 are k numbers with product equals to n. Input : n = 54, k = 8 Output : -1 This problem uses idea very similar to print all prime factors of a given number. The idea is very simple. First we calculate all prime factors of n and store them in a vector. Note we store each prime number as many times as it appears in it’s prime factorization. Now to find k numbers greater than 1, we check if size of our vector is greater then or equal to k or not. - If size is less than k we print -1. - Else we print first k-1 factors as it is from vector and last factor is product of all the remaining elements of vector. Note we inserted all the prime factors in sorted manner hence all our number in vector are sorted. This also satisfy our sorted condition for k numbers. // C++ program to find if it is possible to // write a number n as product of exactly k // positive numbers greater than 1. #include <bits/stdc++.h> using namespace std; // Prints k factors of n if n can be written // as multiple of k numbers. Else prints -1. void kFactors(int n, int k) { // A vector to store all prime factors of n vector<int> P; // Insert all 2's in vector while (n%2 == 0) { P.push_back(2); n /= 2; } // n must be odd at this point // So we skip one element (i = i + 2) for (int i=3; i*i<=n; i=i+2) { while (n%i == 0) { n = n/i; P.push_back(i); } } // This is to handle when n > 2 and // n is prime if (n > 2) P.push_back(n); // If size(P) < k, k factors are not possible if (P.size() < k) { cout << "-1" << endl; return; } // printing first k-1 factors for (int i=0; i<k-1; i++) cout << P[i] << ", "; // calculating and printing product of rest // of numbers int product = 1; for (int i=k-1; i<P.size(); i++) product = product*P[i]; cout << product << endl; } // Driver program to test above function int main() { int n = 54, k = 3; kFactors(n, k); return 0; } Output: 2, 3, 9.
https://www.geeksforgeeks.org/find-if-n-can-be-written-as-product-of-k-numbers/
CC-MAIN-2018-09
refinedweb
382
78.28
In today’s Programming Praxis exercise, our goal is to solve the first problem of the 2013 Facebook hacker cup, which is to give the sum of the highest values of all possible subsequences of length k of a given list of integers. Let’s get started, shall we? A quick import: import Data.List For this problem, we’re going to need to calculate a lot of binomial coefficients, i.e. the amount of ways to choose k out of n items. This involves calculating factorials. The trivial way to do this in Haskell is to use product [1..n], but that’s not very efficient when you need to calculate many different factorials. So instead we create a lazy lookup table of all factorials, so that we save a lot of duplicated effort. facts :: [Integer] facts = scanl (*) 1 [1..] The brute force way to solve the problem would be to simply enumerate all possible subsequences and sum their maximums. Unfortunately there are a LOT of combinations once you get to the maximum number of 10000 possible values (just printing 10000 choose 5000 takes several terminal screens), so clearly that’s not going to work. Instead, we can solve the problem in O(n) by realizing that each number will be the highest in every combination with lower numbers, e.g. the highest number will occur (n-1) choose (k-1) times, the second highest (n-2) choose (k-2) times, etc. Since the answer needs to be given modulo 1000000007, we do this at every step in order to keep the total down. facebook :: Int -> [Int] -> Integer facebook size = foldr (\(i,x) a -> mod (a + x * choose (size-1) i) 1000000007) 0 . drop (size - 1) . zip [0..] . map fromIntegral . sort where choose k n = div (facts!!n) (facts!!k * facts!!(n-k)) Some test cases to see if everything is working properly: main :: IO () main = do print $ facebook 3 [3,6,2,8] == 30 print $ facebook 2 [10,20,30,40,50] == 400 print $ facebook 4 [0,1,2,3,5,8] == 103 print $ facebook 2 [1069,1122] == 1122 print $ facebook 5 [10386,10257,10432,10087,10381 ,10035,10167,10206,10347,10088] == 2621483 print $ facebook 1 [3,4] == 7 print $ facebook 3 [3,4,5] == 5 print $ facebook 5000 [1..10000] The worst-case scenario, 5000 cards and 10000 numbers, takes just under 5 seconds. Since there’s a maximum of 25 test cases, the total time should be about two minutes at most. Not too bad. Tags: 2013, bonsai, choose, code, cup, facebook, factorial, hacker, Haskell, kata, praxis, programming
https://bonsaicode.wordpress.com/2013/02/15/programming-praxis-facebook-hacker-cup-2013-round-1-problem-1/
CC-MAIN-2015-27
refinedweb
432
71.44
A command line interface for the QUnit testing framework A Node module that adds colorful CLI support for the QUnit testing framework. There are two ways to use qunit-cli: Include it at the top of your test files. First, install the module using npm. npm install qunit-cli And now, require it in your test files: if (typeof QUnit == 'undefined') // if your tests also run in the browser... QUnit = require('qunit-cli'); // use QUnit as you normally would. Note that this module does not introduce QUnit into the global scope like QUnit does in the browser, so you'll have to do that yourself if needed. To run, use the node program. node mytests.js Use the command-line testrunner located at bin/qunit-cli, passing it the test files as arguments. If you install the module globally using npm, you can use the qunit-cli command which will be installed into your PATH. npm install qunit-cli -g qunit-cli mytests.js This will introduce QUnit into the global scope like QUnit does in the browser, so you don't need to modify the tests themselves. You can use both methods in the same test files without problems. There are several command line options available when running your tests using qunit-cli that mimic some of the options in the standard browser-based QUnit testing interface. They are: --module, -m Limits testing to an individual module --test, -t Limits testing to a single test (by number) --quiet, -q Flag to hide passed tests from the output The command-line test runner has some additional options available: --code, -c Path to code loaded globally. You can prefix a namespace using a colon (:) Here are some examples: # code exports are added to global namespacequnit-cli -c /path/to/code test.js# code exports are added to ns namespacequnit-cli -c ns:/path/to/code test.js qunit-cli is released under the MIT license.
https://www.npmjs.com/package/qunit-cli
CC-MAIN-2015-18
refinedweb
324
62.17
12-15-2016 04:16 AM Hi. Downloaded spark 2.0 from and deployed it according to the instructions for cloudera manager. Installed latest livy server from github with options "mvn clean package -DskipTests -Dspark-2.0 -Dscala-2.11". During startup livy server can't figure out the spark-submit version due to a regex problem in livy server LivySparkUtils.scala file. "Fail to parse Spark version from 2.0.0.cloudera1" Here is a similar issue,. Is there any official guidelines from Cloudera on what version of Livy server to use for Spark 2.0? And will livy server be packaged in future CDH releases? 01-11-2017 01:05 AM Hi, you could replace the last '\d' in the regex with a dot and livy will start corectly: def formatSparkVersion(version: String): (Int, Int) = { val versionPattern = """(\d)+\.(\d)+(?:[\.-]\d*)*""".r fixed: def formatSparkVersion(version: String): (Int, Int) = { val versionPattern = """(\d)+\.(\d)+(?:[\.-].*)*""".r 01-12-2017 12:20 AM Thanks!
http://community.cloudera.com/t5/Web-UI-Hue-Beeswax/Spark-2-0-livy-server-3/m-p/49352
CC-MAIN-2018-43
refinedweb
162
68.57
I need a Python program I'm using to poll a remote server for SSH connectivity and notify when it is available. I am currently doing this using paramiko; attempt to connect, if failure, wait and retry until success or max retries. This works, but it's a bit clunky. Also paramiko seems to either connect or throw an error, so the only way I could see to do this was with a try/except block which is bad, bad, bad. Here is the method: def check_ssh(self, ip, user, key_file, initial_wait=0, interval=0, retries=1): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) sleep(initial_wait) for x in range(retries): try: ssh.connect(ip, username=user, key_filename=key_file) return True except Exception, e: print e sleep(interval) return False As mentioned in the comment by frb, a try ... except block is a good approach to test availability of a specific service. You shouldn't use a "catch-all" except block though, but limit it to the specific exceptions that occur if the service is unavailable. According to documentation, paramiko.SSHClient.connect may throw different exceptions, depending on the problem that occured while connecting. If you want to catch all those, your try ... except block would look like this: try: ssh.connect(ip, username=user, key_filename=key_file) return True except (BadHostKeyException, AuthenticationException, SSHException, socket.error) as e: print e sleep(interval) If just a subset of these exceptions is relevant to your case, put only those into the tuple after except.
https://codedump.io/share/Kbw1izv42Nza/1/elegant-way-to-test-ssh-availability
CC-MAIN-2018-22
refinedweb
251
56.35
[Fuente:] Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. import React, {. Note React 16.8.0 is the first release to support Hooks. When upgrading, don’t forget to update all packages, including React DOM. React Native supports Hooks since the 0.59 release of React Native. now available with the release of v16.8.0. addition to making code reuse and code organization more difficult, we’ve found that classes can be a large. Examples Hooks at a Glance is a good place to start learning Hooks.... Building Your Own Hooks [TODO] Other Hooks [TODO]
http://jesidea.com/pakdb/react-hooks-introduction/
CC-MAIN-2020-16
refinedweb
110
70.5
.NET Framework Support on Windows Operating Systems Hans Verbeeck Microsoft EMEA September 2002 Applies to: Microsoft® .NET Framework Microsoft® Windows® operating systems Summary: Provides information about which versions of Microsoft Windows that the Microsoft .NET Framework can be installed on. Software requirements of the .NET Framework and exceptions to the general platform support are listed. Explains how to prepare applications for cross-platform support. (14 printed pages) Contents Supported Platforms .NET Framework Software Requirements Preparing for Cross-Platform Support Appendix Supported Platforms The .NET Framework can be installed on the platforms shown in Table 1. Table 1. Platforms the .NET Framework can be installed on The first thing to notice is that the .NET Framework will not run at all on Windows 95. This is consistent with other Microsoft® products like Microsoft® Office XP that also do not support Windows 95. The operating systems, on which the .NET Framework will run, can be divided in two groups: one that will run the .NET Framework with ASP .NET and one that will run it without. This can also be seen as the distinction between operating systems that can be used as a server for .NET applications and operating systems that should be used as clients running .NET applications. Note that all of the versions of Windows NT 4.0, even the Server edition, should be regarded as a client operating system for .NET applications. Besides ASP .NET, there are only minor differences between the functionality supported by the .NET Framework on different platforms. For example, Windows 98 and Windows ME don't have an event-logging system, and the .NET Framework installed on these systems will therefore not support the Eventlog and related objects from the System.Diagnostics namespace. Another area where some differences can be found is XML Enterprise Services. Windows NT 4.0 supported the installation Microsoft® Transaction Server (MTS), which is different from COM+ 1.0 which came with Windows 2000, or COM+ 1.5 which comes with Windows XP. XML Enterprise Services in the .NET Framework will only work with COM+ 1.0 or higher, so the functionality offered through the System.EnterpriseServices namespace won't be available at all on Windows NT 4.0 and will be partially available on Windows 2000. The appendix gives a complete overview of the differences while the Preparing for Cross-Platform Support section will explain how to make your applications handle these differences. .NET Framework Software Requirements Internet Explorer 5.01 The .NET Framework and the underlying common language runtime contain a number of elements that rely on technology delivered by some version of Internet Explorer. The ability to download code, cryptography and intra/internet zone detection are examples of such elements. Technology requirements and the fact that Microsoft Internet Explorer 5.01 reached broad deployment led to the decision to set this version as the minimum version required to install and run the .NET Framework. Table 2 shows that Internet Explorer 5.01 must be installed on Windows 98, Windows 98 SE and Windows NT 4 before the .NET Framework can be installed. Windows ME, Windows 2000 or Windows XP operating systems already contain Internet Explorer 5.01 or higher, so no further action needs to be taken. Table 2. Installation requirements Click to get Internet Explorer 6.0. MDAC 2.6 The Microsoft® Data Access Components (MDAC) have been Microsoft's way to distribute the technology that implements the Universal Data Access Paradigm. MDAC can be downloaded and installed separately or comes with the operating system or other software like Microsoft® SQL Server™, Office XP or any other application that included the components in its setup. In order to work, the functionality from the System.Data namespace (which is Microsoft® ADO.NET) requires MDAC 2.6 or higher to be available. The complete version number for which the runtime checks is MDAC 2.6.6526. When installing the Framework on one of the operating systems regarded as one of the valid server operating systems for the .NET applications (any Windows 2000 version or Windows XP Professional), the setup will actually issue a warning if MDAC 2.7 or higher is not available. This is a warning that you can ignore, but not a blocking issue that will abort the installation. Figure 1 shows such a warning. Figure 1: Setup warning Installing the .NET Framework on any of the other operating systems (Windows 98, Windows ME and Windows NT 4.0) does not issue a warning at all when MDAC is not available, although it's also a requirement on these systems for ADO.NET to work. So this means that the setup of the .NET Framework on Windows 2000 or Windows XP Professional checks for a different version (2.7) than the version that is required a runtime (2.6.6526). To get MDAC go to the Universal Data Access Web site. Other requirements When installing the .NET Framework on Windows 2000, a warning will be issued when Internet Information Server 5 (IIS 5) is not installed and when doing the installation on Windows XP Professional, a warning is raised when IIS 5.1 is not available. On other operating systems, ASP.NET is not supported so the setup does not check for the presence of IIS. When writing code that uses Windows Management Instrumentation (WMI) events and classes, .NET application will make use of the System.Management namespace. If WMI is not supported on the operating system, the functionality in this namespace will not work. PlatformNotSupportedException There are some software components that are required by some parts of the .NET Framework but that do not block the installation. If components are required at runtime but not available, the .NET Framework will throw an Exception of the type PlatformNotSupportedException that your own applications should be prepared for. More about that in the next section. Preparing for Cross-Platform Support Rich support across a broad array of platforms has been a design requirement since the inception of the .NET Framework. As a result, a significant amount of the value proposition offered by the .NET Framework comes from its ability to provide developers with a clear path for writing applications that work across a broad range of platforms. A .NET Framework class in general is limited only by the need for a common language runtime to exist on the underlying platform. As always, there are exceptions to such a general statement and this article is really all about making those exceptions clear. So when designing a managed class, portability across the supported platforms should always be taken into consideration. The best way to ensure portability across the platforms supported by the .NET Framework is to build your classes using other managed code classes already available in the .NET Framework. Any time you create a .NET class that calls a native API, the risk of not supporting the breadth of officially supported platforms increases. As the .NET Framework is a new technology, there will be cases where a new class has a legitimate need to call into Win32® or other native APIs, but this should be done with a solid understanding of trade-offs being made and how the platform support story is affected by that decision. With that thought in mind, some questions that are important to ask are: - •Is it really necessary to call this unmanaged API (through P/Invoke)? - •Is there a class in the .NET Framework that already wraps this API? - •If the technology needs some data about the underlying system; can it be obtained using the System.Management layer rather than calling the native APIs? - •If Win32-native APIs really need to be called, can those APIs be called that are supported across the platforms instead of calling the "Ex" methods that might limit the ability to work on down-level platforms? As the OS layer underneath the .NET Framework continues to evolve with new releases, there will be cases where a .NET class needs to rely on underlying OS technology that isn't available in all of the supported operating systems. In this case, the class designer will need to weigh the cost of supporting that class across all platforms compared to the utility that the target customers will derive from having that functionality available on each of the down-level operating systems. If possible, the class should either provide the equivalent functionality on down-level platforms, or provide a subset of the functionality on those platforms. In cases where the class just won't work without a certain piece of the underlying OS, say IIS for example, the class should not install on that platform or it should check for the underlying dependency and throw a PlatformNotSupportedException when that dependency is not available. Suppose an application trying to create a managed Socket object calls the Socket constructor on an operating system that doesn't have Winsock installed. The following exception will be thrown. "PlatformNotSupportedException: Socket cannot be created due to a missing required platform component, Winsock 1.1" When working with managed classes from namespaces mentioned in the appendix, it's a good idea to add code to handle the PlatformNotSupportedException. Consider the case of an application in which you want log specific events. If this application needs to run on Windows 2000 as well as on Windows 98, you will need to consider writing events to the event log for Windows 2000 as well as to a text file for Windows 98. You can check the appendix to see on which operating systems the EventLog object from the System.Diagnostics namespace is supported. The following code shows how you can write to an event log if this is supported, or fall back on writing to an ordinary text file if it's not. Try Dim objEventlog As New EventLog("Application", ".", "MyApp") objEventlog.WriteEntry("Application Started") Catch ex As PlatformNotSupportedException ' in case of Windows 98 or Windows ME Dim sFile As String = "app.log" Dim sr As System.IO.StreamWriter If Not System.IO.File.Exists(sFile) Then sr = System.IO.File.CreateText(sFile) Else sr = System.IO.File.AppendText(sFile) End If sr.WriteLine("Application Started") sr.Close() Catch ex As Exception MessageBox.Show("Cannot do something") End Try Talking it one step further More information about the .NET Compact Framework (a version which runs on Smart Devices) can be found at the Visual Studio .NET Web site. Appendix Exceptions to the supported platforms
https://msdn.microsoft.com/en-us/library/ms973853.aspx
CC-MAIN-2018-51
refinedweb
1,741
57.87
Monkeypatches to minimize the permissions required to run python under AppArmor Monkeypatches to minimize the permissions required to run python under AppArmor. What does this do? Imagine you’ve written a simple Django application. Maybe you just followed the Django tutorial. All your code does is a bit of database querying. Then you deploy it under AppArmor and: type=AVC msg=audit(1443087838.797:1078): apparmor="DENIED" operation="exec" profile="helloworld-application" name="/bin/dash" pid=8202 comm="python" requested_mask="x" denied_mask="x" fsuid=999 ouid=0 Suddenly your audit log is full of messages complaining that your application is trying to run a shell. You certainly didn’t write code to do that. Whats going on? Did you get hacked? You (probably ;)) didn’t get hacked. Turns out python shells out when doing some fairly mundane stuff. Up until now you could: - Ignore it. Let your audit log have DENIED entries that you have to ignore. Now it’s hard to spot suspicious behaviour in your monitoring. Thinks might be broken, thinks might not be broken. Hope you don’t have to go through that log with a security professional. - Allow it. Now your profile is broader than it needs to be. You are throwing away the security you gain in the first place. Hope you don’t have to go through that profile with a security professional. This package patches several stdlib API’s to avoid subprocess usage, letting you keep your simple profiles and clean audit logs. ctypes vs ldconfig One of the first things I caught by application doing was trying to run gcc. This turned out to be a fallback for when an earlier attempt to run ldconfig had failed. This turned out to be how ctypes.util.find_library works. This can be used in a few places: - Gunicorn uses it for its sendfile implementation. - Python’s uuid module uses for uuid4. Just importing the uuid module triggers this, even if you aren’t using uuid4. platform.uname vs os.uname platform.uname is mostly the same as os.uname, but there is an extra field. The field is sourced by shelling out and running uname -p: sh -c "uname %s 2>%s" This is used in several places: - A command trick for getting your own version number is pkg_resources.require('myapp')[0].version, which triggers it. - Gunicorn triggers it via a platform.system() in gunicorn.workers.workertmp before it even loads your code. Activating the monkey patches Manually As early in your code as possible do: from apparmor_monkeys import patch_modules patch_modules() Automatically via .pth hooks And site-packages directory is scanned for .pth files. These are processed in order and are generally just a list of paths to add to sys.path. However any import lines will be honoured. Create an apparmor-monkeys.pth in your virtualenvs site-packages directory containing: import apparmor_monkeys; apparmor_monkeys.patch_modules() It must be on a single line for this trick to work. Switching profiles You can harden your AppArmor profiles further using change_profile to switch into a different profile after initialising your app. If using multiprocess gunicorn (i.e. synchronous gunicorn) then you can wrap your workers in their own specific profile. In your gunicorn config you can add a hook to do this: from apparmor_monkeys import change_profile def post_fork(server, worker): change_profile("myapplication//worker") You can do this for celery too: from apparmor_monkeys import change_profile from celery import signals @signals.worker_process_init.connect def switch_apparmor_profile(sender=None, signal=None): change_profile("tenselfservice-worker//worker") 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/apparmor_monkeys/
CC-MAIN-2017-43
refinedweb
605
59.9
Ambiguous match found Looks like I've been away a few months. Sorry 'bout that. I've had stuff to write about but not enough time to set aside to do so, which is a little ironic; one of the main reasons I created this blog was so I could take 5 minutes and jot down stuff I find out while developing, largely in case it helps others, not so I could write my usual verbose 5000 word essays (which is what my AspAlliance site is for!). So, on that note, I wanted to share how I solved a goofy error that made no sense. I was upgrading a good-sized web application from .NET 1.1/Visual Studio 2003 to .NET 2.0/Visual Studio 2005 using Scott Guthrie's well-written instructions and the Web Application Projects add-in. Going through VS2005's automatic conversion and building it was pretty painless when I followed Scott's instructions; one wrinkle I ran into is that it forgot about the three web projects, so I had to add those manually using "Add Existing Project" after I converted the others. But it built and I went through the app and everything was fine. I didn't do the "Convert to Web Application" command on the whole project, preferring to keep a closer eye on what it changed, and touch it up after. So I started doing it folder by folder per Step 8 inScott's instructions, and it seemed to work great, until I got to one particular page and got this error. Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Ambiguous match found. Source Error: Line 1: <%@ Control language="c#" Inherits="MyApp.Namespace.MyCoolControl" CodeBehind="MyCoolControl.ascx.cs" AutoEventWireup="false" %> Line 2: <%@ Import Namespace="MyApp.OtherNamespace" %> Line 3: <div class="openingParagraph"> Source File: /MyApp/Namespace/MyCoolControl.ascx Line: 1 So it says Line 1, Line 1 is highlighted, and yet, the only reference in line 1 is a fully-qualified one. To be safe, I pulled all my custom assemblies into the invaluable .NET Reflector and double-checked, and there was only one instance of that class name anywhere. I tried what I normally try when I get weird ASP.NET errors I shouldn't be getting, a process many of you are probably too familiar with if you've worked with ASP.NET very long. I restarted IIS, deleted and recreated the application in IIS Manager, deleted the Temporary ASP.NET Files directory for MyApp (after closing Visual Studio), restarted Visual Studio and rebuilt the project, etc. None of these helped this time. Scott's instructions mentioned this error in some cases, notably the IE WebControls, but the solution has been to specify the full namespace, not just the class name, so that didn't help me. Other Google search results were similarly unhelpful, until I found the blog of a guy named Eran Sandler who talked about his "Ambiguous match found" error and how he solved it--two protected fields with names that differed only in case, apparently confusing reflection. Sure enough, my code had the same problem--I had myRepeaterControl (name changed to protect the innocent, of course), and MyRepeaterControl in my code-behind. The latter wasn't used and was probably left in mistakenly; I removed it, it still built fine, and the control worked great. Thanks, Eran!
http://weblogs.asp.net/pjohnson/Ambiguous-match-found
CC-MAIN-2014-52
refinedweb
588
61.46
1. Right. 2. iBATIS caching can be globally distributed, at the app level, or at the session level. It's just really hard to configure! :-) Here's a simple breakdown For a local/session scoped read/write cache, use: serializable=false, readOnly=false For a shared read-only cache, use: serializable=false, readOnly=true For a shared read/write cache, use: serializable=true, readOnly=false In this context, read/write refers to whether you expect anyone to actually modify the cached instance of the object... thus tainting them if you weren't careful to clone them. I usually suggest using read-only caches and specifically retrieving non-cached instances for updates. In a nutshell, cache lists, don't cache individual objects, flush on update. For globally distributed caches, use OSCache or your own adapter for EHCache, JBossCache or Coherence and depending on their implementation, the rules above may change. Clinton On Thu, Sep 4, 2008 at 9:37 AM, zeppelin <shantanu.u@gmail.com> wrote: > > Thanks for that. I had previously read about RowHandler. Tell me if these are > correct : > > 1. Using the RowHandler, I would have to handle the cache myself and not > rely on iBATIS. Therefore, the 'cacheModel' attribute will be ignored. But > what I really wanted to use was the flushing mechanism. > > 2. Technically the caching in iBATIS is at application level. It is > described to be at session level since we can chage the way a user session > received an object - a cloned object or a reference to the same object. > > Just wanted to cofirm these. Also, it's a little strange that stored proc > out params cannot be cached. > Thanks again. > Zeppelin > > > Clinton Begin wrote: > > > > You can pass in a RowHandler and have the results collect in whatever sort > > of collection you like. The default implementation itself is a > > rowhandler, > > something (not exactly) like this: > > > > public class ListRowHandler implements RowHandler { > > private List list = new ArrayList(); > > > > public void handleRow(Object valueObject) { > > list.add(valueObject); > > } > > > > public List getList() { > > return list; > > } > > } > > > > Clinton > > > > On Thu, Sep 4, 2008 at 8:41 AM, zeppelin <shantanu.u@gmail.com> wrote: > > > >> > >> I have seen a similar question on this forum but it's not answered. > >> > >> My scenario : > >> * I'd like to use the iBATIS cache. It's working fine. > >> * My requirement is to use TreeSet cos I specifically want to use the > >> subset(...) method. > >> > >> It appears there's just no way in iBATIS to return a Set instead of a > >> List. > >> I can't understand why this feature is absent. > >> > >> Using the present approach, I have to pass the list to the TreeSet and > >> then > >> use it. This has to be done for ever user session that wants to access > >> the > >> cached entity. > >> > >> Is there any work around ? Is this supported in the spring framework ? > >> I'm > >> using org.springframework.orm.ibatis.support.SqlMapClientDaoSupport . > >> > >> regards > >> > >> Zeppelin > >> -- > >> View this message in context: > >> > >> Sent from the iBATIS - User - Java mailing list archive at Nabble.com. > >> > >> > > > > > > -- > View this message in context: > Sent from the iBATIS - User - Java mailing list archive at Nabble.com. >
http://mail-archives.apache.org/mod_mbox/ibatis-user-java/200809.mbox/%3C16178eb10809040913i16a05a2bn54d8fee5cb389a01@mail.gmail.com%3E
CC-MAIN-2017-17
refinedweb
508
66.03
<ac:macro ac: <h2>Information</h2> <ul> <li>Date: 22 February 2012, 18:00-19:00 UTC</li> <li><ac:link><ri:page ri:<ac:link-body>Agenda</ac:link-body></ac:link></li> <li>Moderator: Matthew Weier O'Phinney (nickname weierophinney)</li> <li>Next meeting: 29 February 2012</li> </ul> <h2>Summary</h2> <h3>i18n/l10n RFC</h3> <p>(Search for "18:02:08" in the log.)</p> <p>Discussion centered around completeness of the <ac:link><ri:page ri:<ac:link-body>i18n/l10n RFC</ac:link-body></ac:link>.</p> <p>The primary issues raised:</p> <ul> <li>The RFC should clearly note how currency and measurement localisation will be handled.</li> <li>The RFC should note how classes/components dependent on i18n/l10n will be updated; in particular, routing, filters, and view helpers were raised as examples. Several noted that for items like routing, the base routes available should not require i18n/l10n, but that these capabilities should be done either via decoration or extension.</li> <li>A debate arose regarding whether or not i18n/l10n-specific filters, view helpers, and routes should be kept inside the i18n/l10n namespace in order to reduce dependencies in those components (i.e., Zend\Filter would not have a dependency on i18n/l10n). There are good arguments on either side, and we decided to push this to the mailing list.</li> <li>We need a namespace for the i18n/l10n components.</li> </ul> <p><strong>tl;dr</strong>: The RFC is an excellent start, but a few details need to be addressed still.</p> <h3>Forms RFC</h3> <p>(Search for "18:28:41" in the log.)</p> <p>Matthew posted the <ac:link><ri:page ri:<ac:link-body>Forms RFC</ac:link-body></ac:link>, and we had initial discussion<br /> and feedback during the meeting.</p> <ul> <li>Additional use case illustrations were requested: <ul> <li>Use case around forms in MVC</li> <li>Use case about partial validation</li> <li>Use case of PRG</li> </ul> </li> <li>Artur Bodera (Thinkscape) suggested a more "template"-driven way of rendering, a hybrid of sprintf with named segments, which could reduce number of view helpers required, and make rendering fairly flexible.</li> <li>isValid() should not alter form/element state (value should be bound). This was intended in the RFC, but needs to be made explicit.</li> <li>A number of people either like the ZF1-style decorators or the simplicity of "echo $form". The question is whether we may be able to build a solution that makes that possible on top of the proposed architecture. Matthew will take this under consideration.</li> <li>Rob Allen (Akrabat) asked if the intention is for the validation/normalization chain to replace Zend\Filter\Input; Matthew answered in the affirmative, and will update the RFC accordingly.</li> </ul> <p><strong>tl;dr</strong>: A lot of enthusiasm and ideas flying; the RFC has a little ways to go before it captures the various requirements.</p> <h3>Beta 3 Readiness</h3> <p>(Search for "18:48:25" in the log.)</p> <p>Matthew reported that progress is good for shipping beta3 next week. The open<br /> pieces are:</p> <ul> <li>View layer (merged by Rob Allen just prior to the meeting)</li> <li>DB abstraction layer (Ralph Schindler is almost ready to issue a PR for this)</li> <li>Configuration refactoring (Ben Scholzen (DASPRiD) is reviewing the last set of changes submitted by Enrico Zimuel (ezimuel); Evan Coury (EvanDotPro) will prepare the Reader factory once merged)</li> <li>A modest pull request queue</li> <li>Documentation for new/refactored components.</li> </ul> <p>During the meeting, we agreed:</p> <ul> <li>Code Freeze for beta3 will happen Monday morning, CST.</li> <li>Rob Allen will attempt to use the new DB layer with his tutorial application, and Evan Coury will attempt to integrate it in the ZfcUser module, as "real world" tests and review of the DB layer.</li> <li>Everyone will attempt to get documentation in no later than end-of-day on Monday.</li> </ul> <p><strong>tl;dr</strong>: It's a bit tight, but the new features look fairly solid for purposes of the beta, and just need a bit of user testing and polish.<"> Feb 22 18:00:28 <weierophinney> Let's begin! Feb 22 18:00:36 <weierophinney> Once again, I forgot to solicit a moderator. Feb 22 18:00:46 <weierophinney> Which means I'm it. Feb 22 18:00:58 <DASPRiD> heh Feb 22 18:01:03 <weierophinney> Reminder: agenda is here: Feb 22 18:01:32 <weierophinney> First topic: i18n RFC Feb 22 18:01:39 <weierophinney> DASPRiD, want to begin? Feb 22 18:01:55 <DASPRiD> weierophinney, actually i'm half-away right now Feb 22 18:02:03 <DASPRiD> maybe swap order Feb 22 18:02:08 <weierophinney> RFC is here: Feb 22 18:02:35 <weierophinney> DASPRiD, main point is to discuss the RFC – do people feel it's complete? if not, what isn't addressed? etc. Feb 22 18:02:45 <weierophinney> bueller Feb 22 18:02:47 <weierophinney> bueller Feb 22 18:02:54 <weierophinney> (quiet bunch here) Feb 22 18:03:07 <DASPRiD> question is, is anyone actually "here" Feb 22 18:03:10 <DASPRiD> feels kinda silent Feb 22 18:03:10 »» ocramius taking a look again Feb 22 18:03:14 <kobsu> o/ Feb 22 18:03:17 »» ralphschindler is here Feb 22 18:03:20 <MikeA_> Feb 22 18:03:22 <DASPRiD> ah yeah, there we go Feb 22 18:03:34 »» EvanDotPro is lurking Feb 22 18:03:38 <DASPRiD> so, to give a quick brief about the RFC again: Feb 22 18:03:47 <ocramius> are there any other locale-aware components not includedin the RFC? Feb 22 18:04:01 <DASPRiD> ocramius, well, the router Feb 22 18:04:09 <weierophinney> ocramius, only ones I'm aware of are Router, Currency, and Measure. Feb 22 18:04:11 <tom_anderson> Validator\Float Feb 22 18:04:24 <DASPRiD> it's mainly about getting rid of the current i18n core in ZF and using the Intl extension shipped with PHP Feb 22 18:04:44 <DASPRiD> weierophinney, yeah, measure only very briefly for formatting the numbers Feb 22 18:04:55 <ralphschindler> Zend\Form by extension of validator/filter is locale aware Feb 22 18:04:55 <weierophinney> tom_anderson, I think that's covered with the NumberFormatter, as it can parse numbers Feb 22 18:05:03 <DASPRiD> weierophinney, indeed Feb 22 18:05:17 <weierophinney> DASPRiD, that may also cover currency, iirc Feb 22 18:05:21 <ocramius> DASPRiD: so should the router implement that idea of "LocaleAware" DASPRiD? Feb 22 18:05:46 <DASPRiD> ocramius, translatable segments will be integrated into the segment route Feb 22 18:05:50 <ocramius> (I'm repeating myself) Feb 22 18:05:51 <DASPRiD> (this is partly already done) Feb 22 18:05:55 <DASPRiD> weierophinney, it does Feb 22 18:06:04 <weierophinney> ralphschindler, actually, form also has traditionally allowed "translation" of labels. But if that's done in the view layer, it may be a moot point. Feb 22 18:06:04 <DASPRiD> both parsing and formatting Feb 22 18:06:27 <ocramius> okay Feb 22 18:06:34 <ocramius> well, then it's fine for me... Feb 22 18:06:57 <DASPRiD> about the availability of the PHP Intl extension: Feb 22 18:07:10 <DASPRiD> It is actually in the core, but depending on the distribution, it has to be enabled Feb 22 18:07:19 <DASPRiD> Also, for compiling from source, it requries the ICU headers Feb 22 18:07:28 <DASPRiD> else it is silently disabled Feb 22 18:07:51 <weierophinney> I can verify that it's not enabled by default when compiling from source, actually, which is a bit of a PITA. Feb 22 18:08:15 <DASPRiD> weierophinney, so you have to pass --enable-intl ? Feb 22 18:08:18 <ralphschindler> so, is it safe to say that if you want i18n features, you'll have a php distribution with i18n on? Feb 22 18:08:19 <ocramius> weierophinney: should components check if extension_loaded ? Feb 22 18:08:22 <weierophinney> DASPRiD, yes. Feb 22 18:08:38 <weierophinney> ralphschindler, I would think so, if you're using 5.3+ Feb 22 18:09:01 <EvanDotPro> i'm +1 and saying it's up to the user to enable intl if they want i18n. Feb 22 18:09:06 <EvanDotPro> s/and/for Feb 22 18:09:14 <weierophinney> I do know that Zend Server enables it by default, and most distributions do as well. Feb 22 18:09:29 <weierophinney> so to me, it's kind of a moot point whether or not a vanilla install has it enabled. Feb 22 18:09:31 <DASPRiD> weierophinney, yeah, or at least (edbian/ubuntu) ship a php5-intl package Feb 22 18:09:42 <ocramius> repeating question: should components check if extension_loaded ? Feb 22 18:09:48 <weierophinney> ocramius, yes, I think so. Feb 22 18:09:52 <ocramius> okay Feb 22 18:09:54 <weierophinney> DASPRiD, can you note that in the RFC? Feb 22 18:10:05 <DASPRiD> weierophinney, at which points would components check for that? Feb 22 18:10:07 <DASPRiD> on __construct ? Feb 22 18:10:16 <DASPRiD> or above class declaration? Feb 22 18:10:32 <weierophinney> DASPRiD, the only other concern from the comments I've not seen addressed so far is the matter of DateTime allowing reset based on formats. Feb 22 18:10:44 <weierophinney> DASPRiD, we usually do it in __construct. Feb 22 18:10:47 <DASPRiD> weierophinney, ah, i talked with kobsu about that Feb 22 18:10:48 <ralphschindler> DASPRiD: in __construct Feb 22 18:10:53 <weierophinney> DASPRiD, yeah? Feb 22 18:10:56 <kobsu> yes we talked about it Feb 22 18:10:58 <weierophinney> what did kobsu indicate? Feb 22 18:11:02 <ralphschindler> you don't want class_exists($class, true) to throw an error or exception Feb 22 18:11:05 <DASPRiD> kobsu, your turn Feb 22 18:11:15 <kobsu> weierophinney: that maybe i was using it wrongly Feb 22 18:11:21 <weierophinney> kobsu, LOL Feb 22 18:11:30 <weierophinney> okay, can one of you update that comment thread, then? Feb 22 18:11:39 <weierophinney> just so folks know what the resolution to that discussion was. Feb 22 18:11:42 <kobsu> DASPRiD had some better practices in mind Feb 22 18:12:08 <weierophinney> Anybody else have any initial feedback for DASPRiD on the i18n/l10n rfc? Feb 22 18:12:20 <DASPRiD> i'll update the rfc @ module checking Feb 22 18:12:30 <weierophinney> DASPRiD, thx Feb 22 18:12:33 <ralphschindler> i'd prefer composition of i18n features instead of it baked in Feb 22 18:12:46 <weierophinney> ralphschindler, can you clarify? Feb 22 18:12:52 <ralphschindler> so $route = new LocaleRoute(new Route(….)) Feb 22 18:12:58 <weierophinney> ah. Feb 22 18:12:59 <ralphschindler> intend of Route having locale features in its codebase Feb 22 18:13:04 »» weierophinney agrees in that regard. Feb 22 18:13:20 <DASPRiD> ralphschindler, actually i had that idea already Feb 22 18:13:23 <DASPRiD> forgot to not it Feb 22 18:13:29 <ralphschindler> i dislike how our current route has so much code in it for something as simple as parsing out parts (b/c of i18n stuffs) Feb 22 18:13:40 <DASPRiD> ralphschindler, although wrapping around any kind of route doesnt really work Feb 22 18:13:54 <DASPRiD> ralphschindler, i was more thinking about extending the segment route Feb 22 18:13:55 <weierophinney> well, then have separate, locale-aware routes. Feb 22 18:13:59 <DASPRiD> to have a TranslateSegmentRoute Feb 22 18:14:05 <weierophinney> but keep the base ones sane. Feb 22 18:14:16 <DASPRiD> weierophinney, yeah, so extending may be fine? Feb 22 18:14:19 <ralphschindler> I'm just saying to examine that architecture Feb 22 18:14:27 <ocramius> nice catch ralphschindler +1 for this separation Feb 22 18:14:29 <weierophinney> DASPRiD, can you note about router, currency, and measure in the rfc as well? Feb 22 18:14:35 <DASPRiD> sure Feb 22 18:14:36 »» Thinkscape reporting in Feb 22 18:14:38 <weierophinney> greets, Thinkscape and mabe_ Feb 22 18:14:46 <DASPRiD> i'd just have to add a little logic to the base segment rotue to allow such extension Feb 22 18:14:50 <ocramius> Thinkscape: discussing Feb 22 18:14:50 <DASPRiD> without too much copy/paste code Feb 22 18:15:01 <weierophinney> DASPRiD, re: currency/measure, simply indicate that these are addressed with \NumberFormatter. Feb 22 18:15:09 <DASPRiD> weierophinney, sure Feb 22 18:15:19 <weierophinney> DASPRiD, extension would be okay, but composition would be better, if possible. Feb 22 18:15:25 <DASPRiD> weierophinney, oh, it is already noted Feb 22 18:15:29 <weierophinney> DASPRiD, thx Feb 22 18:15:30 <DASPRiD> see last point in the 5.3 list Feb 22 18:15:39 <DASPRiD> "Locale-aware formatting of numbers and currencies"… Feb 22 18:15:50 <Xerkus> i don't understand why routes should be localized at all Feb 22 18:16:04 <weierophinney> DASPRiD, kk – there was a comment about it, and you kind of brushed it off as "maybe" – but it looks like you're planning to address it. Feb 22 18:16:05 <ocramius> Xerkus: I actually got that requirement many times... Feb 22 18:16:09 <Thinkscape> Xerkus: it's useful to me Feb 22 18:16:14 <weierophinney> Xerkus, I don't either, but a lot of folks use them. Feb 22 18:16:22 <weierophinney> which means it's a feature we should target. Feb 22 18:16:29 <DASPRiD> weierophinney, well, the comment was about the old rfc Feb 22 18:16:38 <DASPRiD> i should probably have createad a new page Feb 22 18:16:45 <weierophinney> DASPRiD, so post another comment indicating it's addressed, so folks like me don't get confused. Feb 22 18:17:04 <DASPRiD> yeah will all be updated Feb 22 18:17:16 <weierophinney> kk, coming up on time for this topic shortly... any other feedback for DASPRiD on the i18n/l10n rfc? Feb 22 18:17:22 <Thinkscape_> DASPRiD: all in fafor of auto-detect component in zf2 ? Feb 22 18:17:35 <DASPRiD> Thinkscape_, uh? Feb 22 18:17:44 <ocramius> Thinkscape: that's in PHP 5.3 Feb 22 18:17:44 <Thinkscape_> $locale->setSupported(array('en_GB', 'nl_NL')); $locale->setDefault('en_GB'); $locale->autodetect($request); Feb 22 18:17:50 <ocramius> oh, that one Feb 22 18:17:53 <DASPRiD> Thinkscape_, ah that one Feb 22 18:17:56 <Thinkscape_> it's not integrated into zf2 guts Feb 22 18:18:13 <DASPRiD> Thinkscape_, yeah \Locale has auto detection, but not based on supported locales Feb 22 18:18:22 <Akrabat> back Feb 22 18:18:23 <DASPRiD> so we probably have to a helper for that Feb 22 18:18:30 <EvanDotPro> DASPRiD: you mentioned module checking? what do you mean by that? Feb 22 18:18:32 <DASPRiD> *to add Feb 22 18:18:41 <DASPRiD> EvanDotPro, module_exists() calls in __construct Feb 22 18:18:42 <Thinkscape_> also - have you been discussing integration with other zf2 components.... or rather - usage of locale stuff througout zf2 ? Feb 22 18:18:43 <Akrabat> my only comment on i18n is that if I use \Router I don't want to have to have all of the ii8n stuff Feb 22 18:18:44 <weierophinney> DASPRiD, that was in a comment as well. I think it's important to note in the RFC that there's a plan for it. Feb 22 18:18:51 <weierophinney> Akrabat, yep, we covered that. Feb 22 18:18:54 <ocramius> Akrabat: will be stripped Feb 22 18:18:59 <ocramius> Akrabat: and separated Feb 22 18:19:02 <Akrabat> ok good - so will live in another namespace? Feb 22 18:19:06 <ocramius> (As of current discussion) Feb 22 18:19:15 <DASPRiD> Akrabat, well, will be separate kind of routes Feb 22 18:19:19 <weierophinney> Akrabat, more like there will be separate locale-aware routes. Feb 22 18:19:23 <Akrabat> cos otherwise pear install router will pull in locale Feb 22 18:19:24 <EvanDotPro> DASPRiD: you mean checking for the php extension? not zf2 modules. Feb 22 18:19:32 <DASPRiD> Akrabat, mhhh Feb 22 18:19:36 <DASPRiD> EvanDotPro, right Feb 22 18:19:36 <Thinkscape_> routes is one thing that comes to my mind... but view rendering also requires a good integration. Feb 22 18:19:41 <Akrabat> and that's one of my current pet peeves in zf11 Feb 22 18:19:42 <Akrabat> and that's one of my current pet peeves in zf1 Feb 22 18:19:46 <weierophinney> DASPRiD, Akrabat has a good point – maybe put the locale-aware routes under a l10n namespace? Feb 22 18:20:02 <DASPRiD> weierophinney, mh yeah could make sense Feb 22 18:20:05 <EvanDotPro> DASPRiD: extension_loaded() Feb 22 18:20:10 <DASPRiD> EvanDotPro, whatever Feb 22 18:20:29 <Akrabat> other than that, I'm +1 for using php5.3 extension Feb 22 18:20:42 <weierophinney> Thinkscape, if there are helpers for translation and various localization tasks that are injected with the appropriate objects, does that address things for you? Feb 22 18:20:45 »» Thinkscape_ is now known as Thinkscape Feb 22 18:20:52 <DASPRiD> okay so routes get into the i18n namespace Feb 22 18:21:06 <Thinkscape> "injected with the appropriate object" - intl or zf2-wrapped ? Feb 22 18:21:08 <weierophinney> should i18n/l10n view helpers also be in that namespace? Feb 22 18:21:15 <weierophinney> Thinkscape, the ZF2 bits Feb 22 18:21:21 <DASPRiD> weierophinney, could make sense Feb 22 18:21:24 <EvanDotPro> weierophinney: i'd say yes. Feb 22 18:21:29 <DASPRiD> so yes why not Feb 22 18:21:43 <Akrabat> yes Feb 22 18:21:46 <DASPRiD> same for filters and validators Feb 22 18:21:49 <Thinkscape> weierophinney: well, to follow up: what are other zf2\whateverlocale responsibilities, other that wrapping intl ? Feb 22 18:21:58 <weierophinney> DASPRiD, can you note that bit in the RFC as well, please? Feb 22 18:22:00 <Akrabat> same reasoning from a dependent packaging point of view Feb 22 18:22:08 <DASPRiD> weierophinney, sure, writing it down soon Feb 22 18:22:17 <mabe_> will all i18n/l10n components going into the same namespace ? Feb 22 18:22:29 <DASPRiD> okay, so all components which have hard-dependencies on i18n go into the i18n namespace Feb 22 18:22:32 <weierophinney> mabe_, I think that's the general consensus. Feb 22 18:22:56 <DASPRiD> what are we going to use for i18n namespace? Feb 22 18:22:57 <weierophinney> DASPRiD, i18n/l10n – or g11n (globalisation? is that right?) Feb 22 18:23:06 <Thinkscape> that sounds odd Feb 22 18:23:11 <Thinkscape> i.e. Zend\Filter\Translate Feb 22 18:23:13 <DASPRiD> (l10n is actually the part of translating texts…) Feb 22 18:23:16 <Thinkscape> it's in Filter, because it's a filter Feb 22 18:23:21 <DASPRiD> Thinkscape, uh? Feb 22 18:23:24 <weierophinney> (it's what li3 used) Feb 22 18:23:39 <DASPRiD> (brb, getting pizza out of oven) Feb 22 18:23:47 <weierophinney> Thinkscape, by that logic, all dojo or jquery stuff would be scattered between form, view, and whatnot. Feb 22 18:23:56 <Thinkscape> Why would we move Zend\Filter\Translate into Zend\i18n\Filter ?? Feb 22 18:24:07 <weierophinney> making those packages then have dependencies on multiple other packages. Feb 22 18:24:23 <Thinkscape> By that logic, why is Encrypt, Compress, File in filters ? Feb 22 18:24:42 <weierophinney> Thinkscape, instead of the i18n stuff having dependencies on the components on which interfaces it depends. Feb 22 18:24:49 <weierophinney> Thinkscape, they probably should not be. Feb 22 18:24:58 <DASPRiD> re Feb 22 18:25:00 <Thinkscape> so loosely-coupling as a primary goal? Feb 22 18:25:35 <Thinkscape> because it does not help that 90% other filters are in Zend\Filter, while translate is in Zend\i18n\Filter (or wherever) Feb 22 18:26:06 <Xerkus> filter Translate should be in \Filter\ and do nothing if translator object is not specified IMHO Feb 22 18:26:31 <weierophinney> Thinkscape, can you raise this one on the ML? I think it needs further discussion. Feb 22 18:26:36 <Thinkscape> weierophinney: Feb 22 18:26:38 <Akrabat> Thinkscape its a very important one, yes. Feb 22 18:26:45 <DASPRiD> tbh, is Zend\Translator really a filter? Feb 22 18:26:57 <Thinkscape> it's a translator Feb 22 18:27:04 <DASPRiD> yes Feb 22 18:27:13 <Thinkscape> but yeah, a filter of sorts... Feb 22 18:27:14 <mabe_> but there is a filter for that trnaslator Feb 22 18:27:16 <weierophinney> Thinkscape, but it takes text and transforms it/filters it to an alternate representation. Feb 22 18:27:23 <Thinkscape> true Feb 22 18:27:34 <ocramius> hmm, never thought of it. Making it a filter makes it more flexible Feb 22 18:27:34 <Thinkscape> so Translator goes into a bag of Zend\i18n Feb 22 18:27:37 <DASPRiD> Zend\Transformer then Feb 22 18:27:38 <DASPRiD> Feb 22 18:27:42 <weierophinney> kk, let's move the discussion of where the various i18n/l10n stuff will live to the ML. Feb 22 18:27:44 <Thinkscape> and we still have Filter\Translate to make things easy to find ... Feb 22 18:27:51 <Thinkscape> (my little proposal) Feb 22 18:27:52 <SpiffyJr> Forms! Feb 22 18:27:54 »» SpiffyJr coughs Feb 22 18:27:58 <Thinkscape> well, pyrus will have to manage Feb 22 18:28:07 »» EvanDotPro hands SpiffyJr a bottle of water Feb 22 18:28:18 <Thinkscape> rum Feb 22 18:28:26 <weierophinney> Thinkscape, it's not just pyrus. It's how we set up packages. If we have to separate out individual classes from components, it becomes quite difficult. Feb 22 18:28:34 <Thinkscape> weierophinney: I know Feb 22 18:28:35 <Thinkscape> Next item on the agenda ? Feb 22 18:28:41 <weierophinney> So, next item: forms rfc Feb 22 18:28:44 <weierophinney> RFC is here: Feb 22 18:28:45 »» SpiffyJr cheers Feb 22 18:28:49 <weierophinney> it's a FIRST DRAFT Feb 22 18:29:00 <Thinkscape> Please no dummy </form> at the end... sounds like a bad design. Feb 22 18:29:06 <Akrabat> so now come the disclaimers... Feb 22 18:29:11 <DASPRiD> Thinkscape, i already had that Feb 22 18:29:15 <DASPRiD> <?php echo $this->formRenderer()-->render($form); ?> Feb 22 18:29:16 <weierophinney> Thinkscape, I hadn't thought of that. I totally get it's a bad idea. Feb 22 18:29:24 <weierophinney> can we move on to OTHER bits to discuss, then? Feb 22 18:29:33 <DASPRiD> heh Feb 22 18:29:50 <ralphschindler> weierophinney: LOVE the sprintf model Feb 22 18:29:57 <weierophinney> damn.. just seeing the comments.... Feb 22 18:30:00 »» weierophinney speed reads... Feb 22 18:30:31 <Thinkscape> I'd like to point out little thing: it's nice that we now can output chunks of the form with $this->someChunk() — weierophinney: you explain that it's better, because a designer gets more control. But it is only a small improvement, because $this->label() STILL has some implicit way of rendering that <label>. What if I want labels to be <ul><li> or <span> ? – still need to subclass or whatever. So it does not resolve zf1 f Feb 22 18:30:32 <EvanDotPro> i agree with jurians that we need something for PRG – that's a huge pain in zf1. Feb 22 18:30:39 <DASPRiD> curl -o - > /dev/mwop Feb 22 18:30:51 <DASPRiD> EvanDotPro, what exactly? Feb 22 18:31:07 <SpiffyJr> Thinkscape, <ul><?php echo $this->label();?></ul> ?? Feb 22 18:31:09 <ocramius> Thinkscape: what if we add arguments to the helpers? Feb 22 18:31:24 <Thinkscape> SpiffyJr: no! I don't want <label> but <li> instead. Feb 22 18:31:34 <Thinkscape> SpiffyJr: take a look at the example in RFC Feb 22 18:31:41 <SpiffyJr> Comments or? Feb 22 18:31:43 <EvanDotPro> DASPRiD: Feb 22 18:31:54 <dmitrybelyakov> sometimes you might need your lable to wrap input Feb 22 18:31:56 <DASPRiD> EvanDotPro, thx captn obvious Feb 22 18:31:59 <mabe_> PRG shouldn't part of form - it's part of mvc Feb 22 18:31:59 <DASPRiD> EvanDotPro, i know that pattern Feb 22 18:32:03 <SpiffyJr> Thinkscape, I see. Feb 22 18:32:08 <DASPRiD> mabe_, +1 Feb 22 18:32:15 <weierophinney> Thinkscape, so, the basic form view helpers would spit out a single markup tag. If you wanted the label to be done differently, you either use a different helper, or pull the metadata manually from the object to build your markup. Feb 22 18:32:32 <Thinkscape> weierophinney: back to square one in my opinion. Feb 22 18:32:37 <EvanDotPro> DASPRiD: well i don't have a specific suggestion (maybe integration with a single-hop session container?) .. but we need something Feb 22 18:32:46 <ralphschindler> i think a published/documented sprintf variable list should be the base implementation for output in forms/elements Feb 22 18:32:54 <weierophinney> Thinkscape, what do you mean by "square 1" here? Feb 22 18:33:00 <ralphschindler> that way, you only need to understand PHP in order to customize Feb 22 18:33:08 <DASPRiD> EvanDotPro, flash messenger! Feb 22 18:33:25 <mabe_> lol Feb 22 18:33:38 <Thinkscape> I didn't put much thought about it but I believe a template fragments strategy might be a good compromise ---- each form widget/elements is a hunk of parsable template. Changing it is a simple as replacing one string with another. Something along the lines of sprintf() but much more powerful. Feb 22 18:33:41 <weierophinney> dmitrybelyakov, that's an implementation detail, and something a specialized helper could accomplish. Feb 22 18:33:44 <EvanDotPro> DASPRiD: i use that currently, but i'm not sure that's the intended use case for something like this lol. Feb 22 18:34:11 <jurians> weierophinney: for the RFC, I'd love to see some use cases: #1 forms in MVC setting, #2 forms with partial validation (ie from onBlur AJAX call) and #3 form with PRG pattern. Is that possible? Feb 22 18:34:18 <weierophinney> Thinkscape, the problem with that approach is it requires us to ship templates with the framework. Which then means we need to create a way to make those discoverable. Feb 22 18:34:34 <weierophinney> jurians, noting that now, and will add to the RFC. Feb 22 18:34:39 <jurians> thanks Feb 22 18:34:48 <Thinkscape> i.e. $form->fragments = array( "label" => "<label>:itemName</label>", "errorItem" => "<span class="error">:errorMessage</span>" ........ ) Feb 22 18:34:53 <ralphschindler> Thinkscape: the sprintf example weierophinney has in there is a template fragment Feb 22 18:34:54 <Thinkscape> weierophinney: not really templates Feb 22 18:34:58 <Thinkscape> chunks of code Feb 22 18:35:10 <DASPRiD> jurians, plz no xml Feb 22 18:35:21 <Thinkscape> think - zf1 view helper for "dom element" ...it made a concat of "<" + elName + something + something + ">" ... Feb 22 18:35:29 <Thinkscape> ralphschindler: exactly ... Feb 22 18:35:32 <ralphschindler> return sprintf("<div class=\"%s\">\n%s\n%s\n%s\n</div>", …) could easily be sprintf($this->fragment, … ) Feb 22 18:35:36 <weierophinney> Thinkscape, what about sprintf usage, then? Feb 22 18:35:38 <Thinkscape> ralphschindler: but I mean something more powerful, but simple nevertheless... Feb 22 18:35:40 <ralphschindler> with positional replacements Feb 22 18:35:43 <ocramius> Thinkscape: this probably comes from the depths of my ignorance, but do ZF1 forms support partials? Feb 22 18:35:45 <EvanDotPro> jurians: good call on partial validation – didn't think of that! Feb 22 18:35:48 <weierophinney> Thinkscape, what's not powerful about sprintf? Feb 22 18:35:50 <Thinkscape> ralphschindler: sprintf sucks because it requires knowledge of parameter order.. Feb 22 18:35:58 <ralphschindler> i have an idea on the more powerful part that fits in with sprintf Feb 22 18:36:01 <weierophinney> ocramius, there's a ViewPartial decorator. Feb 22 18:36:12 <weierophinney> Thinkscape, point taken Feb 22 18:36:19 <ocramius> weierophinney: cool, now I need 5 mins of facedesk Feb 22 18:36:28 <Thinkscape> you cannot do this in sprintf: '<label id=":elementId" class="error">:errorMessage</label>' Feb 22 18:36:37 <Akrabat> annotations would be optional? Feb 22 18:36:40 <ralphschindler> a ZenCoding expander could easily solve this as well for more complex fragments Feb 22 18:36:42 <Akrabat> we could still do it via code/ Feb 22 18:36:49 <Akrabat> we could still do it via code? even Feb 22 18:36:57 <EvanDotPro> ralphschindler: ooh that could be pretty cool Feb 22 18:36:57 <weierophinney> Akrabat, yes Feb 22 18:36:57 <DASPRiD> (EvanDotPro: 2 hours until last cigarette, that app worx!) Feb 22 18:37:01 <Akrabat> k Feb 22 18:37:04 <DASPRiD> s/until7since/ Feb 22 18:37:09 <ralphschindler> yes EvanDotPro - i've been sitting on that idea for a while now Feb 22 18:37:23 <ocramius> oh nice =) Feb 22 18:37:25 <Thinkscape> ralphschindler: new syntax though Feb 22 18:37:29 <Thinkscape> (quirky one) Feb 22 18:37:34 <ralphschindler> $element->setFragment('div>#somename%1s') … etc Feb 22 18:37:38 <weierophinney> Thinkscape, I've noted about doing a hybrid of sprintf + named replacements Feb 22 18:37:41 <ralphschindler> Thinkscape: we're not inventing the syntax Feb 22 18:37:47 <ocramius> ralphschindler: sounds like a new component to me Feb 22 18:38:01 <EvanDotPro> a filter? Feb 22 18:38:07 <ralphschindler> yep, a filter Feb 22 18:38:17 <Thinkscape> weierophinney: yes, but please keep in mind that it should be collection of fragments, NOT collection of classes each with a fragment, because this OO will bloat the thing out of proportions. Feb 22 18:38:18 <SpiffyJr> ZenCode sure is handy... I could live with that. Feb 22 18:38:28 <Akrabat> one minor point about zf1: isValid() calls setValues() internally. Can we ensure we don't change state in an isXxx() or hasXx() call please? Feb 22 18:38:45 <EvanDotPro> Akrabat: +50 Feb 22 18:38:47 <weierophinney> Thinkscape, perhaps you can write up a ML post detailing how you envision that, then? Feb 22 18:38:47 <rizza> Akrabat: +1 Feb 22 18:38:54 <SpiffyJr> Akrabat, good point - I'd rather call it something like bind(); Feb 22 18:38:54 <weierophinney> I don't want to interpret incorrectly. Feb 22 18:39:03 <Thinkscape> weierophinney: you intepret correctly Feb 22 18:39:16 <SpiffyJr> Akrabat, some naming that clearly expresses the form state is being modified. Feb 22 18:39:18 <ocramius> SpiffyJr: where did I see that? Feb 22 18:39:22 »» DASPRiD has to note that we should at one point think about Filter policy again, eventually most view helpers and validators can be considered filters) Feb 22 18:39:23 <Thinkscape> weierophinney: think instead of 20 classes, 2-3 form-related classes.... and that's it. Feb 22 18:39:32 <weierophinney> Akrabat, not sure I follow... Feb 22 18:39:45 <ralphschindler> I know he is not here to talk about it but elazar, with large forms, ran into significant performance issues with regards to forms in ZF1, if we lighten the architectural load, performance should increase (things like sprintf over decorators for one) Feb 22 18:39:50 <weierophinney> Thinkscape, right, but are you talking view helpers? or elsewhere? Feb 22 18:39:53 <Thinkscape> DASPRiD: filter filters and returns. View helper spews out the result. Feb 22 18:40:03 <EvanDotPro> weierophinney: when you call isValid($postData) it populates the form object Feb 22 18:40:06 <DASPRiD> Thinkscape, well, same thing kinda Feb 22 18:40:06 <EvanDotPro> with the values Feb 22 18:40:07 <Thinkscape> weierophinney: both view helpers and form-building classes. Feb 22 18:40:15 <Thinkscape> weierophinney: to make it simpler... Feb 22 18:40:27 <SpiffyJr> weierophinney, isValid() changes form state which isn't very intuitive and something that an "isser" doesn't normally do. Feb 22 18:40:30 <weierophinney> EvanDotPro, and Akrabat is suggesting not to do that? Feb 22 18:40:32 <Thinkscape> weierophinney: I remember the stack when debugging zf1 form elements – it was horrendous! Feb 22 18:40:41 <Akrabat> weierophinney: currently callling $form->isValid() causes a state change on the form object. This is "unexpected" for a method name that looks like a test. I want to ensure that we name our methods around validation in zf2 do not do that Feb 22 18:40:54 <weierophinney> Thinkscape, already the plan – the only place I differed was the view helpers. But that may be easy to address. Feb 22 18:40:57 <Thinkscape> weierophinney: (stack when rendering zf1 form elements) Feb 22 18:40:58 <ralphschindler> +1 on Akrabat Feb 22 18:41:03 <EvanDotPro> weierophinney: i'm suggesting not to do that as well.. it's an isXxx() method.. should not be acting like a setter Feb 22 18:41:08 <mabe_> weierophinney: You RFC has a $form->setInputFilter - will there also a output filter ? Feb 22 18:41:11 <Thinkscape> weierophinney: yes, but if we do these fragments, we don't need 10 view helpers Feb 22 18:41:13 <Thinkscape> only one Feb 22 18:41:17 <Thinkscape> or a handful Feb 22 18:41:27 <ocramius> agreed with Akrabat: that one is chaos Feb 22 18:41:29 <weierophinney> Akrabat, makes sense – I'd expect you'd need to bind values from the input filter manually Feb 22 18:41:33 <weierophinney> Akrabat, I'll note that in the rfc Feb 22 18:41:38 <Akrabat> cool Feb 22 18:41:38 <weierophinney> mabe_, no Feb 22 18:41:47 <weierophinney> mabe_, output filter is... the view layer. Feb 22 18:41:53 <Akrabat> also, are we going to lose current zend\filter\input (i.e does this replace it?) Feb 22 18:42:28 <Akrabat> cos two different things that we colloquially call "input filter" could be confusing Feb 22 18:42:28 <weierophinney> Akrabat, I'd imagine this would replace it. Feb 22 18:43:11 <Akrabat> great Feb 22 18:43:15 <weierophinney> Akrabat, btw, I'd expect the isValid() call to either be direclty on the input filter, or, if on the form, proxy to it. Feb 22 18:43:18 <Thinkscape> filter chain Feb 22 18:43:27 <weierophinney> The values would be inside the input filter Feb 22 18:43:30 <SpiffyJr> weierophinney, good Feb 22 18:43:46 <weierophinney> so you'd need to bind them, or the form/elements would proxy to the filter to get their respective value. Feb 22 18:44:19 <Akrabat> As others have mentioned, it would be helpful to add some code sample ideas on the entire process I think Feb 22 18:44:35 <weierophinney> I've noted a number of things for the RFC, including additional usage samples. I'll update in the next day or two. Feb 22 18:44:38 <Akrabat> makes sense Feb 22 18:44:51 <weierophinney> We can discuss more on the lsit – this is simply the first foray, as far as I'm concerned. Feb 22 18:44:58 <weierophinney> Shall we move on to the last topic? Feb 22 18:44:59 <SpiffyJr> weierophinney, action and method are the only things managed in the opening <form> tag, correct? Feb 22 18:45:22 <Thinkscape> SpiffyJr: don't forget enctype Feb 22 18:45:25 <SpiffyJr> Breaking IDE's HTML parser with that opening form helper makes me sad face. Feb 22 18:45:31 <Thinkscape> SpiffyJr: and target.. Feb 22 18:45:38 <rizza> And class, name, id... Feb 22 18:45:42 <SpiffyJr> We didn't touch on annotations! Or a potential form builder! Feb 22 18:45:48 <SpiffyJr> Or all that cool stuff... Feb 22 18:45:58 <Akrabat> form() view helper shoud be formOpener() or something too but in general I'm liking where this is going, but we'll need more ML time Feb 22 18:46:25 <ocramius> SpiffyJr: you mean entity- stuff? Feb 22 18:46:27 <weierophinney> SpiffyJr, and any other attributes you might want. HTML5 now has data-*. Feb 22 18:46:36 <ezimuel> I think we should split the logic of form (like validation) from the form UI (rendering) Feb 22 18:46:38 <ocramius> we can't surely ignore that... that stuff is going to get used more and more... Feb 22 18:46:46 <weierophinney> SpiffyJr, I'll be changing the open/close tag bit. Noted that at the start. Feb 22 18:46:47 <rizza> ezimuel: I believe that's the idea. Feb 22 18:46:51 <SpiffyJr> Okay. Feb 22 18:47:06 <Akrabat> I would love to solve Tomáš' issue too if we can and have a way to render a form without having to write a view script for it Feb 22 18:47:16 <DASPRiD> weierophinney, don't forget "placeholder" is there as well Feb 22 18:47:16 <weierophinney> ezimuel, that's the goal of the RFC. Feb 22 18:47:23 <weierophinney> DASPRiD, ? Feb 22 18:47:28 <DASPRiD> on input elements Feb 22 18:47:30 <SpiffyJr> Akrabat, Should be easy to write a generic view helper... Feb 22 18:47:35 <rizza> Akrabat: I'd like that, too. Feb 22 18:47:41 <DASPRiD> <input type="text" placeholder="Username" /> Feb 22 18:47:48 <SpiffyJr> Akrabat, $this->renderFormWithPTags($form); ... or whatever. Feb 22 18:47:49 <weierophinney> DASPRiD, ah, right. Feb 22 18:47:56 <weierophinney> I was thinking the view helper. Feb 22 18:48:01 <DASPRiD> oh, heh Feb 22 18:48:05 <Thinkscape> and input type="datetime"... Feb 22 18:48:06 <Akrabat> SpiffyJr: yes, something like that Feb 22 18:48:09 <Thinkscape> among others Feb 22 18:48:10 <weierophinney> Akrabat, we may be able to do that. I'll think on it. Feb 22 18:48:16 <weierophinney> kk, let's move on to the last topic. Feb 22 18:48:17 <DASPRiD> Thinkscape, yeah, but thats sadly not widely supported yet Feb 22 18:48:23 <DASPRiD> there's another topic? Feb 22 18:48:25 <weierophinney> BETA 3 READINESS Feb 22 18:48:26 <rizza> beta3 Feb 22 18:48:29 <DASPRiD> ah! Feb 22 18:48:30 <Thinkscape> DASPRiD: but it's there, and easy to add-on to old browsers Feb 22 18:48:35 <SpiffyJr> SHIP IT! Ship it all! Feb 22 18:48:35 <DASPRiD> Thinkscape, true Feb 22 18:48:40 <DASPRiD> modernizr to the rescue Feb 22 18:48:44 <SpiffyJr> Oh wait, I'm not at work right now... Feb 22 18:48:46 <ocramius> SpiffyJr: I think the entity- related stuff fits a module then Feb 22 18:48:53 <weierophinney> MOVING ON Feb 22 18:49:07 <weierophinney> I want to do code freeze (note, NOT docs freeze) by Friday. Feb 22 18:49:08 <SpiffyJr> ocramius, fair enough, then. I'll keep working on SpiffyForm. Feb 22 18:49:12 <DASPRiD> cat Form-Topic > /dev/null Feb 22 18:49:14 <DASPRiD> next one Feb 22 18:49:14 »» Thinkscape hears ringing in his ears.. Feb 22 18:49:16 <weierophinney> Akrabat has merged the view layer today. Feb 22 18:49:16 <Akrabat> Friday?!?!? Feb 22 18:49:26 <Thinkscape> already? Feb 22 18:49:28 <SpiffyJr> It's merged and ready? Feb 22 18:49:34 <weierophinney> and we have DB about to be queued up for a PR Feb 22 18:49:37 <Akrabat> has someone else other than ralphschindler used db yet? Feb 22 18:49:39 <weierophinney> (right, ralphschindler?!?!?!) Feb 22 18:49:50 <ralphschindler> yep, I'm getting close on the pull request Feb 22 18:49:51 <weierophinney> Config is ready to merge (if not done already) Feb 22 18:49:59 <DASPRiD> weierophinney, uhm Feb 22 18:50:06 <weierophinney> And I have a massive PR queue to go through. Feb 22 18:50:13 <DASPRiD> weierophinney, i only briefly looked over it Feb 22 18:50:14 <Akrabat> Thinkscape, SpiffyJr: view-layer is definitely rounded off enough to go to beta Feb 22 18:50:23 <weierophinney> DASPRiD, kk, GET CRAKING. Feb 22 18:50:23 <DASPRiD> weierophinney, there are a few things left which have to be changed Feb 22 18:50:28 <SpiffyJr> Akrabat, is it already merged? Feb 22 18:50:31 <weierophinney> SpiffyJr, YES Feb 22 18:50:35 <SpiffyJr> Beautiful! Feb 22 18:50:39 <DASPRiD> weierophinney, will try to review it this evening Feb 22 18:50:39 <Akrabat> SpiffyJr: yes - I closed the PR 1 hour ago roughly Feb 22 18:50:40 <SpiffyJr> I'll put up another PR for you then. Feb 22 18:50:47 <weierophinney> DASPRiD, thanks! Feb 22 18:50:53 <Thinkscape> DASPRiD: next evening Feb 22 18:50:57 <DASPRiD> Thinkscape, uh? Feb 22 18:51:03 <SpiffyJr> weierophinney, I have some Zend\Navigation PR's that I will try to get in by Friday. Feb 22 18:51:03 <Akrabat> I'm concerned about Friday code freeze Feb 22 18:51:12 <weierophinney> Akrabat has a good point: ralphschindler will post when he has the PR ready, and point folks to the various samples. PLEASE REVIEW AND TEST Feb 22 18:51:21 <weierophinney> Akrabat, is it due to the DB stuff? Feb 22 18:51:23 <Thinkscape> Akrabat: what code freeze? Feb 22 18:51:25 <rizza> Seems like a lot of things that need to be done by Friday... Feb 22 18:51:30 <SpiffyJr> Thinkscape, the beta3 code freeze for Friday Feb 22 18:51:35 <weierophinney> I can maybe extend to Monday Feb 22 18:51:41 <DASPRiD> monday is probably more sane Feb 22 18:51:44 <Akrabat> weierophinney: yes = db Feb 22 18:51:45 <DASPRiD> gives us the weekend just in case Feb 22 18:51:46 <weierophinney> Does having the weekend seem reasonable? Feb 22 18:51:59 <Thinkscape> db is for beta4. right ? Feb 22 18:52:15 <weierophinney> Thinkscape, no, beta3. There will be additional adapters for beta4, though. Feb 22 18:52:46 <weierophinney> Thinkscape, ralphschindler has been testing on sqlite, mysqli/pdo_mysql, and sqlsrv/pdo_sqlsrv Feb 22 18:52:54 <weierophinney> (and pdo_sqlite, obviously) Feb 22 18:53:17 <weierophinney> There's enough differences between them that he's been able to ensure the architecture accommodates variances. Feb 22 18:53:57 <Akrabat> something without auto-increment would be useful to test too really Feb 22 18:54:11 <Akrabat> e.g. oracle Feb 22 18:54:12 <weierophinney> ralphschindler, have you tested that scenario? Feb 22 18:54:18 <SpiffyJr> New to B3: View, Log, Config, and DB? Feb 22 18:54:20 <Akrabat> but I wouldn't wish that on anyone Feb 22 18:54:30 <ralphschindler> Akrabat: sql server has IDENTITY Feb 22 18:54:32 <weierophinney> SpiffyJr, yes. Feb 22 18:55:00 <Thinkscape> Akrabat: ralphschindler: postgresql Feb 22 18:55:01 <weierophinney> SpiffyJr, plus a host of PRs. I think this beta will have something like 200 PRs merged. Feb 22 18:55:03 <Akrabat> ralphschindler: true Feb 22 18:55:12 <weierophinney> Thinkscape, that's planned for beta4. Feb 22 18:55:16 <SpiffyJr> weierophinney, very nice - removing the CLA was a very very good step. Feb 22 18:55:24 <Thinkscape> weierophinney: you sure you can handle that before mon? Feb 22 18:55:24 »» weierophinney agrees. Feb 22 18:55:26 <ralphschindler> postgres is closer to my heart so, i plan on hitting it pretty soon Feb 22 18:55:34 <Thinkscape> weierophinney: I believe in you nevertheless Feb 22 18:55:34 <DASPRiD> indeed @ cla Feb 22 18:55:44 <ralphschindler> i've learned to dislike mysql after dealing with the wide range of databases out there Feb 22 18:55:46 <weierophinney> Thinkscape, on my end? Yes. PRs are typically not bad, and I hope to be through them by tomorrow regardless. Feb 22 18:56:08 <ocramius> ralphschindler: you're late haven't you ever read the pgsql motto? Feb 22 18:56:09 <ocramius> Feb 22 18:56:13 <weierophinney> Thinkscape, but I think having the weekend for folks to review DB before we freeze the repo is a good idea. Feb 22 18:56:16 <Thinkscape> ralphschindler: good for you postgresql is quite under-appreciated Feb 22 18:56:26 <ralphschindler> ocramius: i'd been using postgres for postgis stuff in my spare time Feb 22 18:56:29 <ralphschindler> i really like it Feb 22 18:56:35 <Thinkscape> weierophinney: ok, worst case: some pr's wont go in Feb 22 18:56:40 <Akrabat> has anyone got a plan to test config? Feb 22 18:56:48 <ocramius> ralphschindler: the feature you need tomorrow, implemented yesterday Feb 22 18:56:50 <weierophinney> Thinkscape, exactly. I'm not too worried abou tthem. Feb 22 18:57:05 <weierophinney> Akrabat, ezimuel has written tests at this time, and is writing usage examples. Feb 22 18:57:07 <Akrabat> a good use-case would be to redo the skeleton using config\reader Feb 22 18:57:10 <ezimuel> Akrabat: I tested Feb 22 18:57:16 <weierophinney> Akrabat, but we should do that part as well. Feb 22 18:57:16 <DASPRiD> Akrabat, thankfully the new config layer is so simple, it can't really break Feb 22 18:57:19 <ocramius> weierophinney: don't forget about the PR discussion later Feb 22 18:57:27 <SpiffyJr> weierophinney, does the Zend\Config change require components consuming it to be refactored or has that already been done? Feb 22 18:57:34 <weierophinney> ocramius, it didn't make the agenda. Will have to do it next week. Feb 22 18:57:43 <weierophinney> ocramius, hint: you should add it. Feb 22 18:57:43 <DASPRiD> EvanDotPro should use the Zend\Config\Factory in the module layer Feb 22 18:57:45 <Thinkscape> i think I missed it - but have there been any developments with: 1) php5.4 poll 2) interface naming poll ? Feb 22 18:57:46 <ocramius> oh, ok Feb 22 18:57:54 <Akrabat> ezimuel: that's a good start Feb 22 18:58:05 <EvanDotPro> DASPRiD: yep Feb 22 18:58:12 <weierophinney> SpiffyJr, I think that no further work has to be done. DASPRiD, Thinkscape, and ezimuel can better answer that. Feb 22 18:58:18 <DASPRiD> SpiffyJr, well, no, Config() object is still the same, and the readers only return arrays Feb 22 18:58:20 <weierophinney> Thinkscape, yes, I can update on those. Feb 22 18:58:27 <SpiffyJr> DASPRiD, okay, thanks. Feb 22 18:58:38 <Thinkscape> weierophinney: we have to plan a fat refactor ... Feb 22 18:58:43 »» SpiffyJr heads to the hospital for the gigantic baby ultrasound Feb 22 18:58:45 <Akrabat> generally, for db and config, I personally would like to see that someone has implemented these into a test mvc app Feb 22 18:58:46 <weierophinney> Thinkscape, official decision: not doing a poll on 5.4 usage. We'll target 5.3, and ship a variety of traits for 5.4 users. Feb 22 18:58:47 <SpiffyJr> Ciao. Feb 22 18:58:51 <DASPRiD> SpiffyJr, and we already changed most componetns to be not aware of config but Traversable Feb 22 18:58:58 <DASPRiD> SpiffyJr, enjoy Feb 22 18:59:06 <weierophinney> Thinkscape, as for interface poll: it's closed. Abstracts are prefixed, interfaces and traits are suffixed. Feb 22 18:59:07 <SpiffyJr> DASPRiD, I noticed Zend\Navigation wasn't updated yet. I'll update that as well before I submit my PR. Feb 22 18:59:15 <weierophinney> (which goes in line with other frameworks as well) Feb 22 18:59:25 <Akrabat> weierophinney: we need to write that up and post it on the dev blog Feb 22 18:59:26 <DASPRiD> SpiffyJr, updated? Feb 22 18:59:31 <DASPRiD> you mean config wise? Feb 22 18:59:32 <weierophinney> Thinkscape, which means refactoring components to do those things Feb 22 18:59:33 <weierophinney> Akrabat, noted. Feb 22 18:59:34 <Thinkscape> weierophinney:are we targeting beta4 for the interface naming refactor? Feb 22 18:59:34 <SpiffyJr> DASPRiD, yes Feb 22 18:59:38 <DASPRiD> SpiffyJr, ah sure Feb 22 18:59:42 <SpiffyJr> DASPRiD, it's still looking for Zend\Config not Traversable Feb 22 18:59:45 <DASPRiD> SpiffyJr, just steal the traversable snippet from another component Feb 22 18:59:48 <DASPRiD> Feb 22 18:59:58 <EvanDotPro> DASPRiD: added to agilezen (config factory in zend\module) Feb 22 13:00:03 <weierophinney> Akrabat, I'll get my site refactored with latest config/view stuff. No DB there for me to work with, though. Feb 22 13:00:13 <SpiffyJr> DASPRiD, fully plan on it. Feb 22 13:00:15 »» SpiffyJr leaves, for real Feb 22 13:00:43 <weierophinney> gl, SpiffyJr Feb 22 13:00:45 <Akrabat> k Feb 22 13:00:58 <weierophinney> who wants to try using Zend\Db in a test site for us? Feb 22 13:01:04 <weierophinney> can I get a volunteer? Feb 22 13:01:13 <weierophinney> please? Feb 22 13:01:34 <Akrabat> do we have db\table still? Feb 22 13:01:40 <DASPRiD> (hopefully not) Feb 22 13:01:43 <Akrabat> or is that not refactored this round? Feb 22 13:01:46 <weierophinney> Akrabat, yes – that was part of this beta. Feb 22 13:01:51 <weierophinney> (and yes, refactored) Feb 22 13:02:00 <weierophinney> ralphschindler, can you point Akrabat to table examples? Feb 22 13:02:06 <Akrabat> I'll do db\table as part of my tutorial Feb 22 13:02:12 <weierophinney> Akrabat, that's awesome, thanks Feb 22 13:02:14 <EvanDotPro> weierophinney: we could try using zend\db in a ZfcUser branch Feb 22 13:02:21 <Thinkscape> ralphschindler: does it have lastInsertId() ? Feb 22 13:02:26 <ralphschindler> Thinkscape: yes Feb 22 13:02:27 <Akrabat> afk - kids bedtime Feb 22 13:02:29 <Akrabat> thanks guys Feb 22 13:02:29 <ralphschindler> Akrabat: Feb 22 13:02:29 <weierophinney> EvanDotPro, that would be awesome - do you have time? Feb 22 13:02:31 <ralphschindler> 6-9 Feb 22 13:02:41 <ralphschindler> examples 6-9 that is Feb 22 13:02:52 <weierophinney> kk, so: Feb 22 13:02:56 <weierophinney> * code freeze Monday Feb 22 13:03:00 <EvanDotPro> weierophinney: i might, i wanna knock out the few stories on agilezen that i have pending too but those are really minor. Feb 22 13:03:05 <Thinkscape> ralphschindler: is query abstr. finished? Feb 22 13:03:06 <DASPRiD> btw, i gotta leave here soon as well, can somebody post me the i18n log so i can update the RFC based on that? Feb 22 13:03:14 <weierophinney> * Akrabat and EvanDotPro to try out Zend\Db on projects Feb 22 13:03:21 <ralphschindler> Thinkscape: sql abstraction has basic implementation Feb 22 13:03:25 <weierophinney> * Matthew to hit the PR queue Feb 22 13:03:32 <weierophinney> * EVERYONE to help with docs. Feb 22 13:03:34 <ralphschindler> trying to get the metadata component finished up Feb 22 13:03:43 <DASPRiD> * DASPRiD to review Config Feb 22 13:03:52 <weierophinney> DASPRiD, I'll get the log posted today. Feb 22 13:03:58 <DASPRiD> weierophinney, perfect, thx Feb 22 13:04:03 <weierophinney> DASPRiD, and, yes, good note on Config Feb 22 13:04:37 <weierophinney> Thinkscape, you can see what ralphschindler has been working on on the board, btw – all are under the "completed" heading (except metadata) Feb 22 13:04:37 <DASPRiD> are we through now? Feb 22 13:04:42 <weierophinney> I think so, yes. Feb 22 13:04:49 <weierophinney> Any last words, or do we call it a day? Feb 22 13:04:59 <DASPRiD> i call it a meeting Feb 22 13:05:00 <ocramius> awesome day, not just day Feb 22 13:05:02 <Thinkscape> you rock! Feb 22 13:05:04 <ocramius> very well done! Feb 22 13:05:11 <EvanDotPro> good meeting Feb 22 13:05:15 <EvanDotPro> Feb 22 13:05:27 <weierophinney> I'll get the log up in a bit, and I've taken notes for the forms rfc. Feb 22 13:05:32 <DASPRiD> mwop calls it his 4th meeting today Feb 22 13:05:43 <weierophinney> everyone, start testing the view layer, and the DB stuff so we can merge. <<<
http://framework.zend.com/wiki/display/ZFDEV2/2012-02-22+Meeting+Log
CC-MAIN-2013-48
refinedweb
9,008
75.34
/* * : @(#) 1 /* * INCLUDES * LIBRARIES * These control the handling of the .INCLUDES and .LIBS variables. * If INCLUDES is defined, the .INCLUDES variable will be filled * from the search paths of those suffixes which are marked by * .INCLUDES dependency lines. Similarly for LIBRARIES and .LIBS * See suff.c for more details. */ #define INCLUDES #define LIBRARIES /* * LIBSUFF * Is the suffix used to denote libraries and is used by the Suff module * to find the search path on which to seek any -l<xx> targets. * * RECHECK * If defined, Make_Update will check a target for its current * modification time after it has been re-made, setting it to the * starting time of the make only if the target still doesn't exist. * Unfortunately, under NFS the modification time often doesn't * get updated in time, so a target will appear to not have been * re-made, causing later targets to appear up-to-date. On systems * that don't have this problem, you should defined this. Under * NFS you probably should not, unless you aren't exporting jobs. */ #define LIBSUFF ".a" #define RECHECK /* * POSIX * Adhere to the POSIX 1003.2 draft for the make(1) program. * - Use MAKEFLAGS instead of MAKE to pick arguments from the * environment. * - Allow empty command lines if starting with tab. */ #define POSIX /* * SYSVINCLUDE * Recognize system V like include directives [include "filename"] * SYSVVARSUB * Recognize system V like ${VAR:x=y} variable substitutions */ #define SYSVINCLUDE #define SYSVVARSUB /* * SUNSHCMD * Recognize SunOS and Solaris: * VAR :sh= CMD # Assign VAR to the command substitution of CMD * ${VAR:sh} # Return the command substitution of the value * # of ${VAR} */ #define SUNSHCMD #if !defined(__svr4__) && !defined(__SVR4) && !defined(__ELF__) # ifndef RANLIBMAG # define RANLIBMAG "__.SYMDEF" # endif #else # ifndef RANLIBMAG # define RANLIBMAG "/" # endif #endif
http://opensource.apple.com/source/bsdmake/bsdmake-8/config.h
CC-MAIN-2015-35
refinedweb
284
57.37
Forum Index On Monday, 11 October 2021 at 15:59:10 UTC, Atila Neves wrote: I'm brainstorming about what I'll talk about at DConf, and during a conversation with Walter I thought it might be cool to talk about: It's a hard one. Variables implicitly declared as global in JS certainly is up there. Pretty much anything working around the incompleteness of type qualifiers. @nogc, shared being a nightmare, the impossibility of having a proper container library, all stem from the same place. owned as a type qualifier. Because it would fix most of the problems for which many features have been introduced. I think we could reduce the language size overall by adding this one. On Wednesday, 13 October 2021 at 02:39:47 UTC, Paul Backus wrote: > On Wednesday, 13 October 2021 at 01:56:19 UTC, russhy wrote: >> this is why things like tagged union (sumtype) and multiple return type should be implemented as language features, that way it is easier to parse (on top of other benefits) >> >> please push for language feature! your work on sumtype was great, but there is much more to gain from upgrading it as a language feature > > std should serve for bigger (missing) purposes - Filesystem package: std.fs - Networking package: std.net - Event Loop package: std.event - Graphics package: std.gfx - Datastructure package: std.collections - Memory package: std.mem not for little things that doesn't have any purpose other than inflating the std with tiny packages that everyone already has implemented in their own "utils" module it's to get issues like this: then even more no.. On Thursday, 14 October 2021 at 01:33:59 UTC, russhy wrote: > On Wednesday, 13 October 2021 at 02:39:47 UTC, Paul Backus wrote: >> Sometimes the difference is not between "easy" and "hard", but between "possible" and "impossible". If you have never written a DIP, or contributed to DMD, it is easy to underestimate the amount of work required to add a new language feature to D. I have done both, and I can say with confidence that adding built-in sum types will take *at least* 10x the effort it has taken to get std.sumtype to its current state. I would love for D to have built-in sum types, believe me. But adding them is simply too big a project for a single volunteer like me to take on. If you really want this to happen, I think your best bet is to convince Walter and the D Foundation to make it an official priority, and sponsor someone to work on it. On Thursday, 14 October 2021 at 02:13:00 UTC, Paul Backus wrote: > ... > If you really want this to happen, I think your best bet is to convince Walter and the D Foundation to make it an official priority, and sponsor someone to work on it. Possibly, in a parallel universe. I guess that kind of goes for most of the suggested language additions though as well which isn't very... comforting. On Wednesday, 13 October 2021 at 20:10:06 UTC, Imperatorn wrote: "Native tuples with destruction", are you sure you don't want deconstruction instead 😉 Yes, that's what I meant. -- /Jacob Carlborg On Wednesday, 13 October 2021 at 19:55:29 UTC, Jacob Carlborg wrote: (int, int) point = (x: 2, y: 4); auto x = point.x + a; ``` This would be better if the identifier was tied to the type. Like below: (int x, int y) point = (2, 4); auto x = point.x + a; Because with your example the following fails: (int, int) getPoint1() { return (x: 2, y: 4); } (int, int) getPoint2(bool shouldGetPoint1) { if (shouldGetPoint1) return getPoint1(); return (left: 2, top: 4); // Possible error since the named values will be different?? } auto point1 = getPoint1(); auto point2 = getPoint2(true); auto point3 = getPoint2(false); writeln("%d %d", point1.x, point1.y); writeln("%d %d", point2.left, point2.top); // Error writeln("%d %d", point3.left, point3.top); However it wouldn't fail if it worked like below: (int x, int y) getPoint1() { return (2, 4); } (int left, int top) getPoint2(bool shouldGetPoint1) { if (shouldGetPoint1) return getPoint1(); return (2, 4); // Ok } auto point1 = getPoint1(); auto point2 = getPoint2(true); auto point3 = getPoint2(false); writeln("%d %d", point1.x, point1.y); writeln("%d %d", point2.left, point2.top); // Ok writeln("%d %d", point3.left, point3.top); On Thursday, 14 October 2021 at 10:55:14 UTC, bauss wrote: Ofc. these are supposed to be writefln and not writeln. Ideas? Examples? Thanks! Worst features in a non-toy language. This is going to be controversial, but templates. They start innocent enough, just a way for functions to work with generic arguments. But then you build templates upon templates, and suddenly IDEs get lost, auto-refactoring stops becoming a possibility because most code doesn't exist yet, and you have to read documentation to understand what the return types and input types are of method T doStuff(T, U)(T val, U min, U max); I wouldn't say worst, but I feel like D has many features which just don't get much use. For example contracts. Sure, they sound nice in principle, and I am sure there are some users of that feature. There's nothing wrong with that, but every feature adds more complexity and bugs to fix. Features I'd like to see in D? Named arguments and struct/associative array initializers working outside of initialization, e.g. as function arguments. Some syntactic sugar I like from other languages: Named constructors as a replacement for factory static methods: class Angle { this.fromDegrees(float deg) { ... } this.fromRadians(float rad) { ... } } Angle a = new Angle.fromDegrees(90.0f); Initializer fields: class Person { string firstName, lastName; int age; this(this.firstName, this.lastName, this.age); } Person p = new Person("Michael", "Schumacher", 52); On Thursday, 14 October 2021 at 11:06:00 UTC, JN wrote: You can somewhat hack your way to it, by generating static functions at compile-time. Of course they're not real constructors, so immutable cannot be used and you can't utilize it like new Angle.fromDegrees(90.0f) and will have to do it like Angle.fromDegrees(90.0f) instead. new Angle.fromDegrees(90.0f) Angle.fromDegrees(90.0f) Example: class Angle { private: this(){} @Ctor void _fromDegrees(float deg) { writeln("from degrees"); } @Ctor void _fromRadians(float rad) { writeln("from radians"); } mixin NamedConstructors!Angle; } void main() { auto a = Angle.fromDegrees(90.0f); auto b = Angle.fromRadians(90.0f); } Implementation of the hacky stuff: struct Ctor {} template ParametersFullyQualified(alias fun) { Tuple!(string,string)[] produceIndexed(T)(T[] a, T[] b) { Tuple!(string,string)[] produced = []; if (a.length == b.length) { foreach (i; 0 .. a.length) { produced ~= tuple(a[i], b[i]); } } return produced; } enum ParametersTypeArray = Parameters!(fun).stringof[1..$-1].split(", "); enum ParameterNamesArray = [ParameterIdentifierTuple!(fun)]; enum ParametersFullyQualified = produceIndexed(ParametersTypeArray, ParameterNamesArray).map!(t => t[0] ~ " " ~ t[1]).join(", "); } mixin template NamedConstructors(T) { public: static: static foreach (member; __traits(derivedMembers, T)) { static if (mixin("hasUDA!(" ~ T.stringof ~ "." ~ member ~ ", Ctor)")) { mixin(T.stringof ~ " " ~ member[1 .. $] ~ "(" ~ ParametersFullyQualified!(mixin(T.stringof ~ "." ~ member)) ~ ") { auto o = new " ~ T.stringof ~ "(); o." ~ member ~ "(" ~ [ParameterIdentifierTuple!(mixin(T.stringof ~ "." ~ member))].join(", ") ~ "); return o; }"); } } } On Monday, 11 October 2021 at 18:27:29 UTC, russhy wrote: [...] It's been a while i haven't used anything other than D, so i don't have much to say, i'll need to research to remember first The enum thing works now: ``` enum MyEnum { A, B, C} with(MyEnum) { auto e = A; myFunction(A); switch(e) { case A: break; default: } } ```
https://forum.dlang.org/thread/kgyfyujtnzdbrrhuwhvj@forum.dlang.org?page=8#post-nezbekijuelnrqfxcqpq:40forum.dlang.org
CC-MAIN-2022-40
refinedweb
1,258
55.84
Advertising --- Comment #29 from Greg Grossmeier <g...@wikimedia.org> --- (In reply to comment #23) > I'm seeing missing arrows next to "Templates used on this page:" below the > edit > window on mediawiki.org as well. Example URL: > < > Custom_inter-namespace_tabs&action=edit>. > I'm not sure if this is already covered by the Gerrit changes linked above. Ditto. Also seeing it on the Beta Cluster, eg at The Beta Cluster is already running with though, ie: even the cherrypick to wmf9 () won't fix it on mw.org most likely. So, this issue isn't fixed with any of the already merged (to master) patches. (In reply to comment #16) > Created attachment 14228 [details] > Screenshot of missing arrows from [[mw:Special:RecentChanges]] > > (In reply to comment #13) > > I don't know what you are looking at on mw.org, but it certainly isn't fixed > > for me or Mz ;) > > I uploaded a screenshot of how [[mw:Special:RecentChanges]] looks to me at > the > moment. Perhaps cache? I don't see that issue on the BetaCluster, but I can confirm on mw.org. So, this one is indeed fixed with the patches merged to master. -- You are receiving this mail because: You are the assignee for the bug. You are on the CC list for the bug. _______________________________________________ Wikibugs-l mailing list Wikibugs-l@lists.wikimedia.org
https://www.mail-archive.com/wikibugs-l@lists.wikimedia.org/msg324798.html
CC-MAIN-2018-30
refinedweb
225
66.44
error.JPGerror.JPG using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CDManagementSoftware { public partial class FormSalesEntry : Form { public FormSalesEntry() { InitializeComponent(); } private void FormSalesEntry_Load(object sender, EventArgs e) { } private void tabPage1_Click(object sender, EventArgs e) { } private void button_Save_Click(object sender, EventArgs e) { CDCenterManagementDatabaseDataContext dc = new CDCenterManagementDatabaseDataContext(); Table_Membership newMember = new Table_Membership(); newMember.Address = textBox_Address.Text; newMember.F_Name = textBox_FName.Text; newMember.L_Name = textBox_LName.Text; newMember.Area = textBox_Area.Text; newMember.PostalCode = Convert.ToInt32(textBox_Postalcode.Text.ToString()); //newMember.PostalCode = textBox_Postalcode.Text.ToString(); newMember.Phone = textBox_Phone.Text.ToString(); newMember.email = textBox_Email.Text; newMember.Amount_Paid = Convert.ToDecimal(textBox_AmountPaid.Text.ToString()); //newMember.Amount_Paid = textBox_AmountPaid.Text.ToString(); ; newMember.M_option = comboBox_choice.SelectedItem.ToString(); newMember.Date_Of_Payment = DateTime.Now; dc.Table_Memberships.InsertOnSubmit(newMember); dc.SubmitChanges(); MessageBox.Show(" {0} " +newMember.Member_Id.ToString()); } private void tabPage2_Click(object sender, EventArgs your variables (probably a VARCHAR) is set to a limit of something and you are inserting something that is longer than the given space. For example, if you have Area set as a VARCHAR(20) and you try to put in a string that is 21 characters, you will get this error. So you either need to truncate your values to the specified DB size before entry, or increase the size of your columns. string sFName = textBox_FName.Text.Trim(). newMember.F_Name = sFName; // Do same thing for all string fields with limited length. dc.Table_Memberships.Inser dc.SubmitChanges(); MessageBox.Show(" {0} " +newMember.Member_Id.ToStr HTH Ashok Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications. open FormSalesEntry.cs [Design] click on a TextBox Press F4 change MaxLength property to 20 characters for example. Do samething for all other limited charactes string fields. Now you do not need to code anything as in my previous post. HTH Ashok I have done the code change as you said but you see the error. The screen shot is having the 1. input 2. error 3.code changed as per your instruction The code is also there in the attached code section as per your instruction . Please Sir help me. I am not understanding what is my mistake. I am trying your 2 nd method also. Thanking you Anindya Open in new windowerror.JPG I have tried your 2nd method also . Please see the screen shot. 3 screen shot are there one by one. Please see the code here I have used is the previous code of at the beginning of my question . Thanking you Anindya Open in new windowerror.JPG I am not ignoring any suggestion. But as you can see the problem is not getting solved. Although I have tried all the options. I hope you can see. Please do not get angry or upset Expert naspinski Thanking you anindya I want you to set it to same length as size of the field in the Database. I think Phone's size is 10 characters. If any other field's size is less than 20, please set MaxLength accordingly. Ashok Thanks for your timely intervention in this. Thanking you, Anindya Chatterjee Bangalore India
https://www.experts-exchange.com/questions/25906184/LINQ-error-insert-data-in-table.html
CC-MAIN-2018-47
refinedweb
559
51.55
extend for loop syntax with if expr like listcomp&genexp ? Discussion in 'Python' started by Bengt Rich genexp reduce syntax in 2.5a1Boris Borcic, Apr 18, 2006, in forum: Python - Replies: - 0 - Views: - 309 - Boris Borcic - Apr 18, 2006 loop beats generator expr creating large dict!?George Young, Oct 3, 2006, in forum: Python - Replies: - 7 - Views: - 275 - David Isaac - Oct 4, 2006 Odd listcomp behaviourEmile van Sebille, Dec 17, 2010, in forum: Python - Replies: - 0 - Views: - 246 - Emile van Sebille - Dec 17, 2010 Syntax bug, in 1.8.5? return not (some expr) <-- syntax error vsreturn (not (some expr)) <-- fineGood Night Moon, Jul 22, 2007, in forum: Ruby - Replies: - 9 - Views: - 325 - Rick DeNatale - Jul 25, 2007 Triple nested loop python (While loop insde of for loop inside ofwhile loop)Isaac Won, Mar 1, 2013, in forum: Python - Replies: - 9 - Views: - 486 - Ulrich Eckhardt - Mar 4, 2013
http://www.thecodingforums.com/threads/extend-for-loop-syntax-with-if-expr-like-listcomp-genexp.346992/
CC-MAIN-2015-06
refinedweb
148
59.57
Manage webhooksEstimated reading time: 1 minute You can configure DTR to automatically post event notifications to a webhook URL of your choosing. This lets you build complex CI and CD pipelines with your Docker images. The following is a complete list of event types you can trigger webhook notifications for via the web interface or the API. Webhook types You must have admin privileges to a repository or namespace in order to subscribe to its webhook events. For example, a user must be an admin of repository “foo/bar” to subscribe to its tag push events. A DTR admin can subscribe to any event.
https://docs.docker.com/ee/dtr/admin/manage-webhooks/
CC-MAIN-2019-26
refinedweb
104
54.02
By Gary simon - May 14, 2017 Looking to integrate Google's Material Design in your Angular 4+ app? Look no further! I created a tutorial a few months ago based on this very subject, except it was for Angular 2. Now, we need to revisit this topic because a few things have changed and that tutorial is now outdated. Be sure to Subscribe to the Official Coursetro Youtube Channel for more awesome design and development videos. I like to start from scratch with these tutorials. So, I'm going to use the Angular CLI to generate a new project. If you're new to Angular and the CLI, check out our Free Angular Course (version 4). Hop into the command line: > ng new ng4-material Once finished: > cd ng4-material We're going to take care of installing all of the necessary dependencies in one command. I'll explain beneath: > npm install --save @angular/material @angular/animations So, we have 2 packages being installed here. Let's also run and watch our app: > ng serve Open our the /src/app/app.module.ts file and import the packages that we just installed: import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MdButtonModule, MdCardModule, MdMenuModule, MdToolbarModule, MdIconModule } from '@angular/material'; Okay, so a lot is happening here. First, we're importing the animations package. The next import is what's unique to Angular 4 Material. Before, we just included a single MaterialModule. Now, we have to import each component that we intend to use. As you can see, I've added 6 different modules here for material buttons, cards, menus, toolbars and icons. Now, let's add each of these as imports in the @NgModule: @NgModule({ // Other properties removed from brevity imports: [ BrowserModule, FormsModule, HttpModule, BrowserAnimationsModule, MdButtonModule, MdMenuModule, MdCardModule, MdToolbarModule, MdIconModule ], }) Go ahead and save this file. You might be wondering though, how did I know the names of the modules to import? Well, I read the official angular material documentation of course! If you click on any of the components on the left menu, and then click on the API REFERENCE tab, it provides you with the exact import line that you need to use. In terms of setup, that's all that we need to do to before we actually begin using and integrating material components into our templates. You just have to remember to import each unique component that you plan on using. While this tutorial will not go in-depth in terms of covering Material components, we will setup a real quick example just so you can get your feet wet. We're going to use JSONPlaceholder to feed us some dummy JSON data for our app. This site provides you with a public API to help test and build your app. To access the API, we have to import the Http library in our /src/app/app.component.ts: import { Component } from '@angular/core'; import { Http } from '@angular/http'; Then, in the AppComponent class, let's add: export class AppComponent { myData: Array<any>; constructor(private http:Http) { this.http.get('') .map(response => response.json()) .subscribe(res => this.myData = res); } } We're defining a property myData as an array, and then in the constructor we're creating an http instance through dependency injection. Then, we're using that instance to grab JSON from the JSONPlaceholder API. Save the file. In our /src/styles.css file, which is generated by the Angular CLI, let's add the following: @import '~@angular/material/prebuilt-themes/indigo-pink.css'; body { padding: 2em 23em; background:lightgray; } Based on your preferences, you can change indigo-pink.css to: I'm also adding some CSS to the body tag only for demonstrating this layout. This helps it look more like an app, even on a desktop. Let's also add 2 lines to our /src/index.html file just before the closing </head> tag: <link href="" rel="stylesheet"> <link rel="stylesheet" href=""> This is importing the material design icon font, and also the Roboto font, which is used by Material design. In /src/app/app.component.html let's start off by adding a toolbar through md-toolbar: <md-toolbar <span>MyCompany</span> <span class="example-spacer"></span> <button md-button [mdMenuTriggerFor]="appMenu"><md-icon>menu</md-icon> Menu</button> </md-toolbar> <md-menu # <button md-menu-item> Settings </button> <button md-menu-item> Help </button> </md-menu> This is what your app should look like in the browser: And when you click on the menu button: Underneath the menu, let's use *ngFor to display some of the photos we're pulling from the API, in card-format: <md-card <img md-card-image <md-card-header> <md-card-title>{{ data.title }}</md-card-title> </md-card-header> <md-card-actions> <button md-button>LIKE</button> <button md-button>SHARE</button> </md-card-actions> </md-card> We're using *ngFor along with a .slice function to only return 10 results; otherwise, we will get over 5,000. We're also defining a local variable of i for the index, in case you want to do something specific with the result, such as making the like or share buttons function. We won't be doing that though, because that extends beyond the scope and purpose of this tutorial. Now, your app should look like this: And that's really all there is to it! An entire course could be dedicated to illustrating the usage of all the various Material components, but that's not really what I wanted to do here. As I mentioned earlier, I created this tutorial to help you understand how to integrate Material in Angular 4+, being that the process has changed since Angular 2. In the future, I may do a course specifically on building an app using Angular Material. If you would like to see that, let me know in the comments! In the mean time, the Angular Material documentation is pretty solid. It provides you with an overview of each component, an API and an example. Good luck everyone!
https://coursetro.com/posts/code/67/Angular-4-Material-Tutorial
CC-MAIN-2017-26
refinedweb
1,011
53.71
December 2007: Firebird Dmitry Yemanov Age: 30 Occupation: Software developer and coordinator Education: Systems Engineering, Penza State University Location: Penza, Russia. Key developers: Alex Peshkov Age: 44 Occupation or experience: Computer programmer Education: Moscow Physical-Technical Institute, 1986 Location: Yaroslavl, Russia Vladyslav Khorsun Age: 33 Occupation or experience: Software developer Education: Faculty of Applied Mathematics, Dnepropetrovsk State University, Ukraine Location: Dnepropetrovsk, Ukraine Adriano dos Santos Fernandes Age: 24 Occupation or experience: Software developer Education: Studying Computer science Location: Sao Paulo, Brazil Claudio Valderrama Age: 36 Occupation or experience: Information engineer Education: Ingenieria Informatica, Universidad Tecnica Federico Santa Maria, Valparaiso Location: Vina del Mar, Chile Arno Brinkman Age: 35 Occupation or experience: Software developer Education: Telematics Location: Bemmel, The Netherlands Quote about SourceForge.net SourceForge.net is the reference site for open source projects. It gave us the ability to work together on Firebird from Day One. When we used the tracker at SF.net, it worked more reliably than our own JIRA tracker does today! Where would open source be without it? Why did you place the project on SourceForge.net? At the beginning, we had no money, and what SF.net offered was not only ideal, it was free. We even hosted our community Web site at SF.net originally, although we moved the site about 18 months ago. We thought that, SF.net being the hub of open source development, it would be the right place to be for picking up new people with good skills — and so it has proven. How has SourceForge.net helped you? It’s a central point for sharing source code. The number one benefit of using SourceForge.net is: It’s free and offers great service. - Project name: Firebird - Date founded/started: July 2000 - Project page: - Community web site: Description of project Firebird is an open source relational database management system that offers many ANSI SQL standard features. It runs on Linux, Windows, and a variety of Unix platforms. Firebird offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. It is used as the back end to a wide variety of two-tier, n-tier, and Web applications. Firebird scales effortlessly from a single-user, single-machine configuration to enterprise environments of 1,000 or more clients. Firebird sources and binaries are distributed free under licences derived from the Mozilla Public License v.1.1. Trove info - Development Status: 5 – Production/Stable - Intended Audience: Developers, End Users/Desktop, System Administrators - License: Mozilla Public License 1.0 (MPL) - Operating System: All 32-bit Microsoft Windows (95/98/NT/2000/XP), all BSD platforms (FreeBSD/NetBSD/OpenBSD/Apple Mac OS X), all POSIX (Linux/BSD/Unix-like OSes), HP-UX, IBM AIX - Programming Language: C, C#, C++, Java, Object Pascal, Python - Topic: Database Engines/Servers - User Interface: Non-interactive (Daemon) Why and how did you get started? The two originators, Mark O’Donohue and Helen Borrie, started it when the (then) Inprise Corp. released almost the entire C source code for its InterBase 6 Beta at the end of July 2000. Other developers quickly joined the project. After a massive code cleanup, Firebird 1.0 was released in March 2002. Alex: Before 2000 I had been successfully developing and maintaining my own C++ library for DBF support but, even then, it was clear that DBF’s days were gone. The company where I worked at that time needed SQL software that was free and able to run on various operating systems, including Windows 95. It wasn’t an option to suggest that clients use pirated copies of Microsoft SQL Server, and buying licences for it wasn’t an option for most firms in Russia at that time either. In 2000 I was happy to discover that Borland had open-sourced InterBase. The first thing I did was to add dynamic SQL support to IB6, but it was soon obvious that supporting a SQL server was going to be a bit more complicated than supporting libraries for DBF databases! Before long, I was attracted to the Firebird project, and I became a member of the core team in 2002. What is the software’s intended audience? Mainly database software developers, of course — all flavours. Firebird serves as a solid relational database back end to all kinds of user and Web applications. Because it is largely self-administering, cross-platform, and free, and is well supported with driver options, it appeals at all levels. How many people do you believe are using your software? Total number of downloads from SF.net is around 2.5 million since the project started, but those statistics aren’t reliable and, anyway, deployment to production sites is not usually done via the Internet. Because it’s free, we don’t have any reliable way to assess the numbers accurately. We can certainly estimate it conservatively in six figures, but it is no doubt much higher in terms of end users; one deploys a single Firebird database server to serve anything from a single user to thousands of concurrent users at the enterprise level. Deployments of embedded Firebird in appliances, such as the Telefonica “o2″ mobile Internet software, run into the millions worldwide. What are a couple of notable examples of how people are using your software? Canadian telcom company Distributel manages its call system 24/7 on a network of satellite Firebird servers all replicating to a central Firebird server cluster. Services is “five-nines” (because it is required by law to be so). Customer dial-in and Internet billing services are also handled on the same network. Alex: There is a lot of software in Russia based on Firebird, because it’s free, reliable, cross-platform, and (an important factor, at least in Russia!) highly compatible with Delphi. Firebird is used in the Yaroslavl region in a 24/7 ticket sales environment in bus stations. Big stations are linked, enabling real-time dispatch of buses. And I’ve just received a letter telling me that the medical triage unit here is about to migrate from SQL Server to Firebird. Adriano: The Brazilian government distributes its SEFIP (social welfare contribution) software to companies through a federal bank. It switched its back end from the original open source InterBase 6 to embedded Firebird at the start of this year. Between 1.2 million and 1.5 million companies in Brazil are required to use SEFIP. This is a case not unlike the “o2″ one mentioned above, where possibly millions of people are using Firebird without even knowing. What gave you an indication that your project was becoming successful? Really it was successful from Day One. We started out with a mass migration of former InterBase users for whom Firebird was, at the time, the only hope of continuity. The first full release went through a long beta phase, with many users running our betas in production during 2000 and 2001. Once the releases started to flow, the user base took off, and the torrent just keeps growing. Getting nominated in four categories for this year’s SourceForge.net Community Choice awards was a welcome set of feathers, especially when we won in two of them (Best Project for the Enterprise and Best User Support). We’ve always had a problem with recognition. As a non-commercial project distributing free software, we aren’t in the rat race of marketing budgets, competing for the software dollar. Whenever the online technology press gets interested in us, we get good write-ups. We started off with zero funds. The formation of the Firebird Foundation in 2002 gave us a way to collect and centralize funding from well-wishers and users who have reasons to want Firebird to survive. To date, however, the overwhelming majority of Firebird users, including commercial companies with huge deployments, don’t contribute anything. Our income is way too small to divert funds away from the essential developer grants into marketing. What has been your biggest surprise? Even though the project has a very supportive community around it, more often than not we get no indication of who is about to launch a major product that uses Firebird. The recent discovery that Firebird was behind “o2″ was a complete surprise. We are a truly international community. Meeting one another face-to-face at conferences is always a surprise we look forward to. To date, Claudio (in Chile) and Adriano (in Brazil) have never met any of the other team members, nor each other. Perhaps some of our biggest surprises are still to come. What has been your biggest challenge? The really big challenge is one that never goes away: weighing up the incessant demand for more features against strict, self-imposed quality standards and finite resources. Technically, our biggest challenge is upon us right now. Firebird 3, due in alpha next year, represents a substantial re-architecting of a huge system that has been around for more than 20 years. Simultaneously, we are providing new subreleases of the v.1.5.x and v.2.0.x release series, and a 2.1 series is in beta. Why do you think your project has been so well received? Those who understand the benefits of open development appear to appreciate the responsiveness of our project members to their problems and needs. Bugs get fixed as quickly as possible, and we are easy to approach when explanations are wanted. Many driver interfaces are available and under active onward development (Jaybird for Java, ADO.NET, ODBC, C++, Delphi, and PHP, to name a few). We maintain a large number of support lists, for Firebird itself and for the associated driver projects. Firebird is also undeniably a good value for money. Where do you see your project going? Alex: The main goals that I see for the next major release are enhancements to the shared data cache and implementation of full support for SMP on our main platforms. What’s on your project wish list? Alex: The main goal of the next release is a multi-threaded, SMP-friendly engine. Vlad: Long life, stability, better public visibility, more developers and other resources. Adriano: For Firebird to make the life of application developers and DBAs easier, be more reliable and predictable in metadata updates, and to be used by more big enterprises. What are you most proud of? Arno: Firebird users who give support in our support list. How do you coordinate the project? We use two SourceForge.net lists for day-to-day coordination: firebird-devel is our “development lab,” and firebird-admins is where the core codeworkers reach decisions about feature sets, release dates, and build details. Architectural discussions usually take place in a Yahoo! list, firebird-architect, typically in threads spawned from an RFC presentation. We maintain a JIRA tracker linked to our CVS and SVN trees at SourceForge.net where both project members and the public can browse bugs, feature requests, and current activities. Assignments, for both features/enhancements and bugs, are usually picked up by whoever is working closest to the area concerned. We have a comprehensive testing suite developed in Python by Pavel Cisar. Tests are available to everyone for unit testing. Pavel oversees the QA process for all prerelease testing, including regression programs for specific changes. We rely heavily on public field-testers during alphas and betas and encourage them to report their results (good or bad) to firebird-devel or the tracker. What is your development environment like? Dmitry: AMD64-x2, Windows XP 64-bit and Microsoft Visual C 2005, Ubuntu Linux 64-bit and gcc Alex: Linux, based on Gentoo, but almost completely rebuilt from sources manually; to make Firebird fit better with what distro packagers do with it, I prefer to use software from the original developers. I’ve never got used to using a variety of IDEs and, for my everyday work, a minimum text editor (like the one in Midnight Commander) and gcc 3.2 to 4.2.1 with appropriate gdb versions are OK. Hardware is AMD64-x2/3800, RAM 1GB, 2*250GB SATA disks in RAID1 configuration. Vladyslav: Intel Core 2 Duo CPU, 4GB RAM, 3*320GB SATA-II hard drives. I use Windows XP 64-bit and Microsoft Visual C 8. Adriano: AMD Athlon 64 dual core with 2GB RAM running Windows XP and Microsoft Visual C++ 2005 Express Edition; AMD Athlon XP with 512MB RAM running Ubuntu Gutsy Gibbon Linux, Eclipse, and GCC. Arno: Two Xeon 3.6, Windows 98, Vista, Microsoft Visual C, Delphi, Glowcode Do you work on the project full-time, or do you have another job? If you work on the project part-time, how much time would you say you spend, per week, on it? Dmitry: Full-time Alex: Full-time Vladyslav: I worked part-time on Firebird starting in 2004, and full-time since March 2007. Adriano: Part-time, about 15 hours per week. Claudio: Part-time about 9 hours per week or more. Arno: Part-time, currently a few hours per month, but I hope to do again 12 hours per week. Milestones: - 2000: Fledgling developers get the long-awaited source code. - 2000-2001: Birth of the Jaybird (Java) and Firebird-ODBC driver subprojects, with project leads Roman Rokytskyy and Vladimir Tsvigun, respectively. A Java/Docbook documentation system is introduced by David Jencks. - 2002: First full release, v.1.0, features thousands of bug fixes to the original source code, new SQL language features, and first attempts to resolve non-ISO-standard implementations and logical ambiguities inherent in legacy InterBase. First Linux builds. V.1.0.x went to three subreleases; no further development since November 2003. - 2002: Carlos Guzman Alvarez begins development of .Net and Mono providers. Mark O’Donohue and Helen Borrie assemble a steering group of 12 developer users to form the Firebird Foundation. Formal incorporation as a nonprofit association under the legal jurisdiction of the NSW state government happens on November 20. Members pay subscriptions, first sponsors appear. Active codeworkers are honorary members. - 2003: First full release of v.1.5, entire codebase refactored from C to C++ to pave the way for plug-in architecture planned for v.2 and for mobile OSes and appliances. Many SQL language enhancements and re-implementations. Classic and embedded models for Windows are introduced and the embedded implementation on POSIX is rationalized. First international Firebird Conference is held in Fulda, Germany. - 2003: Paul Vinkenoog joins the Firebird-docs project and breathes life into it. He completes the Java/DocBook tools development started by David and sets about organising authors and materials. V.2 development is under way, with substantial improvements in code structure, development of reusable elements, and fixes for vulnerabilities and bugs. - 2004: Jim Starkey joins the project and begins work for a private customer on a tree forked from the v.1.5.2 codebase, codenamed Vulcan, which represents a major re-architecting of his original 1990 design. Many aspects of Vulcan will be subsequently incorporated into Firebird 3. Second international Firebird Conference, also in Fulda. - 2005: Firebird 2 betas hit the bricks. Vulcan beta is available to field-testers and SAS Institute developers join the project. Third international Firebird Conference in Prague. - 2006: Release of Firebird 2.0. at Fourth International Firebird Conference in Prague. Features a large number of new language implementations, tightened security, a pluggable incremental backup subsystem (nbackup), and total revamping of the INTL (international language support) subsystem using the ICU Unicode libraries distributed by IBM. - 2007: Release of v.1.5.4, more subreleases of v.2.0.x, and two beta releases of v.2.1, which introduces important developments in SQL language, operations monitoring, and international language support. Preparations are under way for v. 3 development, including design for fine-grained SMP support, pluggable cluster support, pluggable security, and schema namespaces. We win in two categories of the SourceForge.net Community Choice Awards (Best Project for Enterprise and Best User Support). Fifth international Firebird Conference in Hamburg, Germany. - 2007, December: Release of v.1.5.5 before Christmas, with some important v.2.0 backports. - 2008, early: Task group will decide and publish the roadmap for 2008-9. - 2008, first quarter: At least one RC followed by full release of v.2.1. - 2008, by mid-year: [Speculative] v.2.5 Betas and release; v.3.0 Alpha[s]. How can others contribute? In the core, we have plenty of room for more people with good C++ skills who are interested and willing to share their time. Firebird isn’t a project for dilettantes. New “inductees” typically demonstrate an interest in doing a particular implementation or enhancement by having downloaded and familiarized themselves with a module and presenting some code to the firebird-devel list. If it shows they understand what they’re doing (or know what they need in order to understand better) and intend to stick around, one or more of the active codeworkers will step in as mentor. Serious, regular contributors may become eligible for Foundation grants if they’re able to make a minimum time commitment per month. In QA we can always use more testers: field-testers for snapshots, betas, and RCs (the more the merrier!) and also more hands to run the test suites. Grants can be made available to seriously useful suite testers. Initial contact point is the firebird-devel list although we do have the firebird-test list at SF as another meeting-point. Coordinator is Pavel Cisar. We have an ongoing, desperate need for documenters: people to write and maintain user documentation. The user manuals and reference guides are ongoing projects that need skillful contributors. One-off how-tos and white papers are also highly welcome. The meeting point is the firebird-docs list at SF.net, coordinator Paul Vinkenoog. MONEY! The project couldn’t achieve what it does without our voluntary funders. We hope that companies making or saving money by being able to download and deploy Firebird free of charge would want to “put something back” to contribute to Firebird’s continuity and survival. The Firebird Foundation manages funds derived from membership subscriptions, donations, sponsorships, and miscellaneous fund-raising activities. Visit the Web site and click the buttons!
http://sourceforge.net/blog/potm-200712/
crawl-003
refinedweb
3,041
57.06
Adding a sensor backpack to a toy robot and using it to control a 3D model displayed in a browser. This project uses a 3D printed ‘backpack’ containing an ESP32, a 9 axis movement sensor, battery and touch switch attached to a toy robot. The ESP32 reads data from the movement sensor as the robot is rotated and tilted. This data is received by a web page served by the ESP32 and using the three.js JavaScript library a previously captured 3D model of the robot follows the movement. Oh… and there’s 3D generated lightning! For this project I used an Iron Man toy from eBay, an ESP32 board with microSD card reader, an MPU9250 9-axis board and a TTP223 capacitive touch button from AliExpress. Some cables and a spare microSD card. You also need a little 500mAh 43x25x8.5 mm LiPo if you want to power it from a battery. You can either print the robot backpack using a 3D printer or just use thick cardboard and some elastic bands. You might prefer to use your own action toy or other item as the basis for the 3D model. To do this you need to turn your physical object into a 3D file to be displayed in a browser. Creating a 3D Model from Photos Creating the 3D model from photographs, often called photogrammetry involves taking many photos of your object from many different angles and using software to recreate the object in 3D. There are many ways of doing this and for my project I used a combination of Regard3D, Meshmixer, Creators3D online viewer and Microsoft’s 3D Builder. The workflow is a little convoluted but worked for my application. To start I took about 50 images of the robot from three different heights. In Regard3D I used the following settings to create the 3D data: Matches Detector(s): AKAZE Threshold: 0.0001 Dist ratio: 0.9 Camera model: Pinhole radial 3 Matching algorithm: FLANN Triangulation New Incremental, MaxPair initilization, intrinsic camera parameters refined Densification CMVS/PMVS UseVis: no Level: 1 Cell size: 2 Threshold: 0.7 wsize: 7 Min image num: 3 Max cluster size: 100 Surface Type: Posisson Parameters: Depth: 9 Samples per Node: 8.6 Point weight: 4 Trim threshold: 5 Colorization: Textures Color Params: GeomVisTest: yes Global seam level: yes Local seam level: yes Outlier removal: None The result isn’t perfect but usable to start. There are many tutorials for Regard3D and possibly other settings will work better for your case. At this point I was exporting the surface as a obj file to clean up in MeshLab but I couldn’t find any way of re-exporting it from Meshlab which included the textures. I turned to Meshmixer and used Select > Unwrap Brush to clean all the extraneous material you can see in the Regard 3D screen above. I saved the cleaned up file in 3mf format because this format contains all the 3D data and textures in one file. At this point your 3D model is probably the wrong way up and too small to be used in the second part of the project. I found Microsoft’s 3D Builder worked really well for re-orientating and enlarging the model using a combination of the rotation and movement controls, especially with the Object > Settle command to make the model sit flat. Making the model similar to the dimensions below worked well for three.js So the model rotates around the centre, set the location as below. You can see the model will sunk half way into the floor. The model is now ready to be export as a GLB file and used in three.js but the filesize is large and will take ages to download and display from the SD card on the ESP32 board. The easiest solution I found to reduce the file size is the Creators 3D online viewer and converter found here:. Drag and drop the GLB file and choose the following options to export a new GLB file: Assembling the Backpack Once you have your 3D file ready you can assemble the backpack with the ESP32 and motion sensor. I used Tinkercad to create the parts and then just glued them together. You can see in the Tinkercad screen below that I used an STL export of the robot to make a robot shaped hole in the backpack so it fits over the robot. The 3D prints look like this: Assembled, the backpack looks like this: The Arduino Code The Sketch consists of two parts. The first part reads from the movement sensor and converts it into calibrated data. The second part is a webserver hosting a web page. The webpage contains JavaScript including the three.js library that receives the calibrated data over websockets and updates the position of the 3D model. There’s several Arduino libraries for the MPU-9250. I used the refactored version of kriswiner library found here:. This can be installed using the Arduino Library Manager: To increase the sensitivity level of the readings. I changed line 20 in Documents\Arduino\libraries\MPU9250\mPU9250.h to: template <typename WireType, AFS AFSSEL = AFS::A2G, GFS GFSSEL = GFS::G250DPS, MFS MFSSEL = MFS::M16BITS> The ESPAsyncWebserver library also needs to be installed by downloading the ‘Download ZIP’ link and in the IDE installing it with Sketch > Include Library > Add .ZIP Library. Connect the ESP32 and MPU9250 as below, copy the files in the SD folder from the Github repository here – onto the SD card, insert it and connect via USB. Before assembling the backpack, the MPU9250 should be calibrated. The first time you upload the script make sure you have the Serial Monitor open in the Arduino IDE because a calibration script will start. During the first part of calibration the MPU9250 sensor needs to be flat. During the second part, move it in a figure of 8 movement using the full extent of your arm. After the calibration has completed you can assemble the backpack. The project is now complete. If you open the IP address shown in the Serial Monitor or on your router’s list of connections in the browser you will see the 3D model of the robot. The on-screen robot should follow the movements of the physical robot and pressing the button on the backpack should result in lightning between the robot’s hands. Project Demonstration Here’s a quick demo of the 3D robot following the movement of the physical robot: I’ve uploaded another demo but without the ESP32 and sensor so you can see the effect without building the project. Click on the robot to move it. The three.js Library and ESPAsyncWebserver If you want to recreate the code from scratch and not use the files in the SD card folder you can install three.js in a few ways . For me the easiest way was to download the zip file from Github, extract it and copy the build and examples folders to my app folder and refer to them like this in my HTML file: import * as THREE from './build/three.module.js'; import { GLTFLoader } from './examples/jsm/loaders/GLTFLoader.js'; For a simple application with only a few dependencies the ESP32 works fine but I discovered that the lightning code requested too many JS files for ESP32 webserver to cope with so I used Parcel to bundle all the JS files into one file and this only requires one request: webserver.on("/parcel.e31bb0bc.js", HTTP_GET, [](AsyncWebServerRequest * request) { request->send(SD_MMC, "/parcel.e31bb0bc.js", "application/javascript"); }); I found Parcel easier to set up and use than Webpack. The Github repository contains the files that I used to build the bundled script file here: MPU-9250 Libraries for the ESP32 There’s quite a few MPU-9250 libraries for the Arduino IDE. Some of them work with the ESP32. Probably the most comprehensive library which includes sensor fusion algorithms – Port of the kriswiner’s library for the GY-21 (the board I have) to include the BMP280 sensor – Refactored version of kriswiner library (used in this project) – An ESP32 library that allows control over the 9250’s DMP features – . An alternative library – Easiest library I found – just works with an ESP32 but doesn’t have ‘fusion’. Need to run the GetMadOffset sketch to see magnet data. For my purposes it came down to choice between the refactored kriswiner library and using the correction algorithms in the library code or using the ported Sparkfun library where the correction algorithms are done on the chip. Other Sensor Options BNO080 replacement for the not well received 005 devices – (and the library –) Links Great article about 9 D0F sensors – Buy Me A Coffee If you found something useful above please say thanks by buying me a coffee here...
https://robotzero.one/esp32-mpu9250-three-js/
CC-MAIN-2022-33
refinedweb
1,473
60.04
Home-Made Twitter and Gmail Notifications with PHP and Arduino This article was peer reviewed by Claudio Ribeiro. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!…. Well need to be able to identify each service by a friendly name, and we’ll also need to know which light colors to associate with the service. Connecting To Twitter Communicating with Twitter means dealing with OAuth. There’s no point writing yet another abstraction for this, so we’re going to use a fairly popular Twitter library: composer require endroid/twitter We’re also going to need to create and store various API keys. Head over to and create a new application. You can use any callback URL, since we’re going to override it anyway. Creating new Twitter applications Note the consumer and access tokens and keys. Committing these kinds of things to Github is usually a terrible idea, so instead we’ll store them as environment variables. Let’s create a couple of files (called .env and .env.example): SERVICE_GMAIL_USERNAME= SERVICE_GMAIL_PASSWORD= SERVICE_TWITTER_CONSUMER_KEY= SERVICE_TWITTER_CONSUMER_SECRET= SERVICE_TWITTER_ACCESS_TOKEN= SERVICE_TWITTER_ACCESS_TOKEN_SECRET= This is from .env.example Before doing anything else, create a .gitignore file, and add .env to it. That’s where we will store the secret things, so we definitely don’t want to commit it to Github. Next, let’s create the Twitter notifier service: namespace Notifier\Service; use Notifier\Service; use Endroid\Twitter\Twitter as Client; class Twitter implements Service { /** * @var Client */ private $client; /** * @var bool */ private $new = false; /** * @var int */ private $since; /** * @param string $consumerKey * @param string $consumerSecret * @param string $accessToken * @param string $accessTokenSecret */ public function __construct($consumerKey, ↩ $consumerSecret, $accessToken, $accessTokenSecret) { $this->client = new Client( getenv("SERVICE_TWITTER_CONSUMER_KEY"), getenv("SERVICE_TWITTER_CONSUMER_SECRET"), getenv("SERVICE_TWITTER_ACCESS_TOKEN"), getenv("SERVICE_TWITTER_ACCESS_TOKEN_SECRET") ); } } This is from src/Service/Twitter.php Generally, it’s a good idea to create dependencies like the Client outside the class, and bring them in as constructor parameters. But this client is just an implementation detail, and I have no interface to hint against. I think it’s OK to create a new instance inside. The getenv function gets environmental variables – the same ones we defined in .env. We’ll load them shortly. Let’s create the query method: /** * @inheritdoc * * @return bool */ public function query() { if ($this->new) { return true; } $parameters = [ "count" => 1, ]; if ($this->since) { $parameters["since_id"] = $this->since; } $response = $this->client->query( "statuses/mentions_timeline", "GET", "json", $parameters ); $tweets = json_decode($response->getContent()); if (count($tweets) > 0) { $this->new = true; $this->since = (int) $tweets[0]->id; } return $this->new; } This is from src/Service/Twitter.php We’re going to be querying this service often, and until we dismiss the tweet notifications, we want them to continue showing on the LED. Therefore, if we previously found new tweets, we can return early. If we’ve already queried Twitter for new tweets, we add its ID into the request parameters. That means we’ll only return new tweets in subsequent API requests. We already connected with the client in the constructor. So, we can immediately call the client->query method, fetching tweets from the mentions timeline. If there are any new tweets since the since ID, we report new tweets. We just need to complete the interface: /** * @inheritdoc */ public function dismiss() { $this->new = false; } /** * @inheritdoc * * @return string */ public function name() { return "twitter"; } /** * @inheritdoc * * @return int[] */ public function colors() { return [1 - 0.11, 1 - 0.62, 1 - 0.94]; } This is from src/Service/Twitter.php We’ll see how to use this class shortly. Connecting To Gmail We don’t have to use OAuth to connect to GMail, but we do have to enable IMAP, and generate an application-specific password. If you don’t already have IMAP enabled with PHP, refer to your installation’s/operating sytem’s help for doing that. When building from source, you can generally install it with the --with-imap flag. That also works with Homebrew on OS X: brew install phpXX --with-imap XX is your PHP version number like 56 or 71 To create a new application-specific password, head over to : Creating new Google application-specific passwords Once you have a new password, set it in .env, along with the email address you created it for. Next, let’s connect to GMail: namespace Notifier\Service; use Notifier\Service; class Gmail implements Service { /** * @var bool */ private $new = false; /** * @var array */ private $emails = []; /** * @var string */ private $username; /** * @var string */ private $password; /** * @param string $username * @param string $password */ public function __construct($username, $password) { $this->username = $username; $this->password = $password; } } This is from src/Service/Gmail.php This looks similar to how we began the Twitter service class, but instead of creating a new Twitter client, we’re going to use imap_open to get a new inbox resource. As I discovered earlier, we need to reconnect each time we want to check for new emails. A curious side-effect of this IMAP client… Next, we need to create the query method: /** * @inheritdoc * * @return bool */ public function query() { if ($this->new) { return true; } $inbox = imap_open( "{imap.gmail.com:993/imap/ssl}INBOX", $this->username, $this->password ); if (!inbox) { return false; } $emails = imap_search($inbox, "ALL", SE_UID); if ($emails) { foreach ($emails as $email) { if (!in_array($email, $this->emails)) { $this->new = true; break; } } $this->emails = array_values($emails); } return $this->new; } This is from src/Service/Gmail.php As I mentioned earlier, we need to reconnect to the IMAP server each time we want to see new emails. So, we do that, searching for all emails in the inbox. Then we compare what is returned with the list of previously cached message IDs. If there are any new ones, we report new emails. Let’s finish up the rest of the interface implementation: /** * @inheritdoc */ public function dismiss() { $this->new = false; } /** * @inheritdoc * * @return string */ public function name() { return "gmail"; } /** * @inheritdoc * * @return int[] */ public function colors() { return [1 - 0.89, 1 - 0.15, 1 - 0.15]; } This is from src/Service/Gmail.php Curiously, the RGB colors used in the YouTube and GMail logos are 226, 38, and 28. We subtract these from one because common-anode LEDs are brighter the lower PWM value we set. That’s because the lower PWM value we set, the more we ground the color pins, and grounding the pins leads to stronger current flow through the LEDs. Let’s put these together with the Arduino code… Connecting To Arduino We don’t have a lot of time to go through the basics of Arduino PHP programming. Fortunately, I wrote another excellent post about it. Follow the instructions there, being sure to install the Gorilla extension (if you’re on OS X). Once we’ve installed Firmata, we can install the Carica libraries: composer require carica/io dev-master@dev composer require carica/firmata dev-master@dev In addition, we also need to install that environment variables library: composer require vlucas/phpdotenv We can get things started by loading the environmental variables, and connecting to the Arduino: require __DIR__ . "/vendor/autoload.php"; use Dotenv\Dotenv; (new Dotenv(__DIR__))->load(); use Carica\Io; use Carica\Firmata; $loop = Io\Event\Loop\Factory::get(); $board = new Firmata\Board( Io\Stream\Serial\Factory::create( "/dev/cu.usbmodem1421", 57600 ) ); print "connecting to arduino..."; $board ->activate() ->done(function () use ($loop, $board) { print "done" . PHP_EOL; }); $loop->run(); This is from notifier.php If you’re unsure what port to use (in place of my /dev/cu.usbmodem1421), type the following: ls /dev | grep usbmodem Try each of the returned items, until you can successfully connect to the Arduino. Once that’s there, let’s initialize the pins: // diode pins $board->pins[10]->mode = Firmata\Pin::MODE_PWM; $board->pins[10]->analog = 1; $board->pins[11]->mode = Firmata\Pin::MODE_PWM; $board->pins[11]->analog = 1; $board->pins[9]->mode = Firmata\Pin::MODE_PWM; $board->pins[9]->analog = 1; // sensor pins $board->pins[12]->mode = Firmata\Pin::MODE_OUTPUT; $board->pins[12]->digital = 1; $board->pins[14]->mode = Firmata\Pin::MODE_ANALOG; This is from notifier.php Not much to say about this. Each RGB LED pin is set to PWM mode, and their values are set to 1 (so that they LED appears to be off). Since my infrared sensor has an enable/disable pin, I need to set that pin to 1 (enabled). Finally, we set the sensor read pin mode to analog. Next, let’s connect to Twitter and GMail: print "connecting to services..."; $services = new SplQueue(); $services->enqueue([ new Notifier\Service\Twitter( getenv("SERVICE_TWITTER_CONSUMER_KEY"), getenv("SERVICE_TWITTER_CONSUMER_SECRET"), getenv("SERVICE_TWITTER_ACCESS_TOKEN"), getenv("SERVICE_TWITTER_ACCESS_TOKEN_SECRET") ), false ]); $services->enqueue([ new Notifier\Service\Gmail( getenv("SERVICE_GMAIL_USERNAME"), getenv("SERVICE_GMAIL_PASSWORD") ), false ]); print "done" . PHP_EOL; This is from notifier.php We can enqueue each service we want to connect to in an SPLQueue. It’s a useful abstract for first-in-first-out (or FIFO) object storage. The second boolean parameter is whether of not the service has new notifications to display. We’ll change this as new notifications are detected and dismissed. Now, let’s set up a repeating check for new notifications: $loop->setInterval(function () use (&$services) { $remaining = count($services); while ($remaining--) { $next = $services->dequeue(); $next[1] = $next[0]->query(); $services->enqueue($next); } }, 1000 * 5); This is from notifier.php We can use the event loop’s setInterval method, which reoccurs every 1000 millisecond * 5 (or 5 seconds). We step through each service in the queue, pull it out, set whether or not it should display new notifications, and then put it back into the queue. This is strange syntax, to be sure. But it’s just a side-effect of using the queue. Now we need to loop through the services again, changing the LED to their color in a rotation. We can set this to show one notification type every 4 seconds: $service = null; $next = function () use ($loop, $board, &$next, ↩ &$services, &$service) { $remaining = count($services); while ($remaining--) { $next = $services->dequeue(); $services->enqueue($next); if ($next[1]) { print "showing {$next[0]->name()}" . PHP_EOL; $service = $next; break; } } if (!$service) { print "no notifications" . PHP_EOL; return; } $colors = $service[0]->colors(); $board->pins[10]->analog = $colors[0]; $board->pins[11]->analog = $colors[1]; $board->pins[9]->analog = $colors[2]; $loop->setTimeout(function () use ($board, &$service) { $board->pins[10]->analog = 1; $board->pins[11]->analog = 1; $board->pins[9]->analog = 1; $service = null; }, 1000 * 1.5); }; $loop->setInterval($next, 1000 * 4); This is from notifier.php We use a similar loop syntax to loop over each service until we find one that needs to be displayed. If we find one, we pull it off the front of the queue and put it back at the end. Then, we fetch its colors and set the pins to the appropriate value. After 1.5 seconds, we turn the pins off again (by setting them back to 1). This $next function is called every 4 seconds. Finally, we want to be able to dismiss notification types, by waving our hand in front of the infrared sensor: $loop->setInterval(function() use ($board, ↩ &$services, &$service) { if ($service !== null && ↩ $board->pins[14]->analog < 0.1) { $remaining = count($services); while ($remaining--) { print "dismissing {$service[0]->name()}" ↩ . PHP_EOL; $next = $services->dequeue(); if ($next[0]->name() === $service[0]->name()) { $service = null; $next[0]->dismiss(); $next[1] = false; } $services->enqueue($next); } } }, 50); This is from notifier.php If there is a service currently displaying a notification, and the sensor is reading a value below 0.1, we take that to mean that there’s a hand in front of the sensor (and that it is dismissing the notification type). We loop through the services, telling the matching service to stop displaying notification alerts. We also call the dismiss method, so that the service will start checking for new messages again. This check happens every 50 milliseconds. Conclusion There are so many interesting things we can do using Arduino and PHP. This is just one useful project. While I was finishing this post, it let me know about multiple new emails and tweets. Now all I have to do is package it up in a project box, and I’ll be able to take it to work! Did you enjoy this? Perhaps you have ideas for the next project I can work on. Let us know in the comments below.
https://www.sitepoint.com/home-made-twitter-and-gmail-notifications-with-php-and-arduino/
CC-MAIN-2019-30
refinedweb
2,032
55.44
s/new/newTHING/. "n" is just too short. Dunno what to rename "this" to. Depends on context, I'd say. On Mon, Aug 21, 2000 at 12:30:25AM -0500, William A. Rowe, Jr. wrote: > Speaking of which, any objection to a mass update of s/new/n/ and > s/this/t/ throughout the sources? There should be few other major > problems (I'll look carefully, however, and make sure no new problems > are introduced) > > It would be nice to be able to compile as c++ without the whole > project throwing up. Syntax coloring gets ugly, as well. > > Bill > > > -----Original Message----- > > From: Greg Marr [mailto:gregm@alum.wpi.edu] > > Sent: Thursday, August 17, 2000 8:21 AM > > To: new-httpd@apache.org > > Subject: Re: filters as stack > > > > > > At 10:59 PM 08/16/2000, Roy T. Fielding wrote: > > >Basically, each filter contains a filter->next to which they write, > > >just like the generators write to r->filters. In fact, I would call > > >it r->output, but there is probably some conflict there with a C++ > > >reserved word. > > > > Nope, there is no output keyword in C++. > > > > These are the keywords in C++ that aren't in C: > > asm bad_cast bad_typeid bool catch class const_cast delete > > dynamic_cast except explicit false finally friend inline mutable > > namespace new operator private protected public reinterpret_cast > > static_cast template this throw true try type_info typeid typename > > using virtual > > > > -- > > Greg Marr > > gregm@alum.wpi.edu > > "We thought you were dead." > > "I was, but I'm better now." - Sheridan, "The Summoning" > > -- Greg Stein,
http://mail-archives.apache.org/mod_mbox/httpd-dev/200008.mbox/%3C20000821005942.F11327@lyra.org%3E
CC-MAIN-2018-17
refinedweb
253
66.54
2009-09-08 16:27:26 8 Comments Client provided me the wsdl to generate the web service.But when I used the wsdl.exe command it generated the .cs class out of it. I consumed that class in my web service and when I provided the wsdl to client it didn't match their schema. Actually I want the .asmx to be automatically generated from the wsdl so that I could fill in the web method. So that it will exactly match their schema. Hope it make sense. Related Questions Sponsored Content 9 Answered Questions [SOLVED] How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3 - 2010-12-16 00:42:14 - bill - 914517 View - 4595 Score - 9 Answer - Tags: apache-flex actionscript soap coldfusion wsdl 32 Answered Questions [SOLVED] How do I generate a random int number? 27 Answered Questions [SOLVED] How to enumerate an enum? - 2008-09-19 20:34:50 - Ian Boyd - 722511 View - 3598 Score - 27 Answer - Tags: c# .net loops enums enumeration 26 Answered Questions [SOLVED] Why not inherit from List<T>? - 2014-02-11 03:01:36 - Superbest - 165396 View - 1284 Score - 26 Answer - Tags: c# .net list oop inheritance 2 Answered Questions [SOLVED] Create an ASMX web service from a WSDL file - 2009-02-14 01:28:29 - dtc - 51152 View - 57 Score - 2 Answer - Tags: asp.net web-services wsdl asmx 1 Answered Questions [SOLVED] Consume a web service via WSDL url - 2019-01-29 08:26:49 - user7245746 - 43 View - 3 Score - 1 Answer - Tags: c# web-services wsdl 0 Answered Questions Generated web service by WSDL, and different WSDL type - 2014-04-27 17:14:48 - user1339609 - 91 View - 0 Score - 0 Answer - Tags: c# web-services wsdl 1 Answered Questions [SOLVED] Generate a WSDL from a dll? - 2011-08-24 18:27:57 - JackAce - 3099 View - 2 Score - 1 Answer - Tags: .net web-services wsdl asmx svcutil.exe 1 Answered Questions [SOLVED] Different WSDL ASMX,WCF web-services - 2011-05-27 06:02:57 - Andrew Kalashnikov - 4391 View - 6 Score - 1 Answer - Tags: .net wcf web-services delphi wsdl 3 Answered Questions [SOLVED] How do I include my own wsdl in my web service in C# - 2009-09-01 14:02:35 - Örjan Jämte - 6320 View - 5 Score - 3 Answer - Tags: c# web-services wsdl asmx @abdul rehman kk 2019-08-02 10:51:17 step-1 step-2 step-2 create new "Web service Project" step-3 add -> web service step-4 copy all code from myFile.cs (generated above) except "using classes" eg: step-4 past it into your webService.asmx.cs (inside of namespace) created above in step-2 step-5 inherit the interface class with your web service class eg: @Red Swan 2016-01-15 07:28:18 This may be very late in answering. But might be helpful to needy: How to convert WSDL to SVC : Go to directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64, Where respective .CS file should be generated. 9.Move generated CS file to appropriate location. @Pradvaar cruz 2018-02-05 19:16:57 this is the easiest and straight approach from vs cmd window. @Neilb 2010-05-20 15:50:58 You can generate the WS proxy classes using WSCF (Web Services Contract First) tool from thinktecture.com. So essentially, YOU CAN create webservices from wsdl's. Creating the asmx's, maybe not, but that's the easy bit isn't it? This tool integrates brilliantly into VS2005-8 (new version for 2010/WCF called WSCF-blue). I've used it loads and always found it to be really good. @Dave Ziegler 2013-07-09 20:26:32 I was going to note this as well, although I never had much luck with it myself (WSCF Blue in particular). Maybe I used an early version or something. @p.campbell 2009-09-10 17:04:31 There isn't a magic bullet solution for what you're looking for, unfortunately. Here's what you can do: create an Interface class using this command in the Visual Studio Command Prompt window: wsdl.exe yourFile.wsdl /l:CS /serverInterface Use VB or CS for your language of choice. This will create a new .csor .vbfile. Create a new .NET Web Service project. Import Existing File into your project - the file that was created in the step above. In your .asmx.csfile in Code-View, modify your class as such: @Joshua G 2013-09-26 18:59:01 Also you can put /out:"path\to\folder" to put the generated code in a certain location. @Jeremy Ray Brown 2014-10-03 23:00:43 Thank you, huge help @Wouter Vanherck 2018-06-26 10:11:31 The command wsdl.exe C:Folder\File.wsdl /l:CS /ServerInterface /out:C:Folderdid it for me. For all those that don't recognise wsdl.exein the command prompt: You can use it in the Developer Command Prompt for VS 2017(found under start when VS17 is installed) @John Saunders 2009-09-10 16:54:16 You cannot guarantee that the automatically-generated WSDL will match the WSDL from which you create the service interface. In your scenario, you should place the WSDL file on your web site somewhere, and have consumers use that URL. You should disable the Documentationprotocol in the web.config so that "?wsdl" does not return a WSDL. See <protocols>Element. Also, note the first paragraph of that article: @marc_s 2009-09-08 17:03:09 How about using the wsdl /serveror wsdl /serverinterfaceswitches? As far as I understand the wsdl.exe command line properties, that's what you're looking for. /server On the other hand: why do you want to create obsolete technology solutions? Why not create this web service as a WCF service. That's the current and more modern, much more flexible way to do this! Marc UPDATE: When I use wsdl /serveron a WSDL file, I get this file created: This is basically almost exactly the same code that gets generated when you add an ASMX file to your solution (in the code behind file - "yourservice.asmx.cs"). I don't think you can get any closer to creating an ASMX file from a WSDL file. You can always add the "yourservice.asmx" manually - it doesn't really contain much: @alice7 2009-09-08 17:49:24 NO that's not actually Im looking for.It would generate the proxy class which I don't want.I want to generate abc.asmx automatically.And I thought for WCF but went to be simple by making web service.
https://tutel.me/c/programming/questions/1394930/how+to+generate+web+service+out+of+wsdl
CC-MAIN-2019-47
refinedweb
1,111
65.01
When reading the reference solution, you may find it helpful to think of j as the position of the next character to match, having matched the previous (ie j-1) character See here for an alternative solution that hopefully is easier to understand. See here for a solution that tests your understanding of loops, especially the termination conditions. As discussed in class: /* * Base case: n is a single-digit number * return n * * Inductive step: * Let: * a = rightmost digit of n * m = rest of digits in n * return a + sum_digits(m) */ // Return sum of digits in n // Precond: n >= 0 int sum_digits(int n) { if (n / 10 == 0) return n; else return (n%10) + sum_digits(n/10); } As discussed in class: /* * Base case: n is < 100 (n is a 2-digit or 1-digit number) * return n * Inductive step: * Let: * a = rightmost pair of digits in n * m = rest of the digits/pairs in n * if a > largest_digit_pairs(m): * return a * else * largest_digit_pairs(m) */ /* * Base case 1: size = 0 * do nothing! (since nothing to reverse) * * Base case 2: size = 1 * do nothing! (reversing it would give back the original array) * * Inductive step: (for size >= 2) * Let: * head = arr[0] * tail = arr[size - 1] * body = arr + 1, size - 1 * * swap head and tail * call reverse_array on body */ void reverse_array(int arr[], int size) { if (size == 0) ; else if (size == 1) ; else { swap(&arr[0], &arr[size-1]); reverse_array(arr+1, size - 2); } } (definition of swap is omitted) Be sure to bump up NUM (size of array), otherwise the sample array in the question wouldn't work. First, let us remind ourselves what ne(x,y) computes: number of unique NE-paths between two points separated by x rows (north) and y columns (east). In this case, it seems easier to come up with the recursive step: ne(x,y) = ne(x-1,y) + ne(x,y-1) This is interpreted as saying: the number of (x,y) paths is given by: Now we define the base cases to ensure that we terminate: if (x==0 || y==0) return 1; Why 1? Let's say x is 0; that would mean we can't go north, so there is only 1 path - go east. Similarly for y=0. Note that the recursive step may lead to calls with negative x,y, so it may be safer to say if (x<=0 || y<=0) return 1; even though ne called with negative x,y doesn't make any sense. Alternatively, we could add ifs to guard against negative x,y before calling ne(x-1,y) etc, at the expense of some readability. The code: int ne(int x, int y) { /* be safe, not sorry! */ if (x <= 0 || y <= 0) return 1; return ne(x-1, y) + ne(x, y-1); } A robot can take steps of size 5, 3, 2, or 1. Write a program to compute the number of ways the robot can walk n steps. (If you are spending too much time, try a different approach!) This is an example where the things being sorted is different from the things being compared. '\062' is the octal (base 8) representation of the decimal number 50, which is the ASCII character '2'. '\x41' is the hexadecimal (base 16) representation of the decimal number 65, which is the ASCII character 'A'. The string "pineapple" is itself 9 characters long; including the NUL \0 character, we would need an array of size 10. So the strcpy is unsafe. Below is a carefully-constructed program to illustrate that strcpy may write outside of the array's allocated memory: char fruitname[15], x='a'; strcpy(fruitname, "a big pineapple"); printf("fruitname='%s', x=%d\n", fruitname, (int) x); ( fruitname is chosen to be size 15, so that x sits nicely right after it.) The string "a big pineapple" is exactly 15 characters; but to store it, we would need 16, to accomodate the trailing NUL. Thus, the NUL byte is writen by strcpy into x, giving x=0 in the output. No NUL byte for the strings board[0] and board[1]. fruit1, fruit2, str1, str2 are string literals and may not be allocated in writable memory space. Thus, writing to them (like with strcpy) may not succeed. At compile time, string literals are used to create an array of static storage duration of sufficient length to contain the character sequence and a null-termination character. It is unspecified whether these arrays are distinct. The behavior is undefined if a program attempts to modify string literals but frequently results in an access violation because string literals are typically stored in read-only memory — Consider this snippet: while (str[i]) { ... i++ } Assuming str is a NUL-terminated string, this will loop through the characters in str and terminate upon encountering NUL (since NUL=0 which evaluates to "false"). Apart from using multiple scanf("%s") to read in words individually, you may read in the full sentence (with fgets) and then use strtok (introduced in Q3). (Got this idea from QW) See Week 06 for issues associated with scanf() on characters and possible solutions. Visualization: n-1 th n th n+1 th m-1 th | | y | | m th | z | x=y+z| | m-2 th | | | | where: Interpretation: each cell is summed with the cell in its "reflection" along x=y diagonal. It's useful to keep in mind these idioms, so that the you don't have to re-analyze when you encounter a for/while loop. with the for construct: for (i=0; i<=SIZE-1; i++) { /* do something with arr[i] */ } also: for (i=0; i<SIZE; i++) { /* do something with arr[i] */ } Both forms are equivalent. with the while construct: i = SIZE; while (i--) { /* do something with arr[i] */ } Note that the order of this form is different from the above ones; it goes through the array backwards. Diff from our discussion: --- Week7_Q1a.c Fri Mar 2 00:32:10 2012 +++ Week7_Q1a-ours.c Wed Mar 7 13:57:49 2012 @@ -2,13 +2,13 @@ int main(void) { - float[5] values; + float values[5]; int i; - for (i=1; i<=5; i++) + for (i=0; i<=4; i++) values[i] = 2.5*i; - for (i=1; i<=5; i++) + for (i=0; i<=4; i++) printf("%f ", values[i]); printf("\n"); I said in class that it is possible, by adding '{' and '}' to the first for loop, like this: --- Week7_Q1a-ours.c Wed Mar 7 13:57:49 2012 +++ Week7_Q1b-ours.c Wed Mar 7 23:50:00 2012 @@ -5,11 +5,11 @@ float values[5]; int i; - for (i=0; i<=4; i++) + for (i=0; i<=4; i++) { values[i] = 2.5*i; - for (i=0; i<=4; i++) printf("%f ", values[i]); + } printf("\n"); return 0; Clearly, this is incorrect, as the question's printf() intends to print all the elements, not element-by-element, like the above. (Thanks to QW for pointing this out) Diff from our discussion: --- Week7_Q1c.c Wed Mar 7 14:40:24 2012 +++ Week7_Q1c-ours.c Fri Mar 2 12:25:46 2012 @@ -1,23 +1,22 @@ #include <stdio.h> -float sumArray(float, int); +float sumArray(float[], int); int main(void) { - float prices[6], total; - prices = { 10.2, 5.3, 4.4, 6.8, 7.7, 9.5 }; + float prices[6]= { 10.2, 5.3, 4.4, 6.8, 7.7, 9.5 }, total; - sumArray(prices[6], 6); + total = sumArray(prices, 6); printf("Total = %f\n", total); return 0; } -float sumArray(float arr, int size) +float sumArray(float arr[], int size) { int i; float sum = 0.0; for (i=0; i<size; i++) - sum += prices[i]; + sum += arr[i]; return sum; } The infinite loop is due to i being set to 0 arr[4] = 0 is executed. Moral of the story: only "use" [0-4] what you "declared"! --- Q2.c Wed Mar 7 14:03:43 2012 +++ Q2-ours.c Fri Mar 2 12:28:21 2012 @@ -4,7 +4,7 @@ { double arr[] = { 1.1, 2.2, 3.3, 4.4 }; int i; - for (i = 0; i < 4; i++) { + for (i = 0; i <= 4; i++) { printf("%d\n", i); arr[i] = 0; } Of course, the infinite loop that we observe is coincidental - generally, we cannot predict the program's behaviour if operations like accessing arr[4] are done. Simple animation to better visualize this program I mentioned that arrays and pointers are equivalent. This is incorrect. When we say int arr[5]; int *p; p = arr; the compiler actually generates a pointer to the first element of arr: p = &arr[0]; This is due to the "decaying" rule. Read more here: Hopefully you haven't forgotten your MA1100/CS1231. When dealing with arrays, being able to find the negative of a universal (which is an existential) will help you "break" iteration early. For example, Q5 wants a program to return 1 if: $$ \forall i: arr[i] < 0 $$ The negative of this statement is then: $$ \exists i : arr[i] \ge 0 $$ So our program should return 0 the moment we encounter an arr[i] >= 0. (Note that the worst-case running time of your program would still be O(n). More on this next time.) It asks what is the property you have "abstracted" out to check? implying that there is some similarity between Q5 and Q6. However, in Q6, your code either has to "lookahead" or "lookbehind", so the iteration condition would be different from Q5. The universal-to-existential strategy in Q5 is still applicable. Aston was right. To see why, consider the factorization of 100, which is 2^2 x 5^2. The powers of each factor are 0, 1, 2. So we have 3 x 3 ways of choosing those powers. Excluding the number itself, we get 3 x 3 - 1 = 8, which agrees with the result of running the program. The issue is that stdin is buffered. For a visualization of this, refer to slide 5. The three solutions we talked about were: scanf(), ignoring whitespace characters (using isspace()from <ctype.h>) scanf(" %c"). This works because: A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread. (asked by YM) The purpose of Q4 is to actually type and run your code. However, some of them can be interpreted in an interesting manner. For example, we see in Q4d that Q4c can be used to "draw" all segments of length >= 1. We also saw in Q4c that it also gives us the number of edges in a complete graph of size 6: We may wonder if Q4e also has an interesting interpretation. It seems there is one. Let's put a * every time execution reaches the innermost loop body (line 6: count++). For example, when x=1 and y=3, the z loop runs from 1 to 3, giving us: x=1, y=3 * * * With that notation defined, let's look at the y and z loops when x=1. y loops from 1 to 5, giving us: x=1, y=1 * x=1, y=2 * * x=1, y=3 * * * x=1, y=4 * * * * x=1, y=5 * * * * * and when x=2, x=2, y=2 * x=2, y=3 * * x=2, y=4 * * * x=2, y=5 * * * * Repeating this all the way to x=4: x=4, y=4 * x=4, y=5 * * and finally with x=5: x=5, y=5 * Thus, count is just the sum of the sum of integers from 1 to n, where n=y-x+1. Recall that the sum of integers from 1 to k is $$ \sum_{j=1}^k j = \frac{k^2 + k}{2} $$ The sum of these sums is thus: Indeed, substituting n=5 gives us 35, agreeing with the output of the code snippet. Q5 illustrates the problem-solving approach that I've been emphasizing. To see how, let's magine you're in PE, and the task statement reads: Write a program that takes in two integers, and outputs the largest possible integer that divides both of them. For most of us, after some guessing, what we'd probably come up with would look like Adam's code. Yes, it may not be efficient, but it does give us the right answer. So, at least aim for a correct algorithm; after that try to find something better. If you're interested, a simple to understand proof of validity of Euclid's algorithm can be found on page 3 of this document. As I mentioned, the purpose of this lab is to give additional practice for coding on sunfire, as well as to pick up good style and habits that will stay with your for the subsequent labs. Overall comments: void foo(void) { /* on a new line */ /* body goes here... */ Ex 4 let's us see how switch-case can be used. Some students used the fall-through switch-case pattern to determine the number of days in a month. Since the months that have 30 or 31 days are (mostly) non-overlapping, this seems like a job appropriate for switch-case. Eg: switch(month) { case 1: case 3: case 5: case 7: /* ... */ days_in_month = 31; Diff for the code resulting from our discussion: --- Week4_Q2.c Fri Feb 3 09:52:50 2012 +++ Week4_Q2-ours.c Fri Feb 3 12:39:04 2012 @@ -1,14 +1,16 @@ #include <stdio.h> +void func(int); + int main(void) { - void func(5); - void func(3-7); + func(5); + func(3-7); return 0; } -void func(y) +void func(int y) { if (y<0) printf("Nothing\n"); Diff for the code resulting from our discussion: --- Week4_Q5a.c Fri Feb 3 09:52:50 2012 +++ Week4_Q5a-ours.c Fri Feb 3 12:51:28 2012 @@ -7,9 +7,9 @@ float value; printf("Enter value: "); - scanf("%f", &value); + scanf("%f", value); - if (0 < value < 1) + if ((0 < value)&&(value < 1)) printf("%f is between 0 and 1\n", value); else printf("%f is not between 0 and 1\n", value); Here I will paste a snippet of the code resulting from our discussion, instead of a diff, since it's not easy to see what's going on from the diff. /*...*/ printf("Enter 3 integers: "); scanf("%d %d %d", &a, &b, &c); if (a <= b && b <= c) printf("The values are in non-decreasing order.\n"); else printf("The values are not in non-decreasing order.\n"); /*...*/ In Q5c, we are provided with code that handles 3 integers, and asked to reduce the redundancy/duplication of code. But what if we have 2 integers? Or 4? Can we extend the code to handle n different integers? In class I introduce some imaginary operations on the object which I called a "list". (Note that these functions and types are not "standard", I made it up for this exercise, so you can't use it elsewhere.) list_head(the_list) gives us the first item in the list. So if we have a list (-5, 6, 9, 12), it would give us -5. list_rest(the_list) gives us the rest of the list. So for the list above, it would give us (6, 9, 12). But for a list with only 1 item like (2), it would give an empty list. Below is a sample session on how to work on this exercise. $ cp ~rctay/cs1010/dg04/q5-ext/skeleton.c my-q5.c $ # edit... $ ~rctay/cs1010/dg04/q5-ext/compile -Wall my-q5.c $ a.out Enter next int: -5 Enter next int: 6 Enter next int: 9 Enter next int: 12 Enter next int: done the integers are in non-decreasing order $ echo 2 8 8 15 15 | a.out Enter next int: Enter next int: Enter next int: Enter next int: Enter next int: Enter next int: the integers are in non-decreasing order Also available as a gist. Download and try out the questions in the slides, we will discuss this in the next DG session. What we covered: Q3 is a good introduction to algorithm design. To score well in this course, you would have to design algorithms under stress while being contrained by time (ie during PE and exams). Try and solve a simple case. Come out with any method. Don't worry about being "slow" or not efficient*, just come with a method. Extend your method to handle the problem space. *analysing algorithms for speed and resource-requirements will be done later in the course. Even if your algorithm doesn't handle all cases correctly, marks will be given for a partially correct solution. Marks may also be awarded if the idea of the algorithm is correct but its implementation (C syntax) is wrong. “Programs should be written for people to read, and only incidentally for machines to execute.” — SICP, Preface to 1st Ed Q8 shows how whitespace is important. Having well-indented code helps the examiner understand your program. If the examiner can't understand it, then you may not get the full mark even if your algorithm is correct. Later on in the course the concept of modularity, another best practice, will be introduced. The value of num1 will be displayed as 123.099998 instead of 123.100000. The reason is that not all numerical values can be represented accurately in computers, due to the finite number of bits used to represent a value. For details, students may look up IEEE 754 Floating-Point Representation, but that is not within the scope of CS1010. For our purpose, it suffices to say that some values cannot be represented accurately, as shown above. That is the inherent limitation of computers. We may use double instead of float to improve accuracy, but still the inaccuracy cannot be eliminated totally. This has implications when we do comparison of real numbers in an ‘if’ condition or a loop condition which we will cover later. %3.2ido? (asked by HW) Refer to your preferred printf reference, as well as try this out: printf("got '%3.2i'!\n", 2); printf("got '%3.2i'!\n", 12); printf("got '%3.2i'!\n", 102); printf("got '%3.2i'!\n", 1023); yes | rm <file>? If you recall, the reason why we have to run this is due to rm being paranoid and asking for confirmation for each file being deleted, which can slow down your work. Understanding this command is a little complicated, as it involves a pipe (done with the | symbol), so here I present a simpler way to do the same thing. If you look carefully, you'll realise that rm is actually aliased to rm -i (run alias to see this). Thus, a simpler alternative would just be $ /bin/rm <file> ... more? (extra) (asked by QW) more is pager, so it chops up output so that you can scroll through it a page at a time. But you shouldn't use more, you should use less, because its more than more. :) This is just a trial lab to familiarise yourselves with Unix/ssh/vim/gcc etc, as well as CodeCrunch. You should also have used scp to download your code. Almost always, we will provide you with sample output that your program is expected to produce when some sample input (also given). First, download the sample input and output files with wget. Continually work in this cycle: Feed the program with the sample input, and capture its output (for later use). $ a.out <sample.input >myoutput The >myoutput specifies which file to save the output into; you should not be running $ a.out <sample.input >sample.output Because that just overwrites the sample output and you'd have nothing to check against. Check whether the produced output was expected. $ diff -u sample.input myoutput Notice that the arguments to diff is of the order <expected> <actual> Any differences? If so, start from the top. You'll have to delete the output file, since sunfire complains about overwriting the file. You can use $ /bin/rm myoutput to avoid the irritating confirmation prompt from rm. CodeCrunch reads the output of your program and tried to match it with its own expected output, much like diff does. The exact test cases are not revealed, however. But not to worry, the CodeCrunch grade will not affect your CA grade.
http://www.comp.nus.edu.sg/~rctay/
crawl-003
refinedweb
3,403
70.33
Introduction Analytics”. Topic Models are very useful for the purpose for document clustering, organizing large blocks of textual data, information retrieval from unstructured text and feature selection. For Example – New York Times are using topic models to boost their user – article recommendation engines. Various professionals are using topic models for recruitment industries where they aim to extract latent features of job descriptions and map them to right candidates. They are being used to organize large datasets of emails, customer reviews, and user social media profiles. So, if you aren’t sure about the complete process of topic modeling, this guide would introduce you to various concepts followed by its implementation in python. Table of Content - There are many approaches for obtaining topics from a text such as – Term Frequency and Inverse Document Frequency. NonNegative Matrix Factorization techniques. Latent Dirichlet Allocation is the most popular topic modeling technique and in this article, we will discuss the same.. In vector space, any corpus (collection of documents) can be represented as a document-term matrix. The following matrix shows a corpus of N documents D1, D2, D3 … Dn and vocabulary size of M words W1,W2 .. Wn. The value of i,j cell gives the frequency count of word Wj in Document Di. LDA converts this Document-Term Matrix into two lower dimensional matrices – M1 and M2. M1 is a document-topics matrix and M2 is a topic – terms matrix with dimensions (N, K) and (K, M) respectively, where N is the number of documents, K is the number of topics and M is the vocabulary size. Notice that these two matrices already provides topic word and document topic distributions, However, these distribution needs to be improved, which is the main aim of LDA. LDA makes use of sampling techniques in order to improve these matrices. It Iterates through each word “w” for each document “d” and tries to adjust the current topic – word assignment with a new assignment. A new topic “k” is assigned to word “w” with a probability P which is a product of two probabilities p1 and p2. For every topic, two probabilities p1 and p2 are calculated. P1 – p(topic t / document d) = the proportion of words in document d that are currently assigned to topic t. P2 – p(word w / topic t) = the proportion of assignments to topic t over all documents that come from this word w. The current topic – word assignment is updated with a new topic with the probability, product of p1 and p2 . In this step, the model assumes that all the existing word – topic assignments except the current word are correct. This is essentially the probability that topic t generated word w, so it makes sense to adjust the current word’s topic with new probability. After a number of iterations, a steady state is achieved where the document topic and topic term distributions are fairly good. This is the convergence point of LDA. Parameters of LDA Alpha and Beta Hyperparameters – alpha represents document-topic density and Beta represents topic-word density. Higher the value of alpha, documents are composed of more topics and lower the value of alpha, documents contain fewer topics. On the other hand, higher the beta, topics are composed of a large number of words in the corpus, and with the lower value of beta, they are composed of few words. Number of Topics – Number of topics to be extracted from the corpus. Researchers have developed approaches to obtain an optimal number of topics by using Kullback Leibler Divergence Score. I will not discuss this in detail, as it is too mathematical. For understanding, one can refer to this[1] original paper on the use of KL divergence. Number of Topic Terms – Number of terms composed in a single topic. It is generally decided according to the requirement. If the problem statement talks about extracting themes or concepts, it is recommended to choose a higher number, if problem statement talks about extracting features or terms, a low number is recommended. Number of Iterations / passes – Maximum number of iterations allowed to LDA algorithm for convergence. You can learn topic modeling in depth here. Running in python Preparing Documents Here are the sample documents combining together to form a corpus. doc1 = "Sugar is bad to consume. My sister likes to have sugar, but not my father." doc2 = "My father spends a lot of time driving my sister around to dance practice." doc3 = "Doctors suggest that driving may cause increased stress and blood pressure." doc4 = "Sometimes I feel pressure to perform well at school, but my father never seems to drive my sister to do better." doc5 = "Health experts say that Sugar is not good for your lifestyle." # compile documents doc_complete = [doc1, doc2, doc3, doc4, doc5] Cleaning and Preprocessing Cleaning is an important step before any text mining task, in this step, we will remove the punctuations, stopwords and normalize the corpus. ``` doc_clean = [clean(doc).split() for doc in doc_complete] ``` Preparing Document-Term Matrix All the text documents combined is known as the corpus. To. It is scalable, robust and efficient. Following code shows how to convert a corpus into a document-term matrix. ``` # Importing Gensim import gensim from gensim import corpora # Creating the term dictionary of our courpus, where every unique term is assigned an index. dictionary = corpora.Dictionary(doc_clean) # Converting list of documents (corpus) into Document Term Matrix using dictionary prepared above. doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] ``` Running LDA Model Next step is to create an object for LDA model and train it on Document-Term matrix. The training also requires few parameters as input which are explained in the above section. The gensim module allows both LDA model estimation from a training corpus and inference of topic distribution on new, unseen documents. ``` # Creating the object for LDA model using gensim library Lda = gensim.models.ldamodel.LdaModel # Running and Trainign LDA model on the document term matrix. ldamodel = Lda(doc_term_matrix, num_topics=3, id2word = dictionary, passes=50) ``` Results ``` print(ldamodel.print_topics(num_topics=3, num_words=3)) ['0.168*health + 0.083*sugar + 0.072*bad, '0.061*consume + 0.050*drive + 0.050*sister, '0.049*pressur + 0.049*father + 0.049*sister] ``` Each line is a topic with individual topic terms and weights. Topic1 can be termed as Bad Health, and Topic3 can be termed as Family. Tips to improve results of topic modeling The results of topic models are completely dependent on the features (terms) present in the corpus. The corpus is represented as document term matrix, which in general is very sparse in nature. Reducing the dimensionality of the matrix can improve the results of topic modelling. Based on my practical experience, there are few approaches which do the trick. 1. Frequency Filter – Arrange every term according to its frequency. Terms with higher frequencies are more likely to appear in the results as compared ones with low frequency. The low frequency terms are essentially weak features of the corpus, hence it is a good practice to get rid of all those weak features. An exploratory analysis of terms and their frequency can help to decide what frequency value should be considered as the threshold. 2. Part of Speech Tag Filter – POS tag filter is more about the context of the features than frequencies of features. Topic Modelling tries to map out the recurring patterns of terms into topics. However, every term might not be equally important contextually. For example, POS tag IN contain terms such as – “within”, “upon”, “except”. “CD” contains – “one”,”two”, “hundred” etc. “MD” contains “may”, “must” etc. These terms are the supporting words of a language and can be removed by studying their post tags. 3. Batch Wise LDA –In order to retrieve most important topic terms, a corpus can be divided into batches of fixed sizes. Running LDA multiple times on these batches will provide different results, however, the best topic terms will be the intersection of all batches. Note: We also have a video based course on NLP, covering Topic Modelling and its implementation in Python. Topic Modelling for Feature Selection Sometimes LDA can also be used as feature selection technique. Take an example of text classification problem where the training data contain category wise documents. If LDA is running on sets of category wise documents. Followed by removing common topic terms across the results of different categories will give the best features for a category. Endnotes With this, we come to this end of tutorial on Topic Modeling. I hope this will help you to improve your knowledge to work on text data. To reap maximum benefits out of this tutorial, I’d suggest you practice the codes side by side and check the results. Did you find the article useful? Share with us if you have done similar kind of analysis before. Do let us know your thoughts about this article in the box below. References - Got expertise in Business Intelligence / Machine Learning / Big Data / Data Science? Showcase your knowledge and help Analytics Vidhya community by posting your blog.You can also read this article on Analytics Vidhya's Android APP 35 Comments Good One.. NMF and SOM are also very useful techinques for this.if possible please share same with SOM Thanks for the feedback, we will do an article on this in the future. Do stay tuned! Amazing blog Shivam. (speaking for the author) Glad you like it! Hi Shivam…..code “dictionary = corpora.Dictionary(doc_clean)” giving error “TypeError: doc2bow expects an array of unicode tokens on input, not a single string”…..please help! Ankur, there was a mistake in the code. Its updated now. Thanks ! Hi Shivam…m still getting the same error. I Hope its fixed now 🙂 You can always convert a string to unicode in this way! mystring = mystring..decode(‘utf-8’) convert your text encoding to ‘utf-8’ i am using the following code and still getting the error: decoded_doc_clean=[] for i in doc_clean: decoded_doc_clean.append(i.decode(‘utf-8’)) dictionary=corpora.Dictionary(decoded_doc_clean) normalized = ” “.join(lemma.lemmatize(word) for word in punc_free.split()) is this part of code correct?? Staya I got error in this line, did you manage to solve it please ? Hi Ankur…use this code it will help u…. import gensim from gensim import corpora dictionary = corpora.Dictionary(doc_clean ) doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] Can you please explain the result and what each of the outputted value signify? Thanks Very useful and interesting article. But I M looking for analysis articles related to stock market analysis. Please do post them which would be helpful for analysing real time data. Nice tutorial. But I think it will be more helpful if you explained what the code is doing specifically. Especially the following sections: – Preparing Document Term Matrix – Running LDA Model – Results Thanks Its updated. Thanks Hi, Thanks for this wonderful post. I just wish to know how to print the two matrices M1 and M2 mentioned in this post. I wanted to analyse the probability values. Could you please let me know how to do that in python for the code you have mentioned in the post. Any help in this regard is highly appreciated. Very nice and intuitive description!! I’ve been looking for something like this for LDA for a long time. I’m curious how sparsity is enforced during the sampling if that makes sense. Not sure if I’m asking the right question, have to do more reading on the subject. Anyway, Thanks a lot for the writeup and code Good Insights on LDA Hi Shivam, I ran the code that you have published in this article But the results i get is different from yours. This is a sample output i received: [(0, ‘0.076*”sugar” + 0.075*”say” + 0.075*”lifestyle”‘), (1, ‘0.076*”father” + 0.076*”sister” + 0.076*”sugar”‘), (2, ‘0.079*”driving” + 0.045*”stress” + 0.045*”blood”‘)] Infact I get different result at each run. We kindly request you to explain why this happens. is there something like set.seed to address this problem? We could solve the problem just by set seeding. Thanks. There are some random effects when we use lDA. If you run several the code provided by Shivam you could’nt have the same result each time. If you want the same result each time you should include a cod like thate : randome-state=1998 (no matter for the number) Very nice article!! Describing the whole process step by step. Though, I am bit confused about the “Frequency filter” for document term corpus. It says to ignore low frequency terms. Doesn’t we use TfidfVectorizor() for giving more weigh to uncommon terms , Correct me if i have a wrong understanding about it. Please upload LSA (Latent Semantic Allocation ) code also. Can you suggest a hassle free method to install gensim. ?When I installed via pip, it tried upgrading Scipy (0.18.1 to 0.19.1 ) and created lot of problems. I had to uninstall scipy and re install again. Thanks for putting up a very informative blog. Can you give references regarding Batch Wise LDA? I would like to understand it more and to try implementing it. When you say that “the best topic terms will be the intersection of all batches”, how do we implement it? Looking forward to reading more. Great forum post. Much obliged. […] o algoritmo Latent Dirichlet Allocation (LDA). Mais informações sobre modelagem de tópicos e LDA aqui. Os códigos utilizados, sempre em Python, veja […] Did you ever receive a response to this? I encountered similar-sounding difficulty installing gensim. I am running Windows 7 64-bit and tried installing gensim with pip install, but the installation failed. Very good article. I have used the code to analize a couple of similar news in Spanish to check on the patterns that pop up. Very clear as well, as I am a nobbie I got strugle on installing some libraries but after that easy Great Post!!!
https://www.analyticsvidhya.com/blog/2016/08/beginners-guide-to-topic-modeling-in-python/?utm_source=blog&utm_medium=heroes-of-machine-learning-experts-researchers
CC-MAIN-2019-39
refinedweb
2,337
57.27
Hitting snags as it stitches together its wide-reaching software-as-a-service plans, Microsoft casts .Net farther and wider. Microsoft acknowledges that its software strategy has been slow to catch on and lays out a plan to move it forward. Therefore, it’s opening up to one of the most important open-source software projects, Apache, and getting closer to a key software rival as well, Oracle. Bill Gates: Slow going for .Net 2002-07-24 .NET 51 Comments I’m certainly not surprised. People seem very much to hate subscriptions (Just look at .Mac, $9/mo for webhosting that integrates with your operating system and people are complaining that it’s too expensive) and Web Services seems doomed to failure in that respect.. If Microsoft does succeed in releasing a version of Office compiled completely to CLR bytecode, it will be interesting to see how quickly it is adopted compared to previous versions. What? are they going to copy (oops, I meant ‘learn from’) code from Apache now? .NET still needs more grouming before is becomes as mature as Java. I love C#, but the .NET API needs more work. Althoug I eventually think it will get big. I hate to MS going about an swallowing every good software project (open or not) in its path. my2c. We’ve seen this enough times. Note: Embrace. Extend. Assimilate. Destroy. Apply these in a timeline to Apache’s situation we see here. .NET is great as the .NET framework on the client-side. Any serious developer would use J2EE and refactoring tools on the server-side. The MS IDE and it’s tools just don’t cut it for more than drag’n’drop prototypes. Do it fast, do it all over again… All in my not so humble opinion. I’m all for .NET framework (compared to the Win32 API), but it has to much of IIS on the server in it for me to like it otherwise. I hope I’m proven wrong, tha Apache deal sounds interesting…. (I may be a sceptic though, don’t flame me just express your opinion) And as far as C# goes, it’s more or less extended from Java, which means that any developer has to keep more, not less, in mind than in Java. The more a developer has to keep in mind, the more errors. All in proven studys, read ‘Code Complete’ by MS Press for examples about what you screw up with defines, preprocessors and other things you never thought about. After that read a good book about refactoring. Then you are set for RAD (Rapid Application Development), and remember that you should be able to have the same codebase for a couple of years… I don’t know about the rest of you, but I haven’t seen any services or apps whatsoever relating to.NET, unless I’ve seen them and don’t know about it? So naturally, it doesn’t suprise me when MS says it has been slow going I guess the MSN/Hotmail/Passport thing may be related to .NET, but where’s the rest of it? Offices, coprorations & most all people in general want complete applications installed to their own harddrives, they don’t want a skeleton installed that depends on another entity and a internet connection to that entity just to function… this is why .net wont fly… It’ll fly if Microsoft decides it wants you to want it to fly. Sure, the .NET api needs some work. But it is MUCH further along than the Java API was at it’s first release. In fact, it is further along in many areas now. Take a look at the XML/XSL namespaces. They will make you wonder what the hell Sun has been doing the last few years. As for Visual Studio only being good for rapid development, you are out of your mind. There is no better development environment on any platform. Period. .NET is not a skeleton, and it WILL be included in Windows releases, so there will be no dependency while installing apps. If you think it won’t fly, you are going to be very surprised. -G >>I guess the MSN/Hotmail/Passport thing may be related to .NET, but where’s the rest of it?<< It’s not like .Net is some minor undertaking here. Uncle Bill’s grand scheme is still in the process of hatching. AFAIK the first true .Net OS will be Windows “Blackcomb”, which IIRC isn’t due out now until 2005 (so make it Q4 2006). I think it will be some time before we see all of this stuff, as the groundwork is only now being laid. Whoo, and wait until they couple .Net with Palladium. I can hear the sweet sound of goosestepping Microsoft Certified Stormtroopers in the distance already. This next Office.Net seems to be all about tying Office to a bunch of web services that MS can charge for. I’m curious to see if/when they will replace VBA with .net Like ASP.net they could host a .net environment (forgot the actual terminology) within Office in which to run macros written in .net languages. Theoretically they could then take advantage of the .net security features (assuming they work) to reduce the risk from/of viruses. And as FH mentioned, they could also tie it to Palladium, so everyone can feel warma and fuzzy passing thier macro-laden secure Office documents around. The problem, imho, is that when someone mentions .NET no-one knows immediately what you mean. Web services over SOAP? Apps built for the .net runtime? Hailstorm? Passport^2? I’m not saying it’s unclear what the pieces (like C# etc) are, but they shouldn’t have lumped everything in one heap and call it .NET. I mean how do you market _that_ to your customers, when even the developers are often still confused about what it really refers to. End result: nobody cares. Business goes on as usual. The guy who wrote that article is a moron. They can’t make the difference between .NET Framework and .NET My Services. Also it says that .NET has “been out” for 2 years ?! I mean…what the hack…the final version of .NET framework (build 1.0.3705.0) was released in febraury. Yeap .NET My Services are not ok..but who cares ? The .NET framework is doing ok and that’s all that counts. >. Have you even tried there CLR? My guess is that you haven’t. I have done performance testing on it, and it is quite fast. They have one _BIG_ advantage with there virtual machine in that it only runs on x86. That is a huge advantage in the area of tuning versus Sun’s virtual machine which has to run on multiple flavors. Don’t get me wrong, I am not a Microsoft fan, but you do need to give the Devil his do sometimes. Java was there 7 years ago. Now, it is working on many platforms, and proved itself. There are millions of Java developers, thousands of matured and ready to use open/closed programs, libraries, frameworks. Why should I use .NET? – .NET is not mature. .NET needs at least 3 years to get mature. .NET implementations on Linux, such as Mono, are completely untrustable, at least for 5 years for me. During this time, Java will already hit the space. – There is no considerable performance difference between .NET and Java. Both are slow. Both are virtual machine based. .NET do not have JNI-like layer, but calling unmanaged code is still unacceptably slow, in the most cases, useless. (My company tried it on Windows, and abandoned it immediately after huge performance hit.) On Windows, .NET can be faster for client programs, but so what? Processors are getting faster and faster, and Java is getting more and more optimized. Latest JVM from Sun (1.4.1b) is running Swing programs incredibly fast. 1.4.2 will be even faster, as far as I know. – .NET is NOT cross platform compatible, and never will be. First MS would never let it. Standards etc are all story. The important parts of .NET are not submitted to ECMA, such as Winforms and ADO.NET. Dear Miguel of course changed his idea, now telling Mono will not include WinForms. Haha. In short, even Linux versions will never be 100 percent compatible. So, for cross platform applications it is useless. Why should I lock myself to one platform? (Linux or Windows or whatever) – I do not need to use any new technology. Java is good enough and working on many platforms already. Why should I try something else? C# is a copy of Java with couple of not so important improvements. Why should I shift to .Net? There is no reason to shift at all. – I will never use .NET, since it means helping the most unethical company on the face of the world. Hell no! Even for the sake of Linux, I will never do that. The guy who claims VS.NET is a good IDE is completely moron. It is for sure huge improvement over VS, but still very, very bad. It even do not have refactoring support yet. For a nice IDE, check out IDEA () or Eclipse (). Especially Eclipse rocks! It changed my ideas about IDEs completely. Any its open source and free, as in beer. Period.? I’ve worked with both and each has jood and bad things going for it. Yes, Java can be slow (if it’s not running on an UltraSPARC of some sort). .NET seems to be a bit zippier on Windows but I can’t compare it to Java on the UltraSPARC (at least I haven’t tried to compile and benchmark mint or rotor on the Sun boxes at school). Does anyone in here have real data or information concerning this topic? – I will never use .NET, since it means helping the most unethical company on the face of the world. Hell no! Even for the sake of Linux, I will never do that. Get a life. Use what works, whether it’s Java, .NET, Snobol, LISP, etc. JM2C >> I will never use .NET, since it means helping the most >> unethical company on the face of the world. Hell no! Even >> for the sake of Linux, I will never do that. > Get a life. Use what works, whether it’s Java, .NET, > Snobol, LISP, etc. You know. Some people believe in ethics. If you want, you can use .NET. I won’t. Its not a anyway, since I am using what works, and luckily it is Java. “The guy who claims VS.NET is a good IDE is completely moron. It is for sure huge improvement over VS, but still very, very bad. It even do not have refactoring support yet.” Please…. Just because it doesn’t have refactoring support yet does not make it a bad IDE. IDEA and Eclipse don’t have RAD support, so does that make them bad? Nope. I am absolutely positive that you have never used .NET or VS .NET for that matter. The CLR is extremely fast compared to any JVM. Try using it before you open your mouth and show your ignorance. Just because it is MS, does not mean that it is bad. They do have some of the best engineers. Don’t let your hatred for their business practices cloud your judgement. -G I cannot recall Microsoft fumbling around with a project of this magnitude as they have. They are capable of doing almost anything – look how they turned on a dime to focus on the internet and wiped out everyone in their path. But this, they can’t seem to get a real handle on it. And it leaves consumers and busnisses puzzled and baffled. I used .NET while evaluating it for my firm, and VS.NET. And, I know a lot about .NET. I still think that it is not very good. I do not like VS.NET not only because it does not have refactorings. There are many other issues that I don’t like about it. It is more of a personal issue. Why are you accusing me of lying? I again think that IDEA () and Eclipse () are much better ides. Its my opinion. You may think different. MS can have money and the best engineers. It does not mean that they will create the best. We saw the products their best engineers ended up with before. Secure, nice, beautiful products such as IE, IIS, WMP, etc. CLI is faster than JVM: True on Windows. But not significantly faster. Not enough to make me shift to .NET and lock myself to Windows. hey…let’s go fight over PC/Mac Vi/Emacs Linux/BSD… when will people learn that these pissing contests really don’t matter…people will use what they LIKE to use and that’s really what freedom is all about…it’s fine to try to persuade someone that something is better based on TECHNICAL MERITS but that seldom happens on topics like these…instead it boils down to things like “it’s Microsoft so it’s bad” or “i use Emacs b/c Stallman wrote it” people forget that these things are TOOLS and at the end of the day it doesn’t matter if you build a playset using a Stanley screwdriver or a Craftsman so long as you get the job done -bytes256 This might seem like a stupid question. But what is .NET good for? How does it help a user? How does it help a buisness? Please…. Just because it doesn’t have refactoring support yet does not make it a bad IDE. No, what makes VisualStudio.NET a piss poor IDE is that it takes over 2GB of disk space and runs incredibly slow. I mean it’s nice sometimes to start typing a line of code and have an excuse to take a half hour break while VS chugs away on generating its context sensitive information and line completion information, but sometimes I really want to get something done. If you are talking only about RAD designers, I think Borland makes the best ones for Windows. They are significantly faster. Since MS hired one of the Delphi creators (who for some reason turned into a complete phallus upon his arrival at MS) to do C#, VS.NET does have some of the nice features of the Borland products, but they are still not quite up to snuff in my opinion. So you’re saying that Vi is more productive than Emacs b/c it runs faster and takes up a lot less space right? <sarcasm> And forget about Windows…let’s start using DOS again…it’s gotta be wicked productive for development…yeah i can see it now…using vi to code NASM assembly code on DOS 2.0…yeah now that’s productivity!!! </sarcasm>? Well, when the company you are talking about has the complete obliteration of its competitors and the complete domination over what you do on your computer as its goals, I think a “holy war” is perhaps in order. Anyway, I have discussed the merits and lack thereof of concerning .NET since the dumb thing was release in February and I’ve been forced to program using it at work. Usually, when a new technology is forced down my throat, I eventually find some redeeming value that lets me tolerate it or even like it; which is what happened with Java. However, .NET just pisses me off to use. The reasons I don’t like it are that it is slow, cumbersome and convoluted to program web apps with. Why people think it is better to build web apps via a mish mash of disparate technologies glued together with a gargantuan IDE when there are better, readily available technologies out there is beyond me. The thing I dislike about .NET the most is ties to IIS; the digital, fetid lump of poo. Another thing I don’t like, although a minor issue, is Microsoft’s documentation. They throw so much crap and nonsense into the MSDN library that it hinders my ability to find what I’m after. There is nothing new about .NET. All the technologies, such as XML, SOAP, etc. are already available to me. CLR is just a VM; of which there are better ones available. Why tie myself down to Microsoft’s whipping post when there is no need? when will people learn that these pissing contests really don’t matter… If they don’t matter, why do you keep getting into them with me? i just try to fight ignorance…if you actually put forth the technical merits or lack thereof to persuade people to not use .NET in favor of a technically superior alternative, but you don’t do that…you just give the tired old “MS is the evil empire” and “MS Software is slow and bloated” arguments…which no one cares about…tell me a platform that does what .NET does w/o being slow and bloated? Java…hahahaha…ROFL…I like Java a lot…but it’s about the same as .NET speedwise…which means…they’re both pretty darn good…and as far as bloat…guess what…for now .NET is actually LEANER than Java -bytes256 So you’re saying that Vi is more productive than Emacs b/c it runs faster and takes up a lot less space right? No, I don’t recall saying anything at all regarding either editor. You have been reading OSNews haven’t you? I think that’s the problem with posting concerning .NET or anything else. There are those, such as yourself apparently, who have no idea what .NET is or does, or that you can do all of those things in a more cross-platform and open way. I won’t discuss this furthur with you if all you’re going to do is metaphorically place your hands over your ears and chant prayers to Microsoft. Actually i was just making an illogical comparison based on what you were saying…you said VS.NET is unproductive b/c it is large and slow…which is not necessarily the case if the “bloat” is a set of useful features… just b/c VS.NET is too bloated for you doesn’t make it worthless or a “piss-poor IDE”…just say you prefer something else…simple as that -bytes256 Oh, and I guess we can all look to the massive amount of technical data that you have presented proving that .NET is worth anyones attention as an example of posting perfection. Have you actually ever created anything with .NET? If so, what? If you want examples of what I’m saying, fine. Open a new project and create a drag and drop clicky ASP.NET control in C# or VB. For example, create a calander control that displays in a drop-down combo box and is totally internationalized (meaning it displays the time and date information in the correct formats depending on the default language setting of the browser that accesses the page once you are done). Next, open up an ASP.NET application and drag your point and click control onto the page designer. Pretty simple so far, but I need the page to be displayed in a seperate layer so that the web page’s contents wont get shifted around when I click on the drop-down combo calander that you are going to create. Next, compile the program and then make the page available to more that 100 people at the same time (can’t do it without forking over some big bucks since IIS only comes with a 5 simultaneous user license by default). Okay, this might make you feel that .NET is cool at this point since the calendar works well and looks nice (assuming you programmed in the ability to change colors, highlight the current day, show weekends in a different color from weekdays and store the selected date in a variable). Well guess what, I can accomplish the exact same functionality using standard HTML and JavaScript. And do you know what the best part is? When all the programming you did in .NET finally makes it down to the client’s browser and displays your calander on the screen, guess what a quick look at the source code of the HTML page will reveal? JAVASCRIPT!!! So, if you want to tie yourself to .NET and wrap your legs around Bill, fine. But .NET is nothing more that a bunch of existing technology wrapped and bundled into a new box and sold to you for several thousand dollars and your freedom. I can go on if you require. yeah that’s fine, but how long would it take you to code that very same app in raw javascript? and make sure that it looks ok in a variety of browsers? and i will admit i’ve never done anything with .NET (i can’t afford VS.NET) i’m just concerned that your dislike for .NET is more about politics than technical merit…and that’s fine…we get the picture…you HATE Microsoft…they’re monopolists wanna dominate the world…yadda, yadda, yadda…and that’s fine but you gotta admit, .NET can do some pretty slick stuff and when Mono gets here your argument about it not being cross platform won’t hold any water Visual Studio .NET takes up so much space because it is installing the SDK and TONS of documentation. No other development environment has any where near as much doc. And in my experiences with it, it is NOT slow. “you can do all of those things in a more cross-platform and open way” Please… “CLI is faster than JVM…But not significantly faster” Dude. It is many TIMES faster. It is really like night and day. Check out… -G I don’t know if any of you actually code in Java. We are doing things with Java that will make your head explode. Its very very fast. We do 100% Java on all layers, all the time. .NET is nowhere on the map. We do the REAL work behind the scenes for financial institutions. I don’t see .NET or C# going anywhere in the financial market. Seriously, I don’t think we even have a copy of Studio .NET, because our customers aren’t asking for any products. TO:gmlongo again: “Dude. It is many TIMES faster. It is really like night and day.” No dude. I tried it by myself for my own projects dude. It is really not that faster dude. AND dude, even if it was dude, I have much important things to do rather than licking Billy’s balls dude. AND dude, it is not CROSS PLATFORM COMPATIBLE dude, which is my most important factor dude. Sorry dude, but I won’t use .NET dude. Cau Dude. bitch about .NET not being cross-platform and then bitch about Mono which will make it cross-platform hmm…very interesting -bytes256 Will Mono include WinForms? No. There are even problems with covering ADO.NET, since MS has the patents. How many of .NET’s passport related classes will be covered? Answer from the Mono site: We are not there yet. There is still a long time until we reach that part of .NET. Mono will NOT make .NET cross platform. It will not be 100 percent cross platform. We will see in 3 years, since it will probably take 3 years to reach production quality. yeah that’s fine, but how long would it take you to code that very same app in raw javascript? and make sure that it looks ok in a variety of browsers? Not long. and i will admit i’ve never done anything with .NET (i can’t afford VS.NET) You don’t need to have VS.NET to create .NET apps. If you want to try it, you can download one of the free tools and the .NET runtime and try .NET today. i’m just concerned that your dislike for .NET is more about politics than technical merit… There are political reasons I don’t like .NET, but I have used .NET every weekday since February. Technically, I can already do anything .NET can do with other technologies. Nothing new here. If people understand that .NET is just a repackaging of current technologies in an albeit appealing form for some, then fine. But it simply isn’t the great, earth-shattering, world-changing technology that everyone makes it out to be. but you gotta admit, .NET can do some pretty slick stuff and when Mono gets here your argument about it not being cross platform won’t hold any water I have said that .NET is an excellent replacement for the Win32 API and MFC. I have also said that one of the .NET languages, C#, is an outstanding replacement for VB (however, outshining VB can’t be too hard. ) .NET does have it’s place. However, I think that a lot of people are buying into .NET not because it is a superior technology to what exists today, but rather because of all the marketing hype. Sorry to create an atmosphere of ire here today. I hope you’ll accept my apologies. bitch about .NET not being cross-platform and then bitch about Mono which will make it cross-platform hmm…very interesting Personally, I think the Mono project is misguided. The reason for this opinion is that it’s pretty much guaranteed that Mono will never achieve 100% full compatibility with .NET. The result will be the same catastrophe that awaited Java had Sun not won their suit against MS. That catastrophe is that Windows programmers will develop .NET applications, which utilize WinForms, ADO.NET, or any number of other “unsupported” APIs. The result is that these programs will only run under Windows. It probably will be possible to write Mono programs and have them run on Windows, but the model will be broken the other way around. I hope for Miguel’s sake that I’m wrong, but I doubt I am. Everybody always says, “Microsoft doesn’t innovate.” Is that so? And if it’s true, does open source do any better? Let’s see. Here at, Microsoft seems to be doing quite a lot. I remember a while back using a sample release of their Whisper speech technology. It wasn’t as good as ViaVoice, but it was quite good, and free. Now they’ve implemented it into Word. Sure, WordPerfect had a “speech edition” first, but it wasn’t as good as Microsoft’s – and still, the innovation was done by a private company. Now, Microsoft has .NET. Like it or not, it’s a very good idea, and it’s not necessarily controlled by MS. Web services alone are not particularly innovative, but the degree to which Microsoft is integrating them into their operating systems, and therefore the degree to which the Internet is made more transparent and easier to use, is. What about other companies? Apple and Dell are the two most important computer companies of the 90s. Dell helped on the economic end, bringing the price of computers so low that the average family can now spend $200 a year to get an up-to-date computer (lifespan of 3 yrs.). Those technologies were standard in Apple’s product line years before they were in the first PC; now, a PC maker without USB would get laughed out of the market, and parallel is finally on its deathbed. When you download a distribution of Linux, what do you get? You get a kernel and system tools that are directly copied from AT&T’s Unix, at the time an innovative operating system. You get a graphical desktop that at a low-level is based on 1970’s dumb-terminal X Window System, and the GUI the user actually sees is increasingly a direct ripoff of Windows; KDE has ~70% marketshare, and Gnome, almost as Windows-like as KDE, has ~20%. Everything in a standard Linux distro is a direct ripoff of a corporate-created product. Open source is great. Once a technology is innovated, hackers working in their free time can generally create a much better quality end product than paid workers can. And open source can prevent Microsoft’s “embrace and extend” from working; Mono will mean that closing .NET is a loss for Microsoft and Microsoft only. But OSS isn’t coming up with any new ideas. The companies are, whether they’re Microsoft, Apple, or someone else. .NET is one of those technologies. And now all the people who said Microsoft doesn’t innovate are watching Microsoft innovate, and laughing at them. If there has been one thing I have learned these last few years, it is that people don’t buy products because of technical superiority but rather they buy them because of the pretty shrink wrapping they come in. Marketing hype and clout is what makes the difference and sometimes it seems its all that matters. For example why is it that so many people use Visual Studio and gimpy, rehashed MS frameworks when (well in my opinion for what it is worth) companies like Borland clearly produce superior RADs and frameworks. This is why Microsoft and .NET will win in the end. Microsoft will do everything and anything to shove .NET down everyones throat. Your comming along for the ride wether you like it or not. Period. Microsoft is the #1 corporation on the planet with the top market cap at $500 Billion (General Electric is #2). I just read today that MS is adding another $1 Billion per year to R&D (for a total of $5.2 Billion), which they say is mostly going to be spent on .NET… Also, they announced plans to immediately hire another 5,000 developers to add to their existing 50,000 employees… Even IBM, MS’s biggest rival, has been unable to avoid making layoffs this year. How exactly are you supposed to compete with that, even if you have great technology like Borland or Novell? > I just read today that MS is adding another $1 Billion > per year to R&D (for a total of $5.2 Billion), which > they say is mostly going to be spent on .NET… R&D or reverse engineering? Low blow but yeah as long as they keep investing in R&D they’ll remain strong. It seems companies flounder when they stop doing R&D. > Also, they announced plans to immediately hire another > 5,000 developers to add to their existing 50,000 > employees… Intresting. How many of those are actual American employees? My bet is that a lot of them will be H-1Bs or the equivelent. > How exactly are you supposed to compete with that, even > if you have great technology like Borland or Novell? You don’t. They assimlate your ideas and you get shoved to the side. Haven’t we learned anything from the DOJs attempt to break up Microsoft (even though is was unsuccessful)? Thats why I don’t buy into this whole “OSS is not innovative and yet Microsoft is” argument. IMO, its like the kettle calling the pot black. >. hell no i dont want wireless replacing anything wired. especially in a business enviroment. having it as an option is fine though. plus mozilla is a pretty innovative open source project. We saw their beautifully secure, nice and efficient products such as IIS, WMP, IE, VS, VS.NET etc. which they created with their millions, and the best computer engineers in the world. They all suck. I will never use .NET. I’m still confused on the hole .NET thing, so forgive me, seriously. (We code in JAVA that handles TRILLIONS of US $ worldwide) Isn’t this passport one log-in thing required for .NET or is this something different? And if so, are they going to REQUIRE for development/deployment on Microsoft only software/hardware? If this is the case, I don’t see how they could make this pig fly. I don’t see it. “I have much important things to do rather than licking Billy’s balls dude” How old are you? You make my points better than I ever could. Your ignorant bashing of Microsoft products reveals more about yourself than you will ever know. You obviously are blinded by your own stupidity. -G well said gmlongo! IIS only comes with a 5 simultaneous user license by default… I’ve been looking for info on this (on MS site and Google) since reading your post. Are you referring to authenticated users or anonymous users? I can’t find anything that restricts the number of simultaneous anonymous web users. That wouldn’t make much sense, even for MS. If so, it means MS has a funny definition of “free” regarding IIS. I would appreciate a URL. Now, Microsoft has .NET. Like it or not, it’s a very good idea… Good idea or not, it is not an original idea. It is re-packaging and marketing of existing ideas. and it’s not necessarily controlled by MS. My only response to this statement would have to be a slight shake of the head and a smile. When you download a distribution of Linux, what do you get? A stable system. You get a kernel and system tools that are directly copied from AT&T’s Unix, at the time an innovative operating system. The BSD crowd is more closely related to AT&T’s Unix than Linux is. You get a graphical desktop that at a low-level is based on 1970’s dumb-terminal X Window System… And yet it is funny how much more functional it is that the Windows GUI. …and the GUI the user actually sees is increasingly a direct ripoff of Windows What Corporate OS does enlightenment, fluxbox, blackbox, and such mimic? Also, KDE looks more like CDE that Windows. There are similarities, yes, but Windows doesn’t support pop-up icons on the taskbar, applets on the taskbar, etc. Therefore, even if KDE was a direct rip-off from Windows, they’ve obviously improved, or innovated, beyond what MS has done wouldn’t you say? Everything in a standard Linux distro is a direct ripoff of a corporate-created product. It is fair to say that there are similarities, but to say that everything is a direct rip-off is entirely false. Open source is great. Once a technology is innovated, hackers working in their free time can generally create a much better quality end product than paid workers can. An excellent endorsement of the power of OSS. Mono will mean that closing .NET is a loss for Microsoft and Microsoft only. And what data do you have to support that statement? We already now that Microsoft tried to “extend” Java and add WFC to it, thereby making it “better” under Windows and making J++ incompatible with the Java standard used everywhere else. Why people don’t think this will happen with .NET is entirely beyond me. But OSS isn’t coming up with any new ideas. You are completely wrong here. But even if you weren’t, how do you explain, for example, Mozilla being a lot better than IE; or Apache being better than IIS? And now all the people who said Microsoft doesn’t innovate are watching Microsoft innovate, and laughing at them. Well, I haven’t seen anything new in .NET, just as many people have posted here. I have even seen some pretty good examples. You have made a lot of claims with no evidence to back them up. If you can show me something new and innovative, perhaps I will stop laughing. hell no i dont want wireless replacing anything wired. especially in a business enviroment. having it as an option is fine though. plus mozilla is a pretty innovative open source project. Why not? Is it a problem of security? Encryption will soon be quite secure, so that won’t be a problem. A stable system… and yet it is funny how much more functional it is that the Windows GUI. You’re making the mistake that I’m attacking Linux. I’m not. I use Debian as my primary OS. Everything that Microsoft or Apple does, OSS does better. That includes Apache and Moz, among others. And as of yet, Microsoft hasn’t released all that much in the way of innovation in their products. But that’s not the point. Microsoft has their research labs going full-speed. I don’t suppose you took a look at – they really do have a lot going there. The kind of research they’re doing at that lab is the kind that used to go on in universities. The original UNIX was hugely developed and improved upon at universities, and Mosaic, the first web browser, was developed in publicly-funded labs. Both of those were extremely innovative. So what happened? How come now, instead of universities, it’s corporations doing the research? It seems strange that there could be such a shift in only 30 years.
https://www.osnews.com/story/1416/bill-gates-slow-going-for-net/
CC-MAIN-2019-51
refinedweb
6,258
75.61
The #endif directive has the following syntax: This directive ends the scope of the #if , #ifdef , #ifndef , #else , or #elif directive. The number of necessary #endif directives changes according to whether the elif or #else directive is used. Consider the following equivalent examples: #if true #if true . . . . . . #elif true . . #else . #if false . . #endif . . #endif #endif: #ifdef macro1 printf( "Hello!\n" ); #endif #ifndef macro2 printf( "Hello!\n" ); #endif #ifdef macro3 printf( "Hello!\n" ); #endif Another use of the defined operator is in a single #if directive to perform similar macro checks: #if defined (macro1) || !defined (macro2) || defined (macro3) printf( "Hello!\n" ); #endif Note that defined operators can be combined in any logical expression using the C logical operators. However, defined can only be used in the evaluated expression of an #if or #elif preprocessor directive.: #define macro1 "file.ext" #include macro1 specified in a previous #line directive. In the third form, macros in the #line directive are expanded before it is interpreted. This allows a macro call to expand into the integer-constant, filename, or both. The resulting #line directive must match one of the other two forms, and is then processed as appropriate. The #pragma directive is a standard method for implementing platform-dependent features. This directive has the following syntax: The supported pragmas vary across platforms. All unrecognized pragmas are diagnosed with an informational message. See your platform-specific Compaq C documentation for a list of supported pragmas. Some pragma directives are subject to macro expansion. They are: builtins inline linkage standard dictionary noinline module nostandard extern_model member_alignment message use_linkage extern_prefix nomember_alignment The following pragmas are also subject to macro expansion, primarily for use in preprocess-only mode (that is, with the /PREPROCESS_ONLY qualifier on OpenVMS systems or the -E switch on Tru64 UNIX systems), and are not normally used when generating an object module with the Compaq C compiler: A macro reference can occur anywhere after the keyword pragma . For example: #define opt inline #define f func #pragma opt(f) After both macros are expanded, the #pragma directive becomes #pragma inline (func) . The following describes how the compiler decides whether or not to macro-expand a given pragma: In compilation modes other than /STANDARD=COMMON (OpenVMS systems) or -std0 (Tru64 UNIX systems), do Step 1: Step 1: The token following the keyword pragma is first checked to see if it is a currently-defined macro. If it is a macro and the identifier does not match the name of a pragma that is not subject to macro expansion, then just that macro (with its arguments, if function-like) is expanded. The tokens produced by that macro expansion are then processed along with the rest of the tokens on the line in Step 2. In all compilation modes, do Step 2: Step 2: The first token following the keyword pragma is checked to see if it matches the name of a pragma that is subject to macro expansion. If it does, then macro expansion is applied to that token and to the rest of tokens on the line. The test for matching a known pragma permits an optional double leading underscore. For example, #pragma __nostandard is equivalent to #pragma standard . Example The following example illustrates that for pragmas coded directly with a name that matches a known pragma, the macro-expansion behavior is generally the same in all modes and is backward-compatible. It is only in cases where a pragma was coded with a name that was not the name of a known pragma, expecting macro expansion to produce the pragma name, that backward-compatibility is broken, and then only in common mode. The exception is made in common mode to maintain compatibility with the Tru64 UNIX preprocessor. #define pointer_size error #define m1 e1 #define e1 pointer_size 32 #define standard message #define x disable(all) #define disable(y) enable(y) #pragma pointer_size 32 /* In common mode, Step 1 skipped. In other modes, Step 1 finds that pointer_size is known not to expand. In any mode, Step 2 finds pointer_size is not a pragma requiring expansion. */ #pragma m1 /* In common mode, Step 1 skipped. In other modes, Step 1 expands m1 to pointer_size 32. In common mode, Step 2 finds m1 is not a pragma requiring expansion. In other modes, Step 2 finds pointer_size is not a pragma requiring expansion. */ #pragma standard x /* In common mode, Step 1 skipped. In other modes, Step 1 expands to message x. In common mode, Step 2 expands to message enable(all). In other modes, Step 2 expands message x to message enable(all). */ The #error preprocessor directive issues an E-level diagnostic message and continues compilation, but no object module is produced. This directive has the following syntax: A preprocessing directive of the form # newline is a null directive and has no effect. The following sections describe the predefined macro names that are provided to assist in transporting code and performing simple tasks common to many programs. The __DATE__ macro evaluates to a string literal specifying the date on which the compilation started. The date has the following format: The names of the months are the same as those generated by the asctime library function. The first d is a space if dd is less than 10. For example: printf("%s",_ _DATE_ _); The value of this macro remains constant throughout the translation unit. The __FILE__ macro evaluates to a string literal specifying the file specification of the current source file. For example: printf("file %s", _ _FILE_ _); The __LINE__ macro evaluates to a decimal constant specifying the number of the line in the source file containing the macro reference. For example: printf("At line %d in file %s", _ _LINE_ _, _ _FILE_ _); The __TIME__ macro evaluates to a string specifying the time that the compilation started. The time has the following format (the same as the asctime function): For example: printf("%s", _ _TIME_ _); The __STDC__ macro evaluates to the integer constant 1, which indicates a conforming implementation. The __STDC_HOSTED__ macro evaluates to the integer constant 1 if the implementation is a hosted implementation, or to the integer constant 0 if it is not. The __STDC_VERSION__ macro evaluates to the integer constant 199901L. The __STDC_ISO_10646__ macro evaluates to. 8.8.9. The __func__ predeclared identifier evaluates to a static array of char initialized with the spelling of the function's name. It is visible anywhere within the body of a function definition. For example, a function defined as follows will print "f1". void f1(void) {printf("%s\n", __func__);}
http://h71000.www7.hp.com/commercial/c/docs/6180p021.html
CC-MAIN-2014-15
refinedweb
1,093
53.81
Working with .NET DataSets - Understanding the ADO.NET DataSet - Populating a DataSet - Manipulating Multiple DataSets - Using a DataView - Summary - Workshop - Answers for Day 3 Yesterday you walked through an end-to-end example of building an ASP.NET application designed to put the use of ADO.NET in perspective. However, the reliance on code-generating wizards can certainly obscure the breadth of functionality that is at your disposal. For that reason, today and the next four days will be devoted to an in-depth look at all aspects of the DataSet object. Unlike yesterday, the format of the next few days will not take you through an application or work with graphical tools, but rather will examine short snippets and code listings that highlight specific features and behaviors of the DataSet. Specifically, today you will learn the most common techniques for working with DataSet objects, including How a DataSet compares to an ADO Recordset How to programmatically populate and traverse a DataSet How to select and find rows within a table How to copy, clone, and merge DataSet objects How to be notified of events The importance and use of a DataView Understanding the ADO.NET DataSet The DataSet class is a member of the System.Data namespace. It represents the first of the two major components of the ADO.NET architecture you learned about on Day 1, "ADO.NET In Perspective," the other being the .NET Data Providers. Its major attributes include the following: It is XML-based. It is an in-memory cache of data that is not backed by a file or data storeit is disconnected. It is independent of a data store and cannot communicate with one by itself. It can store data in multiple tables from multiple data stores that can be related through foreign key relationships. It stores multiple versions of the data for each column and for each row in each table. It can be serialized with full fidelity to XML for transport between tiers of a distributed application even when those tiers reside on separate physical machines. As is evident from this list, the DataSet provides the core object for building applications using a disconnected programming model. ADO.NET also supports a connected model for data retrieval through the use of the data readers, as you'll learn on Day 11, "Using a DataReader." This list should also point to several of the similarities and differences between the DataSet and the Recordset object available in ADO that might be helpful if you are experienced with ADO.. The DataSet class itself is derived from the class System.ComponentModel.MarshalByValueComponent, from which it receives its ability to be serialized, added to the VS .NET toolbox, and visually designed in a designer. Its place in the .NET Framework is shown in Figure 3.1. Figure 3.1 The DataSet in context within the .NET Framework. Note that all objects are ultimately derived from System.Object and that namespaces are denoted with dotted borders. The major properties, methods, and events (collectively referred to as members) of the DataSet class can be seen in Table 3.1. Table 3.1 Important DataSet Members Throughout the next several days, you'll become very familiar with these members and how they can be used in your applications. Keep in mind that through overloading, many of the methods shown in Table 3.1 can accept different sets of arguments and therefore work in several different ways.
https://www.informit.com/articles/article.aspx?p=30228&amp;seqNum=6
CC-MAIN-2021-10
refinedweb
576
55.03
You can subscribe to this list here. Showing 14 results of 14 I am pleased to announce that Saxon 7.6 is now available, and offers support for XQuery 1.0 as well as XSLT 2.0 and XPath 2.0. It is available from the usual location The XQuery support has been implemented largely by writing an XQuery parser and generating the same internal interpretable code that is currently generated by the XSLT front end. Since there is very little functionality in XQuery that is not already present in XSLT, this was not a major upheaval. The main run-time changes have involved making the join between the XSLT and XPath parts of the products more seamless, which should in time greatly improve potential for optimization. Have fun! Michael Kay Saxon 7.5.1 fixes the bugs reported in tail recursion with Saxon 7.5. It also contains a rudimentary implementation of the format-date(), format-time(), and format-dateTime() functions. As usual, go to Michael Kay Saxon 7.5 is available at The new version implements many of the new and changed features of the working drafts published today (dated 2 May 2003). There are also quite a few internal changes - as usual the details are all in the change log at Michael Kay Saxon 7.4 is available at The main theme for this release is stronger type checking, in accordance with the XPath 2.0 draft. This means that function arguments are now checked to be the correct type (rather than being implicitly converted), and there are stricter rules for arithmetic and for comparison operations. The benefits are that errors are detected earlier, and more decisions can be made at compile time. This still applies only to built-in types such as xs:integer, xs:string, and xs:date - Saxon still has no schema support. I would encourage you to declare types explicitly on variables, functions parameters, etc: it gives the optimizer much more information to work with, and helps to detect many errors in your coding. XPath 1.0 backwards compatibility mode is implemented, and can be switched on by specifying version="1.0" on any element in the stylesheet, or xsl:version="1.0" on a literal result element. There are two new diagnostic features you may find handy. Setting saxon:explain="yes" on any stylesheet element gives you a compile-time display of the compiled/optimized expression tree for any XPath expressions on that element. And the -TJ command line switch gives you detailed explanations of how calls to Java extension functions are fixed up (or why they cannot be fixed up). There's a full change log in the changes.html file, as usual. Have fun! Michael Kay Saxon 7.3 is available: see There are lots of new features in this version, and as usual all the changes are listed in the change log. The main headlines are probably: * many new "minor" features from the XPath 2.0 and XSLT 2.0 specs have been implemented, including some from the 15 November 2002 drafts * "compiled" stylesheets are now serializable to disk (and occupy much less memory) * internal data structures and interfaces have been adapted to accommodate type annotation on nodes. This is mainly infrastructure to support schema validation in the future, but it does already allow explicit annotation of nodes in temporary trees using the built-in simple types of XML Schema. I have dropped the FOP interface because I found that FOP had changed again between 0.20.3 and 0.20.4, and I was getting fed up of tracking the changes. If anyone feels strongly about this, let me know. Offers to take over the maintenance of this module will be gratefully accepted! Michael Kay Saxon 7.2 is available at A full list of changes is at Probably the most interesting new feature is support for regular expressions, specifically the xsl:analyze-string instruction and the matches(), replace(), and tokenize() functions defined in the 16 August 2002 working drafts from W3C. Saxon uses the regular expression libraries in JDK 1.4, so you must install this version of the JDK. Also, because JDK 1.4 includes an XML parser as standard, Saxon no longer bundles the AElfred parser. Production systems should stick with Saxon 6.5.2 until the XSLT 2.0 and XPath 2.0 specs become more stable. Michael Kay Software AG Saxon 6.5.2 is a maintenance release that clears a number of bugs found in 6.5.1. It is available for both full Saxon and Instant Saxon. Details at: Michael Kay Software AG home: Michael.H.Kay@... work: Michael.Kay@... Saxon 6.5.1 is a maintenance release that fixes about twenty known errors in Saxon 6.5. This is a separate code branch from 7.0; my intention is to maintain the 6.5 line as a conformant and reliable implementation of XSLT 1.0 until such time as XSLT 2.0 becomes a stable Recommendation, but not to add any new features. See Michael Kay Software AG home: Michael.H.Kay@... work: Michael.Kay@... Note: I'm on vacation next week; if there are any problems with this release, they will have to wait until my return. Saxon 7.0 is available at This is an experimental implementation of the new XSLT 2.0 and XPath 2.0 working drafts, published today; it is not intended to replace Saxon 6.5, which you should continue to use for production applications. There are some summary notes on the new instructions, expressions, and functions in the documentation pages, but for full detail you'll need to read the W3C specs. Resources permitting, I hope to continue fixing any critical bugs in 6.5 until such time as XSLT 2.0 is finalized; at that time Saxon 7.x will become mainstream. (But as always, I never make any commitments...) Saxon 7.0 depends on JDK 1.2 or later, so the Instant Saxon build, which relied on the Microsoft JVM, is no longer available. Note that I've taken the opportunity to change the Java package names, the namespace URI, etc: so read the changes.html file carefully. Mike Kay Saxon 6.5 is available via the homepage at Note that if you use XSLT 1.1 features such as xsl:document, xsl:script, or the ability to refer to a result tree fragment as it it were a node-set, then you will now need to specify <xsl:stylesheet. This change is made to reflect the fact that the W3C XSL working group has announced that XSLT 1.1 will not be progressed beyond working draft status: it is designed to improve Saxon's conformance with XSLT 1.0 and to improve portability of stylesheets. Mike Kay Saxon 6.4.4 and Instant Saxon 6.4.4 are now available, see This is largely a maintenance release to clear 13 bugs identified in the two months since 6.4.3 was released. The release also updates Saxon to work with FOP 0.20.1 and with JDOM 0.7. There are some new performance optimizations, these will give a very substantial speed-up to a rather small number of stylesheets. As always, the detailed list of changes, including references to the bugs that have been fixed, is included in the release documentation. Mike Kay Saxon 6.4.3 fixes 99% of all known bugs... See Mike Kay
http://sourceforge.net/p/saxon/mailman/saxon-announce/
CC-MAIN-2015-35
refinedweb
1,247
67.15
- Advertisement CrypterMember Content count1299 Joined Last visited Community Reputation748 Good About Crypter - RankContributor Location of data in the class Crypter replied to JoshuaWaring's topic in General and Gameplay ProgrammingTechnically you can enforce a specific alignment or none at all via compiler specific #pragma options. For example, in MSVC, #pragma pack directive or G++ attribute((packed)). TheComet is correct though, floats are very well standardized and guaranteed to be 32 bits so it is most probably safe to assume proper dword alignment without padding. The only guaranteed methods however would be compiler dependent; that is, resulting to nameless structures or #pragma. You can also just overload operator[] and call it directly. Alternatively just don't do it. You are not gaining anything from doing this after all. It can be done, of course, but at what benefit? Location of data in the class Crypter replied to JoshuaWaring's topic in General and Gameplay ProgrammingAs mentioned above, it is not safe due to possible padding between members. You can however use a nameless struct here to achieve the same effect, class matrix { public: union { float m[9]; struct { float _m11, _m12, _m13; float _m21, _m22, _m23; float _m31, _m32, _m33; }; }; // now m[1] = _m11, m[2] = _m12 etc. }; It is important to note that nameless structures are not standard although a few modern compilers support it. Prevent Losing Entire Project To Malware Crypter replied to RalemProductions's topic in General and Gameplay ProgrammingSorry for the loss. It is strongly encouraged to always make backups; version control software is also worth checking into (we use BitBucket with Mercurial) and is the recommended suggestion for software projects. This is a good reminder to everyone - if you have not made any backups yet, do it now. I suggest MalwareBytes AntiMaware; its free (although there is a paid pro version) and can both remove it and can potentially aid in preventing it. Please reference this post regarding Crypto Locker and how to remove it if not already done so (note however that your documents cannot be uncovered unfortunately.) Alternatively the Norton anti-malware suite is also really good although a bit expensive. This one might also be useful to try. Particularly the section about recovering files from shadow copies if system restore is enabled. However I cannot guarantee it will work. Engine architecture questions Crypter replied to Crypter's topic in General and Gameplay ProgrammingThanks again for the suggestions. I really liked the idea of moving the window management code to a higher level and have been considering the problem with polling and waiting for system events in the event loop. I myself am not all that familiar with SDL either; only know a little bit - though I did eventually learn online that the main event loop cannot be in a separate thread which poses a potential problem. Although none of this is yet official in the design, this is what I came up with. Please note that in this design I have dropped SDL in favor of Win32: Project : HgKernel Implements the real entry point such as main or WinMain depending on operating system and platform. All the entry point does is the following, extern int HgApplicationEntryPoint(int argc, char** argv); namespace hg { static DWORD WINAPI HgApplicationThreadEntry (void* Param) { if (!wglMakeCurrent (GetDC(_hwnd), _hglrc)) cout << "ERROR" << endl; if (HgApplicationEntryPoint (__argc, __argv)) return 0; return 1; } class HgKernelCore : public HgKernel { public: void run () { startup(); HANDLE h = CreateThread(0,0,HgApplicationThreadEntry,0,0,0); SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_ABOVE_NORMAL); eventLoop(); } }; } //namespace hg int main () { hg::HgKernelCore core; core.run (); return 0; } HgKernel::startup creates a default hidden window and enters the event loop. HgKernel::eventLoop is the event loop; it sets its own default thread priority before entering it. It also creates and runs HgApplicationEntryPoint as a separate thread -- this is defined in the actual game software. Engine application Since engine start up is automated yet still configurable, all the game program linked with the engine needs to do is define HgApplicationEntryPoint which acts as an operating system independent entry point. Note the initial window is not displayed until the engine is initialized by the game program. The engine can provide static access methods for the game program for all major sub systems; for example, HgKernel::GetVideoDriver or HgKernel::GetInputManager, etc. int HgApplicationEntryPoint(int argc, char** argv) { HgKernel::initialize("My Game",800,600,32,false); /* simple test for OpenGL in this game/render thread. */ glViewport(0,0,800,600); glDisable(GL_CULL_FACE); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); while (true) { glColor3f(1,0,0); glRectf(-0.25,-0.25,0.25,0.25); HgKernel::endFrame(); } return 0; } Thanks again for all the suggestions and feedback; it is greatly appreciated. As far as I could see, this design resolves all current concerns - no singletons; no global access point. Although HgKernel provides access methods; it is only for use by the game software since no other system links to it, the game/render loop runs in a separate thread from the event loop; the event loop thread runs with a configurable priority level and can send the events to the input manager using the input managers event classes to be buffered and time stamped, and also hides the entry point for operating system independence from the game programs perspective. Questions for all programmers. Crypter replied to Roberts91's topic in GDNet Lounge1) What was the first programming language you studied? C++ however the first language I actually practiced in was C. 2) Did you have any Computer Science background before your first language (ie: boolean algebra, memory organisation, algorithms)? Not really. 3) The first language you studied was it self-taught, formal instruction, or both? Self taught. 4) Was the Computer-Science background self-taught, formal instruction, or both? Both; I studied my first language long ago when I was young. Formal courses later on in university. 5) When you started to study Computer Science did it help your understanding of the language you first learned? To be honest, not really. It did give me a new appreciation for the underlying concepts that go into language design and software engineering; introducing me to a few more languages (Java and Scheme.) 6) What kind of environment did you first program in (ie: the IDE or text editor, and the OS)? Turbo C 2.1 followed quickly by Borland Builder 5 on Windows 95 IIRC. Engine architecture questions Crypter replied to Crypter's topic in General and Gameplay ProgrammingThanks for the response. I would like to clarify some things if possible; it would help greatly. That is correct; the problem lies with how operating systems send event messages to the event callbacks responsible for a particular window. While the window should be within the graphics system (initialized with OpenGL compatibility) the event processing and dispatching should be within the input system. That is, who should be responsible for the window procedure to process events? If it is the input manager, then it must be in the same thread as the same thread that created the window via a call to the Win32 RegisterClassEx and CreateWindowEx (as far as I know; please correct me if wrong.) This would also require the graphics system to initialize the window with the window procedure callback found in the input module. If it is the graphics system, the graphics system would need to pass those events to the input manager to be processed. Is there an alternative? Sorry, I am not entirely sure how that is related to the use of SDL. Under the standard Windows event loop, messages are polled via GetMessage or PeekMessage and the window procedure is only called when the main thread executes DispatchMessage in the event loop. That is, polling for system events always occurs. SDL_PollEvent is just a wrapper around the event dispatching for the underlying operating system in this manner. That is, I think the problem you mentioned would occur regardless of the use of SDL or not. Thanks for the suggestions so far and for clarifying some things. Engine architecture questions Crypter replied to Crypter's topic in General and Gameplay ProgrammingThanks for the responses. Technically the only statically allocated pointer was HgKernel::singleton. All other pointers were run time allocated on the heap. To be fair however, despite the design it has almost never been used since there really was no need (except in a few places discussed below.) Really good advice there. The goal of the redesign was to aid in the following, 1. Improve build times. The original design had the entire engine in its one module; a change in one source file typically resulted in an entire build. This I blame MSVC; it would rebuild source files that are completely unrelated. This would resolve this and any future annoyances from the MSVC build system since the projects are smaller. 2. Improve structure. The only reason I originally designed the HgKernel::get() method and design was for safety reasons - one cannot foresee what might be needed by systems that have yet to be written. In writing a lot of the system though I realized that this is rarely used and most probably indicates a design flaw since it opens up any system to any other system; it is easy to couple systems together this way that should not be if not careful. I do completely agree though; the goal of this is to simplify the current design rather then make it more complicated then needed. I think I will do this; all image related material can go into that same module (HgImage class, HgImageCodec class, all image codecs for loading and saving the different images, HgImageColorFormat etc.) This way anything related to images are in the same project and not scattered between projects; the image library would define what an HgImage is -- not the engine or kernel or even the graphics manager that would link to the image library. It also makes it easy to use in engine tools as well that can just link to the library as needed. Very true. I realized this in the original design. There was a few cases however that I wanted to address for possible feedback - possible there is something that I don't see here. Window events - Graphics manager or Input manager? Currently I am using SDL to abstract the operating system specific API; I can easily just use SDL_PollEvent in the HgInput module and set up SDL OpenGL support in the HGOpenGL module separately. This of course won't work on standard Win32/Win64 or other system API's which the original designed used. That is, lets say the system is using Win32. The graphics system creates a new render target (a Win32 Window.) Windows of course will send events to this Window, such as mouse, key, and system events (like Window close.) Do you typically handle this in the Graphics or Input manager? The way I originally handled this (since I used Win32 not SDL) was to have the graphics manager handle these Windows events and pass them off to the Input manager. This means though that the Graphics manager needed access to the Input manager. How would you handle cases like this? Again please note that since I currently am using SDL I don't currently have this problem - its more so an interest. Thanks for the help and suggestions! Engine architecture questions Crypter posted a topic in General and Gameplay ProgrammingHello everyone, I am currently in the process of restructuring our current engine into multiple projects/library modules to improve compilation time and to better allow different modules to be selectively reused as needed in engine utilities. This posed a few questions in general architecture design however : 1. Where does resource loading actually occur? In the file module? In a special module dedicated to resource factories (like a "modelLoader" or "audioStream" etc.? Currently the file module only provides a basic file manager that allows loading files from ZIP/PAK and disk directories as it were a single abstract file system. Under the Single Responsibility Principle I would expect the actual loaders to be elsewhere in their own dedicated modules (note that by "module" here I am referring to a project in a Visual Studio solution that compiles as a static or dynamic library.) That is, what I was considering was having different projects for different loaders; such as imageLoaderTGA, imageLoaderDDS, modelLoaderHG etc. These would inherit from some base class defined in another more abstract module, such as hgImage or hgModel. For example, Project : LoaderDDS #include <hgimage/loader.h> class HgLoaderDDS : public HgImageLoader { //... }; Project : HgImage class HgImageLoader { // abstract class for load,save for creating HgImage objects. }; This of course works I am just not sure if its good nor where it fits in with resource management. 2. Is it common to have a single module that is itself a library that links all the major libraries together? That is, I currently have an Hg module that has the HgKernel class. This would provide system startup and shutdown as well as the main loop; it is the only singleton in the entire engine that allows a single access point to all systems. In order for this design to stay (I can rewrite it if needed) we need a single library that imports all major other engine libraries/projects and basically provides a very thin interface like so, class HgKernel { private: static HgKernel* singleton; gfx::HgVideoDriver* pkVideo; public: HgKernel (); /*** KERNEL ACCESSOR METHODS ***/ virtual ~HgKernel () { if (singleton) { shutdown (); } } static inline HgKernel* get () { if (! singleton) singleton = new HgKernel; return singleton; } /*** ACCESSOR METHODS ***/ inline gfx::HgVideoDriver* getVideoDriver () {return pkVideo;} inline double getFramesPerSecond (); /*** SYSTEM METHODS ***/ virtual bool initialize (); virtual bool initialize (std::string caption, int w, int h, int bpp=16, bool fullscreen=false); virtual void shutdown (); virtual bool run (); }; The concern is that HgVideoDriver is implemented in a completely different library. If we extend this example to include an inputManager, audioManager, scriptManager, networkManager, etc., etc., all implemented in other libraries. Although the editor and game only need to link to this one HgKernel class, the HgKernel class would need to be able to link to all other main systems. To make it worse, the whole point of this setup was to allow any major system to call any other major system as needed; this would thus make this design impossible anymore - for example, the kernel object cant depend on the videoManager when the videoManager also needs to depend on HgKernel::get() -- we would have a circular dependency. So the question for (2) is, how do you allow the major components to communicate with each other as needed without using a central setup like the above? Or is there a better alternative or way to implement the above that does not result in circular dependencies? Thanks for any help! - Thank you! 20 chapters has gone by in the OS development series. A little over a year sense it has started on this very site. I want to give a public thank you to everyone - it is the support that I get from readers and members of communities that helps keep the series going. Thank you everyone!! OSDev Series Chapter 20 Chapter 20 has been officially released. It covers: FDC and FDD History Disk Layout CHS and LBA FDD Structure FDC and FDD Hardware Interfacing with the FDC FDC Registers and Commands Programming the FDC It also now includes a demo that is built from the Textual User Interface (TUI) that we have built from the previous chapter. We build a floppy driver in this demo, and impliment a read command to allow us to read from any sector on disk. Check it out here. Please feel free to let me know if there is any comments or suggestions! OSDev Series Updates - Revision 3 I have also added navigational icons to the chapters of the series to help making navigating the series easier for the readers. More updates for the series are also planned including bug fixes, additional content, and more as I impliment Revision 3 of the OS development series. - OSDev Series Chaoter 20 I cannot believe it... I am at chapter 20 of the OS development series going on to chapter 21. It all started with a forum post here on GDNet and is continuing on thanks to the great support that it gets. I thank all of the supporters of the series [grin] Chapter 20 covers almost everything about floppy drive programming including: FDD history Disk layout CHS, LBA FDD Structure FDC Hardware FDC Registers and Commands FDC Interfacing FDC Programming The demo adds a read command to the TUI demo developed in the last chapter that allows you to read any sector on disk using the floppy driver developed in the chapter. OSDev Series: Chapter 20 OS Dev Series Base Site If anyone has any questions, comments, suggestions, or ideas, please feel free to let me know [grin] Small update on Neptune Crypter posted a blog entry in BrokenThorn EntertainmentNeptune Kernels new Debug Screen - Running in VPC Hello everyone, This is just a small update on Neptune. I have finally gotten native Win32 compatible resources implemented in the kernel. (Well, just images anyways but still [grin]) Thanks to this, the kernel can now use bitmaps for different things without loading anything from disk. This also makes development easier as we can just use an image program and resource scripts [smile] Also, thanks to boot time DLLs, the kernel itself is still a microkernel and has no internal drivers for anything. DLLs are used by the kernel but are separate programs. With these additions, the kernel is still being cleaned up to better fit the new design. I suppose thats all for now [smile] I know it somewhat looks like Windows XP do to the colors. What can I say? I like those colors [grin] I am always looking for suggestions though if you have any! Neptune Updates Crypter posted a blog entry in BrokenThorn EntertainmentHello folks, this is just a small update on Neptune! We have been working on Neptune a bit in the last few weeks. The Kernel now supports native Win32-complaint bitmap resources. Thus we can create images in any image program and create a simple resource script to compile into the kernel for it to work [smile] I really like this current setup as it allows the kernel to work with resources without needing to load anything from disk. And do to it using a VGA DLL, the kernel itself doesnt do anything at all with hardware so it follows a microkernel design. With regards to the colors; they do look alot like XPs. What can I say, I like how they look [grin] but if anyone does have any suggestions please feel free to share! I guess thats all for now [smile] Neptune Boot Loader 2.0 Crypter posted a blog entry in BrokenThorn EntertainmentHello everyone, I have gotten the 2nd rewrite of Neptune Boot Loader complete. Thanks to the new Boot Library, the boot loader itself took only two days to make [smile] It is capable of booting multiple operating systems through an LST file (which is basically an INI file in disguise.), and a dynamic boot menu. Supports any mountable volume and filesystem that the boot library nativity supports. About 6,000 lines smaller then the previous version as well thanks to the boot library. Click here for a snapshot and the documentation on the new and improved boot loader [smile] Neptune Boot Library & OSDev Series Chapter 20 Crypter commented on Crypter's blog entry in BrokenThorn EntertainmentQuote:Original post by O-san I which I understood half of those abbreviations but I am very impressed by your work nonetheless. Is the OS going to have graphics or is it more sort of text-based, like DOS? Neptune is graphical. The OS for the series I do not know yet.. I may cover a basic graphics tutorial for the series OS as an "Advanced Topic" rather then fully integrating it with the series as its not really a beginner topic. I am still considering it though and am always looking for opinions on it [smile] Neptune Boot Library & OSDev Series Chapter 20 Crypter posted a blog entry in BrokenThorn EntertainmentHello everyone! [smile] I know that I should start posting more often again - I have been very busy with work and my projects. I have still been visiting this site every day though. I am hoping to get back to a regular posting schedule soon, I promise! [grin] OS Dev Series Chapter 20 - FDC Programming The 20th (Yes, 20th!) installment has been released. I plan another update very soon which will include a demo. This chapter looks at: FDC and FDD History Disk Layout CHS, LBA FDD Structure FDC Hardware Interfacing with the FDC FDC registers and commands This chapter can be reached at here (Clicky!). Please let me know if there are any comments or suggestions! I am still thinking of what should be next. I am considering between DMA and a C FAT12 minidriver chapter. I don't like filesystem programming so I may go DMA first [wink] Update - Neptune Boot Library The Neptune Boot Library helps reorganize the way Neptune boots and loads. It provides a very portable and hardware independent way of interfacing with display (text output), loading files (abstract filesystem access and volume mounting), PE loading, dynamic library loading, generic disk access, and a standard method of error handling. I originally got the idea from Windows Vistas booting design. The Boot Library interfaces with the system BIOS (or can be extended to support EFI) and is written in C. Only one function - io_services () - is architecture dependent do to its usage of the system BIOS. It also supports INI and Neptune LST configuration file parsing through a standard function very similar to the Win32 APIs GetProfileString () method. This library makes it very easy to develop C boot loaders and startup applications using Microsoft Visual C++ 2008, or any compilier (hopefully) that can support Win32 compliant PE executable images. I am still considering if I will release this library to the generic public or not though... It certainly makes things much easier and reduces code duplication alot. I suppose thats all for an update for now. As always any comments are welcome! [grin] - Advertisement
https://www.gamedev.net/profile/66590-crypter/
CC-MAIN-2018-34
refinedweb
3,724
51.68
class WLANWiPy – WiPy specific WiFi control¶ Note This class is a non-standard WLAN implementation for the WiPy. It is available simply as network.WLAN on the WiPy but is named in the documentation below as network.WLANWiPy to distinguish it from the more general network.WLAN class. This class provides a driver for the WiFi network processor in the WiPy. Example usage: import network import time # setup as a station wlan = network.WLAN(mode=WLAN.STA) wlan.connect('your-ssid', auth=(WLAN.WPA2, 'your-key')) while not wlan.isconnected(): time.sleep_ms(50) print(wlan.ifconfig()) # now use socket as usual ... Constructors¶ - class network.WLANWiPy(id=0, ...)¶ Create a WLAN object, and optionally configure it. See init()for params of configuration. Note The WLAN constructor is special in the sense that if no arguments besides the id are given, it will return the already existing WLAN instance without re-configuring it. This is because WLAN is a system feature of the WiPy. If the already existing instance is not initialized it will do the same as the other constructors an will initialize it with default values. Methods¶ - WLANWiPy.init(mode, *, ssid, auth, channel, antenna)¶ Set or get the WiFi network processor configuration. Arguments are: mode can be either WLAN.STAor WLAN.AP. ssid is a string with the ssid name. Only needed when mode is WLAN.AP.’). Only needed when mode is WLAN.AP. channel a number in the range 1-11. Only needed when mode is WLAN.AP. antenna selects between the internal and the external antenna. Can be either WLAN.INT_ANTor WLAN.EXT_ANT. For example, you can do: # create and configure as an access point wlan.init(mode=WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2,''), channel=7, antenna=WLAN.INT_ANT) or: # configure as an station wlan.init(mode=WLAN.STA) - WLANWiPy.connect(ssid, *, auth=None, bssid=None, timeout=None)¶ Connect to a WiFi access point using the given SSID, and other security parameters.’). bssid is the MAC address of the AP to connect to. Useful when there are several APs with the same ssid. timeout is the maximum time in milliseconds to wait for the connection to succeed. - WLANWiPy.scan()¶ Performs a network scan and returns a list of named tuples with (ssid, bssid, sec, channel, rssi). Note that channel is always Nonesince this info is not provided by the WiPy. - WLANWiPy.isconnected()¶ In case of STA mode, returns Trueif connected to a WiFi access point and has a valid IP address. In AP mode returns Truewhen a station is connected, Falseotherwise. - WLANWiPy.ifconfig(if_id=0, config=['dhcp' or configtuple])¶ With no parameters given returns a 4-tuple of (ip, subnet_mask, gateway, DNS_server). if 'dhcp'is passed as a parameter then the DHCP client is enabled and the IP params are negotiated with the AP. If the 4-tuple config is given then a static IP is configured. For instance: wlan.ifconfig(config=('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8')) - WLANWiPy.irq(*, handler, wake)¶ Create a callback to be triggered when a WLAN event occurs during machine.SLEEPmode. Events are triggered by socket activity or by WLAN connection/disconnection. handler is the function that gets called when the IRQ is triggered. wake must be machine.SLEEP. Returns an IRQ object.
https://docs.micropython.org/en/latest/library/network.WLANWiPy.html
CC-MAIN-2022-21
refinedweb
552
60.61