text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
I just did an assignment too quickly so I want to make sure that I did it right. It works properly but seems too easy to be true. The assignment says to write a program that defines and uses macro SUMMARY to sum the values in a numeric array. The macro should recieve the array and the number of elements in the array as arguments. I was not sure if I am supposed to somehow add the elements when I define it or as I did which works fine. Any advise is appreciated thanks. Code: #include <stdio.h> #define SUMMARY (total) #define SIZE 10 int main() /* program main begins execution */ { int A[SIZE] ={1,2,3,4,5,6,7,8,9,10}; /* define array */ int i; /* counter */ int total = 0; /* initialize total to zero */ for (i=0; i< SIZE; i++ ) { /* compute total */ total += A[i]; } printf( "Total value of array is %d\n", SUMMARY ); /* print results */ return 0; /* indicates successful program execution */ }
http://cboard.cprogramming.com/c-programming/72810-macros-printable-thread.html
CC-MAIN-2016-07
refinedweb
163
61.06
Creating a #macOS App using HTML and #Javascript You can create great macOS apps with Swift, and if you’ve got the time to learn a new language, then this is the way to go. But if you already have something cool made with HTML and Javascript, then you can turn it into a macOS app with a few simple steps. TL;DR; If you want to skip to the end, you can just clone the GIT repo at But, if you fancy going step by step, – open up XCode and create a new macOS / Cocoa app. Drop a WKWebView onto the form, and set it’s constraints so that it fills the view. Then drag an outlet called; @IBOutlet weak var webkitview: WKWebView! You’ll need to add a reference to WebKit as follows; import WebKit Then in the viewDidLoad, add the following lines let url = Bundle.main.url(forResource: “index”, withExtension: “html”)! webkitview.loadFileURL(url, allowingReadAccessTo: url) let request = URLRequest(url: url) webkitview.load(request) You can then go Add files to … and add your index.html to the project. Now, if you run this now, you may get a white page. To get around this, you will need to go to the project > Capabilities > App Sandbox and click “Outgoing connections (Client)” Another thing that you may have to do, or else the app may get rejected by apple, is to exit the app when the window is closed. you do this in AppDelegate.swift as follows; func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true }
https://blog.dotnetframework.org/2018/10/06/creating-a-macos-app-using-html-and-javascript/
CC-MAIN-2021-17
refinedweb
257
70.84
Introduction to Maintaining User-Specific Data Using Isolated Storage and C# Introduction The .NET framework provides a very useful feature that allows an application to store and retrieve data on a per-user basis. This new Isolated Storage mechanism replaces the previous methods of storing such data in Windows .ini files and the system Registry. Isolated Storage allows applications to save user-specific data into a unique location determined via the user and assembly identities. This effectively eliminates storage conflicts and provides the developer with a completely transparent and reliable storage location. Although the .NET Framework Developer's Guide suggests many situations where Isolated Storage is useful, an obvious and highly effective use for it is to maintain simple user-specific preferences and configurations for an application. In today's applications, it is becoming more and more common to maintain an application state and to provide users with the ability to customize features and appearance. Users now expect that an application will maintain their settings when they run it. The second part of this tutorial is a step-by-step guide to develop a simple example application which demonstrates user-customizability via Isolated Storage. Because many people are new to C#, I've made the guide detailed enough for a beginner to work through from start to finish. Hopefully, if you're new to .NET and C#, and you work through the entire example from start to finish, you'll learn a few other useful things on the way. The example guide assumes that the developer is familiar with the very basics of C# development using MicroSoft Visual Studio .NET. Using Isolated Storage Isolated Storage is very easy to use within your C# application. As previously explained, this feature allows an application to save user-specific data into a unique location (data compartment) that is associated with both the user and assembly identities. It is possible to actually limit and control the size of an application's Isolated Storage, as well as configuring the security around it. For the scope of this tutorial, we are primarily interested in simply using the feature to read and write data reliably and easily. Isolated Storage is implemented as a file stream. To store data, you first must create an instance of an IsolatedStorageFileStream. To write to this stream, we also will require the creation of a StreamWriter object. To create these objects, we need to include the appropriate namespaces: using System.IO; using System.IO.IsolatedStorage; The IsolatedStorageFileStream object can be initialized with a filename and file mode. With Isolated Storage, the developer does not know what the storage location will be in advance (and so cannot create a pre-installed default settings file), and so it is essential that the application assumes that the file could not exist and must therefore be created if required. This is done using the FileMode.Create file mode. After the IsolatedStorageFileStream is created, it can be used as the stream parameter in the initialization of a StreamWriter object. This StreamWriter object then can be used to output any form of string-based data that you want. The opportunities are endless here—you could quite easily store XML data in there. Here is an example WriteUserData function that performs the actions we have described, storing five simple string values from the containing class: private void WriteUserData() { // create an isolated storage stream... IsolatedStorageFileStream userDataFile = new IsolatedStorageFileStream("UserData.dat", FileMode.Create); // create a writer to the stream... StreamWriter writeStream = new StreamWriter(userDataFile); // write strings to the Isolated Storage file... writeStream.WriteLine(string1); writeStream.WriteLine(string2); writeStream.WriteLine(string3); writeStream.WriteLine(string4); writeStream.WriteLine(string5); // Tidy up by flushing the stream buffer and then closing // the streams... writeStream.Flush(); writeStream.Close(); userDataFile.Close(); } Yes, it is as simple as that! All we need to supply is the filename. The actual location never concerns us; the .NET framework takes care of it. Similarly, the following ReadUserData example function shows how the file can be read again to retrieve the five string values: private void ReadUserData() { // create an isolated storage stream... IsolatedStorageFileStream userDataFile = new IsolatedStorageFileStream("UserData.dat", FileMode.Open); // create a reader to the stream... StreamReader readStream = new StreamReader(userDataFile); // write strings to the Isolated Storage file... string1 = readStream.ReadLine(); string2 = readStream.ReadLine(); string3 = readStream.ReadLine(); string4 = readStream.ReadLine(); string5 = readStream.ReadLine(); // Tidy up by closing the streams... readStream.Close(); userDataFile.Close(); } When the IsolatedStorageFileStream object is initialized here, we pass the FileMode.Open file mode because we want to open an existing file. The code does not handle the exception that would occur if the file did not exist, which must be considered when used in a real application. The simple methods described above also store and retrieve the strings in a known order for clarity. It would be safer to store data as name-value pairs and parse the values when reading (to remove order-dependency). Isolated Storage Example—A Step-by-StepGuide This step-by-step guide can be followed to build the example solution included with this tutorial. In fact, if you follow it carefully, you won't need to download anything at all! The example is a simple customizable application which enables the user to select what a message on the application displays, if the application has minimize and/or maximize buttons available in the title bar, if the application appears in the Windows task bar, and finally the background color of the application. Start by creating a new C# Windows application called IsolatedStorageExample. First, we need to do some tidying up. In the Solution Explorer, right-click Form1.cs and rename the file to MainForm.cs. Now, right-click MainForm.cs and select View Code. With the code visible, press Control+H to invoke the Find and Replace dialog. We want to give the form class a suitable name, so Replace all instances of Form1 with MainForm (there should have been four). We are now ready to begin creating our application. In the Design view of MainForm.cs, select the MainForm object and change the Text property to "Isolated Storage Example" (ignore the quotations). This gives our application a sensible title. Now set the form's Height and Width properties to be 200 and 300 respectively (found under the Size property). Your form should now look something like this: Now add two new labels to the form. Stretch the width of each label so that they fill the width of the form. Position the labels one above the other on the form. Set the names of these labels to lblMessage and lblLastCustomized. Set the Text property of lblMessage to "Message: No Message" and the Text property of lblLastCustomized to "Last Customized: Not Yet Customized". Now set the BackColor property of both lblMessage and lblLastCustomized to White. The form now should look something like this: Add a button to the form and call it bnCustomize. Position the button at the bottom of the form somewhere, clear of the labels. Set the Text property of bnCustomize to "Customize". Now set the BackColor property of bnCustomize to Yellow. At this point, our MainForm's appearance is complete. It represents our customizable application and should look something like this: Okay, so we have our customizable application but how to we actually allow the user to customize it? We need to create a new form. To do this, select Add Windows Form from the Project menu. Select the Windows Form template and name the file CustomizeForm.cs. Add a textbox to the new form and name it txtMessage. Change the Text property of txtMessage to be empty and widen the object so that it nearly fills the form width. Add three checkboxes to the form and name them cbMinimize, cbMaximize, and cbTaskBar. Set the Text property of cbMinimize to "Minimize Box". Set the Text property of cbMaximize to "Maximize Box". Set the Text property of cbTaskBar to "Show In Task Bar". You can widen any of these checkboxes if the label does not fit on one line. If you want, you now can add some static labels to your form to give lblMessage a heading of "Message" and the checkboxes a label of "Settings". I have done this using two static groupbox objects (you will need to place existing object on top of these groupboxes), and the form look like this: There is one last customizable setting to add to this form—the background color. We will add a button now to enable the user to select a color. Call the new button bnColor and set the Text property of it to "Set Background Color". Resize the button so that the label fits correctly and position it along with the checkboxes (under the Settings heading). Because we will need to read settings from the controls on this dialog, it is very important that we now set the Modifiers properties of lblMessage, cbMinimize, cbMaximize, cbTaskBar, and bnColor to Public. Finally, we need to enable the user to accept or reject the settings, so we add two new buttons and call them bnApply and bnCancel. These are positioned at the bottom of the dialog. For bnApply, set the Text property to "Apply" and the DialogResult property to "OK". For bnCancel, set both the Text property and the DialogResult property to "Cancel". Finally, add a ColorDialog object to the form and name it colorDialog (notice that this object is placed under the form in Visual Studio .NET). Your form should look something like this: Okay, the visual aspects of our forms have been created now, and up until this point you have probably noticed that we have not yet written any code at all! We shall do that now.... In MainForm.cs, the first thing that we are going to do is create some useful constants at the beginning of the MainForm class declaration. Add the following code within the start of the MainForm class: const string MessageLabel = "Message: "; const string CustomizedLabel = "Last Customized: "; const string UserConfigFile = "StorageExample.dat"; Both MessageLabel and CustomizedLabel represent strings that we always want to precede corresponding output on our application, whereas UserConfigFile represents a filename which is specific to this application and will be used as our Isolated Storage data file. In CustomizeForm.cs, you will notice that a default constructor has been created which takes no parameters. Because our Customize form needs to be set up with the current user settings on creation, we will change this constructor so that it takes five settings as parameters. Change the constructor to the following: public CustomizeForm(string message, bool minBox, bool maxBox, bool taskBar, Color formColor) { InitializeComponent(); // Set up the form controls... txtMessage.Text = message; cbMinimize.Checked = minBox; cbMaximize.Checked = maxBox; cbTaskBar.Checked = taskBar; bnColor.BackColor = formColor; } It can be seen here that when the form is created with the five passed parameter settings, we then set up our form to reflect these settings. The txtMessage text box is set to display the string message, the checkboxes cbMinimize, cbMaximize, and cbTaskBar are checked/unchecked appropriately, and the color select button color is set to match the Color parameter passed. Now that we can construct and set up our Customize form, we can put some code in place to actually do this. In the Design view of MainForm.cs, double-click the bnCustomize button to automatically generate an event handler for it, called bnCustomize_Click. This function shall contain any code we wish to execute if the user presses this button. We want this action to invoke our Customize form as a dialog. To do this, add code in the bnCustomize_Click function as follows:; } // Close the Customize dialog... customizeDialog.Dispose(); } You can see here that when the bnCustomize button is pressed, the first thing that happens is that we instantiate our CustomizeForm object. We supply the constructor with our application's current state for all five of the customizable parameters. In the case of the message string, we pick out only the actual message part of it using the Substring function to remove the preceding label (the MessageLabel constant). Next, we have a conditional statement that looks to see if the result of the dialog is "OK". You may remember earlier that we set the DialogResult value for the Apply button (on the CustomizeForm object) to be "OK". If the user presses the Apply button, we will enter this conditional statement; otherwise, we will skip it (for example, when the dialog is closed or the Cancel button is pressed). If the user has pressed Apply, we copy over the new custom settings from the CustomizeForm object. This is pretty straightforward in that we copy over directly the boolean state of the MinimizeBox, MaximizeBox, and ShowInTaskbar options, along with the BackColor value. It also can be seen that when we copy over the message string, we add our MessageLabel constant to the beginning. Finally, it can be seen that there is another property present that is not actually copied over from the CustomizeForm object. This is the current date and time, which we add a preceding label to (the CustomizedLabel) and then display on our MainForm. This extra string displays the date and time that the application was last customized (as in, the last time the user pressed the Apply button on the CustomizeDialog form). The next thing we need to do is to deal with any remaining functionality on our CustomizeForm. We have already seen that when we instantiate it, we set the values of all customizable properties to the controls on the form. All of these controls then can be manipulated, ready for the values to be read back from them when we click Apply—apart from the bnColor object. The BackColor property of bnColor cannot yet be changed, and this is where our ColorDialog object becomes useful. The colorDialog object provides us with a standard dialog object for selecting a new color. We need to invoke this dialog when the user presses the bnColor button. Double-click the bnColor button to automatically generate an event handler for it, called bnColor_Click. Add the following code into that function: private void bnColor_Click(object sender, System.EventArgs e) { colorDialog.Color = bnColor.BackColor; if (colorDialog.ShowDialog(this) == DialogResult.OK) { bnColor.BackColor = colorDialog.Color; } } It can be seen here that when the bnColor button is pressed, we simply set the current color of the colorDialog object to match our current BackColor, before actually invoking the dialog. When the user has finished selecting a new color from the colorDialog object and clicked "OK", we simply copy the new color over and set our bnColor.BackColor property to it. If the user closed the colorDialog object by any other method, we do nothing. At this point, we are have nearly completed the functionality of our CustomizeForm object. Double-click the bnCancel button and set the event handler function to the following: private void bnCancel_Click(object sender, System.EventArgs e) { this.Close(); } This will simply close CustomizeForm if the Cancel button is pressed. Finally, it would be nice to add a little user-specific feature to the CustomizeForm object. Every time the form is created, we can set the title of the form to display "Customize for username", where username is the actual Windows username of the current user. To do this, we double-click the title bar of the form to create an event handler for when the form is loaded, called CustomizeForm_Load. Add the following code to that function to set the form title as we require: private void CustomizeForm_Load(object sender, System.EventArgs e) { this.Text = "Customize for " + SystemInformation.UserName; } The code for the CustomizeForm object is now complete. Now we move on to the whole point of this little tutorial—Isolated Storage. The first thing we need to do is set up the MainForm class to use this feature by ensuring the following namespaces are used in MainForm.cs: using System.IO; using System.IO.IsolatedStorage; Next, we will create a new function called WriteCustomUserSettings to our MainForm class. This function will write all of our user-customizable settings to a user-specific file via Isolated Storage. It can be seen that it is very similar to the example given at the start of this tutorial. Add the function in the end of the MainForm class as follows: private void WriteCustomUserSettings() { IsolatedStorageFileStream userConfigFile = new IsolatedStorageFileStream(UserConfigFile, FileMode.Create); // create a writer to the stream... StreamWriter writeStream = new StreamWriter(userConfigFile); // write the form configuration to the file... writeStream.WriteLine(lblMessage.Text.Substring (MessageLabel.Length)); writeStream.WriteLine(lblLastCustomized.Text.Substring (CustomizedLabel.Length)); writeStream.WriteLine(this.MinimizeBox); writeStream.WriteLine(this.MaximizeBox); writeStream.WriteLine(this.ShowInTaskbar); writeStream.WriteLine(this.BackColor.ToArgb()); // clean up... writeStream.Flush(); writeStream.Close(); userConfigFile.Close(); } In this function, the first thing we do is to instantiate a new IsolatedStorageFileStream object. We call it userConfigFile and construct it using our preset filename (UserConfigFile) and a FileMode.Create parameter. Obviously, the filename parameter is the name of the file in which we will store our data and the FileMode.Create parameter signifies that the file should be created if it does not yet exist. It can be seen that we write the value of each of the customizable settings in a specific order (this is for simplicity, and so this order must be adhered to when reading). Any non-string value is automatically converted. Notice that we store the color as a string representation of the ARGB value. This will allow us to store any color, and successfully retrieve that color. If the color had been stored using the ToName() function, this would cause problems if the colour was anonymous as it would not be easy to read back in (try it!). The WriteCustomUserSettings function will be called only if the user clicks Apply via the CustomizeForm dialog. This is handled within the bnCustomize_click function, when the DialogResult is "OK". Add the WriteCustomUserSettings call to the conditional statement so that the bnCustomize_click function now looks like this:; // Write using Isolated Storage... WriteCustomUserSettings(); } // Close the Customize dialog... customizeDialog.Dispose(); } We now can write our user settings via Isolated Storage, but this is useless unless we can read them again. To do this, we create another function, called ReadCustomUserSettings. This function uses the Isolated Storage procedure already described to read our settings back into the appropriate places. We add preceding labels (our string constants) to the two strings for lblMessage.Text and lblLastCustomized.Text. We then also use some simple built-in functions to convert the stored Boolean string representations back to usable values. Finally, we convert the string representation of the color back to a usable Color object using the FromArgb() function. The full ReadCustomUserSettings should be added in the end of the MainForm class as follows: private void ReadCustomUserSettings() { try { IsolatedStorageFileStream userConfigFile = new IsolatedStorageFileStream(UserConfigFile, FileMode.Open); // create a reader to the stream... StreamReader readStream = new StreamReader(userConfigFile); // read each setting from the file... lblMessage.Text = MessageLabel + readStream.ReadLine(); lblLastCustomized.Text = CustomizedLabel + readStream.ReadLine(); this.MinimizeBox = readStream.ReadLine().Equals (Boolean.TrueString); this.MaximizeBox = readStream.ReadLine().Equals (Boolean.TrueString); this.ShowInTaskbar = readStream.ReadLine().Equals (Boolean.TrueString); this.BackColor = Color.FromArgb(System.Int32.Parse (readStream.ReadLine())); // clean up... readStream.Close(); userConfigFile.Close(); } catch (System.IO.FileNotFoundException) { // Warn the user that no user configuration file has been found // and the default settings will therefore be used... MessageBox.Show("This application has not yet been user-customized.\n\n" + "Default settings will be applied.\n\n", "Isolated Storage Example"); } } Notice here that we have added an exception handler which catches System.IO.FileNotFoundException. This needs to be present to cover the situation where a file does not exist. If the application is being run for the first time, this will be the case. If the exception occurs, we assume that this is why and output an appropriate message to the user. The last thing that we need to do is make a call to our ReadCustomUserSettings function. We want this to occur every time our application is started. Double-click the title bar of the MainForm form to generate an event handler called MainForm_Load, which handles any functionality required when loading the form. Add a call to the ReadCustomUserSettings within it. It should look like this: private void MainForm_Load(object sender, System.EventArgs e) { ReadCustomUserSettings(); } The example is now complete and can be built and run. Experiment with it by opening the application, customizing it, and then closing it. Re-launch it again to see how your settings are retained. Notice that the message box appears the first time you run the application, proving that the expected exception has been thrown when the file does not yet exist. Try logging into Windows as a different user. Run the application again and you will see that the retained settings really are user-specific. If you want to investigate where the application is writing to, search for StorageExample.dat on your hard drive (you may need to search hidden and system files). DownloadsDownload demo project - 13 Kb Download source - 4 Kb Dont rate this so harshlyPosted by darwen on 12/13/2004 05:49pm Look, the .NET framework is like this. It's one of the things I don't like about .NET remoting : the fact that backward compatibility is completely impossible. Now, some would say that changes in settings between versions would require you to start anew. To prevent bugs/exceptions being made. In actual fact if you use this article sensibly then there's no problems. It shouldn't be rated one star. It's well written, comprehensive (except for the omission of versioning problems) and pretty good.Reply Unfortunately, if you copy or move your app ...Posted by Legacy on 11/13/2003 12:00am Originally posted by: Rob Unfortunately, if you copy or move your app to another location it will create another *.dat file. Using registry keys makes it location-independent which is quite more functional and useful. Reply What about upgrades?Posted by Legacy on 12/26/2002 12:00am Originally posted by: Michael Potter Very nice intro article. What happens when an application is upgraded. The Assembly changes and would no longer have access to the user settings. How can the upgrade access/import the previous versions settings? Thanks,Reply Mike
http://www.codeguru.com/csharp/csharp/cs_data/article.php/c4225/Introduction-to-Maintaining-UserSpecific-Data-Using-Isolated-Storage-and-C.htm
CC-MAIN-2015-48
refinedweb
3,707
56.35
createAsyncThunk is a function with two parameters—an action type string and an asynchronous callback—that generates a thunk action creator that will run the provided callback and automatically dispatch promise lifecycle actions as appropriate so that you don’t have to dispatch pending/fulfilled/rejected actions by hand. To use createAsyncThunk, you’ll first need to import it from Redux Toolkit like so: import { createAsyncThunk } from '@reduxjs/toolkit'; Next, you’ll need to call createAsyncThunk, passing two arguments. The first is a string representing the asynchronous action’s type. Conventionally, type strings take the form "resourceType/actionName". In this case, since we are getting an individual user by their id, our action type will be users/fetchUserById. The second argument to createAsyncThunk is the payload creator: an asynchronous function that returns a promise resolving to the result of an asynchronous operation. Here is fetchUserById rewritten using createAsyncThunk: import { createAsyncThunk } from '@reduxjs/toolkit' import { fetchUser } from './api' const fetchUserById = createAsyncThunk( 'users/fetchUserById', // action type async (arg, thunkAPI) => { // payload creator const response = await fetchUser(arg); return response.json(); } ) There are a few things worth highlighting here. First, observe that the payload creator receives two arguments— arg and thunkAPI. We will elaborate on those in the next exercise. Second, note that the payload creator we provided doesn’t dispatch any actions at all. It just returns the result of an asynchronous operation. As you can see, createAsyncThunk makes defining thunk action creators more concise. All you have to write is an asynchronous thunk function; createAsyncThunk takes care of the rest, returning an action creator that will dispatch pending/fulfilled/rejected actions as appropriate. Instructions In the code editor, we’ve provided loadRecipes, the asynchronous action creator you wrote in the last lesson. Now we’re going to refactor it using createAsyncThunk. To start, import createAsyncThunk from Redux toolkit (make sure you continue to import createSlice as well). Refactor loadRecipes using createAsyncThunk. Remember, createAsyncThunk takes two arguments: an action type string, and a payload creator function. Your action type string should be 'allRecipes/loadRecipes'. Your payload creator should retrieve the recipes by calling fetchRecipes, which we’ve imported for you. Once the recipes are fetched, you should return their json data, which you can access by calling .json() on the response to your call to fetchRecipes. Note: .json() is asynchronous, so you’ll want to await the result of that call.
https://www.codecademy.com/courses/learn-redux/lessons/managing-promise-lifecycle-actions/exercises/createasyncthunk
CC-MAIN-2021-39
refinedweb
398
56.25
Hide Forgot Description of problem: ---Problem Description--- On RHEL4U4 mod_python 3.1.3 is included. When passing large files through a python script these files get corrupted. When building and installing mod_python 3.2.8 from EL5 the problem is fixed and the files are passed through correctly. This URL s.apache.org/bugzilla/show_bug.cgi?id=41468 is about the same issue but filed wrongly for httpd itself. Contact Information = Tim Verhoeven/tim.verhoeven@be.ibm.com ---uname output--- Linux wegdaap40 2.6.9-42.EL #1 Wed Jul 12 23:15:20 EDT 2006 x86_64 x86_64 x86_64 GNU/Linux Machine Type = VMWare ESX 3.0 guest ---Debugger--- A debugger is not configured Version-Release number of selected component (if applicable): mod_python-3.1.3-5.1 How reproducible: always Steps to Reproduce: 1. Install the following filter under DocumentRoot import time from mod_python import apache def outputfilter(filter): # extract important info request = filter.req connection = request.connection (address,port) = connection.remote_addr # if requesting this file, don't return it if request.the_request.find("watcher.py") != -1: filter.close() return # pass-through filter s = filter.read() while s: filter.write(s) s = filter.read() if s is None: filter.close() 2. Add the following statements to the directory section containing the file in the httpd config to enable python parsing : AddHandler mod_python .py PythonOutputFilter watcher WATCHER AddOutputFilter WATCHER ks.cfg AddOutputFilter WATCHER .rpm AddOutputFilter WATCHER .xml AddOutputFilter WATCHER .py 3. Put a small and large file ending in .rpm of .xml in the same dir and retrieve the file using mozilla, wget, ... additional. The file only needs to be >8192 bytes 4. When using mod_python 3.1.3 the file is corrupted at the end with 3.2.8 not. Actual results: Corrupted file Expected results: clean file. Additional info: backported two lines of fix from the 3.2.8 version included with RHEL5, patch attached. Created attachment 152700 [details] mod_python-3.1.3-buflen.patch buffer read fixes *** This bug has been marked as a duplicate of 231065 ***
https://partner-bugzilla.redhat.com/show_bug.cgi?id=236578
CC-MAIN-2019-35
refinedweb
340
54.9
grahampaul1,865 Points On the first task, I get an error with code that is not present (on line 67). Not enough chars to paste the error. JavaTester.java:67: error: constructor Course in class Course cannot be applied to given types; Course course = new Course("Java Data Structures"); ^ required: String,Set found: String This code doesn't exist! package com.example.model; import java.util.List; import java.util.Set; public class Course { private String mTitle; private Set<String> mTags; public Course(String title, Set<String> tags) { mTitle = title; mTags = tags; //; } } 2 Answers Steve HunterTreehouse Moderator 57,555 Points Hi Graham, The code it is referring to is the code that runs behind the scenes to test that you've addeed the correct code to the challenge. In this instance, it is calling the constructor for the Course class and is finding an error. That's because you have amended the constructor to take a String and a Set of String. It is expecting it just to take a String` object, in this case, "Java Data Structures". The first task asks you to initialize the Set in the constructor. You don't need to pass it in to do that; you just want to assign something to it inside there. Take that parameter out of the constructor so that it just takes the single string parameter. The member variable mTags is a Set but you'll want to initialize it as a HashSet. First, add the HashSet to the imports: import java.util.HashSet; Then, inside the constructor, assign a new HashSet to mTags: mTags = new HashSet<String>(); That should do it for the first task. Steve. Steve HunterTreehouse Moderator 57,555 Points Steve HunterTreehouse Moderator 57,555 Points No problem. As long as you got through.
https://teamtreehouse.com/community/on-the-first-task-i-get-an-error-with-code-that-is-not-present-on-line-67-not-enough-chars-to-paste-the-error
CC-MAIN-2019-51
refinedweb
298
72.05
Feature #16812closed Allow slicing arrays with ArithmeticSequence Description I believe when concepts of ArithmeticSequence and Range#% were introduced, one of the main intended usages was array slicing in scientific data processing. So, it seems to make sense to allow this in Array#[]: ary[(5..20) % 2] # each second element between 5 and 20 ary[(0..) % 3] # each third element ary[10.step(by: -1)] # elements 10, 9, 8, 7 .... My reasoning is as follows: - As stated above, ArithmeticSequence and Range#%seem to have been introduced exactly for this goal - Python has its slicing syntax as begin:end:step(with a possibility to omit either), and it seems to be well respected and used feature for data processing. So I believe it is useful, and relatively easy to integrate into existing functionality I expect the usual "it is ugly and unreadable!" backlash. I don't have an incentive, nor energy, to "defend" the proposal, so I would not. Updated by Eregon (Benoit Daloze) over 1 year ago Rather neutral on this, but would you want that to work for Array#[]= too? I would be against Array#[]= as it's already so complicated and that would just make it a lot more so. In Array#[] it's probably fine though. Updated by zverok (Victor Shepelev) over 1 year ago Eregon (Benoit Daloze), I wanted at first to see what people say about this one :) Array#[]= is a thing that should be kinda "symmetric", but playing a bit with it, I understood that I am afraid of trying to guess what would be "logical". Honestly, I can't remember I've ever used a form like a[1..3] = 'x', and its behavior is kinda "theoretically logical", but at the same time only one of the things you may "intuitively" expect ("replace all three elements with one, changing array's size" wouldn't be my first guess...). So, at least for now, my only proposal is Array#[]. Updated by Dan0042 (Daniel DeLorme) over 1 year ago Theoretically I'm in favor but there's some edge cases that need consideration. nums = (0..20).to_a s = 10.step(by: -2) # 10, 8, 6, 4, 2, 0, -2, ... nums[s] #=> [10, 8, 6, 4, 2, 0, 19, 17, ...] ??? s = (-5..5) % 2 # -5, -3, -1, 1, 3, 5 nums[s] #=> [16, 18, 20, 1, 3, 5] ??? Updated by nobu (Nobuyoshi Nakada) over 1 year ago A few bugs. Float ArithmeticSequencecrashes. $ ./ruby -e '[*0..10][(0.0..)%10]' Assertion Failed: ../src/include/ruby/3/arithmetic/long.h:136:ruby3_fix2long_by_shift:"RB_FIXNUM_P(x)" If overridden take_while(and drop_while) returns non- Array, crashes. $ ./ruby 'a = (1..10)%2; def a.take_while; nil; end; [*1..10][a]' -e:1:in `<main>': wrong argument type nil (expected Array) (TypeError) These resulted in assertion failures, but would segfault when compiled with NDEBUG. Updated by mrkn (Kenta Murata) over 1 year ago - Assignee set to matz (Yukihiro Matsumoto) - Status changed from Open to Assigned I'm positive this if the behavior is the same as Python's list slicing. If the behavior will be different from Python's, I'm negative because it confuses PyCall users. Updated by zverok (Victor Shepelev) over 1 year ago As there is no immediate rejection, I updated the implementation, making it more robust. Dan0042 (Daniel DeLorme), I tried to make edge cases consistent, so now they are... (0..20).to_a[10.step(by: -2)] # => [10, 8, 6, 4, 2, 0] -- avoids weird cycling (0..20).to_a[(-5..5) % 2] # => [] -- this is consistent with (0..20).to_a[-5..5] # which can be thought as (-5..5) % 1 # => [] # Note, though: (0..20).to_a[-19..5] # => [2, 3, 4, 5] -- not literally "from -19 to 5", but "from 19th from the end to 5th from the beginning" # ...so... (0..20).to_a[(-19..5)%2] # => [2, 4] nobu (Nobuyoshi Nakada) I've tried to fix bugs. Now float begin/end is processed correctly, float step is TypeError, and the code does not rely on #take_while/ #drop_while. mrkn (Kenta Murata) I've checked against Python impl, and believe the behavior is mostly the same. One difference I am aware of is this: Python: list(range(10))[-100:100:2] #=> [0, 2, 4, 6, 8] Ruby: [*0..10][(-100..100)%2] # => nil That's because first of all I wanted to make it consistent with [*0..10][-100..100] # => nil ...which may be questioned (like, "range from -100 to 100 includes 0..10, so it should fetch entire array"), but that's how it is now :) Updated by mrkn (Kenta Murata) over 1 year ago It may be better to change the behavior of [*0..10][-100..100] because [*0..10][..100] does not return nil: [*0..10][..100] # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] And the following cases seems inconsistent to me: [*0..10][0..12] # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [*0..10][-12..-1] # => nil Updated by mrkn (Kenta Murata) over 1 year ago I made a patch: Updated by Dan0042 (Daniel DeLorme) over 1 year ago mrkn (Kenta Murata) wrote in #note-7: It may be better to change the behavior of [*0..10][-100..100] I somewhat agree with that. When using range slicing most combinations make sense: [*0..10][0..4] #first elements [*0..10][-5..-1] #last elements [*0..10][1..-2] #middle elements But a negative start with a non-negative end is quite weird. What is that operation even supposed to mean? What is it useful for? [*0..10][-8..8] #???? 8.times{ |i| p (0..i) => [*0..i][-3..3] } {0..0=>nil} {0..1=>nil} {0..2=>[0, 1, 2]} {0..3=>[1, 2, 3]} {0..4=>[2, 3]} {0..5=>[3]} {0..6=>[]} {0..7=>[]} So even if [*0..10][-100..100] remains supported forever (there doesn't seem to be a point in breaking compatibility; see #16822), it could emit a verbose-mode warning. And ArithmeticSequence slicing should not attempt to be consistent with that case, because it's useless to start with. So I believe there are two useful/meaningful possibilities for (0..20).to_a[(-5..5) % 2] a) [16, 18, 20] ignore trailing non-negative values, like (-5..) % 2; I think this makes the most sense b) [1, 3, 5] ignore leading negative values, like python Updated by zverok (Victor Shepelev) over 1 year ago But a negative start with a non-negative end is quite weird. What is that operation even supposed to mean? What is it useful for? I believe such edge cases might emerge not being directly written, but when dynamically calculated. Imagine calculating some anchor element, and then taking N elements around it. Then, you have, say... def around_mean(ary, count: 3) i = ary.index(ary.sum / ary.length) ary[i-count..i+count] end around_mean((1..20).to_a) # => [7, 8, 9, 10, 11, 12, 13] around_mean((1..6).to_a) # => [6] -- hm, it is a bit strange around_mean((1..6).to_a, count: 10) # => nil -- hm, it is even weirder... The example before last is [1, 2, 3, 4, 5, 6][-1..5] which "intuitively weird", as one might expect something like: 1 2 3 4 5 6 ^^^^^^^^^^^ The very last example is [1, 2, 3, 4, 5, 6][-8..12] -- and it even doesn't produce empty array (I pointed at this at #16822, too). That's not the best possible example, but at least it demonstrates how we can arrive at edge case situation and why we (probably) might expect different behavior here. Updated by matz (Yukihiro Matsumoto) over 1 year ago The basic bahavior seems OK. Probably we need to investigate some corner cases, but you can commit (and we experiment). Matz. Updated by Anonymous about 1 year ago - Status changed from Assigned to Closed Applied in changeset git|a6a8576e877b02b83cabd0e712ecd377e7bc156b. Feature #16812: Allow slicing arrays with ArithmeticSequence (#3241) Support ArithmeticSequence in Array#slice Extract rb_range_component_beg_len Use rb_range_values to check Range object Fix ary_make_partial_step Fix for negative step cases range.c: Describe the role of err argument in rb_range_component_beg_len Raise a RangeError when an arithmetic sequence refers the outside of an array Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/16812
CC-MAIN-2021-49
refinedweb
1,364
65.83
Greetings, The amounts that the trust pays for your son's expenses are not income to you and the payments to you for administration are income to you. This payment to you is an expense of the trust. The trust will file a tax return (and is required if it has more than $600 of income). Even if not required, it may be beneficial to at least prepare (and probably file) a return to have a record of the transactions. The distributions to your son may cause some of the trust income to be taxable to your son; but he should receive a Form K-1 to report the amoutns to include on his return if he is required to file. The problem may arise of keeping separate the two types of payments. My suggestion is that you keep a separate account for the amounts distributed for your son's expenses and to repay you for the amounts you spend on him or have payments made directly from that account for his care and support. That way, there is no question what is and is not your income and how the funds were spent. As both the paid administrator and the caretaker of your son you can avoid any question of using his money for yourself by keeping separate acccounts and preparing a return. I hope this helps for separating the paymnets from the trust.
http://www.justanswer.com/tax/109aq-trustee-disabled-sons-account.html
CC-MAIN-2015-40
refinedweb
235
73.31
Each DOP network builds a tree of data, and then Houdini examines and updates this tree when it runs the simulation. DOP data elements can be DOP objects, geometry, volumes, forces, solvers, etc. The data is arranged in a tree structure, where child nodes are called subdata and are said to be attached to their parent nodes. Under the root of the tree are usually the DOP objects and data describing their relationships. Note that the same piece of data can appear in the tree in multiple locations, with different names. DopData objects thus do not store their name, and the name of a piece of data in the tree is instead stored with its parent data(s). By default, DopData objects store the path within the tree to the data. As a consequence, if the time changes and the solvers within the simulation change the contents of the tree of data, the Python DopData object will update to refer to the simulation’s new state. If the data path no longer refers to valid data, Houdini raises hou.ObjectWasDeleted when you try to access the DopData object from Python. If you do not want the DopData to update with changes to the simulation, you can call hou.DopData.freeze(). freeze returns another DopData object that refers the simulation’s state at the current time, and will not change when the simulation time changes. Each piece of data can contain records, and each record stores a list of name and value pairs called fields. Each record has a name, but it’s possible for multiple records with the same name to exist in the same piece of data. In this case, the record also has an index, and you can think of the records as rows of a spreadsheet. Methods subData() → dict of str to hou.DopData Return a dictionary mapping names to DOP data instances for the subdata attached to this data. # The following code assumes you have created a box from the shelf and used # Rigid Bodies > RBD Object on the shelf to make it a rigid body. >>> obj = hou.node("/obj/AutoDopNetwork").simulation().objects()[0] >>> obj <hou.DopObject box_object1 id 0> >>> obj.recordTypes() ('Basic', 'Options', 'RelInGroup', 'RelInAffectors') >>> record = obj.record("Options") >>> record.fieldNames() ('name', 'groups', 'affectors', 'affectorids', 'objid') >>> record.field("name") 'box_object1' >>> obj.subData().keys() ['PhysicalParms', 'ODE_Body', 'Solver', 'Geometry', 'SolverParms', 'ODE_Geometry', 'Forces', 'Position', 'Colliders'] >>> obj.findSubData("Forces/Gravity_gravity1") <hou.DopData of type SIM_ForceGravity> >>> obj.findSubData("Forces/Gravity_gravity1").options().field("force") <hou.Vector3 [0, -9.80665, 0]> findSubData(data_spec) → hou.DopData or None Return the DOP data with the given name that is attached to this DOP data, or None if no such data exists. Note that the name may also be a slash-separated path to nested subdata. See hou.DopData.subData() for an example. This method can be approximately implemented as follows: def findSubData(self, data_spec): data = self for name in data_spec.split("/"): if name not in data.subData(): return None data = data.subData()[name] return data findAllSubData(data_spec, recurse=False) → dict of str to hou.DopData Given a pattern, return a dictionary mapping subdata paths to DOP data instances for all the subdatas whose name matches the pattern. If recurse is True, all grandchildren subdata will be added to the result. # The following code assumes you have created a box from the shelf and used # Rigid Bodies > RBD Object on the shelf to make it a rigid body. >>> obj = hou.node("/obj/AutoDopNetwork").simulation().objects()[0] >>> obj.findAllSubData("S*").keys() ['SolverParms', 'Solver'] >>> obj.findAllSubData("S*", recurse=True).keys() ['SolverParms', 'Solver/Random', 'SolverParms/ActiveValue', 'Solver'] >>> obj.findAllSubData("S*/*", recurse=True).keys() ['SolverParms/ActiveValue', 'Solver/Random'] freeze() → hou.DopData Return a frozen version of this DopData. Frozen versions of the data will not update when the simulation updates. Instead, they will refer to the state of the simulation at the time they were frozen. It is ok to call this method on a DopData object that is already frozen. isFrozen() → bool Return whether or not this data is frozen. See hou.DopData.freeze() for more information. path() → str Return the path to this object within the tree of DOP data. This path includes the DOP object or relationship as the first part of the path. Note that the same piece of DOP data can exist in multiple places of the tree. The path returned is the path stored inside this Python DopData object, since the Python object uses the path to look up the underlying data each time you call a method on it. Note that the path is only available for unfrozen objects. If you call this method on a frozen DopData object it raises hou.OperationFailed. selectionPath() → str For DopData objects returned from a hou.SceneViewer.selectDynamics() function call, this will return the a string that contains both the path to the DOP Network that created the data, and the path within the DOP data tree which uniquely identifies this DopData. This string is specifically intended to be passed in the prior_selection_paths argument of the hou.SceneViewer selection methods. dataType() → str Return a string describing the type of data this object contains. >>> obj = hou.node("/obj/AutoDopNetwork").simulation().objects()[0] >>> obj.dataType() 'SIM_Object' See also hou.DopData.dataTypeObject. dataTypeObject() → hou.DopDataType or None recordTypes() → tuple of str Return a tuple of strings containing the record types stored inside this DOP data. Each DOP data contains records named "Basic" and "Options", and some types of DOP data contain additional records. record(record_type, record_index=0) → hou.DopRecord Given a record type name return that record, or None if no record exists with that name. If this DOP data contains multiple records with this record type name you can think of each record as a row in a spreadsheet, and record_index determines which one is returned. Use len(self.records(record_type)) to determine how many records of this type are in this DOP data. Use hou.DopData.recordTypes() to get a tuple of record types in a DOP data. See also hou.DopData.records() for an example, and see hou.DopData.options() for a way to easily access the "Options" record. records(record_type) → tuple of hou.DopRecord Return a tuple of all the records of this record type. See also hou.DopData.record(). This example lists the input affectors for a rigid body box that collides with a ground plane: >>> obj = hou.node("/obj/AutoDopNetwork").simulation().objects()[-1] >>> obj.records("RelInAffectors") (<hou.DopRecord of type RelInAffectors index 0>, <hou.DopRecord of type RelInAffectors index 1>) >>> [record.field("relname") for record in obj.records("RelInAffectors")] ['merge1', 'staticsolver1_staticsolver1'] >>> obj.record("RelInAffectors", 1).field("relname") 'staticsolver1_staticsolver1' options() → hou.DopRecord Return the Options record. This method is a shortcut for self.record("Options"). Return the DOP network node containing this DOP data. simulation() → hou.DopSimulation Return the DOP simulation containing this DOP data. This method is a shortcut for self.dopNetNode().simulation(). creator() → hou.DopNode Return the DOP node that created this DOP data inside the DOP network. id() → str Return the globally unique identifier (GUID) for this DOP data. This method is a shortcut for self.record("Basic").field("uniqueid"). If you want an object’s index, hou.DopObject.objid(). >>> obj = hou.node("/obj/AutoDopNetwork").simulation().objects()[0] >>> obj.id() '0xD011E41C-0x000034AE-0x494C12E4-0x000018B9' >>> obj.objid() 0 save(file_path) createSubData(data_name, data_type="SIM_EmptyData", avoid_name_collisions=False) → hou.DopData Create subdata under this data with the specified name and type. You would call this method from a script solver DOP. data_name The name of the new data. Note that this name may contain slashes to create subdata on existing data. data_type Either the name of the data type to create or a hou.DopDataType instance. If you simply want something containing an empty options record, use "SIM_EmptyData".. Use hou.DopData.attachSubData() to create a reference to existing data. See hou.DopData.copyContentsFrom() for an example of how to create a copy of existing data. attachSubData(data, new_data_name, avoid_name_collisions=False) Make existing data become subdata of this data. Houdini does not create a duplicate of the data. Instead, the data’s parent(s) and this data will both refer to the same instance of subdata. You would call this method from a script solver DOP. data The DopData that will become subdata of this data. new_data_name The name of the new subdata.. See hou.DopData.copyContentsFrom() for an example of how to create a copy of existing data. removeSubData(data_spec) Remove subdata with the given name. Raises hou.PermissionError if called from outside a script solver DOP. Raises hou.OperationFailed if data with that name already exists. copyContentsFrom(data) Copy the contents of the given DopData into this one, adapting the data if it is of a different type. You would call this method from a script solver DOP. Raises hou.PermissionError if called from outside a script solver DOP. Use this method along with hou.DopData.createSubData() to copy existing subdata: def copySubData(new_parent_data, data_to_copy, new_data_name, avoid_name_collisions=False): '''Create a copy of data and attach it to other data.''' new_data = new_parent_data.createSubData(new_data_name, data_to_copy.dataType(), avoid_name_collisions) new_data.copyContentsFrom(data_to_copy) return new_data
http://www.sidefx.com/docs/houdini/hom/hou/DopData.html
CC-MAIN-2018-51
refinedweb
1,518
50.94
Solution 1 def convert_pirate_to_dog(pirate_saying): result_in_dog_speak = "" for letter in pirate_saying: result_in_dog_speak += letter result_in_dog_speak += "oo" return result_in_dog_speak Time is over! You can keep submitting you assignments, but they won't compute for the score of this quiz. Convert Pirate to Dog Today we're going to write a function to convert what a pirate would say into the way a dog would say it. Roo roo roo roo! Complete the function convert_pirate_to_dog with a for loop so that it goes through each letter of pirate_saying and then adds 'oo' after each letter. Remember that strings are immutable, so you will have to create a new string for the result of how a dog would sound. Examples: >>> convert_pirate_to_dog("arrrr") 'aoorooroorooroo' Hint: To add letters to the result string, use the += operator.
https://learn.rmotr.com/python/introduction-to-programming-with-python/getting-started/convert-pirate-to-dog
CC-MAIN-2018-47
refinedweb
129
53.31
Your Account by Rick Jelliffe And it is very WS-* centric. More details here: Having co-authored one XML configuration language already, and written an implementation plus test cases (The GGF CDDLM CDL language), I'm not ovewhelmed with SML. If we are staying in the XML space, we could do better with -a simple schema that does not need to be extended by every configuration author. That is, if all you are doing are nested name/value pairs with simple types, then you can use elements with fixed names, values in nested elements, type defined as attributes which can be overwritten on demand. -a way of adding constraints to descriptions (schematron may fit here) -A way of validating your model with meaningful messages Good OSS implementations, with a public test suite. I haven't yet proposed my CDL2 language yet, but I am thinking of something very simple, very RESTy. The alternative would be to bite the bullet and go for RDF in N3 notation, which does open the tooling up quite widely. The actual details of SML are at "The Service Modeling Language (SML) provides a rich set of constructs for creating models of complex IT services and systems. These models typically include information about configuration, deployment, monitoring, policy, health, capacity planning, target operating range, service level agreements, and so on. " : 1. Schemas - these are constraints on the structure and content of the documents in a model. SML uses a profile of XML Schema 1.0 [2,3] as the schema language. SML also defines a set of extensions to XML Schema to support inter-document references. 2. Rules - are Boolean expressions that constrain the structure and content of documents in a model. SML uses a profile of Schematron [4,5,6] and XPath 1.0 [9] for rules." I haven't looked too closely at this, but I see no signs that it is at all "WS-* centric." There is no reference to SOAP or WSDL, and the only reference to any WS-* spec says "An SML reference is a link from one element to another. It can be represented by using a variety of schemes, such as Uniform Resource Identifiers (URIs) [7] and Endpoint References (EPRs) [8]." (reference 8 is to the WS-Addressing spec). "SML supports a conforming profile of Schematron. All elements and attributes are supported." XPath 1 extended by sml namespace elements is used. The little Schematron schemas can appear in complex type declarations and global element declarations. SML is quite interesting too in that they define their own key/uniqueness constraint language: an extended version of the XSD one but allowing cross-document checks. At ISO, DSDL has a part for path-based integrity checks, which has been dormant because we did not see anyone in industry demanding or prototyping anything: I wonder if we at DSDL should cooperate with the SML people and adopt their extended keyref language for DSDL Part ?6?. I had been thinking of adopting a StaX (that nice streaming profile of XML) language, but I didn't get any response from the instifators of StaX. © 2014, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://archive.oreilly.com/pub/post/service_modeling_languagel_wit.html
CC-MAIN-2014-41
refinedweb
545
62.17
This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project. On 7 October 2011 23:24, James Y Knight wrote: > I just noted at (due to > std::list), that it's currently impossible to use any C++11-compiled code > in a program which also uses any C++98 code, even if the two pieces of > code never actually touch each other or share objects. I think that's overstating the case. There are some incompatiblities in the standard library, but there's no problem linking e.g. int f() { return 0; } and int f(); int g() { return f(); } So it's not true that it's "impossible" to link "any" code using the two modes. > (Presumably std::string will be made > non-refcounting soon to be C++11-conformant, breaking interoperability > much more.) Yes, std::string will be made non-reference counting at some point, but as a non-reference-counted string is valid in C++98 as well, one option would be to switch to a non-ref-counted string for both -std=c++98 and -std=c++11 modes. I'm not saying that's what will happen, but it could be. The same is true of an O(1) std::list::size(). For the next major ABI change we could switch c++98 mode to use a non-ref-counted string and O(1) list::size. Currently we aren't changing string or list in c++98 mode, because that would break code. But we are changing it for c++0x mode, because people want the C++11 semantics. Breaking things for people using the experimental c++0x mode is less catastrophic, as noone is forced to use that mode and noone has years of existing code relying on its semantics. > * Will STL-using Standard Library, not STL, please. > code compiled with -std=c++98 and -std=c++11 remain > incompatible forever, or only until it's no longer experimental? I don't think it's been settled, but as I said above, there are ways to change both modes at once. Currently we can't do that > * If so, will version namespaces be used to give c++98 std::* and c++11 > std::* non-conflicting symbols eventually, so that at least the same > program can load two shared libs that only use the STL internally and not > in their interfaces? Maybe. Or symbol versioning. > * For that matter, are the c++98 and c++11 languages even link-compatible > without STL? Is the incompatibility only due to the #ifdefs in the STL > headers or is it more fundamental than that? The basic ABI hasn't changed, the differences are because the standard library code is different in c++0x mode (e.g. functions take different parameter types), not because the compiler does different things when compiling it. > * How are binary linux distributions expected to support c++11 programs? > (in that they'll need to eventually provide shared libraries to link > against which a c++11-compiled binary can use). > > It seems to me that it can't be done like previous ABI transitions (just > recompile the whole world with the new ABI, boom done), since C++11 is not > source compatible with c++98. > > So should a distro compile two copies of all C++ libraries, one for C++11 > and one for C++98? Then, I suppose people will have to change e.g. > "-lPocoNet" to "-lPocoNetCXX11" in their link lines? Or maybe ld/gcc will > be modified to automatically choose a different library search path, based > on the compilation mode? Having separate libs is a posibility, but it might make more sense to have a single lib with versioned symbols. > Or will there be a giant flag day after most projects compile can compile > in both c++11 and c++98, where c++98 support is removed, and everything is > compiled in c++11 from then on? (but then, how would we get there: all > developers would have to compile their entire dependent set of libraries > from scratch themselves to test their code, I guess.) Not going to happen. > I hope the experts here have a better idea of how this is all going to > work that I do. IMO it would be best if if the new ABI could be enabled > separately from the C++11 language, so that you *could* compile everything > with the new ABI, and have c++98 and c++11 code?interoperate. But I have > no clue if that's even remotely feasible. The current ABI changes are caused by C++11 requirements on the library, so I don't see how that's possible.
http://gcc.gnu.org/ml/gcc/2011-10/msg00115.html
CC-MAIN-2016-07
refinedweb
782
69.82
I'm attempting to convert a Matrix4x4 which is being currently being applied to a camera using camera.worldToCameraMatrix and works fine. I'm able to get the position out with: Vector4 newCameraPos = matrix.GetColumn(3); Camera.main.transform.position = Vector3(newCameraPos.x,newCameraPos.y,newCameraPos.z); But at the moment can't get the quaternion to come out. I've pulled some code from a matrix and quaternion FAQ I stumbled across and have partially implemented, but at the moment its not behaving. Quaternion matrixToQuaternionx(Matrix4x4 m1){ float T = 1 + m1[0] + m1[5] + m1[10];; } If I turn off the camera.worldToCameraMatrix, and rely on the Vector and Quaternion I get out (ignoring cases where it gets to the 'more to calculate here') the position of the camera looks fine, but its rotation is way off. Answer by runevision · Feb 11, 2010 at 11:08 AM For getting a quaternion from a Matrix4x4, this function works:; } For getting the position, GetColumn(3) works fine. Thanks! It should be noted that if you're attempting to convert a valid worldToCameraMatrix to a quaternion rotation you'll need to adjust for the reversed z on camera and call something like: Camera.main.transform.rotation = Quaternion.QuaternionFromMatrix(matrixToSet.inverse * Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1,1,-1))); such a great solution, thank you Rune! What about the inverse operation? Obtaining a 4x4 out of a quaternion. Is that possible? @roamcel (or anyone else reading this more realistically) You can in fact get the reverse (4x4mat from a quat). The following is python code I wrote so it shouldn't be too hard to read and write in your preferred language: from math import * q = (0, 1.87, 3.22, 6.43) q2 = [0,0,0,0] q2[0] = q[0] / sqrt(q[0]**2 + q[1]**2 + q[2]**2 + q[3]**2) q2[1] = q[1] / sqrt(q[0]**2 + q[1]**2 + q[2]**2 + q[3]**2) q2[2] = q[2] / sqrt(q[0]**2 + q[1]**2 + q[2]**2 + q[3]**2) q2[3] = q[3] / sqrt(q[0]**2 + q[1]**2 + q[2]**2 + q[3]**2) print q2, "\n" quat_Matrix = [ [1 - 2*q2[2]**2 - 2*q2[3]**2, 2*q2[1]*q2[2] - 2*q2[3]*q2[0], 2*q2[1]*q2[3] + 2*q2[2]*q2[0]], [2*q2[1]*q2[2] + 2*q2[3]*q2[0], 1 - 2*q2[1]**2 - 2*q2[3]**2, 2*q2[2]*q2[3] - 2*q2[1]*q2[0]], [2*q2[1]*q2[3] - 2*q2[2]*q2[0], 2*q2[2]*q2[3] + 2*q2[1]*q2[0], 1 - 2*q2[1]**2 - 2*q2[2]**2] ] for i in quat_Matrix: print i @roamcel @JoryRFerrell Unity provides a nice easy way: Matrix4x4 m = Matrix4x4.TRS(Vector3.zero, quaterion, Vector3.one); As for matrix decomposition (the question subject) here is the approach which I use: Answer by Leto · May 21, 2012 at 09:50 AM Here's a faster and easier solution: public static Quaternion QuaternionFromMatrix(Matrix4x4 m) { return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1)); } Answer by peacefulshade · Jul 25, 2012 at 01:08 AM Actually I can confirm that the "For getting a quaternion from a Matrix4x4, this function works: ..." "For getting a quaternion from a Matrix4x4, this function works: ..." Doesn't work, and the "Here's a faster and easier solution: ..." "Here's a faster and easier solution: ..." Works. I'm making a voxel engine that performs all sorts of transforms and the first method produces: While the second función produces And the control test uses Graphics.DrawMesh() with the matrix transform as a parameter. Click to move 1 Answer Rotate an Object by a spezific value 2 Answers Calculate Quaternion.LookRotation manually 1 Answer Rotation math problem 1 Answer Need help to get 3D rotation from 2 points in space 1 Answer
http://answers.unity3d.com/questions/11363/converting-matrix4x4-to-quaternion-vector3.html
CC-MAIN-2015-35
refinedweb
656
52.7
Opened 8 years ago Closed 3 years ago #11264 closed Bug (invalid) "from django.db import models" clobbered in functions inside __init__.py of installed apps Description (last modified by ) If an app myapp has the following __init__.py: from django.db import models def myfunc(): assert models.__package__ == 'django.db.models', ( 'models is %r instead of django.db.models' % models) then calling myapp.myfunc() throws: AssertionError: models is <module 'myapp.models' from 'myapp/models.pyc'> instead of django.db.models This happens only if myappis in INSTALLED_APPS myfuncis in myapp/__init__.py, not some other module in it - Django is r10088 or later (thanks, git bisect) This breaks at least Satchmo from a few months back for me, probably trunk too. r10088 claims to have fixed all dynamic imports in Django by backporting importlib from Python 2.7. Attachments (1) Change History (10) Changed 8 years ago by comment:1 Changed 8 years ago by comment:2 Changed 8 years ago by comment:3 Changed 8 years ago by Some extra debug: If your test case invokes import myapp myapp.myfunc() or import myapp from myapp import model myapp.myfunc() everything works as expected. It's only when you run import myapp from myapp.models import * myapp.myfunc() that you get a problem. comment:4 Changed 7 years ago by comment:5 Changed 6 years ago by comment:6 Changed 6 years ago by comment:7 Changed 4 years ago by This bug still exists in master. After adjusting settings.py and manage.py for Django 1.6 in the test project, I was able to reproduce it: >>> import models_clobber_test_app >>> models_clobber_test_app.assert_models_package() Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/myk/Documents/dev/django/models_clobber_test_project/models_clobber_test_app/__init__.py", line 11, in assert_models_package 'models is %r instead of django.db.models' % models) AssertionError: models is <module 'models_clobber_test_app.models' from '/Users/myk/Documents/dev/django/models_clobber_test_project/models_clobber_test_app/models.py'> instead of django.db.models comment:8 Changed 4 years ago by comment:9 Changed 3 years ago by It turns out that this has nothing to do with Django. This surprising behavior can be reproduced with plain Python modules. % cat foo/__init__.py bar = 42 def print_bar(): print(bar) % cat foo/bar.py # Empty module. % python >>> from foo import print_bar >>> print_bar() 42 >>> import foo.bar >>> print_bar() <module 'foo.bar' from 'foo/bar.py'> a minimal test project to reproduce "models" clobbering
https://code.djangoproject.com/ticket/11264
CC-MAIN-2017-34
refinedweb
405
53.68
2011-07-27 21:29:08 8 Comments When I make an SSL connection with some IRC servers (but not others - presumably due to the server's preferred encryption method) I get the following exception: Caused by: java.lang.RuntimeException: Could not generate DH keypair at com.sun.net.ssl.internal.ssl.DHCrypt.<init>(DHCrypt.java:106) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverKeyExchange(ClientHandshaker.java:556) at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:183):893) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1165) ... 3 more Final cause::100) ... 10 more An example of a server that demonstrates this problem is aperture.esper.net:6697 (this is an IRC server). An example of a server that does not demonstrate the problem is kornbluth.freenode.net:6697. [Not surprisingly, all servers on each network share the same respective behaviour.] My code (which as noted does work when connecting to some SSL servers) is: SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); s = (SSLSocket)sslContext.getSocketFactory().createSocket(); s.connect(new InetSocketAddress(host, port), timeout); s.setSoTimeout(0); ((SSLSocket)s).startHandshake(); It's that last startHandshake that throws the exception. And yes there is some magic going on with the 'trustAllCerts'; that code forces the SSL system not to validate certs. (So... not a cert problem.) Obviously one possibility is that esper's server is misconfigured, but I searched and didn't find any other references to people having problems with esper's SSL ports, and 'openssl' connects to it (see below). So I'm wondering if this is a limitation of Java default SSL support, or something. Any suggestions? Here's what happens when I connect to aperture.esper.net 6697 using 'openssl' from commandline: ~ $ openssl s_client -connect aperture.esper.net:6697 CONNECTED(00000003) depth=0 /C=GB/ST=England/L=London/O=EsperNet/OU=aperture.esper.net/CN=*.esper.net/[email protected] verify error:num=18:self signed certificate verify return:1 depth=0 /C=GB/ST=England/L=London/O=EsperNet/OU=aperture.esper.net/CN=*.esper.net/[email protected] verify return:1 --- Certificate chain 0 s:/C=GB/ST=England/L=London/O=EsperNet/OU=aperture.esper.net/CN=*.esper.net/[email protected] i:/C=GB/ST=England/L=London/O=EsperNet/OU=aperture.esper.net/CN=*.esper.net/[email protected] --- Server certificate -----BEGIN CERTIFICATE----- [There was a certificate here, but I deleted it to save space] -----END CERTIFICATE----- subject=/C=GB/ST=England/L=London/O=EsperNet/OU=aperture.esper.net/CN=*.esper.net/[email protected] issuer=/C=GB/ST=England/L=London/O=EsperNet/OU=aperture.esper.net/CN=*.esper.net/[email protected] --- No client certificate CA names sent --- SSL handshake has read 2178 bytes and written 468: 51F1D40A1B044700365D3BD1C61ABC745FB0C347A334E1410946DCB5EFE37AFD Session-ID-ctx: Master-Key: DF8194F6A60B073E049C87284856B5561476315145B55E35811028C4D97F77696F676DB019BB6E271E9965F289A99083 Key-Arg : None Start Time: 1311801833 Timeout : 300 (sec) Verify return code: 18 (self signed certificate) --- As noted, after all that, it does connect successfully which is more than you can say for my Java app. Should it be relevant, I'm using OS X 10.6.8, Java version 1.6.0_26. Related Questions Sponsored Content 0 Answered Questions Capturing client/server TLS version in Python requests - 2017-10-02 19:02:37 - PalePal - 172 View - 2 Score - 0 Answer - Tags: python ssl python-requests 13 Answered Questions [SOLVED] Why does Java have transient fields? 8 Answered Questions [SOLVED] Why is subtracting these two times (in 1927) giving a strange result? 28 Answered Questions [SOLVED] SSL certificate rejected trying to access GitHub over HTTPS behind firewall - 2010-09-23 09:41:46 - oharab - 536375 View - 366 Score - 28 Answer - Tags: git ssl github cygwin ssl-certificate 2 Answered Questions [SOLVED] Why don't Node.js TLS supported ciphers correspond to the openssl supported ciphers? - 2014-01-21 08:01:47 - Ming-Chih Kao - 1467 View - 3 Score - 2 Answer - Tags: node.js security ssl encryption openssl 0 Answered Questions Is ssl_dhparam necessary for nginx when client use the cipher DHE-RSA-AES256-SHA256 - 2017-09-28 08:02:32 - Y.Tian - 357 View - 0 Score - 0 Answer - Tags: ssl nginx encryption 14 Answered Questions [SOLVED] Why does this code using random strings print "hello world"? 0 Answered Questions MySQL - SSL - with TLS1.2 cipher AES256-SHA256 / DHE-RSA-AES256-SHA256 1 Answered Questions [SOLVED] Some clients accept SSL cert; others reject it - 2014-08-10 02:22:32 - Paul Draper - 6355 View - 6 Score - 1 Answer - Tags: ssl https ssl-certificate @Sam 2018-08-08 19:33:51 Recently I have the same issue and after upgrading jdk version from 1.6.0_45 to jdk1.7.0_191 which resolved the issue. @Jose Antonio Sánchez Pujante 2018-03-22 09:03:54 It is possible that you have incorrect Maven dependencies. You must find these libraries in Maven dependency hierarchy: If you have these dependencies that is the error, and you should do this: Add the dependency: Exclude these dependencies from the artifact that included the wrong dependencies, in my case it is: @David Guyon 2018-03-22 09:20:47 The question already received many answers and has one validated answer. Moreover the question has been asked more than 6 years ago. I'm not sure if it's still relevant. @Vivin Paliath 2011-07-27 22:39:41 The problem is the prime size. The maximum-acceptable size that Java accepts is 1024 bits. This is a known issue (see JDK-6521495). The bug report that I linked to mentions a workaround using BouncyCastle's JCE implementation. Hopefully that should work for you. UPDATE This was reported as bug JDK-7044060 and fixed recently. Note, however, that the limit was only raised to 2048 bit. For sizes > 2048 bit, there is JDK-8072452 - Remove the maximum prime size of DH Keys; the fix appears to be for 9. @Paŭlo Ebermann 2011-07-27 22:56:05 +1. Everyone who has a Sun Developer Network Account, please vote for this bug. @sam 2011-07-28 16:23:53 Thanks. Seems a pretty serious problem given the existence of servers which request a larger size! :( I tried BouncyCastle; if you set it up as preferred provider it crashes with a different exception (sigh), and I can't see an obvious way to use that just for DH. However, I found an alternative solution, which I'll add as a new answer. (It's not pretty.) @N.. 2013-08-26 05:20:56 Cool. This has been fixed in newer versions of Java. But my question is about using older version.. When I use older version, sometimes it works and sometimes it gives above exception..Why so random behaviour? If its a bug in java, then I guess it should never work? @mjj1409 2015-03-20 21:52:35 The BouncyCastle's JCE provider implementation worked for me @bebbo 2015-05-16 20:06:38 This has not been fixed. The limit was changed from 1024 to 2048. Thus a prime size > 2048 yields the same error @fuzzyTew 2015-06-30 22:19:10 The 2048 fix was backported to IcedTea 2.5.3 . Newer versions of IcedTea increased it to 4096. @ajon 2015-07-03 17:31:37 When I updated Java on the machine, this issue went away. @samy 2015-08-17 10:40:47 Is it also fixed for 4096bit keys with java 1.8.0_51 on Ubuntu 14.04? Because I'm getting the same error while trying to connect to a server. @sleske 2016-02-09 16:05:10 @bebbo: Correct. Support for primes > 2048 bit was requested in JDK-8072452 - Remove the maximum prime size of DH Keys. @bebbo 2016-02-09 17:19:10 @sleske: A request does not mean it has already been changed. Such a limitation is simply superfluous. Right now it's not available. @user1332994 2016-05-15 04:36:46 The problem is the DH prime size. The maximum-acceptable size that Java accepts is 2048 bits. While we wait for Oracle to expand the limit, you can compile with Excelsior Jet which has an expanded limit. @plugwash 2017-06-02 15:21:53 @N it depends on the server configuration. The bug only manifests if the server chooses a DHE ciphersuite and then sends a prime that the client considers too large. It is seen less often with Java 7 than Java 6 because Java 7 supports ECDHE and most server's preffer ECDHE over DHE. @Saheed 2017-03-16 16:25:46 I encountered the SSL error on a CentOS server running JDK 6. My plan was to install a higher JDK version (JDK 7) to co-exist with JDK 6 but it turns out that merely installing the newer JDK with rpm -iwas not enough. The JDK 7 installation would only succeed with the rpm -Uupgrade option as illustrated below. 1. Download JDK 7 2. RPM installation fails 3. RPM upgrade succeeds 4. Confirm the new version @covener 2017-01-07 17:00:45 I used to get a similar error accessing svn.apache.org with java SVN clients using an IBM JDK. Currently, svn.apache.org users the clients cipher preferences. After running just once with a packet capture / javax.net.debug=ALL I was able to blacklist just a single DHE cipher and things work for me (ECDHE is negotiated instead). A nice quick fix when it is not easy to change the client. @Raffael Meier 2017-01-05 16:28:13 I use coldfusion 8 on JDK 1.6.45 and had problems with giving me just red crosses instead of images, and also with cfhttp not able to connect to the local webserver with ssl. my test script to reproduce with coldfusion 8 was this gave me the quite generic error of " I/O Exception: peer not authenticated." I then tried to add certificates of the server including root and intermediate certificates to the java keystore and also the coldfusion keystore, but nothing helped. then I debugged the problem with and got and I then had the idea that the webserver (apache in my case) had very modern ciphers for ssl and is quite restrictive (qualys score a+) and uses strong diffie hellmann keys with more than 1024 bits. obviously, coldfusion and java jdk 1.6.45 can not manage this. Next step in the odysee was to think of installing an alternative security provider for java, and I decided for bouncy castle. see also I then downloaded the from and installed it under C:\jdk6_45\jre\lib\ext or where ever your jdk is, in original install of coldfusion 8 it would be under C:\JRun4\jre\lib\ext but I use a newer jdk (1.6.45) located outside the coldfusion directory. it is very important to put the bcprov-ext-jdk15on-156.jar in the \ext directory (this cost me about two hours and some hair ;-) then I edited the file C:\jdk6_45\jre\lib\security\java.security (with wordpad not with editor.exe!) and put in one line for the new provider. afterwards the list looked like (see the new one in position 1) then restart coldfusion service completely. you can then and enjoy the feeling... and of course what a night and what a day. Hopefully this will help (partially or fully) to someone out there. if you have questions, just mail me at info ... (domain above). @Evgeny Lebedev 2016-12-05 07:59:02 I've got this error with Bamboo 5.7 + Gradle project + Apache. Gradle tried to get some dependencies from one of our servers via SSL. Solution: with OpenSSL: example output: Append output to certificate file (for Apache - SSLCertificateFileparam) Restart apache Restart Bamboo Try to build project again @rico-chango 2016-10-18 20:17:07 For me, the following command line fixed the issue: java -jar -Dhttps.protocols=TLSv1.2 -Ddeployment.security.TLSv1.2=true -Djavax.net.debug=ssl:handshake XXXXX.jar I am using JDK 1.7.0_79 @Ramgau 2017-03-02 03:16:10 I faced same situation using JDK 1.7.0_xx. BY default issue will be solved after using jdk 1.8. But sometime we can not upgrade jdk quickly. So my issue solved after adding system configuration: System.setProperty("https.protocols", "TLSv1.2"); System.setProperty("deployment.security.TLSv1.2", "true"); @v.ladynev 2015-11-21 17:11:15 I have the same problem with Yandex Maps server, JDK 1.6 and Apache HttpClient 4.2.1. The error was with enabled debug by -Djavax.net.debug=allthere was a message in a log I have fixed this problem by adding BouncyCastle library bcprov-jdk16-1.46.jarand registering a provider in a map service class A provider is registered at the first usage of MapService. @comeOnGetIt 2016-04-28 20:05:05 Where did you write this static block of code ? @v.ladynev 2016-04-29 06:07:58 @comeOnGetIt I update my answer. @anre 2016-06-01 15:08:47 Solved the problem by upgrading to JDK 8. @mjj1409 2015-03-20 22:12:34 The "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" answer did not work for me but The BouncyCastle's JCE provider suggestion did. Here are the steps I took using Java 1.6.0_65-b14-462 on Mac OSC 10.7.5 1) Download these jars: bcprov-jdk15on-154.jar bcprov-ext-jdk15on-154.jar 2) move these jars to $JAVA_HOME/lib/ext 3) edit $JAVA_HOME/lib/security/java.security as follows: security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider restart app using JRE and give it a try @DiveInto 2015-04-27 01:37:40 works for me! though not quite sure what I am doing. @TinusSky 2015-07-07 13:42:31 security.provider.2=org.bouncycastle.jce.provider.BouncyCastleProvider did work better, putting it on 1. resulted in errors in default software. @v.ladynev 2015-11-22 09:19:56 This works for me too, but I have added a provider dynamically. Reffer my answer here for details. @Majid 2017-04-27 10:21:31 Thanks it works on java 1.6 @phillipuniverse 2017-05-26 20:43:05 Thanks a ton, this worked for me and was required in order to successfully build the Tomcat 7.0.78 source. @Peter Azuka Molokwu 2016-04-05 16:20:42 We got the same exact exception error returned, to fix it was easy after hours surfing the internet. We downloaded the highest version of jdk we could find on oracle.com, installed it and pointed Jboss application server to the directory of the installed new jdk. Restarted Jboss, reprocessed, problemo fixed!!! @pka 2015-11-14 18:57:58 If you are still bitten by this issue AND you are using Apache httpd v> 2.4.7, try this: copied from the url: command. Alternatively, you can use the following standard 1024-bit DH parameters from RFC 2409, section 6.2: Add the custom parameters including the "BEGIN DH PARAMETERS" and "END DH PARAMETERS" lines to the end of the first certificate file you have configured using the SSLCertificateFile directive. I am using java 1.6 on client side, and it solved my issue. I didn't lowered the cipher suites or like, but added a custom generated DH param to the cert file.. @plugwash 2017-06-02 15:39:40 Be aware that it is now believed that 1024 bit DH is computationally feasible (though hellishly expensive) to break. @Tor 2015-07-10 07:44:48 You can disable DHE completely in your jdk, edit jre/lib/security/java.security and make sure DHE is disabled, eg. like jdk.tls.disabledAlgorithms=SSLv3, DHE. @Abhiram mishra 2016-04-19 07:09:49 It did not work for me. I am using java 1.6.0_33 @hoangthienan 2016-06-27 01:19:33 that is only available in JDK 1.7 and later. link @MrSmith42 2018-02-12 15:52:04 Solved the problem for me JDK 1.8.0_144-b01 @Jason Martin 2015-07-01 23:33:36 If the server supports a cipher that does not include DH, you can force the client to select that cipher and avoid the DH error. Such as: Keep in mind that specifying an exact cipher is prone to breakage in the long run. @angelcorral 2015-05-07 12:44:48 You can installing the provider dynamically: 1) Download these jars: bcprov-jdk15on-152.jar bcprov-ext-jdk15on-152.jar 2) Copy jars to WEB-INF/lib(or your classpath) 3) Add provider dynamically: import org.bouncycastle.jce.provider.BouncyCastleProvider; ... Security.addProvider(new BouncyCastleProvider()); @ishanbakshi 2016-01-04 03:33:34 This solution works well, and was a good fit for my case since I wanted to make the changes only at the project level and not at the server/environment level. Thanks @Raphael Roth 2016-03-23 07:41:24 does not work for me @Japheth Ongeri - inkalimeva 2016-11-11 12:19:14 Thanks! this worked for me. In my case it was itext importing bcp 1.4 causing emails to google to fail. @Hadi Momenzadeh 2017-05-23 07:29:00 Tnx, it worked for mee too. :) @Bertl 2014-11-19 17:08:12 This is a quite old post, but if you use Apache HTTPD, you can limit the DH size. See @Zsozso 2013-08-15 13:47:50 Here is my solution (java 1.6), also would be interested why I had to do this: I noticed from the javax.security.debug=ssl, that sometimes the used cipher suite is TLS_DHE_... and sometime it is TLS_ECDHE_.... The later would happen if I added BouncyCastle. If TLS_ECDHE_ was selected, MOST OF the time it worked, but not ALWAYS, so adding even BouncyCastle provider was unreliable (failed with same error, every other time or so). I guess somewhere in the Sun SSL implementation sometimes it choose DHE, sometimes it choose ECDHE. So the solution posted here relies on removing TLS_DHE_ ciphers completely. NOTE: BouncyCastle is NOT required for the solution. So create the server certification file by: Save this as it will be referenced later, than here is the solution for an SSL http get, excluding the TLS_DHE_ cipher suites. Finally here is how it is used (certFilePath if the path of the certificate saved from openssl): @Ludovic Guillaume 2015-08-10 11:16:16 Just tested your solution. It's working as intended. Thanks. Actually, just adding jdk.tls.disabledAlgorithms=DHE, ECDHEin JDK_HOME/jre/lib/security/java.securityalso works and avoid all this code. @stephan f 2015-10-26 13:46:01 Just disabling DHE worked for me: jdk.tls.disabledAlgorithms=DHE. Using 1.7.0_85-b15. @Eric Na 2016-01-12 19:11:06 Added jdk.tls.disabledAlgorithms=DHE, ECDHE in JDK_HOME/jre/lib/security/java.security and worked fine! Thank you! Using 1.7.0_79 @kubanczyk 2016-06-08 13:36:19 Don't disable ECDHE. It's different than DHE and does not even use prime numbers. @user1172490 2016-11-22 23:00:34 Can someone please tell me how i can get the 'certFilePath'. I've been stuck on this for a week. @Zsozso @Lekkie 2013-05-22 08:29:27 If you are using jdk1.7.0_04, upgrade to jdk1.7.0_21. The problem has been fixed in that update. @user2666524 2013-08-19 23:40:11 I just downloaded Java SE Development Kit 7u25, and according to the little program I wrote to determine the maximum supported DH size, it's still 1024. @Sébastien Vanmechelen 2015-07-30 15:43:42 Problem still exists with JDK 1.7.0_25 @Elazaron 2015-08-25 09:07:17 updating jre worked for me .had 6.22 updated to 7.59 . problem solved. @Shashank 2015-10-05 02:29:32 I am using JDK 1.7.0_79. Doesn't work for me @dgoverde 2016-02-17 03:37:30 @Shashank - Upgrading to JDK 1.8.0_73 worked for me. @mjomble 2011-11-17 21:02:40 Try downloading "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" from the Java download site and replacing the files in your JRE. This worked for me and I didn't even need to use BouncyCastle - the standard Sun JCE was able to connect to the server. PS. I got the same error (ArrayIndexOutOfBoundsException: 64) when I tried using BouncyCastle before changing the policy files, so it seems our situation is very similar. @clevertension 2014-12-17 01:51:52 it can't be work in my env when i replace the files from JCE @Joerg 2015-03-16 17:17:20 have you done anyhting else? or just copied the 2 files into the folder? @mjomble 2015-03-16 20:57:09 It's been a while but as far as I remember, that was all I needed to do. Apart from restarting any running Java processes afterwards. @Peter Šály 2018-09-06 10:07:09 Does not work for me. @sam 2011-07-28 16:30:49 The answer above is correct, but in terms of the workaround, I had problems with the BouncyCastle implementation when I set it as preferred provider:. Then, supposing the server supports an alternative algorithm, it will be selecting during normal negotiation. Obviously the downside of this is that if somebody somehow manages to find a server that only supports Diffie-Hellman at 1024 bits or less then this actually means it will not work where it used to work before. Here is code which works given an SSLSocket (before you connect it): Nasty. @Vivin Paliath 2011-07-28 16:38:47 Sad that this is the only way :(. That ticket has been open since '07. Strange that nothing has been done about it in 4 years. @Shashank 2015-10-05 02:28:43 I am new to java securities. Please help where should I write this piece of code? @Gianluca Greco 2016-02-16 11:06:29 I tried every solution in this thread and this was the only one that worked with my ibm jvm (ibm-java-s390x-60).
https://tutel.me/c/programming/questions/6851461/why+does+ssl+handshake+give+39could+not+generate+dh+keypair39+exception
CC-MAIN-2018-39
refinedweb
3,711
66.84
You're enrolled in our new beta rewards program. Join our group to get the inside scoop and share your feedback.Join group Join the community to find out what other Atlassian users are discussing, debating and creating. I am using JIRA Cloud REST API to create an Epic issue. Just to be clear customfield_10011 is actually "Epic Name" field. Here's code snippet I am using to create Epic : def createDoc = [ fields: [ description: "NOT SPECIFIED", "customfield_10011" : "HGHGH", project: [ id: 10255 ], issuetype: [ id: EpicTypeId ], summary: "Epic Summary" ] ] def resp = post("/rest/api/2/issue") .header("Content-Type", "application/json") .body(createDoc) .asObject(Map) With this I am getting an error as : { "errorMessages": [], "errors": { "customfield_10011": "Field 'customfield_10011' cannot be set. It is not on the appropriate screen, or unknown." } } Also, When I try to update "customfield_10011" on existing epic, it works from REST API. FYI, I already have added the field added on screen. (In fact I am using same screen to create, edit and view Epic) Any suggestion/help appreciated. Thanks and Regards, Sameer B Hello @Sameer Bhangale When you update an Epic, the edit screen is used. When you create an Epic, the create screen is used; the two screens are not the same. Double check that you can create an Epic via the web interface in that project, and that the Name and Summary fields are there on the create screen, like this: If you have already double checked that the Name and Summary fields are on the Create screen and that one screen is used for creating, editing and viewing an Epic, then it might be a coding issue in the body of the request. Try removing the inverted commas around the field definition, like this: fields: [ description: "The Epic Description", customfield_10011: "The Epic Name", summary: "The Epic Summary", project: [ id: 10255 ], issuetype: [ name: "Epic" ] ] Try referring to the issueType by its name 'Epic' not by its ID, as show above, just in case you're using the wrong ID. @David Bakkers Thank You for helping. Actually I was getting wrong issue type id for epic. Corrected it and now it is working. Thanks and Regards, Sameer B. You may have the field on the issues "edit" screen, but the error message is clear - you do not have it on the "create" screen. This can also happen if you do not have permission to create issues, the REST API can report missing fields instead of "no create.
https://community.atlassian.com/t5/Adaptavist-questions/Field-customfield-10011-cannot-be-set-It-is-not-on-the/qaq-p/1672153
CC-MAIN-2021-21
refinedweb
410
69.21
Ted Neward Ever spent much time thinking about time? Very early in my career, I was working on a system that ended up deploying to several different call centers. Keeping track of “when” an event occurred was particularly important (it was a medical-related system for a call center of nurses), and so, without thinking about it too much, we dutifully wrote the time of the event into a database row and left it at that. Except, as we discovered later, when the system was deployed to four different call centers, each in a different U.S. time zone, the time logs were all a little “off,” thanks to the fact that we hadn’t thought to include time-zone offsets. Time in a software system is like that—it all seems pretty straightforward and simple, until it suddenly doesn’t anymore. In keeping with the theme of my past two columns (all my columns can be found at bit.ly/ghMsco), once again the .NET community benefits from work done by the Java community; in this case, it’s a package called “Noda Time,” a Microsoft .NET Framework port of the Java “Joda Time” project, which itself was designed as a replacement for the Java “Date” class (a horribly broken piece of software dating back to the days of Java 1.0). Jon Skeet, the author of Noda Time, based it on the algorithms and concepts in Joda Time, but built it from the ground up as a .NET library. Enough preamble: Do an “Install-Package NodaTime” (notice no space between “Noda” and “Time”), and let’s look at some code. The first thing to realize is that, with all due respect to Einstein’s theories, you don’t have to be approaching light speed to realize that time is relative. If it’s 7 p.m. (that’s 1900 to you European folks) here in Seattle, then it’s 7 p.m. for all of us in Seattle, but it’s 8 p.m. for my folks in Salt Lake City, 9 p.m. for my travel agent in Dallas and 10 p.m. for my drinking buddy in Boston. We all get that—that’s the magic of time zones. But my computer doesn’t really understand time zones, per se—it reports the time it’s been set to, which in this case is 7 p.m., despite the fact that it’s the exact same moment in time for all of us around the world. In other words, it’s not that time itself is relative, it’s that our representation of time is relative. In Noda Time, this representation is reflected as “global” time, meaning a moment on a universal timeline with which everyone agrees. What we consider to be “local” time—that is, that time with an associated time zone—Noda Time calls “zoned time,” as opposed to what Noda Time considers “local” time, which is without any time zone attached (more on this later). So, for example, the Noda Time “Instant” refers to a point on the global timeline, with an origin point of midnight on Jan. 1, 1970, Coordinated Universal Time (UTC). (There’s nothing magical about that date, except that this is by convention the “start of the epoch” for Unix systems counting “ticks” since that date, and thus serves as good a reference origin point as any other.) So, doing this gives us the current Instant (assuming that the Noda Time namespace is referenced—“using NodaTime”—of course): var now = SystemClock.Instance.Now; To get a Seattle-relative time, we want a ZonedDateTime. This is essentially an Instant, but with the time zone information included, so that it identifies itself as being relative to “Seattle, on Jan. 9, 2013” (the date being important because we need to know whether we’re in daylight saving time [DST] or not). A ZonedDateTime is obtained through a constructor, passing in an Instant and a DateTime zone. We have the Instant, but we need the DateTime zone for Seattle in DST. To obtain the DateTime zone, we need an IDateTime zoneProvider. (The reason for this indirection is subtle, but has to do with the fact that the .NET Framework uses a representation for time zones different from any other programming platform; the Internet Assigned Names Authority, or IANA, uses a format like “America/Los_Angeles.”) Noda Time offers two built-in providers, one being the IANA version and the other the standard .NET base class library (BCL) version, through static properties on the DateTime zoneProviders class: var seattleTZ = dtzi["America/Vancouver"]; var dtzi = DateTime zoneProviders.Tzdb; The time zone database (TZDB) version is the IANA version, and so obtaining the time zone that represents Seattle is a matter of selecting it (which, according to IANA, is “America/Los_Angeles,” or if you want something closer, “America/Vancouver”): var seattleNow = new ZonedDateTime(now, seattleTZ); And if we print this out, we get a representation of “Local: 1/9/2013 7:54:16 PM Offset: -08 Zone: America/Vancouver.” Notice that “Offset” portion in the representation? It’s important, because remember that based on what day of the year it is (and what country you’re in, and what calendar you’re operating under, and ...), the offset from UTC will change. For those of us in Seattle, DST means gaining or losing an hour off the local clock, so it’s important to note what the offset from UTC is. In fact, Noda Time keeps track of that separately, because when parsing a date such as “2012-06-26T20:41:00+01:00,” for example, we know that it was one hour ahead of UTC, but we don’t know if that was because of DST in that particular time zone or not. Still think time is easy? Now let’s assume that I want to know how long until an important date in my life—such as my 25th wedding anniversary, which will be on Jan. 16, 2018. (Keeping track of such things is somewhat important, as I think any spouse would tell you, and I need to know how long I have before I have to buy a really expensive gift.) This is where Noda Time is really going to shine, because it’s going to keep track of all the niggling little details for you. First, I need to construct a LocalDateTime (or, if I didn’t care about the time, a LocalDate; or, if I didn’t care about the date, a LocalTime). A LocalDateTime (or LocalDate or LocalTime) is a relative position on the timeline that doesn’t know exactly what it’s relative to—in other words, it’s a point in time without knowing its time zone. (Despite not knowing the time zone, this is still a useful bit of information. Think of it like this: If you and I are working together in the same office, and we want to meet later today, I’ll say, “Let’s meet at 4 p.m.” Because we’re both in the same time zone, no additional information is necessary to qualify this time unambiguously to each other.) So, because I know the point in time that I care about already, it’s easy to construct: var twentyFifth = new LocalDate(2018, 1, 16); And because I’m just asking about the difference of two dates without concern for the time zones, I only need the LocalDate part of the LocalDateTime part of the ZonedDateTime from my earlier calculation: var today = seattleNow.LocalDateTime.Date; But what we’re asking here is for a new kind of time unit: a “period” between two times. (In the BCL, this is a Duration.) Noda Time uses a different construct to represent this—a Period—and like all properly represented units of measure, it requires a unit to go with it. For example, the answer “47” is useless without an accompanying unit, such as “47 days,” “47 hours” or “47 years.” Period provides a handy method, Between, to calculate the number of some particular time unit between two LocalDates: var period = Period.Between(today, twentyFifth, PeriodUnits.Days); testContextInstance.WriteLine("Only {0} more days to shop!", period.Days); This tells me exactly how many days, but we don’t usually count days at that large an amount (1,833, at the time I wrote this article) like that. We prefer time to be in more manageable chunks, such as “years, months, days,” which we can again ask Noda Time to manage. We can ask it to give us a Period that contains a years/months/days breakdown, by OR-ing the PeriodUnits flags together: Period.Between(today, twentyFifth, PeriodUnits.Years | PeriodUnits.Months | PeriodUnits.Days) Or, because this is a pretty common request, we can ask it to give us a Period that contains a years/months/days breakdown by using the pre-constructed flag of the same name: Period.Between(today, twentyFifth, PeriodUnits.YearMonthDay) (Apparently, I still have a little time yet, which is good, because I have no idea what to get her.) Frequent readers of this column will know that I like to write exploration tests when investigating a new library, and this column is no exception. However, it’s impossible to write tests based on time, particularly because time has this annoying habit of continuing on. Each millisecond that passes throws off whatever the expected result is, and that makes it hard, if not impossible, to write tests that will produce predictable results that we can assert and report violations. For this reason, anything that provides time (such as, you know, a clock) implements the IClock interface, including the SystemClock I used earlier to obtain the Instant for “right now” (the Now static property). If we, for example, create an implementation that implements the IClock interface and provides a constant value back for the Now property (the only member required by the IClock interface, in fact), because the rest of the Noda Time library basically uses Instants to recognize that moment in time, we have essentially created an entirely testable environment, which allows the entire thing to be tested, asserted and verified. Thus, I can change my earlier code slightly and create a set of exploration tests, as shown in Figure 1. Figure 1 Creating Exploration Tests [TestClass] public class UnitTest1 { // SystemClock.Instance.Now was at 13578106905161124 when I // ran it, so let's mock up a clock that returns that moment // in time as "Now" public class MockClock : IClock { public Instant Now { get { return new Instant(13578106905161124); } } } [TestMethod] public void TestMethod1() { IClock clock = new MockClock(); // was SystemClock.Instance; var now = clock.Now; Assert.AreEqual(13578106905161124, now.Ticks); var dtzi = DateTime zoneProviders.Tzdb; var seattleTZ = dtzi["America/Vancouver"]; Assert.AreEqual("America/Vancouver", seattleTZ.Id); var seattleNow = new ZonedDateTime(now, seattleTZ); Assert.AreEqual(1, seattleNow.Hour); Assert.AreEqual(38, seattleNow.Minute); var today = seattleNow.LocalDateTime.Date; var twentyFifth = new LocalDate(2018, 1, 16); var period = Period.Between(today, twentyFifth, PeriodUnits.Days); Assert.AreEqual(1832, period.Days); } } By going through all of your time-related code and using Noda Time instead of the built-in .NET time types, code becomes much more testable simply by replacing the IClock used to obtain the Instant for “right now” to something controllable and known. There’s a lot more to Noda Time than just what I’ve shown here. For example, it’s relatively easy to add time units (days, months and so on) to a given time by using the “Plus” and “Minus” methods (for which there are also operator overloads, if those make more sense to use), as well as a FakeClock class designed specifically for testing time-related code, including the ability to programmatically “advance” time in some discrete fashion, making it easier to test elapsed-time-sensitive code (such as Windows Workflow instances, for example, that are supposed to act after a period of time has elapsed without activity). At a deeper, more conceptual level, Noda Time also demonstrates how a type system in a programming language can help differentiate between subtly different kinds of values within the problem domain: By separating out the different kinds of time (instants, local time, local dates, local dates and times, and zoned dates and times, for example) into discrete and interrelated types, it helps the programmer be clear and explicit about exactly what this code is supposed to be doing or working with. It can be particularly important, for example, to differentiate a “birth date” from a “birth day” in some code: One reflects the moment in the universe’s timeline when a person was born, the other is a recurring date on which we celebrate that moment in the universe’s timeline. (Practically speaking, one has a year attached to it, the other doesn’t.) Skeet has made it clear that he doesn’t consider the library “finished” in any way, and he has plans to enhance and extend it further. Fortunately, Noda Time is available for use today, and developers owe it to themselves to NuGet Noda Time, have a look, and start figuring out how and where to use it in the problem domain. After all, time is precious. Happy coding! Ted Neward is a principal with Neward & Associates LLC. He has written more than 100 articles and authored: Jon SkeetJon Skeet is a senior software engineer at Google, working in London. By day he codes in Java, but his passion is C#. You can reach Jon on Twitter (@jonskeet) or simply post a question on Stack Overflow. More MSDN Magazine Blog entries > Browse All MSDN Magazines Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
https://msdn.microsoft.com/en-us/magazine/jj991981.aspx
CC-MAIN-2015-18
refinedweb
2,293
58.01
Martijn van Oosterhout wrote: > On Fri, May 04, 2007 at 02:18:31PM +0200, Zdenek Kotala wrote: > > Is the reason for keeping this in a code? Another kind of construct is: > > > > #define PG_RETURN_NULL() \ > > do { fcinfo->isnull = true; return (Datum) 0; } while (0) > > This is a standard way of getting multiple statements into a macro. If > the compiler complains, too bad, there isn't a standard alternative. Advertising So it is standard by it's not standard ;-) > > or > > why is there while ... break instead if? > > > > Not sure about this one. It's not wrong, but it is unusual. Maybe > someone wanted to make it so that in the future it would handle > multiple cases? There are many other cases where we do it cleanly, without the while loop. I don't see any reason to not do this one the same way. - while ((oldtuple = systable_getnext(sd)) != NULL) + oldtuple = systable_getnext(sd); + if (HeapTupleIsValid(oldtuple)) ... - break; -- Alvaro Herrera The PostgreSQL Company - Command Prompt, Inc. ---------------------------(end of broadcast)--------------------------- TIP 6: explain analyze is your friend
https://www.mail-archive.com/pgsql-hackers@postgresql.org/msg93001.html
CC-MAIN-2018-22
refinedweb
171
68.26
Changing the Tires on a Moving Codebase 2020 was a year of reckonings. And for all that was beyond one’s control, as the year went on, I found myself pouring more and more into the one thing that felt within reach: futureproofing of the large enterprise web application I helped build, SimpleLegal. Now complete, this replatforming easily ranks in my most complex projects, and right now, holds the top spot for the happiest ending. That happiness comes at a cost, but with some the right approach that cost may not be as high as you think. The Bottom Line We took SimpleLegal’s primary product, a 300,000 line Django-1.11-Python 2.7-Redis-Postgres-10 codebase, to a Django 2.2-Python 3.8-Postgres-12 stack, on-schedule and without major site incidents. And it feels amazing. Speaking as tech lead on the project, what did it look like? For me, something like this: But as Director of Engineering, what did it cost? 3.5 dev years and just about \$2 per line of code. And I’m especially proud of that result, because along the way, we also substantially improved the speed and reliability of both the site and development process itself. The product now has a bright future ahead, ready to shine in sales RFPs and compliance questionnaires. Most importantly, there’ll be no worrying about when to delicately break it to a candidate that they’ll be working with unsupported technology. In short, a large, solid investment that’s already paying for itself. If you just came here for the estimate we wish we had, you’ve got it. This post is all about how your team can achieve the same result, if not better. The Setup The story begins in 2013, when a freshly YC-incubated SimpleLegal made all the right decisions for a new SaaS LegalTech company: Python, Django, Postgres, Redis. In classic startup fashion, features came first, unless technology was a blocker. Packages were only upgraded incidentally. By 2019, the end of this technical runway had drawn near. While Python 2 may be getting extended support from various vendors, there were precious few volunteers in sight to do Django 1 CVE patches in 2021. A web framework’s a riskier attack surface, so we finally had our compliance forcing function, and it was time to pay off our tech debt. The Outset So began our Tech Refresh replatforming initiative, in Q4 2019. The goal: Upgrade the stack while still shipping features, like changing the tires of a moving car. We wanted to do it carefully, and that would take time. Here are some helpful ground rules for long-running projects: - Any project that gets worked on 10+ hours per week deserves a 30-minute weekly sync. - Every recurring meeting deserves a log. Put it in the invite. Use that Project Log to record progress, blockers, and decisions. - It’s a marathon, not a sprint. Avoid relying on working nights, weekends, and holidays. We started with a sketch of a plan that, generously interpreted, ended up being about halfway correct. Some early guesses that turned into successes: - Move to pip-tools and unpin dependencies based on extensive changelog analysis. Identify packages without py23 compatible versions. (Though we’ve since moved to poetry.) - Add line coverage reporting to CI - Revamp internal testing framework to allow devs to quickly write tests More on these below. Other plans weren’t so realistic: - Take our CI from ~60% to 95% line coverage in 6 months - Parallelized conversion of app packages over the course of 3 months - Use low traffic times around USA holidays (Thanksgiving, Christmas, New Years) to gradually roll onto the new app before 2021. We were young! As naïve as we were, at least we knew it would be a lot of work. To help shoulder the burden, we scouted, hired, and trained three dedicated off-shore developers. The Traction Issues Even with added developers, by mid-2020 it was becoming obvious we were dreaming about 95% coverage, let alone 100%. Total coverage may be best practice, but 3.5 developers couldn’t cover enough ground. We were getting valuable tests, and even finding old bugs, but if we stuck with the letter of the plan, Django 2 would end up being a 2022 project. At 70%, we decided it was time to pivot. We realized that CI is more sensitive than most users for most of the site. So we focused in on testing the highest impact code. What’s high-impact? 1) the code that fails most visibly and 2) the code that’s hardest to retry. You can build an inventory of high-impact code in under a week by looking at traffic stats, batch job schedules, and asking your support staff. Around 80% of the codebase falls outside that high-traffic/high-impact list. What to do about that 80%? Lean in on error detection and fast time-to-fix. The Sentry Pivot One nice thing about startup life is that it’s easy to try new tools. One practice we’ve embraced at SimpleLegal is to reserve every 5th week for developers to work on the development process itself, like a coordinated 20% time. Even the best chef can’t cook five-star food in a messy kitchen. This was our way of cleaning up the shop and ultimately speeding up the ship. During one such period, someone had the genius idea to add dedicated error reporting to the system, using Sentry. Within a day or two, we had a site you could visit and get stack traces. It was pretty magical, and it wasn’t until Tech Refresh that we realized that while integration takes one dev-day, full adoption can take a team months. You see, adding Sentry to a mature-but-fast-moving system means one thing: noise. Our live site was erroring all the time. Most errors weren’t visible or didn’t block users, who in some cases had quietly learned to work around longstanding site quirks. Pretty quickly, our developers learned to treat Sentry as a repository of debugging information. A Sentry event on its own wasn’t something to be taken seriously in 2019. That changed in 2020, with the team responsible for delivering a seamless replatform needing Sentry to be something else: a responsive site quality tool. How did we get there? First step, enhance the data flowing into Sentry by following these best practices: - Split up your products into separate Sentry projects. This includes your frontend and backend. - Tag your releases. Don’t tag dev env deployments with the branch, it clutters up the Releases UI. Add a separate branch tag for searches. - Split up your environments. This is critical for directing alerts. Our Sentry client environment is configured by domain conventions and Django’s sites framework. If it helps, here’s a baseline, we use these environments: - Production: Current official release. DevOps monitored. - Sandbox: Current official release (some companies do next release). Used by customers to test changes. DevOps monitored. - Demo/Sales: Previous official release. Mostly internal traffic, but external visibility at prospect demo time. DevOps monitored. - Canary: Next official release. Otherwise known as staging. Internal traffic. Dev monitored. - ProdQA: Current official release. Used internally to reproduce support issues. Dev monitored. - QA: Dev branches, dev release, internal traffic. Unmonitored debugging data. - Local test/CI: Not published to Sentry by default. With issues finally properly tagged and searchable, we used Sentry’s new Discover tool to export issues weekly, and prioritize legacy errors. To start, we focused on high-visibility production errors with non-internal human users. Our specific query: has:user !transaction:/api/* event.type:error !user.username:*@simplelegal.* We triaged into 4 categories: Quick fix (minor bug), Quick error (turn an opaque 500 error into a actionable 400 of some form), Spike (larger bug, requires research), and Silence (using Sentry’s ignore feature). Over 6 weeks we went from over 2500 weekly events down to less than 500. Further efforts have gotten us under 100 events per week, spread across a handful of issues, which is more than manageable for even a lean team. While “Sentry Zero” remains the ideal, we achieved and maintained the real goal of a responsive flow, in large part thanks to the Slack integration. Our team no longer hears about server errors from our Support team. In fact, these days, we let them know when a client is having trouble and we’ve got a ticket underway. And it really is important to develop close ties with your support team. Embedded in our strategy above was that CI is much more sensitive than a real user. While perfection is tempting, it’s not unrealistic to ask a bit of patience from an enterprise user, provided your support team is prepared. Sync with them weekly so surprise is minimized. If they’re feeling ambitious, you can teach them some Sentry basics, too. The New Road With noise virtually eliminated, we were ready to move fast. While the lean-in on fast-fixing Sentry issues was necessary, a strong reactive game is only useful if there are proactive changes being pushed. Here are some highlights we learned when making those changes: Committing to transactions Used properly, rollbacks can make it like errors never happened, the perfect complement to a fast-fix strategy. The truly atomic request Get as much as possible into the transactions. Turn on ATOMIC_REQUESTS, if you haven’t already. Some requests do more than change the database, though, like sending notifications and enqueuing background tasks. At SimpleLegal, we rearchitected to defer all side effects (except logging) until a successful response was being returned. Middleware can help, but mainly we achieved this by getting rid of our Redis queue, and switching to a PostgreSQL-backed task queue/broker. This arrangement ensures that if an error occurs, the transaction is rolled back, no tasks are enqueued, and the user gets a clean failure. We spot the breakage in Sentry, toggle over to the old site to unblock, and their next retry succeeds. Transactional test setup Transactionality also proved key to our testing strategy. SimpleLegal had long outgrown Django’s primitive fixture system. Most tests required complex Python to set up, making tests slow to write and slow to run. To speed up both writing and running, we wrapped the whole test session in a transaction, then, before any test cases run, we set up exemplary base states. Test cases used these base states as fixtures, and rolled back to the base state after every test case. See this conftest.py excerpt for details. Better than best practices Software scenarios vary so widely, there’s an art to knowing which advice isn’t for you. Here’s an assortment of cul de sacs we learned about firsthand. The utility of namespaces Given how code is divided into modules, packages, Django apps, etc., it may be tempting to treat those as units of work. Don’t start there. Code divisions can be pretty arbitrary, and it’s hard to know when you’ve pulled on a risky thread. Assuming there are automated refactorings, as in a 2to3 conversion, start by porting by type of transformation. That way, one need only review a command and a list of paths affected. Plus, automated fixes necessarily follow a pattern, meaning more people can fix bugs arising from the refactor. Coverage tools Coverage was a mixed bag for us. Obviously our coverage-first strategy wasn’t tenable, but it was still useful for prioritization and status checks. On a per-change basis, we found coverage tools to be somewhat unreliable. We never got to the bottom of why coverage acted nondeterministically, and we left the conclusion at, “off-the-shelf tools like codecov are probably not targeted at monorepos of our scale.” In running into coverage walls, we ended up exploring many other interpretations of coverage. For us, much higher-priority than line coverage were “route coverage” (i.e., every URL has at least one integration test) and “model repr coverage” (i.e., every model object had a useful text representation, useful for debugging in Sentry). With more time, we would have liked to build tools around those, and even around online-profiling based coverage statistics, to prioritize the highest traffic lines, not just the highest traffic routes. If you’ve heard of approaches to these ends, we’d love to discuss them with you. Flattening database migrations On the surface, reducing the number of files we needed to upgrade seems logical. Turns out, flattening migrations is a low-payoff strategy to get rid of files. Changing historical migration file structure complicated our rollout, while upgrading migrations we didn’t flatten was straightforward. Not to mention, if you just wanted the CI speedup, you can take the same page from the Open EdX Platform that we did: build a base DB cache that you check in every couple months. Turns out, you can learn a lot from open-source applications. Easing onto the stack If you have more than one application, use the smaller, simpler application to pilot changes. We were lucky enough to have a separate app whose tests ran faster, making for a tighter development loop we coul learn from. Likewise, if you have more than one production environment, start rollouts with the one with the least impact. Clone your CI jobs for the new stack, too. They’ll all fail, but resist the urge to mark them as optional. Instead, build a single-file inventory of all tests and their current testing state. We built a small extension for our test runner, pytest, which bulk skipped tests based on a status inventory file. Then, ratchet: unskip and fix a test, update the file, check that tests pass, and repeat. Much more convenient and scannable than pytest mark decorators spread throughout the codebase. See this conftest.py excerpt for details. The Rollout In Q4 2020, we doubled up on infrastructure to run the old and new sites in parallel, backed by the same database. We got into a loop of enabling traffic to the new stack, building a queue of Sentry issues to fix, and switching it back off, while tracking the time. After around 120 hours of new stack, strategically spread around the clock and week, enough organizational confidence had been built that we could leave the site on during our most critical hours: Mondays and Tuesdays at the beginning of the month. The sole hiccup was an AWS outage Thanksgiving week. At this point we were ahead of schedule, and enough confidence had been built in our fast-fix workflow that we didn’t need our original holiday testing windows. And for that, many thanks were given. We kept at the fast-fix crank until we were done. Done isn’t when the new system has no errors, it’s when traffic on the new system has fewer events than the old system. Then, fix forward, and start scheduling time to delete the scaffolding. The Aftermath So, once you’re on current LTS versions of Django, Python, Linux, and Postgres, job complete, right? Thankfully, tech debt never quite hits 0. While updating and replacing core technologies on a schedule is no small feat, replacing a rusty part with a shiny one doesn’t change a design. Architectural tech debt — mistakes in abstractions, including the lack thereof — can present an even greater challenge. Solutions to those problems don’t generalize between projects as cleanly, but they do benefit from up-to-date and error-free foundations. For all the projects looking to add tread to their technical tires, we hope this retrospective helps you confidently and pragmatically retrofit your stack for years to come.
https://sentry.io/customers/simplelegal/
CC-MAIN-2022-21
refinedweb
2,639
64.71
. Download the JPT Library: jpt.jar Download the jpt.jar installation notes jpt_jar_readme.doc in Microsoft Word format. Download the jpt.jar installation notes jpt_jar_readme.pdf in Adobe PDF format. Download jpt.jar and the installation notes in zip format Download jpt.jar and the installation notes in self-extracting exe format Access the Annotated Java Power Tools Source Files online (strongly recommended) Access the Alphabetical Java Power Tools Source Files online Download all Java Power Tools Source Files in zip format Download all Java Power Tools Source Files in self-extracting exe format Access the Java Power Tools API documentation online Download the Java Power Tools API documentation in zip format Download the Java Power Tools API documentation in self-extracting exe format Access the SUN Java API Documentation online The Java Power Framework or JPF is designed to permit instant experiments using small methods, quick unit tests of individual classes, systematic integration tests of families of classes, and full tests of entire applications. A detailed discussion of how to use the JPF is presented with the annotated description of the JPF Source Files. In brief, the key idea is that the user can enter certain public methods into a class that extends JPF and these methods will automatically generate buttons in the JPF Button Panel that call the corresponding methods when clicked. In this way, it is possible to create tests and execute them almost instantly. The Java Power Framework may be integrated with the support class LookAndFeelTools to enable setting the look and feel immediately prior to opening the JPF Button Panel. This permits an instructor to automatically adjust the sizes of the fonts used by Java so that they become large for classroom presentation. The following class shows a typical starter class for use with the JPF. The JPF starter class Methods.java. The file Methods.java may also be obtained bundled with a Metrowerks 8 project file: The bundled Methods.java in a zip file. The bundled Methods.java in an exe file. As you can see from examination of the starter class Methods.java, the class is endowed with a rich set of Java import statements. The reason for this decision is that it is very frustrating when doing experiments to have to stop to find a needed import. The imports provided include all imports that we have needed in teaching Java for five years. The structure of the central portion of the starter code in Methods.java is as follows: public class Methods extends JPF { public static void main(String[] args) { // To optionally adjust the look and feel, // remove the comments from one of the two statements below. // LookAndFeelTools.showSelectLookAndFeelDialog(); // LookAndFeelTools.adjustAllDefaultFontSizes(2); new Methods(); } } The critical issues are that Methods extends JPF and that new Methods() is called which automatically calls the default constructor for JPF which in turns sets up the test GUI using the appropriate public methods in the Methods class. In practice, a user would add appropriate public methods to the Methods class and these would give rise to corresponding buttons in the automatically generated JPF Buttons Panel. See the notes in the JPF Source Files documentation for further details. For examples of the use of the Java Power Framework see the sections below on: Access detailed instructions for using JPT in Eclipse here. Numerous screen snapshots are provided in the document and as a slide show. The Kaleidoscope Case Study was the motivating example for the introduction of the interfaces Paintable and MutatablePaintable, and the classes ShapePaintable, ImagePaintable, and TextPaintable that enable to encapsulation of shapes, images, and text in ways that permit both direct painting and the creation of components, buttons, icons, bitmaps, and texture paints. This case study also illustrates the use of the Java Power Framework to easily create a testing environment that scales from simple classes and methods to full scale graphics and GUIs. The Fractals Demo provides access to two programs that demonstrate fractals. These programs are bundled together using an instance of the Java Power Framework. The Concentration Game provides a simple memory game that asks the user to match tiles with hidden images. The user can view two tiles at a time and these tiles will remain visible on the next move only if they match. The goal is to match all tiles with the fewest moves. This game illustrates a core program that may then be launched as an application or an applet using a few small auxiliary classes. The Bit Display Viewers provide an experiment tool that allows students to explore the bit representation of 32-bit entities (int and float) and 64-bit entities (long and double). The WebImageViewer enables a user to scan some or all of the images in a web directory provided that there is a text file available that lists the desired image file names one per line. The viewer therefore requests the URL of the images, the name of the image list text file, and the URL of the text file if it not the same as the images URL. If the name of the image list is not provided, it is taken to be imagelist.txt. The Web Image Viewer is very useful for students and faculty who are building web sites and need to check that all necessary image files are in place. The viewer also illustrates the powerful tools provided by JPT for loading and processing image files. These tools may of course be called by student or faculty Java programs. The Tree Experiments site investigates the structure of random binary search tree by providing graphs of random trees and by gathering experimental statistics on the heights of such trees by doing up to 1000 experiments at a time. The JPT Book will eventually provide a systematic online tutorial to the Java Power Tools and the Java Power Framework. At the moment, this book contains the extensive first chapter. The sample programs from this chapter are bundled together using an instance of the Java Power Framework. The Demos site provides access to numerous JPT demos. The demos vary in age with some from the earliest days of JPT and some more recent. The demos of animated algorithms, automata, 3D boxes, dot patterns, function plot, Hilbert curve, recursive fractals, SIGCSE maze, and swimming fish retain some interest even today. Certain other demos illustrate simple uses of JPT and may be of help to beginners. A few demos are there for historical reasons and have not been removed since the site was created from our internal code as is. The ACM Education Board Java Task Force was formed for the following purpose: To review the Java language, APIs, and tools from the perspective of introductory computing education and to develop a stable collection of pedagogical resources that will make it easier to teach Java to first-year computing students without having those students overwhelmed by its complexity. The JPT Java Submissions to the ACM Task Force act as mini-tutorials for the JPT and may be of some interest to the teaching community. The Java Power Tools team: To send e-mail to the Java Power Tools team, use: jpt@ccs.neu.edu Our postal address and fax number are given below:
http://www.ccs.neu.edu/jpt/jpt_2_3/details.htm
CC-MAIN-2015-35
refinedweb
1,210
51.48
@amueller I don't know if this helps: I ran from scipy import linalg import numpy as np m, n = 9, 6 a = np.random.randn(m, n) + 1.j*np.random.randn(m, n) U, s, Vh = linalg.svd(a) print(U.shape, s.shape, Vh.shape) cProfile says: 394 0.004 0.000 0.017 0.000 <frozen importlib._bootstrap_external>:1233(find_spec) 900 0.004 0.000 0.004 0.000 {built-in method posix.stat} 1 0.006 0.006 0.006 0.006 lil.py:23(lil_matrix) 81/24 0.007 0.000 0.011 0.000 sre_compile.py:64(_compile) 402/399 0.011 0.000 0.022 0.000 {built-in method builtins.__build_class__} 212/1 0.023 0.000 0.222 0.222 {built-in method builtins.exec} 190 0.024 0.000 0.024 0.000 {built-in method marshal.loads} 39/37 0.038 0.001 0.043 0.001 {built-in method _imp.create_dynamic} (sorted by second column) 9 0.000 0.000 0.000 0.000 __future__.py:79(__init__) 9 0.000 0.000 0.000 0.000 _globals.py:77(__repr__) 9 0.000 0.000 0.000 0.000 {method 'encode' of 'str' objects} 9 0.000 0.000 0.000 0.000 {method 'keys' of 'dict' objects} 9 0.000 0.000 0.000 0.000 os.py:742(encode) 9 0.000 0.000 0.001 0.000 abc.py:151(register) 9 0.000 0.000 0.001 0.000 datetime.py:356(__new__) 900 0.001 0.000 0.005 0.000 <frozen importlib._bootstrap_external>:75(_path_stat) 900 0.004 0.000 0.004 0.000 {built-in method posix.stat} 936 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:321(<genexpr>) 96 0.000 0.000 0.000 0.000 enum.py:630(<lambda>) 39/37 0.038 0.001 0.043 0.001 {built-in method _imp.create_dynamic} 1 0.002 0.002 0.002 0.002 __init__.py:259(_reset_cache) 1 0.006 0.006 0.006 0.006 lil.py:23(lil_matrix) (sorted by third column) @amueller when I run this directly on the host (with 24 cores) I get ~30 seconds. When I run it directly on localhost (4 cores, 8 threads) I get around 30-40 seconds as well. When I run inside docker with cpu limit of 6 cores and 6GB RAM, it needs almost 10 minutes. Inside a VirtualBox with 2 cores.. around 30 seconds, seems scikit does not play well with docker limitations which uses the CFS Scheduler: link param_rangeto range(1,5)the code runs much faster (I am no data scientist) validation_curvedoes not really profit from multithreading/multiprocessing. I get almost same results on intel i7 (4 cores) and intel xeon (24 cores). The problem is that if the validation curve runs on the xeon machines.. it uses all cores and the machine is overloaded, which makes no sense, really :) conda install numpy scipy cython matplotlib pytest flake8 sphinx sphinx-galleryor something like that
https://gitter.im/scikit-learn/scikit-learn?at=5d48423fa96def4751c0d3da
CC-MAIN-2022-33
refinedweb
516
80.17
#include <LiquidCrystal.h>//------------ initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 10, 8, 3, 2);void setup (){ lcd.begin(16, 2); // LCD is a 16 by 2 character array lcd.setCursor(0, 0); lcd.print("Manufactured by:"); } Here is my new code that does not work. now it does not work My old code used this statement for the initialization. "LiquidCrystal lcd(2, 8, 9, 10, 11, 12);" How do I get my LCD to operate using different pins? //LiquidCrystal lcd(RS, E, D4, D5, D6, D7);LiquidCrystal lcd(7, 8, 9, 10, 11, 12); // put your pin numbers here Add the loop() function, and have it also send info to the lcd, ever so often (one second maybe). Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=179930.0
CC-MAIN-2016-07
refinedweb
159
73.58
For more information on topics covered in this lesson, check out these resources: Returning Multiple Values With namedtuple 00:00 In a previous lesson, you saw how to return multiple values in a single return statement. Here, we’ll look at a way to make those types of functions more readable. 00:11 In Python, you can use namedtuples in a function with multiple return values to essentially put a label on each value, making your function more understandable to other programmers. 00:23 Officially, a namedtuple is an object of the collections.namedtuple class. A namedtuple is a collection class which returns a subclass of tuple that has fields or attributes. 00:37 You can access those individual attributes using either dot notation or an indexing operation. For more information about namedtuple, you can check out Write Pythonic and Clean Code with namedtuple here on Real Python. 00:53 The initializer of namedtuple takes several arguments, but you only really need to know two of them to get started. The first is typename. 01:03 This is the name of the class you wish to use for your namedtuple. It has to be a string. The second argument is field_names. This holds the names of the fields or attributes your tuple-like object is going to have. 01:20 It can be a sequence of strings or a single string with names separated by whitespace or commas. Here’s an example. It’s a new version of the describe() method you saw in a previous lesson. 01:35 First are some import statements. As before, we need to import statistics to use the statistical functions. And to use the namedtuple, we need to import the namedtuple module from collections. 01:48 Again, our function describe() will take a collection of data for an argument, which we’re calling sample. Now we create our namedtuple class. 01:59 We’ll call this class object Desc, which will match the typename we give to the namedtuple initializer. This isn’t a requirement, but it’s considered proper Python style. 02:12 Now we call the initializer for namedtuple. We see the string "Desc", which is the typename, and in the second argument, we see names for the fields, "mean", "median", and "mode". 02:26 In our return statement, we’re still returning those three values, but instead of in an ordinary tuple, we’ll make them an object of our new Desc namedtuple class. 02:38 The initializer for Desc requires three values, one for each of the attributes we named. In this case, each one will have the result of a different measure of center for the data in sample. 02:53 First will be the mean, then the median, and finally, the mode. These are put in a namedtuple object of type Desc and returned. 03:06 Now let’s look at how to use this returned object. First, let’s import it and create a set of data to use. 03:17 I’m hoping this is the same data we used in that previous lesson. And now call our describe() function on this data and save it to a variable. 03:31 Now let’s explore the various ways we can see the values this function computed. We can display the value of the entire object. 03:41 We can access an individual attribute using its name with the dot operator ( .) 03:48 or by an index number 03:53 for the median. You can also unpack the tuple when you call the function. 04:05 So now, each variable holds a single value. 04:12 Again, by returning an object with the attribute names, our function becomes more readable and easier for other programmers to use. This concludes our series of lessons on best practices using the return statement. 04:26 Next will be some lessons that show some of the more advanced features Python provides for returning objects. Become a Member to join the conversation.
https://realpython.com/lessons/returning-multiple-values-namedtuple/
CC-MAIN-2022-05
refinedweb
670
65.32
SYNOPSIS #include <sys/types.h> #include <regex.h> int regcomp(regex_t *preg, const char *pattern, int cflags); DESCRIPTION The - REG_EXTENDED Use extended regular expressions. - REG_ICASE Ignore case in match. - REG_NOSUB Report only success or failure in regexec(). - REG_NEWLINE Change the handling of newline characters, as described in the text. The default regular expression type for pattern is a basic regular expression. The application can specify extended regular expressions using the REG_EXTENDED cflags flag. The following structure types contain at least the following members: If the REG_NOSUB flag was not set in cflags, The PARAMETERS - preg Points to the structure where the results are placed. - pattern Points to the string that the regular expression. - cflags The bitwise inclusive OR of zero or more of the flags defined in the header <regex.h>. RETURN VALUES On successful completion, the - REG_BADPAT A regular expression was invalid. - REG_ECOLLATE An invalid collating element was referenced. - REG_ECTYPE An invalid character class type was referenced. - REG_EESCAPE A trailing \ was in the pattern. - REG_ESUBREG A number in \digit was invalid or in error. - REG_EBRACK A [ ] imbalance exists - REG_ENOSYS The function is not supported. - REG_EPAREN A \( \) or ( ) imbalance exists. - REG_EBRACE A \{ \} imbalance exists. - REG_BADBR The contents of \{ \} are invalid: not a number, number too large, more than two numbers, first larger than second. - REG_ERANGE An endpoint in a range expression is invalid. - REG_ESPACE Out of memory. - REG_BADRPT ?, * or + is not preceded by valid regular expression. CONFORMANCE POSIX.2 (1992). MULTITHREAD SAFETY LEVEL MT-Safe. PORTING ISSUES None AVAILABILITY PTC MKS Toolkit for Professional Developers PTC MKS Toolkit for Enterprise Developers PTC MKS Toolkit for Enterprise Developers 64-Bit Edition SEE ALSO - Functions: fnmatch(), glob(), regerror(), regexec(), regfree() PTC MKS Toolkit 9.6 patch 1 Documentation Build 5.
http://www.mkssoftware.com/docs/man3/regcomp.3.asp
CC-MAIN-2015-32
refinedweb
288
52.15
I have a site on webfaction that ran Django using their basic installer. It was just for fun, so I did not worry about things like maintainability, etc… A few years passed. I decided to get more serious about that site, so I decided to start using virtualenv and mod_wsgi. I setup a virtualenv on my local machine. Upgraded for Django 1.4 to Django 1.5. Made some tweaks and everything worked. Setup an identical virtualenv on webfaction. Edited my wsgi.py file to activate the env. But things did not work. I was picking up the wrong version of Django. It was the version installed from before virtualenv. I ssh-ed into webfaction. Activated the virtualenv. Started python and ran: import sys for s in sys.path: print s I could see all my paths from my virtualenv. Additionally I saw the global libs; paths starting with /usr/local… There is some documentation on the webfaction forum explaining why those global libs are there. None of them conflict with the libs I an using, so its just a minor annoyance. But I also saw all my local packages; the ones in /home/myaccount/lib/python2.7. I am using virtualenv to NOT include those. Crap! My wsgi.py file looked like this (don’t do this): site.addsitedir('my/virtualenv/lib/python2.7/site-packages') activate_this = '/path/to/env/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) I am pretty sure I got that code from older virtualenv docs. As Graham Dumpleton pointed out, that code is wrong. The virtualenv 1.9.1 docs, section entitled “Using Virtualenv without bin/python”, says to do this: activate_this = '/path/to/env/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) Along with that, put the path to the virtualenv site packages in WSGIDaemonProcess in httpd.conf. Something like this: WSGIDaemonProcess mysite.com processes=2 threads=12 display-name=[wsgi-me]httpd python-path=/path/to/mycode:/home/me/.virtualenvs/my_app/lib/python2.7/site-packages. The paths in python-path end up first on the sys.path list. Problem kind of solve in an unsatisfying way. It bugs me that those local packages are still in sys.path. This could cause a problem if I upgrade one of those packages on my development virtualenv and forget to upgrade it on my production virtualenv. As I see it, there are two alternatives: 1) delete items from sys.paths in wsgi.py, 2) delete the local packages and force everything to run from a virtualenv. I am not sure what sort of strange side effects the former could create. I think I will go with the later. You are not meant to use site.addsitedir() as well as activate_this.py. Using both will result in activate_this.py not doing the right thing. Just use activate_this.py. Also, using site.addsitedir() alone would also be wrong as it doesn’t do the required path reordering. Read Thanks for your comment. In my original post, I say that code came from the virtualenv docs, but then I go on to say that it’s wrong. And not to use site.addsitedir(). I see the code snippet in the virtualenv docs no longer has site.addsitedir(). I have modified my post to make that fact stand out more. The http.conf it’s what saved me. Thanks a million!
https://snakeycode.wordpress.com/2013/04/26/django-virtualenv-and-mod_wsgi/
CC-MAIN-2017-43
refinedweb
563
70.6
Tomato puree is an item acquired by expelling the skin and seeds of tomatoes with concentrated tomato juice. Tomato puree is wealthy in supplements, in addition to it has some helpful fixings that are not high in crude tomatoes. By the properties of tomato puree, all the constructive outcomes that tomato puree has on human well-being. For instance, only one tablespoon of tomato puree is an incredible wellspring of cell reinforcements. wholesale market import tomato past Is it precise to express that you are examining trading or passing on canned tomato? Did you comprehend that today an enormous piece of canned tomato things are accessible around the world? When did you see an outside stepped canned tomato you consider how this canned tomato is orchestrated in another nation? These canned tomato clients are worried about having a canned tomato made in another nation and utilizing canned tomato. The import and charge part of canned tomato manages this issue effectively. This canned tomato is passed on bit by bit to India, Australia, China, India, Iraq, and different nations. Trading canned tomato can be a helpful technique to acquire a living. The stars send canned tomato available to be purchased by drawing in canned tomato clients to different nations and remembering them. This makes it practical for the various relationships of canned tomato to be separate far and wide. Likewise, this certification of canned tomato has different central focuses for them. Makers of canned tomato section to different nations in the wake of verifying private plans markets. These makers set up the best quality and best bundling for passing on by passing on canned tomato. They increase remote trade benefits for their nation by expanding canned tomato promotions in different nations. To pass on their things, they ought to from the outset meet the close by advertising requirements of their canned tomato. They by then trade the best-canned tomatoes in unprecedented bundling to other nations’ business regions utilizing the best unpleasant materials. Tinned Tomato Paste 4.5kg Suppliers Have you anytime pondered how canned tomato creators make canned tomato? Do you know why a couple of shops offer different collections of canned tomato at different expenses? These are the appraisals of the huge makers and producers of canned tomato that we should bestow to you so you can get the best and most complete information on canned tomato. These makers have set up branches over the city for a canned tomato to get their customers the best buy canned tomato as quickly and viably as could be permitted. These branches are a way to deal with interface canned tomato customers with canned tomato creators. Makers of canned tomato are reliably the best creators increasing down to earth involvement with canned tomato. One of the ways our canned tomato consultants have come to consider and offer you associations and makers is through canned tomato bargains goals. These areas are continually open and can clearly interface makers of canned tomato to customers of canned tomato. This grants customers to give their bits of knowledge about canned tomato with canned tomato producers. This will pick up the maker’s ground at the present time. tomato paste tin seller central Have you whenever thought about how canned tomato makers make canned tomato? Do you know why two or three shops offer various mixes of canned tomato at various costs? Before long, we will acclimate you with the colossal producers of canned tomato. These are the evaluations of the vital producers and makers of canned tomato that we ought to present to you so you can get the best and most complete data on canned tomato. Makers of canned tomato produce the best-canned tomato in various qualities as appeared by their clients’ needs in the field of canned tomato. These makers have set up branches over the city for canned tomato to get their clients the best purchase canned tomato as fast and satisfactorily as could be allowed. You can discover tomato Brix and tomato puree sizes and little would tomato be able to puree and purchase tomato puree on numerous sites. These branches are an approach to manage interface canned tomato clients with canned tomato producers. Makers of canned tomato are dependably the best organizers to put colossal vitality in canned tomato. These canned tomato affiliations are perseveringly attempting to make canned tomato and give canned tomato to the client at a sensible cost. One of the ways our canned tomato experts have come to consider and offer you affiliations and makers is through canned tomato deals regions. These objectives are ceaselessly open and can straightforwardly interface creators of canned tomato to clients of canned tomato. This awards clients to give their bits of information about canned tomato with canned tomato makers. This will get the maker’s ground right now. fresh canned tomato paste To make the carefully assembled tomato puree, first, wash the tomatoes and put them in the channel to oust excess water by then split all the tomatoes through the inside and spot in an immense pot. Right when all the tomatoes are warmed to an enormous segment of the pot and trust that the tomato juice will air pocket and air pocket. So the tomatoes peel off viably. Clearly, we in spite of everything grant the tomatoes Boil to smooth fairly. After the tomatoes have mellowed, we place a wirework with incredibly little openings into the pot or colossal compartment and turn it off under the pot and cut the tomatoes right away or all of a sudden (if the wire is gigantic). Fill the pound and press the tomatoes over the squash with the objective that the skin and the seeds inside the pulverize can be viably detached and void the tomato juice into the pot or compartment in which the squash is put. Guarantee the tomato seeds don’t stay away from the matrix strainer since it will cause troublesome development. At the point when all the tomatoes have encountered the smash, put the pot on the glow and trust that the tomato juice will bubble. After the tomato juice has thickened and begins to mollify, incorporate the salt and blend. To check whether the tomato puree has landed at enough obsession, the best and least requesting action is to Draw a spoon on an immediate puree. In case it requires some venture for the opening to fill, that is, it has landed at the gathering of tomato puree, and you should be careful about the tomato puree. To form early, so keep things under control for it to solidify. We have to blend the tomato puree reliably so it doesn’t slow down out considering the way that it gives us a dreadful taste and it may turn dim. Finally, we incorporate and incorporate the oil and in case you wish you can incorporate more incorporate. Turn the pot down and license the prepared tomato puree to cool to room temperature. By then fill the holder and close the top and store in the cooler and for a variety of sustenances, We use sound and uniquely crafted tomato puree. buy tomato paste It may sound odd to you, be that as it may, minute tomato puree is truly home-made tomato puree changing. This method is especially helpful for housewives who prepare some long recollections to get sustenance when there is no passageway to mechanical puree. Also, the prosperity of the home-made tomato puree isn’t verified by anyone. In any case, things, for instance, Leonard tomato puree that isn’t just increasingly beneficial have the issue of conveying minute tomato puree. This technique won’t be reasonable for step by step usage when the expense of tomatoes is extensively higher than its puree. Sustenance fabricating plants nowadays are endeavoring to clear out inorganic added substances to their things as indicated by the enthusiasm of the customers. Thusly, Leonard tomato puree can be a reasonable option for step by step use for a long time. While the puree warming procedure is generally a repetitive and tedious strategy that only one out of every odd individual can do. Keeping up a home puree to keep it from the shape is another issue that has tormented various housewives. Mechanical tomato puree has for quite a while kept up its place among the regular needs of families and, at whatever point used fittingly, will have no medicinal issues for families. Purification and long stretch amassing of Leonard tomato puree are among its undeniable features. The proportion of puree that can be gotten per kilo of fresh and strong tomatoes is compelled. This is an aftereffect of the huge cost of tomatoes nowadays, which makes the home puree exorbitant. What sum does a tomato puree accommodate a 10kg request? It should be seen that each kilo of tomatoes gives around 100 to 150 grams of puree. So using 10kg of tomatoes you can make 1 to 1.5kg of tomato puree. Setting up a tomato puree with a bit of precision and registering the number of tomatoes and the dreary method of tomato creation won’t be reasonable and reasonable. Also, tomatoes with less significance should be used for making tomato puree. This makes it essentially harder to make the tomato puree. good quality tin canned tomato paste The best-canned tomatoes are canned tomatoes that are acceptable quality notwithstanding being very much evaluated. Top organizations creating canned tomato, utilizing the best crude materials and materials, produce the greatest canned tomato with a state-of-the-art plan. By demonstrating their quality to their clients, these brands have had the option to become top brands in the canned tomato market and addition client certainty. These organizations likewise attempt to build their deals and consumer loyalty by offering canned tomato at the best cost and with uncommon limits and everyday limits. To locate the best kind of canned tomato you have to realize that enough will generally have the option to distinguish the sorts of canned tomatoes and decide the best sort. The best sort of canned tomato is one that has the accompanying qualities: - Quality material utilized - Appropriate plan - The cost is correct - appropriate bundling An item with the above highlights can be a decent canned tomato for shopping. To purchase canned tomato you can go to online stores and in the wake of understanding data and highlights of various sorts of canned tomato, request your ideal item and pay after conveyance. Discount canned tomato discount is made by the vendors who produce the best quality and best bundled canned tomato. By providing canned tomato assortments, these offices attempt to address the issues of all portions of society so as to keep the local market from bringing in canned tomato. Discount canned tomato is additionally being sold in mass by online stores that supply direct product and convey the items to home purchasers. You can find tomato paste tin and fresh canned tomato and canned tomato paste on many websites. 70g canned tomato paste 28-30% brix Have you whenever considered utilizing tomato paste brix? Have you whenever thought about where this tomato paste brix is utilized? Today we will reveal to you where the tomato paste brix is ordinarily utilized and who needs the most tomato paste brix. Today, as we likely know, most getting ready plants are industrialized. Tomato paste brix has dependably been one of the human needs since the beginning and individuals experience experienced issues seeing how to make tomato paste brix. Our stars need to help us in the business and in the use of tomato paste brix. They express that today, on the off chance that we go to industry, urban locales, and homes, there will be less and a horrible situation for anybody to utilize tomato paste brix. Close to the day’s end, tomato paste brix is basic. tomato paste brix has fundamentally impacted our lives. Additionally, individuals who are searching for tomato paste brix are continually attempting to get the best pack. You can find out about tomato fare and tomato rate and tomato puree to puree on numerous sites. In the event that you misuse this copious utilization of tomato paste brix, If we watch, this tomato paste brix has dependably been required by people. Today we can purchase and purchase tomato paste brix in various urban regions around the globe. tomato paste brix has made it progressively clear for individuals to complete things and individuals are checking for the most recent tomato paste brix brand to get a tomato paste brix. This is the clarification that tomato paste brix has dependably been huge to individuals and individuals have been calling for a tomato paste brix at a sensible cost and quality. To discover progressively about tomato paste brix, we welcome you to see our different articles on other tomato paste brix districts so you can discover various sorts and occupations of tomato paste brix in urban zones. You can find 70g canned tomato paste and Tinned Tomato Paste on many websites.
https://pastered.com/best-quality-tomato-puree-manufacturers/
CC-MAIN-2020-40
refinedweb
2,184
59.64
Content-type: text/html #include <sys/mman.h> int mlockall ( int flags); int munlockall (void); The mlockall function causes all of the pages mapped by the process's address space to be memory resident until unlocked by a call to the munlockall function, until the process exits, or until the process calls exec. MCL_CURRENT locks all of the pages currently mapped into the process's address space. MCL_FUTURE locks all of the pages that become mapped into the process's address space in the future, when those mappings are established. You can specify MCL_CURRENT and then subsequently specify MCL_FUTURE to lock both current and future address space. The munlockall function unlocks all currently mapped pages of the process's address space. Any pages that become mapped into a process's address space after a call to munlockall are not locked unless otherwise specified by a subsequent call to mlockall. Pages locked or mapped into another process's address space are unaffected by this process's call to the munlockall function. Locking the process's pages into memory also makes the process unswappable. When the pages are unlocked, the process is made swappable. A lock is not inherited across a fork. All memory locks established on an address by this process are removed if an address range associated with the lock is unmapped with a call to the munmap function. You must have superuser privileges to call the mlockall function. On a successful call to the mlockall function, a value of 0 is returned and memory is locked. On an unsuccessful call, a value of -1 is returned, no memory is locked, and errno is set to indicate that an error occurred. On a successful call to the munlockall function, a value of 0 is returned and memory is unlocked. On an unsuccessful call, a value of -1 is returned and errno is set to indicate that an error occurred. The mlockall and munlockall functions fail under the following conditions: If any of the following conditions occur, the mlockall function will fail: Functions: exec(2), _exit(2), fork(2), munmap(2) delim off
http://backdrift.org/man/tru64/man3/mlockall.3.html
CC-MAIN-2017-22
refinedweb
352
60.95
So, you’ve written an amazing Python program, it does everything you want and then some. You stop and stare at it in amazement, and realize that it’s just so great, that it would be selfish not to share it with the entire world. However, there’s one small problem. Your program uses various libraries, which your users will need to install, and you want to make that process as painless as possible, or, if it’s a web app, you want to put it up on a server for everyone to enjoy, but you need to figure out what libraries it uses and install those on the server as well, which is a hassle. What’s a good way to ease this pain? Suppose that your first program has made you a millionaire, and now you’re running low on cash, so you decide to spend a few hours writing another one. However, your system still has all the old versions of the libraries you used to build the first program, and when you try to upgrade them, it breaks because it hasn’t been maintained in ages. How do you solve that problem? Luckily, there’s an easy way to solve both problems. We can use virtualenv to create separate, self-contained virtual environments where each environment is contained in a its own directory. Each environment can be activated when you want to work on the program that uses it. The best way to show how virtualenv works is by example, so let’s go through the process of installing and using it. Assuming you have the average Python installation (probably 2.7, on any of the three main OSes), the following steps should work as they are. Windows might do some things slightly differently, but mostly it should all work the same. In the examples, the lines starting with an “$” is what you will need to type in ($ is my prompt), so ignore the $ and type in the rest of the command. To install virtualenv (and pip, while we’re at it), you can use setuptools: $ easy_install pip virtualenv After that, both packages will be installed globally in your system, so you might want to use sudo if you are on Linux or OS X. We can now continue to creating an environment. I prefer to put the environment in the directory that contains the project I’m working on, so switch to the directory that contains your scripts and run (you shouldn’t need to use sudo): $ virtualenv env That will create a directory called env in your current directory and put the environment there. If you look inside, you should see some subdirectories, containing various files. The bin directory, in particular, should contain executables called python, pip, easy_install, etc. These executables differ from their globally-installed namesakes in that the former will be run in the virtual environment you’ve just created, while the latter will run system-wide. To illustrate this point, we need to install some packages. To do this, we will use pip, because it’s great. We already installed it earlier, so we can use it simply by doing: $ env/bin/pip install ipython shortuuid ipython is a very nice Python shell, which you might already be familiar with, and shortuuid is a small library for creating short unique IDs, which we’ll use to demonstrate how virtualenv works. You might have noticed that we didn’t just run pip, we ran env/bin/pip, which means that the two packages are now installed inside the virtualenv. Sure enough, if you run: $ env/bin/ipython you will see that the ipython shell opens up. If you try to import shortuuid, you will see the following: IPython 0.12.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: import shortuuid In [2]: shortuuid.uuid() Out[2]: 'ogxPuKH7qvtoXSzNmVECW' You will get a different ID, but the gist is the same. shortuuid has been installed and is working properly. If you now type exit to exit ipython, run the system-wide python installation (by typing python), and try to import shortuuid, what do you think will happen? Let’s try it out: Python 2.7.2+ (default, Oct 4 2011, 20:03:08) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import shortuuid Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named shortuuid >>> This is because, as I mentioned before, these packages have only been installed in the virtualenv directory, and we didn’t run the Python interpreter that’s inside the virtualenv, we ran the system-wide one. These packages don’t exist globally in the system, so we can be sure that whatever package we install will be in its own, tidy little directory. What happens if there’s already a package installed system-wide and we try to install it in the virtualenv, or even if we don’t install it in the virtualenv? Can we still access it? The answer is “no, we cannot”, because virtualenv, by default, restricts all access to system packages. This can be changed when creating the virtualenv, but it’s beyond our scope now. As far as the virtualenv is concerned, the system has no packages other than the ones actually installed by us in the virtualenv. If a library is at version X globally, but we install version Y in the virtualenv, programs in that virtualenv will only be able to see version Y. So, we have installed our packages and are able to write our program knowing that we won’t be messing our computer up with the various packages, but using env/bin/python all the time is a bit of a hassle. To activate one virtualenv to work with for one terminal session, we can run: $ source env/bin/activate This should put the environment’s name somewhere on our prompt, and, from now on, any program we run that’s installed in the virtualenv, will be run from it. For example, if we run python, or pip, or ipython, we will actually be running the versions inside the environment, so they will be able to see (and install or remove, in the case of pip) only the packages inside the environment. You might be thinking “This is all very nice so far, but you said I could easily distribute my program, and I see none of that!”, and you would be right. Let’s see how we can obtain a list of all the packages that are installed in the current virtualenv. Fortunately, pip makes this trivial: $ pip freeze ipython==0.12.1 shortuuid==0.2 You can see that pip gave us a list of all the packages we have installed, isn’t that fantastic? Yes, of course it is. We can get that list and stick it in a text file (I like to call it requirements.txt). We can then send that file to a friend, along with the source code, and all they have to do to ensure that our program will run is create a virtualenv and install the packages we’ve provided, with three simple commands: $ virtualenv env $ source env/bin/activate $ pip install -r requirements.txt This will create the virtualenv and install all the packages we have specified in the requirements file, at the specific versions we need, no less. You’re happy, your friend is happy, I’m happy, everyone’s happy. That’s not all pip can do, though. It can remove packages, install them directly from source directories, from remote repositories, just download (but not install) them, and much more, all for one low, low price. To get a better view of what pip (or virtualenv) can do, just look at their respective help sections: $ pip --help $ virtualenv --help They contain much more useful functionality, so feel free to explore around. You can get rid of virtualenvs just by deleting the directory, absolutely nothing else in your system is touched in any way. As always, if you think I’ve missed something, or have an error, or if you have any sort of feedback, please leave a comment below, and remember, if you want to stay up to date on these tutorials and have them available in DRM-free form in one place, you can get the ebook version. Join the conversation!
http://www.stavros.io/posts/developing-and-deploying-python-apps-using-pip-/
CC-MAIN-2013-48
refinedweb
1,430
68.1
DOJO, DOJO 1.0.2 tutorial, DOJO Tutorial ;. The checkbox button do some action on press. Dojo Radio... button do some action on press. Dojo Combo Box...Dojo 1.0.2 Tutorial   DOJO HelloWorld Example - Ajax DOJO HelloWorld Example Hi I am total in using DOJO for AJAX... the dojo.event.connect do here. cause I can take following code away...:// Thanks Ajax Dojo Tutorial Ajax Dojo Tutorial Dojo Tutorials and Examples Dojo is another great framework for developing ajax based applications. Dojo is selected Dojo Checkbox Dojo Checkbox In this section, you will learn how to create a checkbox in dojo. For creating checkbox you require "dijit.form.CheckBox". The checkbox button do Dojo Radio Button Dojo Radio Button In this section, you will learn how to create radio buttons in dojo... button do some action on press. Try Online: Radio Button The RadioButton class Date limit on Dojo Date picker - Date Calendar Date limit on Dojo Date picker Hi all, I am using dojo for date... to 30/04/2009, then user should not select date beyond this limit. I can do... want this validation on dojo date picker only. User should not select date Dojo Filtering Select Dojo Filtering Select In this section, you will learn about the dojo filtering... but the combo box do not allow to user to enter the outside of dojo grid from 3 different sources . On the server-side I use RESTful Web Services (Java, Json). Do you have any suggestion how can I do it with dojo...dojo grid from 3 different sources I'm new with dojo. I need to get. What Checkbox Dojo Checkbox  ... a checkbox in dojo. For creating checkbox you require "dijit.form.CheckBox". The checkbox button do some action on press. [Checkboxes are used when TimeSpinner Dojo TimeSpinner In this section, you will learn about the dojo TimeSpinner. This is same as the dojo NumberSpinner. But the NumberSpinner only worked Is it any code available for auto suggest text box using do? - Development process Is it any code available for auto suggest text box using do? In dojo, we are having combo box, in which auto suggestion already implemented. Like that is it we have auto suggestion for text Radio Button Dojo Radio Button  ... radio buttons in dojo. For creating radio button you need "dijit.form.CheckBox". The radio button do some action on press. The RadioButton AccordionContainer Dojo AccordionContainer In this section, you will learn about the dojo AccordionContainer...;Dojo: Associative arrays, Loosely typed variables BorderContainer Dojo BorderContainer In this section, you will learn about the dojo...;text/javascript" src=". aolcdn.com/dojo/1.1/dojo Dojo Google Blog Search Dojo Google Blog Search In this section, you will learn how to implement... on the filtered data then you go the specific blog site. And do your word. Try Online Ask Dojo Questions Online Ask Dojo Questions Online Dojo is an open source modular JavaScript... and language localizations to rapidly develop Ajax based website. Dojo aims to solvejo Tree Dojo Tree In this section, you will learn about the tree and how to create a tree in dojo... by the powerful dojo.data API. There are following steps for creating Dojo trees The while and do While and do-while  ... that the condition becomes false and the loop terminates. Have a look at do-while statement now. Here is the syntax: do { statement(s how to do this? how to do this? Given any integer 2D array, design then implement a Java program that will add to each element in the array the corresponding column number and the corresponding row number. Then, it prints the array before Dojo Toolbar Dojo Toolbar In this section, you will learn about the toolbar and how to create a toolbar in dojo. Try Online: Toolbar Toolbar : This is a GUI Dojo Editor Example Dojo Editor Example In this example, you will learn about the dojo editor. Editor...;in dojo. In this tips, learn about the  Dojo Color Picker Dojo Color Picker In this section, you will learn about the dojo ColorPicker. ColorPicker: The dojox.widget.ColorPicker widget that allows user to select Problem with DOJO tree with checkbox - Framework Problem with DOJO tree with checkbox Hi Friends, I have to generate a tree structure in a jsp along with checkbox besides each node. The tree structure is displayed on a dialog box. If user clicks on a button , the dialog box Dojo drag and drop Dojo drag and drop In this section, you will learn about dojo drag and drop. Drag and Drop: This is a technique of dragging an item. Click an object how to change background color in dojo tab container - Framework how to change background color in dojo tab container how to change background color in dojo tab container Dojo ToolTipsDialog Dojo ToolTipsDialog In this example you will learn how to develop a dojo tooltipsdialog. You see the following code and follows the following code and crate Tab not allowing external web page!! - Ajax Dojo Tab not allowing external web page!! I have designed a page... using Dojo to get the tab functionality and php for other programming. The Dojo... can I have three html pages (or php pages) showed up in three Dojo tabs Dojo Tool tips Dojo Tool tips In this section, you will learn about the tool tips and how to developed it in dojo. Try Online: Tool Tips Tool tips : This is a GUI Dojo Auto completer Dojo Auto completer In this section, you will learn how to create a auto completer in dojo. Try Online: Auto Completer Auto Completer: The Auto Completer provides Ajax Dojo Tutorial Dojo Menu and Menu Item Dojo Menu and Menu Item In this section, you will learn about the menu and how to create it in dojo. Try Online: Menu and Menu Item Menu : This is the widget models php do while loop php do while loop Difference between do while loop and simple loop in PHP php do while example php do while example Simple example of do while loop in PHP php do while syntax php do while syntax How to create a do while loop in php. What is the syntax how to focus dojo slider to a particular value and then disabling dojo slider so that value not changes on clicking? how to focus dojo slider to a particular value and then disabling dojo slider so that value not changes on clicking? How to focus dojo slider to a particular value (say 2.5 )on the slider and then disabling dojo slider so Dojo Hello World Dojo Hello World  ... World" example in Dojo. Before creating any examples or applications you must... World!". To create a button in dojo you need to a Button Widget DOJO Installation, Dojo 1.0.2 Installation Dojo 1.0.2 Installation Dojo Installation: A quick guide to install Dojo 1.0.2 in your web application. In this section I will show you how you can php do while break php do while break receiving a Fatal saying cannot break/continue.. please suggest. Thank U php do while false php do while false Is there any difference between FALSE and false while and do while while and do while hello, What is the difference between a while statement and a do statement? hello, A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do How to do url rewritting? How to do url rewritting? Dear Sir/Mam I have this link... to do?Please suggest do-while loop do-while loop how many times will the following loop get executed and what will be the final value of the variable I after execution the loop is over. int I = 5; do{ I + = 3; System.out.println(""+I); I=I+1; }while(I>=9 What does COMMIT do? What does COMMIT do? What does COMMIT do? Hi, here is the answer, COMMIT makes permanent the changes made by DML statements in the transaction. The changes made by the DML statements of a transaction become Dont Do this - Java Beginners Dont Do this Whenever you guys ask a question please describe your query? Otherwise you lost your time and other who are given answer to you. thanks Rajanikant what session.flush() do ? what session.flush() do ? Hi frineds , This is RajaSekharReddy can u Please answer these quesions 1.what session.flush() do ? 2.difference between load/get/criteria.these are all for retreving data or any difference Do needful - Java Beginners Do needful Hai how can I do the string to Hex in java. Pls help me use conversion concept Hi friend, import java.io.*; import java.io.IOException.*; public class StringToHexa{ public static void Dojo inline DateTextBox Dojo inline DateTextBox In this section, you will learn about the dojo inline DateTextBox and how to create a inline DateTextBox and how to make its editable Dojo Progress Bar Dojo Progress Bar In this section, you will learn about the progress bar and how to create a progress bar in dojo. Try Online: Progress Bar Progress Bar DOJO Tutorial Dojo Tutorial In this tutorial, you will learn about the dojo... learn to dojo then you need to know about the what is dojo and its directory Dojo Dialog Box Dojo Dialog Box In this section, you will learn about the dialog box with tool tips and how to create it in dojo. Try Online: Dialog Box Dialog Box : Dialog box
http://www.roseindia.net/tutorialhelp/comment/86982
CC-MAIN-2015-14
refinedweb
1,590
64.61
Hi, I would like to share with you an idea to try to optimize CPython. My previous attempts to optimize CPython failed because they changed the language semantic. For example, it's not possible to replace len('abc') with 3 because it is technically possible to override the builtin len() function. I propose to add a new "FAT" mode to Python to allow to add specialized bytecode to function with guards. Example: >>> import builtins >>> def f(): return len("abc") ... >>> f() 3 >>> def g(): return 3 ... >>> i=f.add(g) # i is the index of the new specialized bytecode >>> f.add_dict_key_guard(i, builtins.__dict__, 'len') >>> f() 3 >>> builtins.len = lambda obj: "len" >>> f() 'len' In this example, the f() function gets a fast version (g()) returning directly 3 instead of calling len("abc"). The optimization is disabled when the builtin len() function is modified (when builtins.__dict__['len'] is modified). (The example is not complete, we need a second guard on the current global namespace, but I wanted to write a short example.) With such machinery, it becomes possible to implement interesting optimizations. Some examples: * inline a function instead of calling it: calling a Python function is "expensive". For example, if you inline the _get_sep() call in posixpath.isabs(), the function becomes 20% faster. * move invariant out of the loop: classic micro-optimization done manually. For example, set "append = obj.append" before the loop and then call "append(item)" instead of "obj.append(item)" in the loop body. On a microbenchmark, it's between 5% (1 item) and 30% faster (10 items or more) * call pure functions at the compilation. A pure function has no side effect. Example: len(str). Technical Challenges ==================== The problem is the cost of "guards". A guard is a check done before calling a specialized function. Example of guards: * Type of a function parameter * Watch a dictionary key * Watch a function (especially it's __code__ attribute) Watching a dictionary key is a very important guard to disable an optimization when a builtin function is modified, when a function is replaced in a namespace, etc. The problem is that a dictionary lookup is not cheap: we have to get the hash value of the key, browse the hash table to find the bucket which may require multiple iterations, then we have to compare the key value, etc. To have faster guard, I propose to create a subtype of dict which provides a global "version" of the dictionary, incremented at each modification (create a new key, modify a key, delete a key) and a "version" per key=>value mapping, incremented each time that the mapping is modified. The lookup can be avoided when the dictionary is not modified. If a different key is modified, we need a lookup, but only once (we store the new global version to avoid a lookup at the next guard check). Limitations =========== Specialized bytecode is build at compilation, *not* at runtime: it's not a just-in-time (JIT) compiler. A JIT can implement even more efficient optimizations and can use better guards. Please continue to use PyPy for best performances! ;-) The name "FAT" comes from the fact that multiple bytecode versions of a function are stored in the memory, so a larger memory footprint and larger .pyc files on disk can be expected. Checking guards can also be more expensive than the optimization of the specialized bytecode. The optimizer should use an heuristic to decide if it's worth to use a specialized bytecode or not depending on the theoric speeup and the cost of guards. My motivation to write FAT Python is that CPython remains the reference implementation where new features are implemented, and other Python implementations still have issues with C extensions. JIT also has some issues, like longer startup time, slow warmup and memory footprint (this one may also be an issue of FAT Python!). Implementation ============== I wrote a proof-of-concept of my idea: It's a fork of CPython 3.6. Try it with: hg clone cd fatpython ./configure && make ./python -F See bench.py, Lib/posixpath.py (isabs) and Lib/test/test_fat.py for examples of optimizations. The command line -F flag enables the FAT mode. By default, *all* optimizations are disabled, there is a negligible overhead when the FAT mode is not used. In the FAT mode, the dictionary for modules, classes and instances becomes "versionned". Functions gets new methods to support adding specialized bytecode with guards. You can add manually a specialized bytecode for microbenchmarks, but functions are *not* optimized automatically. (See the Roadmap below.) How to write an optimizer? ========================== Currently, my proof-of-oncept is only the machinery to support adding specialized bytecodes with guards. The next step is to generate automatically these specialized versions. IMHO an optimizer should be implemented in Python and not in C, it's easier to write Python code. We can begin with simple optimizations on AST. See for example my astoptimizer which implements basic optimizations: At the beginning, we may use type hints (PEP 484) and other manual hints to help the optimizer. Later, a profiler learning the most common types of function parameters can be written for automatic optimizations. Example of hints: a list of constants which should not be modified in the application. A global "DEBUG" flag is common in applications, relying on DEBUG=False helps to remove dead code. Roadmap ======= * Finish the proof-of-concept: implement new guards, optimize method calls. For example, guards on module imports are required. Checking if a module is the expected mode can be tricky. * Write an optimizer based on manual hints * Write a profiler to generate hints Right now, my main question is if it will be possible and efficient to optimize classes, not only simple functions, especially classes defined in two different modules. I wrote a proof-of-concept of optimized method (with inlining), but I'm not sure yet that it's safe (don't change Python semantic). For more information on FAT Python, read: So, what do you think? Do you expect real speedup on applications, not only on microbechmarks? Do you know similar optimizations in other scripting languages? Victor Stinner
https://mail.python.org/pipermail/python-ideas/2015-October/036908.html
CC-MAIN-2017-39
refinedweb
1,025
56.45
Re: Active Directory Expiration Notification - From: PaulB <PaulB@xxxxxxxxxxxxxxxxxxxxxxxxx> - Date: Fri, 18 Aug 2006 05:40:02 -0700 Thanks all for your help. The registry entry that Jorge pointed out appears to be the solution to my problem. I do however have one other question. I have been looking at a couple of book on programming against active directory with C#. Yours appears to be very good but it still doesn't appear to give me a map of all attributes that can be set via the policy files agaiinst the active directory properties (and now apparently the registry entries) that hold these values. Can you recommend a good source for that kind if information. Thanks in advance.... "Joe Kaplan (MVP - ADSI)" wrote: Glad you liked the chapter. :) Sorry you already knew that stuff.. Luckily, Jorge and Paul already answered your question so I didn't have to look it up. Joe K. -- Joe Kaplan-MS MVP Directory Services Programming Co-author of "The .NET Developer's Guide to Directory Services Programming" -- "PaulB" <PaulB@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message news:C70A39FE-23F9-4F34-8594-32BA16526715@xxxxxxxxxxxxxxxx Thanks Joe, Chapter 10 was very informative but I already figured out know how to tell if the password is expired. I already know how to tell how many days until the password will expire. What I still do not know how to do is to get the window of time that the security policy has set for displaying a warning message to the user that their password is about to expire. I am pretty sure that it is somewhere in the AD database or in the registry because I can set that value in the security policy via the "Prompt user to change password before expiration" policy attribute . What I don't know is how to fetch that value from AD so my application can display a warning message similar to the one windows displays at login time. "Joe Kaplan (MVP - ADSI)" wrote: We have a complete sample on doing password expiration notifications against AD in .NET in our book in ch. 10. You can download ch 10 for free from the website in the link below, as well as the code samples from the book. The book itself is not free, but it might help you out in general if you need a good reference on .NET directory services programming. The website also has a support forum. Password expiration is determined by the domain password expiration policy and the pwdLastSet attribute on the user object. pwdLastSet contains an 8 byte "large" integer that stores a Windows FILETIME that specifies the date the password was last set, or the value 0 if the user must change at next logon (or is not set at all if the user has never set a By comparing the current date and the domain password expiration policy to the user's pwdLastSet value, you can determine when the password will expire. All the details are in the book. Joe K. -- Joe Kaplan-MS MVP Directory Services Programming Co-author of "The .NET Developer's Guide to Directory Services Programming" -- "PaulB" <PaulB@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message news:679994C8-AB8E-462F-866A-CBE1D9461D3B@xxxxxxxxxxxxxxxx I am trying to retrieve the number of days before password expiration that a user should be warned that their password will be expired. The property is set by setting the value for "Prompt user to change password before expiration" in the security policy. I am using C# and the directory services namespace to retrieve the AD properties. For 2003 I found a property called ShadowWarning that contains this value. Two questions, first is this the proper AD property to check for this value in 2003. Secondly, what property in 2000 server would I check to retrieve this value?? - Follow-Ups: - Re: Active Directory Expiration Notification - From: Paul Williams [MVP] - References: - Re: Active Directory Expiration Notification - From: Joe Kaplan \(MVP - ADSI\) - Re: Active Directory Expiration Notification - From: Joe Kaplan \(MVP - ADSI\) - Prev by Date: Re: trace logger for ADAM - "Windows NT Active Directory Service" - Next by Date: Re: Why 'allow log on locally" is not configured by default?? - Previous by thread: Re: Active Directory Expiration Notification - Next by thread: Re: Active Directory Expiration Notification - Index(es):
http://www.tech-archive.net/Archive/Windows/microsoft.public.windows.server.active_directory/2006-08/msg02301.html
crawl-002
refinedweb
710
51.18
In this section we are going to take a look at the Scene2D library. The first thing you need to be aware of is scene2d is entirely optional! If you don’t want to use it, don’t. All the other parts, except the bits built over Scene2D, will continue to work just fine. Additionally if you want to use Scene2D for parts of your game ( such as a HUD overlain over your game ) you can. So, what is scene2D? In a nutshell, it’s a 2D scene graph. So you might be asking “what’s a scene graph?”. Good Question! Essentially a scene graph is a data structure for storing the stuff in your world. So if your game world is composed of dozens or hundreds of sprites, those sprites are stored in the scene graph. In addition to holding the contents of your world, Scene2D provides a number of functions that it performs on that data. Things such as hit detection, creating hierarchies between game objects, routing input, creating actions for manipulating a node over time, etc. You can think of Scene2D as a higher level framework for creating a game built over top of the LibGDX library. Oh it also is used to provide a very good UI widget library… something we will discuss later. The object design of Scene2D is built around the metaphor of a play ( or at least I assume it is ). At the top of the hierarchy you have the stage. This is where your play (game) will take place. The Stage in turn contains a Viewport… think of this like, um… camera recording the play ( or the view point of someone in the audience ). The next major abstraction is the Actor, which is what fills the stage with… stuff. This name is a bit misleading, as Actor doesn’t necessarily mean a visible actor on stage. Actors could also include the guy running the lighting, a piece of scenery on stage, etc. Basically actors are the stuff that make up your game. So basically, you split your game up into logical Scenes ( be it screens, stages, levels, whatever makes sense ) composed of Actors. Again, if the metaphor doesn’t fit your game, you don’t need to use Scene2D. So, that’s the idea behind the design, let’s look at a more practical example. We are simply going to create a scene with a single stage and add a single actor to it. It’s important to be using the most current version of LibGDX, as recent changes to Batch/SpriteBatch will result in the following code not; public class SceneDemo implements ApplicationListener { public class MyActor extends Actor { Texture texture = new Texture(Gdx.files.internal("data/jet.png")); @Override public void draw(Batch batch, float alpha){ batch.draw(texture,0,0); } } private Stage stage; @Override public void create() { stage = new Stage(Gdx.graphics.getWidth(),Gdx.graphics.getHeight(),true); MyActor myActor = new MyActor(); stage.addActor(myActor); } @Override public void dispose() { stage.dispose(); } @Override public void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.draw(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } } Also note, I also added the jet image I used in earlier examples to the assets folder as a file named jet.png. See the earlier tutorials if you are unsure of how to do this. When you run the application you should see: As you can see it’s fairly simple process working with Stage2D. We create an embedded Actor derived class named MyActor. MyActor simply loads it’s own texture from file. The key part is the draw() method. This will be called every frame by the stage containing the actor. It is here you draw the actor to the stage using the provided Batch. Batch is the interface that SpriteBatch we saw earlier implements and is responsible for batching up drawing calls to OpenGL. In this example we simply draw our Texture to the batch at the location 0,0. Your actor could just as easily be programmatically generated, from a spritesheet, etc. One thing I should point out here, this example is for brevity, in a real world scenario you would want to manage things differently, as every MyActor would leak it’s Texture when it is destroyed! In our applications create() method we create our stage passing in the app resolution. The true value indicates that we want to preserve our devices aspect ratio. Once our stage is created, we create an instance of MyActor and add it to the stage with a call to stage.addActor(). Next up in the render() function, we clear the screen then draw the stage by calling the draw() method. This in turn calls the draw() method of every actor the stage contains. Finally you may notice that we dispose of stage in our app’s dispose() call to prevent a leak. So, that is the basic anatomy of a Scene2D based application. One thing I didn’t touch upon is actually having actors do something or how you would control one. The basic process is remarkably simple with a couple potential gotchas. Let’s look at an updated version of this code, the changes are highlighted:; public class SceneDemo2 implements ApplicationListener { public class MyActor extends Actor { Texture texture = new Texture(Gdx.files.internal("data/jet.png")); float actorX = 0, actorY = 0; public boolean started = false; public MyActor(){ setBounds(actorX,actorY,texture.getWidth(),texture.getHeight()); addListener(new InputListener(){ public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { ((MyActor)event.getTarget()).started = true; return true; } }); } @Override public void draw(Batch batch, float alpha){ batch.draw(texture,actorX,actorY); } @Override public void act(float delta){ if(started){ actorX+=5; } } } private Stage stage; @Override public void create() { stage = new Stage(); Gdx.input.setInputProcessor(stage); MyActor myActor = new MyActor(); myActor.setTouchable(Touchable.enabled); it you will see: Click the jet sprite and it’s action will start. Let’s take a closer look at the code now. Let’s start with the changes we made to the MyActor class. The most obvious change you will see is the addition of a constructor. I did this so I could add an event listener to our actor, that works a lot like event listeners we worked with earlier when dealing with input. This one however passes an InputEvent class as a parameter which contains the method getTarget(), which is the Actor that was touched. We simply cast it to a MyActor object and set the started boolean to true. One other critical thing you may notice is the setBounds() call. This call is very important! If you inherit from Actor, you need to set the bounds or it will not be click/touch-able! This particular gotcha cost me about an hour of my life. Simply set the bounds to match the texture your Actor contains. Another thing you may notice is a lot of the examples and documentation on Actor event handling is currently out of date and there were some breaking changes in the past! Other than the constructor, the other major change we made to MyActor was the addition of the act() method. Just like with draw(), there is an act() method that is called on every actor on the stage. This is where you will update your actor over time. In many other frameworks, act would instead be called update(). In this case we simply add 5 pixels to the X location of our MyActor each frame. Of course, we only do this once the started flag has been set. In our create() method, we made a couple small changes. First we need to register an InputProcessor. Stage implements one, so you simply pass the stage object to setInputProcessor(). As you saw earlier, the stage handles calling the InputListeners of all the child actors. We also set the actor as Touchable, although I do believe this is the default behavior. If you want to make it so an actor cannot be touched/clicked, pass in Touchable.disabled instead. The only other change is in the render() method, we now call stage.act() passing in the elapsed time since the previous frame. This is is what causes the various actors to have their act() function called. Scene2D is a pretty big subject, so I will be dealing with it over several parts.
https://gamefromscratch.com/libgdx-tutorial-9-scene2d-part-1/
CC-MAIN-2021-04
refinedweb
1,401
64.71
CodePlexProject Hosting for Open Source Software I created a global datatype through the admin console (PMG.Article.ArticleContent). The settings are the following Titie: ArticleContent Type name: ArticleContent Type namespace: PMG.Article both has caching and has publishing are not selected. I have some Fields in there too, but that's not the problem (I don't think). I created 2 data entries, and I want to query them through a C# method. I have a class library, PMG.Article, which has a class ArticleFacade in it. The problem is, I have no recognition of the PMG.Article.ArticleContent data type from by C#. I've read a ton of the articles, tried making Demo.User, and I can't see Demo.User either. using(DataConnection connection = new DataConnection) { var articles = from a in connection.Get<PMG.Article.ArticleContent>() a.ArticleId = 1 select a; } I get no intellisense for PMG.Article.ArticleContent. If anyone at all can throw an idea at me, I'd be forever greatful (until I have another problem that breaks my brain on a Friday). Thanks in advance. ~Brian Hi Brian Try to reference ~/Bin/Composite.Generated.dll, it should contain all the generated interfaces // Dmitry Hi Brian, we have a bug right now, where ~/Bin/Composite.Generated.dll do not get updated before you restart the webapp - if you use the "Tools | Restart Server" command in the C1 Console yo should force an update on Composite.Generated.dll - and then you should have sweet Intellisense :) Marcus Hey guys, I appreciate the help. I had already added the reference to Composite.Generated.dll, but reset the server and tried to remove it and add it numerous times, but I'm still not getting the namespace recognized. Just to be clear, this is a class library, that resides in the same solution, but not the WebSite project. I have a reference to the class library in my WebSite project, because through XSLT, I'm able to call the methods inside the class library. I have references to Composite.Generated in both the WebSite and my class lib. I've been resetting the server, removing the .generated.dll from my lib and re-adding it, and still, no PMG.Article namespace is found. Any other ideas? Or, is there a better way to do what I'm trying to do? I'm not opposed to moving some things around here and there. All I'm really doing here is creating a data layer so through the XSLT functions I can call my C#, which will be able to sort the datatype objects and return back what the site is looking for. I've poured through a bunch of the articles, and they all seemed to point to this being the way you want to do things. If you're having your own Class Library where you want to manage your data layer, you should consider defining the datatypes in there as well. That way you will never have any problems references your data type interfaces. These articles show you how to create datatypes directly in your code and not by the WYSIWYG designer. Hey guys, One more question along the same lines. We were having trouble with the Composite.Generated. The server restart (and a bunch of other button mashing) would cause the Composite.Generated to be rebuilt on some users' machines, but not on others. So, recently I've created my datatype entirely in code behind. I've called the EnsureCreateStore function at startup and have verified that the tables get created in the database. But, the kicker is that I can't see this datatype anywhere in the CMS. I need to be able to add it as a global datatype so that my users can add data through the CMS, and that my code behind still has full access to the type. Any suggestions? Thanks Jon I scratched my head on this one the first time as well, but basically you need to create your own TreeDefinition for what is known in C1 terminology as Static Types. The Global Data folder is only for Dynamic Types. It's VERY easy though... lets say the type is called Departments. Create a departments.xml file under /App_Data/Composite/TreeDefinitions and use content similar to this <?xml version="1.0" encoding="utf-8"?> <ElementStructure xmlns="" xmlns: <ElementStructure.AutoAttachments> <NamedParent Name="Content" Position="Bottom" /> </ElementStructure.AutoAttachments> <ElementRoot> <Children> <Element Label="Departments" Id="departments" Icon="pagetype-pagetype-rootfolder" OpenedIcon="pagetype-pagetype-rootfolder-open"> <Actions> <AddDataAction Type="gl.sermersooq.Data.Types.IDepartment, gl.sermersooq" Label="Add" Icon="home-add"/> </Actions> <Children> <DataElements Type="gl.sermersooq.Data.Types.IDepartment, gl.sermersooq" Icon="folder"> <Actions> <EditDataAction Label="Edit" Icon="media-edit-media-folder"/> <DeleteDataAction Label="Delete" Icon="home-delete"/> </Actions> </DataElements> </Children> </Element> </Children> </ElementRoot> </ElementStructure> We haven't made a tool that automatically generate the trees and UI for code based data types (custom IData interfaces written in C#) - you need to build this UI also. The workload can be pretty lightweight though - 2 fairly simple XML files can do it." />. application samples for inspiration. Thanks guys, works like a charm. I think the conceptual barrier was understanding when you shift from working in code over to working with markup and in the admin console. From: mawtex [email removed] Sent: Tuesday, June 28, 2011 12:47 PM To: jmoss@studiopmg.com Subject: Re: Cant find my global datatype in C# [CompositeC1:260994] From: mawtex 1. A tree definition (documentation, video) - a XML file you create in ~/App_Data/Composite/TreeDefinitions. The content of the XML is a domain specific language for declaring tree structures for the C1 Console and what commands tree elements have. 2. A form definition (documentation) - a XML file that layout the form for adding and editing data of your type. It declares UI elements like 'textbox' and how they are bound to data. 3. Optional extension points: types of actions tree definitions can have like a custom aspx files, form workflows, a C# based tree definition, custom asp.net controls and functions running inside existing forms." />. Yes, we have a gap here in our documentation - we will get some 'how to' docs up soon. I finally got past this (my problem at least). From a post back in October... 1) Create a backup 2) Stop the related application pool in IIS 3) Rename App_Code to App_Code1 4*) Move dll-s that are using Composite.Generated.dll, from "/Bin" to "/Bin/Temp" folder 5) Delete file /Bin/Composite.Generated.dll 6) Delete all the files under /App_Data/Composite/Cache/Assemblies 7) Start app pool, run composite backend. (It is possible that backend will not be loaded, in this case just wait 20 seconds) 8) Stop app pool 9) Check that file /Bin/Composite.Generated.dll has been created 10*) Move dlls that were moved on step (4) from "/Bin/Temp" to "/Bin" 11) Rename /App_Code1 to /App_Code 12) Start the application pool It seems that sometimes the Composite.Generated is happy, and sometimes it just decides to not keep in sync. I don't know the rhyme or reason for it, but after 2 very frustrating weeks and doing a million workarounds, I'll finally now be able to start doing things "the right way". We will add this as a blocking issue and have this fixed in our next release. I'm sorry about the inconvenience. If anyone knows how to reproduce this issue, please post the steps here :) @jmoss We have added a compact sample on the topic, with 'read more' links; Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://c1cms.codeplex.com/discussions/260994
CC-MAIN-2017-51
refinedweb
1,300
57.06
#include <ts_trans_int.h> Inheritance diagram for ts_trans_int:: The TS transform is an extension of integer version of the Haar trasform (which is sometimes referred the S-transform in the image processing literature. The TS transform is an integer version of the so called Cohen-Daubechies-Feaveau (3,1) transform. Here the (3,1) refer to 3 vanishing moments for the wavelet function and 1 vanishing moment for the scaling function. The equations for the lifting scheme version of the forward TS transform are shown below. As with all lifting scheme algorithms, the inverse transform exchanges addition and subtraction operators. The TS transform and the S transform are the same in the first two steps (the first predict and update steps). An average interpolation step is added to the S (Haar) transform. d(1)1,i = s0,2i+1 - s0,2i s1,i = s0,2i + floor( d(1)1,i/2 ) d1,i = d(1)1,i + floor((s1,i-1 - s1,i+1)/4.0 + 0.5) This notation and the algorithm implemented here is taken directly from Wavelet Transformst that Map Integers to Integers by A.R. Calderbank, Ingrid Daugbechies, Wim Sweldens, and Boon-Lock Yeo, 1996 The mathematical structure is reflected in the class structure. Here the ts_trans_int class extends the haar_int class. The haar_int class provide the predict() and update functions. An additional predict2() function is added that implements interpolation step. Since an extra step has been added, the forwardStep and inverseStep functions in the base class ( liftbase) are over-ridden by ts_trans_int. A brief note on vanishing moments This algorithm is commonly known as the CDF (3,1) wavelet algorithm. As noted above, these numbers refer to the vanishing moments. I have never found a definition of "vanishing moment" that made intuitive sense to me, at least when applied to wavelet basis functions. As I understand the definition, a vanishing moment is a region over which the integral is zero. So the area of sin(x) in the region 0..2Pi has an integral of zero, since the region between 0..Pi results in a positive integral and the area between Pi..2Pi results in the same integeral value, but with a negative sign. The sum of these two regions is zero. If a wavelet were constructed from the sine function, such that x = {0..2Pi} : y = sin(x) x = anything else : y = 0 This would be a wavelet with "compact support" (it is a defined for a finite region, 0..2Pi) and one vanishing moment. Definition at line 113 of file ts_trans_int.h.
http://www.bearcave.com/misl/misl_tech/wavelets/forecast/doc/classts__trans__int.html
CC-MAIN-2017-47
refinedweb
428
56.96
I decided to write these tutorials after I realized that I didn’t really understand how C# handled transparency. I was doing some alpha blending and the resulting colors were not what I expected. So I built a tool, AlphaBlender Figure 1, to show a Venn diagram of the colors mixed like in standard color theory texts and I was further puzzled that the tool produced an image unlike any I’d seen in school. Figure 1 AlphaBlender demo application Figure 2 shows what I got versus what I expected. Figure2, Alpha blend versus my expectations of ‘real’ blended colors Well… nobody told me that alpha blending was supposed to be like my expectations; in fact, I am frequently surprised at how little anything works like I first expect it too. So I decided to write these tutorials to help me understand what’s really going on with transparency in C#. In each of these tutorials, we consider the ‘what’ before the ‘how’-- a discussion is presented of the concepts behind the code, and then at the end, we look at the code behind the concepts. In the code section, I’ll introduce each relevant new element of GDI+ as it occurs, and I won’t mention it again if it reoccurs in later code. This should help with redundancy and get the elementary stuff over with quickly. Also a word of caution: I’m no C# guru. I’ve written the demonstration code to illustrate the transparency concepts, not to demonstrate good programming practice. I encourage any and all to send me comments on my coding practices and how I might improve them. Color is a human thing. It is defined by our ability to perceive a narrow band of the electromagnetic spectrum that we call visible light. Our eyes have ’rod’ cells that sense variations in black and white, and we have three types of cone cells, one each for red, green and blue. We can simulate our perception of color by mixing red, green, and blue, which is what a computer monitor does. This brings us to the natural use of these components to create colors in C#, where a color is a 32-bit structure of four bytes for Alpha, Red, Green, and Blue Alpha is a transparency parameter that defines how much of the existing display color pixel that should ‘show through’ the new color. I propose that if a picture is worth a thousand words, then a demo program is worth a ten thousand. The following demonstrations show some things about transparency use in C#. I wrote ColorMaker, Figure 3, to show the effect of varying each of the color structure parameters. The color is created over a gradient, black to white, to illustrate how the Alpha value affects the ‘show through’ of the background color Figure 3, ColorMaker demo application Next I wrote WhatColorIsIt, Figure 4, to show the color parameters for any pixel on the screen. (This demo is based on Charles Petzold’s WhatColor example from his C# book). Figure 4, WhatColorIsIt demo application I combined what I learned with these two programs and wrote Spectrum, Figure 5, which simulates the color spectrum of visible light and allows the user to read the color parameters. Figure 5 Light spectrum simulation demo application I started this tutorial because I didn’t understand how alpha blending actually worked. Figure 1 shows what I was getting versus what I was expecting, and it also shows fairly obviously what is really going on. Alpha blending does not work like blending light; it works like stacking glass filters. If you take a red, green, and blue glass filters and lay them on a background, you would get an effect like what we see in the demo. Filters with 50% transparency should look like the demo with alpha set to 127. Here’s the alpha blend algorithm: displayColor = sourceColor×alpha / 255 + backgroundColor×(255 – alpha) / 255 I did some calculations starting with an opaque white background to see what this gives Add a 50% transparent red pixel over an opaque white pixel:sourceColor(127,255,0,0) ( Red, 50% transparent)background Color(255,255,255,255) (Opaque white) displayColor Red = ( 255 * 127/255) + (255)*(255 – 127)/255 = 255; displayColor Green = (0 * 127/255) + (255)*(255 – 127)/255 = 127; displayColor Blue = (0 * 127/255) + (255)*(255 – 127)/255 = 127; Resulting Color (127,255,127,127) Add a 50% transparent green pixel over the results:sourceColor(127,0,255,0) ( Green, 50% transparent)backgroundColor(127,255,127,127) displayColor Red = (0 * 127/255) + (255)*(255 – 127)/255 = 127; displayColor Green = (255 * 127/255) + (127)*(255 – 127)/255 = 192; displayColor Blue = (0 * 127/255) + (127)*(255 – 127)/255 = 65; Resulting Color (127,127,192,64) Add a 50% transparent blue pixel over the results:sourceColor(127,0,0,255) ( Blue, 50% transparent)background Color(127,127,192,64) displayColor Red = (0 * 127/255) + (127)*(255 – 127)/255 = 64; displayColor Green = (0 * 127/255) + (192)*(255 – 127)/255 = 96; displayColor Blue = (255 * 127/255) + (64)*(255 – 127)/255 = 159; Resulting Color (127,64,96,159) Compare the ‘real’ world to the GDI+ world with 50% transparent colors: ‘Real World’ GDI+ WorldRed over white (255,0,0) - Pink. (255,0,0) - PinkGreen over results (255,255,0) - Yellow (127,192,64) – Light Olive?Blue over result (255,255,255) - White. (64,96,159) – Dark Slate Blue? I did the same calculations starting over opaque black and got: Red over black (127,0,0) – Med. Red (127,0,0) – Med. RedGreen over results (127,127,0) – Med. Yellow (64,127,0) – Dark Olive?Blue over results (127127,0) – Med. Gray (32,64,127) – Gray Navy? Conclusion: Alpha blending simulates real world transparency for one layer only. I wrote a tool, Alpha Demonstrator Figure 6, to show the effect of ‘stacking’ order and background color to further illustrate what’s really going on. You can change the stacking order and background color in the demo to view each stacking and background color permutation. Figure 6, Alpha Demonstrator To wind things up for this tutorial, I wrote Color Demo, Figure 7, which shows additive and subtractive color and effects of various backgrounds, the way I think they should look to simulate the ‘real’ world. Figure 7 Color Demo illustrates additive and subtractive color theory Note on flicker-free drawing Some of these tutorial demos push the systems resources and flicker like crazy using ‘standard’ C# coding practices. There are many ways to prevent flicker and I present one way to use a double buffering technique to get fairly flicker free drawing. I say ‘fairly’ because Windows© will draw your image buffer to the screen when it damn well pleases. It would be best to put your buffer into screen memory during the CRT’s vertical blanking interval when nothing is being written to the screen (I’m not sure if this is true for LCD’s). If Windows© is in the process of writing your image in memory as the CRT ‘paints’ the screen through the memory you are using, the loaded part will show, but the rest won’t since it hasn’t been loaded yet. Windows© finishes loading and on the next screen painting cycle the full image shows up. This causes a kind of flicker called ‘tear’ and I know of no way to prevent this in GDI+. In DirectDraw you would load your buffered image during the vertical blanking interval and avoid tear. That said, the double buffering used here prevents most of the flicker that you’d see if you don’t use double buffering and yields results that I can live with. First you set the style using the Control.SetStyle method for setting flags that categorize supported behavior. The flags are listed in the ControlStyles enumeration. We will use three: Control.SetStyle AllPaintingInWmPaint WM_ERASEBKGND UserPaint DoubleBuffer In your form constructor add the following styles: public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true); } Next you override the OnPaint method and draw the background: OnPaint protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { // Fill in Background (for efficiency only the area that has been clipped) e.Graphics.FillRectangle(new SolidBrush(SystemColors.Window), e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width, e.ClipRectangle.Height); // // Do your drawing // // // Make darn sure you dispose of everything that you create // that is disposable (brushs, pens, bitmaps, etc.). Garbage // collection will get rid of the stuff eventually, but it is // real easy to overload the system with lots of paints. // } The ColorMaker, Figure 3, allows the user to use slider controls to set the red, green, blue, and alpha parameters of the color structure and paint the results over a black to white gradient background. We create a rectangle for the gradient and the color. // Create rectangle private Rectangle rect = new Rectangle(8, 48, 272, 72); The user uses scroll bars sets the color elements. private void trackBarRed_Scroll(object sender, System.EventArgs e) { int temp = trackBarRed.Value; if(temp>255)temp = 255; red = (byte)temp; labelRed.Text = "Red: " + red.ToString(); Refresh(); } In the OnPaint method we create the gradient box by first creating a gradient brush that will make a black to white horizontal gradient. // Create back box brush LinearGradientBrush lgBrush = new LinearGradientBrush(backRectangle, Color.Black, Color.White, LinearGradientMode.Horizontal); We then draw this box to the screen using the Graphics FillRectangle method. // Create back box fill e.Graphics.FillRectangle(lgBrush,backRectangle); Next we create the colorBrush from color elements provided by the slider values. // Create transparent brushes SolidBrush colorBrush = new SolidBrush(Color.FromArgb(alpha,red,green,blue)); We then draw the color over the gradient // Create the color box fills e.Graphics.FillRectangle(colorBrush,rect); And don’t forget to clean up. // Dispose now to conserve system resources lgBrush.Dispose(); colorBrush.Dispose(); This is the demonstration that got me to thinking about all this in the first place. As I said in the beginning, it didn’t behave like I expected, instead it did just what it was supposed to. AlphaBlender, Figure 1, adds FillEllipse to the prior discussion. // Create circle fills e.Graphics.FillEllipse(redBrush,redRectangle); e.Graphics.FillEllipse(greenBrush,greenRectangle); e.Graphics.FillEllipse(blueBrush,blueRectangle); WhatColorIsIt, Figure 4, is derived from WhatColor.cs © 2002 by Charles Petzold,. It uses COM Interoperability, which allows C# users to access non-GDI+ functions from the Win32 API. This is hardly a beginner topic, but I’ve included it here because the tool itself is so useful and it gives quick insight in how to expand your C# toolset. Make certain that you dispose of anything you create from a DLL since it is unmanaged and doesn’t get garbage collected when you close. At the top of the code we add: using System.Runtime.InteropServices; In the Form1 class we define the external Win2 functions: [DllImport("gdi32.dll")] public static extern IntPtr CreateDC(string strDriver, string strDevice, string strOutput, IntPtr pData); [DllImport("gdi32.dll")] public static extern bool DeleteDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern int GetPixel(IntPtr hdc, int x, int y); We use the form designer to add a timer. Then we use the properties box to add the Tick event. To this we add our (well, Petzold’s) code. private void timer1_Tick(object sender, System.EventArgs e) { // Get the current mouse position (screen coordinates). Point pt = MousePosition; // Call the three external functions. IntPtr hdcScreen = CreateDC("Display", null, null, IntPtr.Zero); int cr = GetPixel(hdcScreen, pt.X, pt.Y); DeleteDC(hdcScreen); // Convert a Win32 COLORREF to a .NET Color object clr = Color.FromArgb((cr & 0x000000FF), (cr & 0x0000FF00) >> 8, (cr & 0x00FF0000) >> 16); // Only invalidate if there's a new color. if (clr != clrLast) { Invalidate(); } } In our OnPaint method we only do something if something has changed: if (clr != clrLast) { clrLast = clr; … And, to previously discussed concepts we add DrawString e.Graphics.DrawString("\nRed: " + clr.R.ToString("X00") + " - " + clr.R.ToString() + …More strings… ); To the concepts we’ve looked at so far, LightSpectrum, Figure 5, elaborates on the gradient brush to simulate a full spectrum of visible light. I reuse this code in several subsequent demonstrations, so in a real-world coding situation (this is an unreal-world) I’d put this stuff in its own class. This, as is, really has nothing to do with transparency, but I use it later as a backcolor for transparency demos. In the OnPaint method we add a new LinearGradientBrush with some dummy colors. LinearGradientBrush LinearGradientBrush brBrush = new LinearGradientBrush( rect, Color.Blue, Color.Red, LinearGradientMode.Horizontal); Then we create a color array for the gradient. This array is based on the assumption that the values used will give a good simulation, and to my eye it does. Color[] clrArray = { Color.FromArgb(255,0,0,0), Color.FromArgb(255,128,0,128), Color.FromArgb(255,255,0,255), Color.FromArgb(255,128,0,255), Color.FromArgb(255,0,0,255), Color.FromArgb(255,0,128,255), Color.FromArgb(255,0,255,255), Color.FromArgb(255,0, 255,128), Color.FromArgb(255,0,255,0), Color.FromArgb(255,128,255,0), Color.FromArgb(255,255,255,0), Color.FromArgb(255,255,128,0), Color.FromArgb(255,255,0,0), Color.FromArgb(255,128,0,0), Color.FromArgb(255,0,0,0) }; As with the color array, a points array is created with values that we assume will give use a good continuum in our simulation. float[] posArray = { 0.0f, 1.0f/14.0f, 2.0f/14.0f, 3.0f/14.0f, 4.0f/14.0f, 5.0f/14.0f, 6.0f/14.0f, 7.0f/14.0f, 8.0f/14.0f, 9.0f/14.0f, 10.0f/14.0f, 11.0f/14.0f, 12.0f/14.0f, 13.0f/14.0f, 1.0f }; Next we create an instance of the ColorBlend class, which defines color and position arrays used for interpolating color blending in a multicolor gradient ColorBlend colorBlend = new ColorBlend(); We then set the properties. colorBlend.Colors = clrArray; colorBlend.Positions = posArray; And next we set the LinearGradientBrush InterpolationColors property to our ColorBlend. // Set interpolationColors property brBrush.InterpolationColors = colorBlend; I built AlphaDemonstrator, Figure 6, to show more variations on alpha blending as it actually works and contrary to my expectations. No new code concepts are added, so no extra discussion is given. I wrote ColoDemo to provide a simulation of how I thought color and transparency should be simulated for the ‘real world’. That is, what do we need to do to get the effect of mixing paints or projecting colored lights? I hacked around a bit and came up with the following function: private Bitmap trueColorMix(Bitmap bitmap1, Bitmap bitmap2, int X, int Y, byte alpha) { Color clrPixel1; Color clrPixel2; int redMix,greenMix,blueMix; for(int i = 0; i < bitmap2.Width; i++) { for(int j = 0; j < bitmap2.Height; j++) { clrPixel1 = bitmap1.GetPixel(i+X,j+Y); clrPixel2 = bitmap2.GetPixel(i,j); redMix = ((int)clrPixel1.R + (int)clrPixel2.R); if(redMix > 255) redMix = 255; greenMix = ((int)clrPixel1.G + (int)clrPixel2.G); if(greenMix > 255) greenMix = 255; blueMix = ((int)clrPixel1.B + (int)clrPixel2.B); if(blueMix > 255) blueMix = 255; bitmap1.SetPixel(i+X, j+Y, Color.FromArgb(alpha, (byte)redMix, (byte)greenMix, (byte)blueMix)); } } return bitmap1; } This function receives the background bitmap1, the source bitmap2, the source X and Y locations and alpha for the blend. It iterates through each pixel of bitmap2 that overlays bitmap1, adds each pixel together, limiting the maximum value to 255, then resets the bitmap1 pixel to the new red, green, and blue values and sets alpha to the given alpha. This provides a good simulation of additive color over a black background. But it doesn’t work over white since, for white, bitmap1 starts out with all color values already at 255. Putting color over white, subtractive color, is what printers do, using Cyan, Magenta and Yellow as their primary colors. They also use black, since they can’t get a good black mixing the colors, calling their system CYMK, where K is the black. In the Color Demo code, all that’s needed to demo subtractive color is to start with a white background and subtract the pixels in bitmap2. In the next tutorial, we’ll begin with images by looking at the CompositingMode Enumeration and the ColorMatrix, and ImageAttributes classes for making color changes to entire images. ImageAtt.
http://www.codeproject.com/Articles/6502/Transparency-Tutorial-with-C-Part-1?fid=36183&df=90&mpp=10&sort=Position&spc=None&tid=4005952
CC-MAIN-2015-14
refinedweb
2,746
54.12
12 July 2012 04:11 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The move follows a traffic accident on 29 June, in which a truck and an oil tanker collided on a highway in the city, resulting in an explosion which killed 20 people and injured 31 others, they added. Methanol freight rates rose by yuan (CNY) 20-30/tonne ($3-5/tonne), or 50%, from 29 June to CNY60-90/tonne in response to the tighter regulations on 3 July, a south China-based producer said. However, methanol buyers did not accept the higher costs and this weighed on methanol spot prices, a trader said. Methanol prices were at CNY2,700-2,730/tonne ex-tank south The ($1 = CNY6.37) Additional reporting by Sam Li
http://www.icis.com/Articles/2012/07/12/9577603/methanol-freight-rates-rise-in-chinas-guangzhou.html
CC-MAIN-2014-52
refinedweb
127
69.62
table of contents other versions - jessie 3.74-1 - jessie-backports 4.10-2~bpo8+1 - stretch 4.10-2 - testing 4.16-1 - stretch-backports 4.16-1~bpo9+1 - unstable 4.16-1 NAME¶proc - process information pseudo-filesystem DESCRIPTION¶The proc filesystem is a pseudo-filesystem which provides an interface to kernel data structures. It is commonly mounted at /proc. Most of it is read-only, but some files allow kernel variables to be changed. Mount options¶The behavior). - authorized to learn process information otherwise prohibited by hidepid (i.e., users in this group behave as though /proc was mounted with hidepid=0). This group should be used instead of approaches such as putting nonroot users into the sudoers(5) file. Files and directories¶The following list describes many of the files and directories under the /proc hierarchy. - . This attribute may change for the following reasons: - Resetting the "dumpable" attribute to 1 reverts the ownership of the /proc/[pid]/* files to the process's real UID and real/keys.t). - /proc/[pid]/clear_refs (since Linux 2.6.22) - This is a write-only file, writable only by owner of the process. The following values may be written to the file: - 1 (since Linux 2.6.22) - Reset the PG_Referenced and ACCESSED/YOUNG bits for all the pages associated with the process. (Before kernel 2.6.32, writing any nonzero value to this file had this effect.) - 2 (since Linux 2.6.32) - Reset the PG_Referenced and ACCESSED/YOUNG bits for all anonymous pages associated with the process. - 3 (since Linux 2.6.32) - Reset the PG_Referenced and ACCESSED/YOUNG bits for all file-mapped pages associated with the process. - Clearing the PG_Referenced and ACCESSED/YOUNG bits provides a method to measure approximately how much memory a process is using. One first inspects the values in the "Referenced" fields for the VMAs shown in /proc/[pid]/smaps to get an idea of the memory footprint of the process. One then clears the PG_Referenced: - 4 (since Linux 3.11) - Clear the soft-dirty bit for all the pages associated with the process. This is used (in conjunction with /proc/[pid]/pagemap) by the check-point restore system to discover which pages of a process have been dirtied since the file /proc/[pid]/clear_refs was written to. -_PROC_PAGE_MONITOR kernel configuration option is enabled. - /proc/[pid]/cmdline - This read-only file]/comm (since Linux 2.6.33) - This file exposes the process's comm value—that is, the command name associated with the process. Different threads in the same process may have different comm values, accessible via /proc/[pid]/task/[tid]/comm. A thread may modify its comm value, or that of any of other thread in the same thread group (see the discussion of CLONE_THREAD in clone(2)), by writing to the file /proc/self/task/[tid]/comm. Strings longer than TASK_COMM_LEN (16) characters are silently truncated. This file provides a superset of the prctl(2) PR_SET_NAME and PR_GET_NAME operations, and is employed by pthread_setname_np(3) when used to rename threads other than the caller. - ). - /proc/[pid]). - that is being run by process [pid]. If the pathname has been unlinked, the symbolic link will contain the string '(deleted)' appended to the original pathname., and so on. bpf(2), epoll_create(2), eventfd(2), inotify_init(2), perf_event_open(2), signalfd(2), timerfd_create(2), and userfautfd(2)), the entry will be a symbolic link with contents of the form anon_inode:<file-type> In many cases (but not. For example, ... - Permission to dereference or read (readlink(2)) the symbolic links in this directory is governed by a ptrace access mode PTRACE_MODE_READ_FSCREDS check; see ptrace(2). - ). - . Permission to access this file is governed by a ptrace access mode PTRACE_MODE_READ_FSCREDS check; see ptrace(2). - /proc/[pid]/limits (since Linux--------. 1 root root 64 Apr 16 21:31 3252e00000-3252e20000 -> -------. 1 root root 64 Apr 16 21:33 7fc075d2f000-7fc075e6f000 -> /dev/zero (deleted) This directory appears only if the CONFIG_CHECKPOINT_RESTORE kernel configuration option is enabled.).. - [heap] - The process's heap. - If the pathname field is blank, this is an anonymous mapping as obtained via mmap: - (2) - parent ID: the ID of the parent mount (or of self for the top of the mount tree). - )). Lines in this file have the form: device /dev/sda7 mounted on /home with fstype ext3 [statistics] ( 1 ) ( 2 ) (3 ) (4) - The fields in each line are: - (1) - The name of the mounted device (or "nodevice" if there is no corresponding device). - (2) - The mount point within the filesystem tree. - (3) - The filesystem type. - (4) - Optional statistics and configuration information. (-) for factors including: - * - whether the process has been running a long time, or has used a lot of CPU time (-); - * - whether the process has a low nice value (i.e., > 0) (+); - * - whether the process is privileged (-); and - * - whether the process is making direct hardware access (-). - -1000 (OOM_SCORE_ADJ_MIN) to +1000 (OOM_SCORE_ADJ_MAX). This allows user space to control the preference for OOM-killing, ranging from always preferring a certain task or completely disabling it from OOM killing. The lowest possible value, -1000, is equivalent to disabling OOM-killing entirely for that task, since it will always report a badness score of 0. Consequently, it is very simple for user space to define the amount of memory to consider for each task. Setting] Documentation). - /proc/[pid]/root - UNIX and Linux support the idea of a per-process root of the filesystem, set by the chroot(2) system call. This file is a symbolic link that points to the process's root directory, and behaves in the same way as exe, and fd/*.: In a second terminal window, in the initial mount namespace, we look at the contents of the corresponding mounts in the initial and new namespaces: $ PS1='sh1# ' unshare -Urnm sh1# mount -t tmpfs tmpfs /etc # Mount empty tmpfs at /etc sh1# mount --bind /usr /dev # Mount /usr at /dev sh1# echo $$ 27123 In a multithreaded process, the contents of the /proc/[pid]/root). $ - /proc/[pid].) For each mapping there is a series of lines such as the following: 00400000-0048a000 r-xp 00000000 fd:03 960637 /bin/bash Size: 552 kB Rss: 460 kB Pss: 100 kB Shared_Clean: 452 kB Shared_Dirty: 0 kB Private_Clean: 8 kB Private_Dirty: 0 kB Referenced: 460 kB Anonymous: 0 kB AnonHugePages: 0 kB nl - non-linear mapping ar - architecture specific flag dd - do not include area into core dump sd - soft-dirty flag mm - mixed map area hg - huge page advise flag nh - no-huge page advise flag mg - mergeable advise flag ]. - (1) pid %d - (2) comm %s - The filename of the executable, in parentheses. This is visible whether or not the executable is swapped out. - a real-time scheduling policy (policy below; see sched_setscheduler(2)), this is the negated scheduling priority, minus one; that is, a number in the range -2 to -100,. - policy, virtual). - * - Ngid: NUMA group ID (0 if none; since Linux 3.13). - * - PPid: PID of parent process. - * - TracerPid: PID of process tracing this process (0 if not being traced). - * - Uid, Gid: Real, effective, saved set, and filesystem UIDs (GIDs). - * - FDSize: Number of file descriptor slots currently allocated. - * - Groups: Supplementary group list. - * - NStgid : Thread group ID (i.e., PID) in each of the PID namespaces). - * - capabilities(7)). - * - CapBnd: Capability Bounding set (since Linux 2.6.26, see capabilities(7)). - * - CapAmb: Ambient capability set (since Linux 4.3, see capabilities(7)). - * -. - * - voluntary_ctxt_switches, nonvoluntary_ctxt_switches: Number of voluntary and involuntary context switches (since Linux 2.6.23). - ), example: ID: 1 signal: 60/00007fff86e452a8 notify: signal/pid.2634 ClockID: 0 ID: 0 signal: 60/00007fff86e452a8 notify: signal/pid.2634 ClockID: 1 The lines shown for each timer have the following meanings: - ID - The ID for this timer. This is not the same as the timer ID returned by timer_create(2); rather, it is the same kernel-internal ID that is available via the si_timerid field of the siginfo_t structure (see sigaction(2)). - signal - This is the signal number that this timer uses to deliver notifications followed by a slash, and then the sigev_value value supplied to the signal handler. Valid only for timers that notify via a signal. - notify - The part before the slash specifies the mechanism that this timer uses to deliver notifications, and is one of "thread", "signal", or "none". Immediately following the slash is either the string "tid" for timers with SIGEV_THREAD_ID notification, or "pid" for timers that notify by other mechanisms. Following the "." is the PID of the process (or the kernel thread ID of the thread) that will be delivered a signal if the timer delivers notifications via a signal. - ClockID - This field identifies the clock that the timer uses for measuring time. For most clocks, this is a number that matches one of the user-space CLOCK_* constants exposed via <time.h>. CLOCK_PROCESS_CPUTIME_ID timers display with a value of -6 in this field. CLOCK_THREAD_CPUTIME_ID timers display with a value of -2 in this field. -). Permission to access this file is governed by a ptrace access mode PTRACE_MODE_ATTACH_FSCREDS check; see ptrace(2). - ). - ) and zgrep(1). As long as no changes have been made to the following file, the contents of /proc/config.gz are the same as those provided by : cat /lib/modules/$(uname -r)/build/.config - /proc/config.gz is provided only if the kernel is configured with CONFIG_IKCONFIG_PROC. - /proc/crypto - A list of the ciphers provided by the kernel crypto API. For details, see the kernel Linux Kernel Crypto API documentation available under the kernel source directory Documentation/DocBook. (That documentation can be built using a command such as make htmldocs in the root directory of the kernel source tree.) - are supported by the kernel, namely filesystems which were compiled into the kernel or whose kernel modules are currently loaded. (See also filesystems(5).) If a filesystem is marked with "nodev", this means that it does not require a block device to be mounted (e.g., virtual filesystem, network filesystem). Incidentally, this file may be used by mount(8) when no filesystem is specified and it didn't manage to determine the filesystem type. Then filesystems/keys (since Linux 2.6.10) - See keyrings(7). - /proc/key-users (since Linux 2.6.10) - See keyrings(7). - pagecount (since Linux 2.6.25) - This file contains a 64-bit count of the number of times each physical page frame is mapped, indexed by page frame number (see the discussion of /proc/[pid]/pagemap). - The /proc/kpagecount file is present only if the kernel source file Documentation/vm/pagemap.txt. Before kernel 2.6.29, KPF_WRITEBACK, KPF_RECLAIM, KPF_BUDDY, and KPF_LOCKED did not report correctly. - The /proc/kpageflags file is present only if the CONFIG_PROC_PAGE_MONITOR kernel configuration option is enabled. - )). The lslocks(8) command provides a bit more information about each lock. - fields. - MemAvailable %lu (since Linux 3.14) - An estimate of how much memory is available for starting new applications, without swapping. -. - Shmem %lu (since Linux 2.6.32) - Amount of memory consumed in tmpfs(5) filesystems. - Slab %lu - In-kernel data structures cache. (See slabinfo(5).) -) - further details, see. ( CONFIG_CMA is required.) - CmaFree %lu (since Linux 3.1) - Free CMA (Contiguous Memory Allocator) pages. ( CONFIG_CMA is required.) -. - CONFIG filesystems currently mounted on the system. With the introduction of per-process mount namespaces in Linux 2.4.19 (see mount_namespaces - This directory contains various files and subdirectories containing information about the networking layer. The files contain ASCII structures and are, therefore, readable with cat(1). However, the standard netstat(8) suite provides much cleaner access to these files. With the advent of network namespaces, various information relating to the network stack is virtualized (see namespacesTheing, information. - , and so on.: - user - (1) Time spent in user mode. - nice - (2) Time spent in user mode with low priority (nice). - system - (3) Time spent in system mode. - idle - (4) Time spent in the idle task. This value should be USER_HZ times the second entry in the /proc/uptime pseudo-file. -. - disk_io: (2,0):(31,30,5764,1,2) (3,0):... - (major,disk_idx):(noinfo, read_io_ops, blks_read, write_io_ops, blks_written) - filesystem, and the (deprecated) sysctl(2) system call. String values may be terminated by either '\0' or '\n'. Integer and long values may be written either in decimal or in hexadecimal notation (e.g. 0x3FFF). When writing multiple integer or long values, these may be separated by any of the following whitespace characters: ' ', '\t', or '\n'. Using other separators leads to the error EINVAL. - filesystems. - . System calls that fail when encountering this limit fail with the error ENPrivileged system needs to prune the inode list instead of allocating more; since Linux 2.4, this field is a dummy value (always zero). - .) - /proc/sys/fs/overflowgid and /proc/sys/fs/overflowuid - These files allow you to change the value of the fixed UID and GID. The default is 65534. Some filesystems support only. - /proc/sys/fs/protected_hardlinks (since Linux 3.6) - When the value in this file is 0, no restrictions are placed on the creation of hard links (i.e., this is the historical behavior before Linux 3.6). When the value in this file is 1, a hard link can be created to a target file only if one of the following conditions is true: - * - The calling process has the CAP_FOWNER capability in its user namespace and the file UID has a mapping in the namespace. - * - The filesystem UID of the process creating the link matches the owner (UID) of the target file (as described in credentials(7), a process's filesystem UID is normally the same as its effective UID). - * - All of the following conditions are true: - • - the target is a regular file; - • - the target file does not have its set-user-ID mode bit enabled; - • - the target file does not have both its set-group-ID and group-executable mode bits enabled; and - • - the caller has permission to read and write the target file (either via the file's permissions mask or because it has suitable capabilities). - behavior before Linux 3.6). When the value in this file is 1, symbolic links are followed only in the following circumstances: - * - the filesystem UID of the process following the link matches the owner (UID) of the symbolic link (as described in credentials(7), a process's filesystem UID is normally the same as its effective UID); - * - the link is not in a sticky world-writable directory; or - * - the symbolic link and its parent directory have the same owner (UID) - is assigned to a process's "dumpable" flag in the circumstances described in prctl(2). In effect, the value in this file determines whether core dump files are produced for set-user-ID or otherwise protected/tainted binaries. The "dumpable" setting also affects the ownership of files in a process's /proc/[pid] directory, as described above.. processes. -. - For details of the effect of a process's "dumpable" setting on ptrace access mode checking, see ptrace(2). - /proc/sys/fs/super-max - This file controls the maximum number of superblocks, and thus the maximum number of mounted filesystems the kernel can have. You need increase only super-max if you need to mount more filesystems than the current value in super-max allows you to. - /proc/sys/fs/super-nr - This file contains the number of filesystems/auto_msgmni (Linux 2.6.27 to 3.18) - From Linux 2.6.27 to 3.18, this file was used to control recomputing). Echoing ". - /ctrl-alt-del - This file controls the handling of Ctrl-Alt-Del from the keyboard. When the value in this file is 0, Ctrl-Alt-Del is trapped and sent to the init(1)/keys/* - This directory contains various files that define parameters and limits for the key-management facility. These files are described in keyrings(7). - (since Linux 2.2) - This file defines a system-wide limit specifying the maximum number of bytes in a single message written on a System V message queue. - /proc/sys/kernel/msgmni (since Linux 2.4) - This file defines the system-wide limit on the number of message queue identifiers. See also /proc/sys/kernel/auto_msgmni. - . - ). PIDs greater than this value are not allocated; thus, the value in this file also acts as a system-wide limit on the total number of processes and threads.. - of. Set this file to 1 only) -ctl overwrite buffer will be ignored. Writes to numeric /proc/sys entries must always be at file offset 0 and the value must be fully contained in the buffer provided to write(2). - maximum. - filesystem (NFS). On some systems, it is not present. - /proc/sys/vm - This directory contains files for memory management tuning, buffer and cache management. - /proc/sys/vm/admin_reserve_kbytes (since Linux 3.10) - This file defines the amount of free memory (in KiB) on the system that that should be reserved for users with the capability CAP_SYS_ADMIN. The default value in this file is the minimum of [3% of free pages, 8MiB] expressed as KiB. The default is intended to provide application requests memory. - /proc/sys/vm/compact_memory (since Linux 2.6.35) - When 1 is written to this file, all zones are compacted such that free memory is available in contiguous blocks where possible. The effect of this action can be seen by examining /proc/buddyinfo. - Present only if the kernel was configured with CONFIG_COMPACTION. - /proc/sys/vm/drop_caches (since Linux 2.6.16) - Writing to this file causes the kernel to drop clean caches, dentries, and inodes from memory, causing that memory to become free. This can be useful for memory management testing and performing): - 1: - Kill all processes that have the corrupted-and-not-reloadable_MEMORY_FAILURE. - /proc/sys/vm/memory_failure_recovery (since Linux 2.6.32) - Enable memory failure recovery (when supported by the platform) - 1: - Attempt recovery. - 0: - Always panic on a memory failure. - Present only_kbytes (since Linux 3.14) - This writable file provides an alternative to /proc/sys/vm/overcommit Commit. - /proc/sys/vm/overcommit_memory - This file contains the kernel virtual memory accounting mode. Values are: - 0: heuristic overcommit (this is the default) - In mode 0, calls of mmap(2) with MAP_NORESERVE are not checked, and the default check is very weak, leading to the risk of getting a process "OOM-killed".commit processes, This is intended to prevent a user from starting a single application requests memory. - /thread-self (since Linux 3.17) - This directory refers to the thread accessing the /proc filesystem,. - .0) - This file displays various virtual memory statistics. Each line of this file contains a single name-value pair, delimited by white space. Some files are present only if the kernel was configured with suitable options. (In some cases, the options required for particular files have changed across kernel versions,/transhuge.txt. - compact_fail (since Linux 2.6.35) - See the kernel source file Documentation/vm/transhuge.txt. - compact_success (since Linux 2.6.35) - See the kernel source file Documentation/vm/transhuge/transhuge.txt. - thp_fault_fallback (since Linux 2.6.39) - See the kernel source file Documentation/vm/transhuge.txt. - thp_collapse_alloc (since Linux 2.6.39) - See the kernel source file Documentation/vm/transhuge.txt. - thp_collapse_alloc_failed (since Linux 2.6.39) - See the kernel source file Documentation/vm/transhuge.txt. - thp_split (since Linux 2.6.39) - See the kernel source file Documentation/vm/transhuge.txt. - thp_zero_page_alloc (since Linux 3.8) - See the kernel source file Documentation/vm/transhuge.txt. - thp_zero_page_alloc_failed (since Linux 3.8) - See the kernel source file Documentation/vm/transhuge useful for analyzing virtual memory behavior.
https://manpages.debian.org/jessie-backports/manpages/proc.5.en.html
CC-MAIN-2022-40
refinedweb
3,245
58.08
Socialwg/2017-04-18-minutes Contents Social Web Working Group Teleconference 18 Apr 2017 Attendees - Present - cwebber, aaronpk, rhiaro, sandro, ajordan, eprodrom, KevinMarks, csarven, ben_thatmustbeme - Regrets Chair - eprodrom - Scribe - aaronpk Contents - Topics - Summary of Action Items - Summary of Resolutions <cwebber> o/ <Loqi> meeting time <Loqi> Countdown set by ben_thatmustbeme on 2017-04-18 at 2:27pm UTC <cwebber> agenda is at <cwebber> ajordan, np <rhiaro> o/ <scribe> scribenick: aaronpk <KevinMarks> May be irc only <eprodrom> last week's minutes <eprodrom> PROPOSED: Accept as minutes for previous telecon <cwebber> +1 <sandro> +1 <rhiaro> +1 <eprodrom> +1 <aaronpk> +1 RESOLUTION: Accept as minutes for previous telecon ActivityPub cwebber: a new tutorial for activitypub, i threw it together after sketching it out on paper. i was thinking about adding something like this to the introduction to the activitypub document eprodrom: i need an update on why we have a meeting today, since we had a scheduled meeting next week ... i understand there is a crucial deadline for activitypub? why are we here sandro: i wouldn't characterize it as quite that urgent. but it seems like activity is picking up on activitypub and we have a lot to do. ... i sent an email that there's a process loophole that gives us more time than we thought. we just have to get to PR by the charter, not REC by the charter. ... so we have until May 13th to make any normative changes if we really push the line. ... but given we have all this external interest, it seems like keeping the discussion going quickly is good. like if it turns out mastodon says you really need to make this change then we need to know this as soon as possible eprodrom: the thing i want to avoid is doing a deep dive on the tutorial for examle and then we have 5 minutes to do the important things ... do we have a vote we need to take by the end of the day? cwebber: no sandro: lets' focus on the things that are going to get the community together on an interoperable implementation eprodrom: so we're going to be going through some of the issues on activitypub and make sure we move things forward ActivityPub cwebber: we had an open item to include an introduction with clear diagrams and examples. i had sketched out on paper how to make it clear what's happening with the inbox and outbox. i turned that into the ascii art tutorial. ... a lot of people responded positively especially in the ostatus sphere ... i'd encourage people to read it and see what they think. one of the pieces of feedback we got before was "oh this seems like a lot" but now with the tutorial it's more "this is pretty straightforward" eprodrom: i've seen tutorials as separate documents. is it normal to have a tutorial in a spec document? sandro: if it goes through every feature then it makes sense separate, but this seems more like a hello world so it's fine in the spec eprodrom: the only thing i'm worried about putting such a large text in the spec is it asks for some definitions, but that's probably okay. getting the text right is non-normative so we don't have to worry about getting it perfect the first time out. Implementation Updates cwebber: there's been a lot of discussion. the most interesting is probably with mastodon. ... there's been a lot of questions, the leader seems supportive of exploring things. people seem to want activitypub because they want a better private distribution support. ... evanminto is making progress on it. we've got open issues elsewhere like diaspora, but that seems more like conversation right now. tho one person seems to think diaspora might move forward with it. ... other projects like postActiv and gnusocial are considering it. postActiv has someone assigned to it. ... for pump.io, they plan to do a branch soon as a feature branch but won't merge it until PR <ajordan> so for pump.io <ajordan> we will probably ship it preffed off July 1 <eprodrom> ajordan: can we get an implementation report and test results sooner? <ajordan> eprodrom: absolutely <eprodrom> +1 <eprodrom> Implementation reports are what get us out the door <ajordan> I'm planning on submitting an implementation report as soon as the code is written, which should be this week or the next week <eprodrom> eprodrom: there is a page which links to all the known open issues on different projects ... we are talking about getting implmeentations of server-to-server and client-to-server as separate things. mastodon was only interested in server-to-server for example. ... sounds like a lot of activity. pushing it through from open issues to online implementations will be the big move over the next few weeks. test suite cwebber: i know i said i'd have it earlier. it took me a while toget the interface stuff done, and have some initial test done, but i need to document it so you don't go insane looking at the code ... i'm feeling very optimistic about it. by next week we should have a much more exciting update. ... evan would you want to schedule time this week to do an overview of the code? or just email eprodrom: yeah i'm happy to sit down and talk about it ... i volunteered to help out with the test code, if anyone else wants to help then you're welcome to come otherwise it's not a helpful meeting to be at activitypub issues <ajordan> which meeting? next WG meeting? cwebber: i put the issues that need more heavy discussion first <cwebber> cwebber: there are two sides for this. pump.io has this and we somehow omitted it. ... every object can be favorited and liked and shared around, and you want to track that. ... pump.io has two names for this, "likes" and "shares" ... and we don't have those ... hilariously we've clobbered the namespace. we use "likes" to be what pump.io calls "favorites" ... i think what we need to do is add these two properties "shares" and "likes" and possibly rename the "actors" collection to "favorites" to avoid a naming collision <ajordan> I believe favorites and likes are the same thing in pump.io? eprodrom? eprodrom: that seems reasonable <eprodrom> {totalItems: 30, url: "..."} eprodrom: this would be a valid collection <eprodrom> {type: "Collection", totalItems: 30, ...} eprodrom: there's a way to link to the collection with the number and url for the collection ... the big thing is getting the number out ... there's synchronization issues when you include numbers like this across boundaries, but i think that's a reasonable mechanism cwebber: i think one advantage of using the collection is it could be someone included just the number but hopefully they included all the objects as well ... you can't really trust a number you get across a federated boundary anyway ... i think it's useful to have it be a number and also a collection sandro: i was worried about the security there. if you get all the objects, you can dereference as many as you like, and see that they check out. if you get a number, you can't verify it, an attractive nuicance. cwebber: that's why having it be a collection with a number as a cache is the best route sandro: what would you do with the number? if you display it, then you've propagated the attractive nuisance to the user. cwebber: all the federated implementations have that problem anyway. you either trust that number or you don't sandro: we should at least say something in the security considerations. ... is there also some sort of security checks you should or must do before passing the number on? cwebber: i'm hesitant to suggest that because i don't think we'd get that completely right rhiaro: i wanted to comment on renaming the collection ... favorites bugs me because there are two spellings of it ... could we call it something more precise like "things liked"? cwebber: we could call it 'liked' instead of 'likes' eprodrom: 'likes' is a link to a collection of objects this actor has liked cwebber: okay i think that will be a normative change so we've already entered that territory. <rhiaro> yep cwebber: given the comments sandro has made then we should just do normative changes instead of trying to work around that <cwebber> cwebber: i wanted amy's feedback on this. we mention that you can discover an actor's profile at one point in the exit criteria and then it's never mentioned again. ... shoudl we allow the profile to be used as an actor. it allows people to have multiple identities. Zakim: who is on the call? Zakim: who is here? <eprodrom> Please mute you mic <cwebber> muted <eprodrom> Muted <csarven> Muted when joined <ajordan> already muted <aaronpk> muted <eprodrom> Thank you <rhiaro> always muted when I'm not talking <eprodrom> KevinMarks: ? <ben_thatmustbeme> oops <csarven> ^^^ that guy <ajordan> lol cwebber: it looks like amy made a suggestion on this issue already ... that would allow people to create sub-identities for themselves. does that seem like ar easonable thing to add? ... does that mean the new profiles would have their own inbox and outbox? rhiaro: i feel like making it clear that it's allow, then let the implementations decide how it's allowed ... i think all we need for activitypub is to make it clear you can use it eprodrom: this feels like a lot of complication without a lot of payoff ... having multiple profiles with multiple endpoints, i don't see a lot of reason to not just use multiple accounts in that case <cwebber> cwebber- eprodrom: it seems like we're using it because it got into activitystreams and i'm not a fan of how it got there either. so unless there's a clear use case we need this then i feel very -1 on this cwebber: i'm okay with it existing as long as we treat it exactly like an actor object anyway <rhiaro> right cwebber: but i agree if we start doing the thing where the implementation needs to traverse and find the relationship between it and the actor then it will add more complexity ... i'm okay with including it but i dont feel strongly about it <rhiaro> Talkinga bout different personas was the use case. Not something I think should be in the spec. <rhiaro> I don't want to add ANY of this stuff to the spec. eprodrom: once we're talking about different identities, like evan as w3c chair, or evan as fuzzy.io ceo, or evan as father of children, those are all different aspects to my personality. i think diaspora calls that aspects event. ... what we do for that is lists in pump.io and direct things to different follower lists <ajordan> ajordan- cwebber: i might have a quick way to resolve this. <rhiaro> but Profile isn't listed in AS2 as an actor type <rhiaro> just under objects cwebber: to drop all the language about the profile object. since activitypub says these are generally activitystreams actor types then it's expected you're probably producing one of the existing ones. if someone wants to go crazy they can. <rhiaro> q <Zakim> rhiaro, you wanted to comment on rename of actor's likes and to and to rhiaro: i said it was an implementation detail, so we leave it open for implementations but we don't add anything to the spec ... that's whyu i suggested adding the "or a profile object" because profiles aren't actors ... but i wouldn't try to figure out implemnentation details in the spec eprodrom: i feel like this is important but complex. if an implementation has a Profile as one of the things that has inbox/outbox etc then that's up to the implementation ajordan: since we're talking about complexity, it's worth noting that getting the privacy right on this is difficult. <cwebber> I agree re: privacy w/ these use cases eprodrom: adding a privacy note to the security considerations is probably important. sandro: so far this has been too loosey-goosey to know what the argument is. so maybe we can look at this as what will the test suite have different based on the resolution of this <ajordan> so we talkd earlier about treating Profiles as Actors so they didn't share inboxes or anything, but assuming that wasn't the case there's this issue of identity correlation based on inbox URLs cwebber: i don't think the test suite would do anything differently <ajordan> no nono eprodrom: let's focus on profiles as actors ... it seems like we could add that to the test suite ... have a Profile that you can follow as if it were an Actor cwebber: are people fine with adding the Profile object then? ... my suggestion for how to close this out is to just not mention it and it wouldn't specifically be blocked it would just be not mentioned ... would people prefer to include it as an option? or just be never mentioned? sandro: we need test cases either way ... otherwise we don't have interoperability cwebber: i suggest we include it and add a test case ... adopting the language amy added, and mentioning it in the security section, and adding it as a test case <eprodrom> PROPOSED: Accept rhiaro's edit to close <cwebber> +1 <eprodrom> +1 <rhiaro> +1 <ajordan> +1 <sandro> +1 with new test case <ben_thatmustbeme> +1 sounds reasonable RESOLUTION: Accept rhiaro's edit to close <cwebber> <cwebber> cwebber: actually if we only have 10 minutes let's go back to the previous issue ... we never ended up saying what the "share" object was ... we used to have a "share" object in AS2 but it was dropped ... now we have an "announce" object which is ambiguous and doesn't mean "share" <cwebber> eprodrom: this is sharing cwebber: we're going to agree that this is sharing and i'll add the side effects to the document then? <cwebber> cwebber: one challenging thing is the webfinger side of things. this came up from mastodon ... how do people migrate from using webfinger identity into a https identifiers rather than webfinger ... i have a suggestion for how to do this <cwebber> cwebber: in this mastodon thread, sandro pointed out that we can use the acct uri, it could create problems by using both a mixture of https and acct URIs ... so my suggestion is to add an informative section as follows ... you'd end up saying okay if you have a post that uses a webfinger ID in the UI somewhere, you look up the webfinger ID and look up their https address to send it via activitypub ... the other thing is you have an actor's profile, how do you look up what the webfinger ID is. my suggestion is you take the "preferred username" slot and append @ the domain name ... however there's a possibly problem. there's the possibility that preferredusername is not unique ... eprodrom do you have comments on this? <eprodrom> webfinger: "evan@e14n.com" eprodrom: it seems to me like a property "webfinger" would solve the problem ... i agree that doing webfinger lookup to get the activitypub ID is good, we may need to define a link type to make that happen ... i'm not sure this is core to activitypub though, this might need to be an extension cwebber: i think your suggestion of adding a webfinger property is good especially since this is coming up now eprodrom: my suggestion is to make it an extension ... a bridge between webfinger and actiivtypub. it's only important right now because there are people using webfinger but that might drop off cwebber: i don't know what to say to the mastodon people then, if we don't have any extension process now. sandro: i think it would be great to see how lightweight we can make the extension process then eprodrom: could it be a wiki page? <KevinMarks> What is the webfinger use case? Give me the profile url for $username at $domain? eprodrom: anyone doing a new implementation of activitypub would look at that section and say why do i need to support webfinger? <ajordan> KevinMarks: basically <ajordan> we're discussing transitioning legacy Webfinger systems eprodrom: i think just because mastodon wants it now, isn't a good reason to include it for the people reading this 10 years from now cwebber: i guess we're out of time so iw on't bring up any more issues ... the spec didn't permit federation without client to server but last week we talked about allowing that <KevinMarks> I think there is a much simpler way to do that. eprodrom: do we need fto have a discussion about that cwebber: there's nothing that jumps out to me as long as people are okay with ...... eprodrom: i'm going to ask to extend for 10 minutes <sandro> +1 extending whatever's useful eprodrom: i don't udnerstand your question. do you want us to look through the list and see if anything else needs to be addressed today? cwebber: i'm just getting confused by process i guess <eprodrom> PROPOSED: Extend meeting by 30 minutes <sandro> +1 <cwebber> +1 <ajordan> +1 <wilkie> do we have a wiki for activity pub for cwebber and my own notes on the webfinger/identity legacy stuff? because it should go there, not in the spec itself, I'd think <rhiaro> +1 <eprodrom> +1 <sandro> wilkie, sure, the group wiki is the w3c wiki which is fine RESOLUTION: Extend meeting by 30 minutes <eprodrom> wilkie: agreed! <KevinMarks> +1 for Wiki about webfinger replacement sandro: if it's going to affect the test suite, change implementations, or make someone mad, then bring it to the group. otherwise you don't need to. <cwebber> cwebber: inboxes. this is a conversation that amy and i went through already. <KevinMarks> Wilkie: I have some ideas on replacing webfinger to contribute as well. rhiaro: this is basically a clarification but turns out to be a normative clarification <eprodrom> <wilkie> we don't need to *replace* webfinger, I mean... that's a little bit extreme rhiaro: whenever we say "inboxes must accept post request" we caveat that with "federated implementations" because some implementations may not accept post requsts and still be valid <eprodrom> PROPOSED: close issue 189 by adding text from <KevinMarks> Implementing webmention is extreme, I think we can do something much simpler. <cwebber> +1 <ajordan> +1 <eprodrom> +1 <wilkie> +1 <rhiaro> +1 <KevinMarks> (I meant replace in the mastodon codebase/ostatus stack) RESOLUTION: close issue 189 by adding text from <sandro> +1 <cwebber> cwebber: we have endpoints for OAuth authorize, but never added an endpoint for getting an access token ... this person suggested adding it to the endpoint section ... i haven't thought what the best name for it is sandro: everyone has to do this? or only if you're doing oauth? cwebber: only if you're doing oauth ... it doesn't make anyone reverse anything they already did. eprodrom: i'd like to push this to the end of the call <eprodrom> PROPOSED: close by adding properties with names from OAuth2 spec and revising current oauthClientAuthorize property name <cwebber> +1 <ajordan> +1 <eprodrom> +1 <sandro> +1 <aaronpk> +1 RESOLUTION: close by adding properties with names from OAuth2 spec and revising current oauthClientAuthorize property name <rhiaro> +1 <cwebber> cwebber: there's some ambiguity around what ambiguity means. it sounds fine but it makes it sound like the only way to do delivery is HTTP post ... but there's an obvious exception which is that you don't have to do this if you're on the same server ... so i don't want to make it sound like iuf you're on the same server you have to do a POST to yourself <eprodrom> eprodrom: amy gave some proposed text in a comment <eprodrom> PROPOSED: close issue 198 by including text from <eprodrom> +1 <rhiaro> +1 <ajordan> +1 <sandro> +1 <cwebber> +1 <wilkie> +1 RESOLUTION: close issue 198 by including text from <cwebber> cwebber: this person has experience around distributed database things. they suggested including revision IDs to avoid accidentally clobbering things eprodrom: you know there's an updated timestamp on activities, so the ID plus the updated timestamp should be unique enough to say what revision it is ... that's what we used for pump.io aaronpk- ajordan: using the timestamp assumes everyone's clock is reasonably synchronized eprodrom: i don't think it's as much as a big deal being synchronized as it is having your clock stay current. ... as long as i'm talking to you, we go by your clock. <KevinMarks> This is how Google's protocol ended up mandating atomic clocks sandro: is this supposed to be aligned in any way with HTTP? if you're doing a GET or PUT then HTTP has last-modified and etags which are all for revision control ... it would be nice if this is using URIs for things then to just use those eprodrom: there isn't really anything keeping it from being aligned. i think "update" ends up being the same as "last-modified" header. etag would map to this revision ID idea. <cwebber> cwebber: one reason to explore this in future efforts... as for adding anything new, we should wait for the future sandro: one simple thing we could do is to say that the time counter MUST increment. you try to make it an accurate time, but you at least never use the same timestamp twice. <KevinMarks> <Loqi> [Kevin Marks] @maiyannah can you just use etag/lastmodified for this? if the etag is a hash of the profile then it should do what you want. <KevinMarks> So fuzz leapseconds <cwebber> cwebber: if you imagine you're using any of these social networks, you might have your stream of posts and a different 1-1 conversation thread with someone ... the commenter said they want the private message flagged differently and not just the things streaming through the inbox ... there were a number of directions to go with this, a "priority" flag property <wilkie> I don't think you need to spec how the revision or tag is generated, just that it may be used to reject updates cwebber: i have a hard time thinking that we're going to make any sensible change to the spec within the timeframe we have ... but we're seeing that they're insistent we hvae some sort of flag, otherwise they will use an extension ... my feeling is to do this as an extension <wilkie> I don't understand the distinction they want and how audience tracking doesn't just solve this <wilkie> what is the difference between a message sent to only you and an important message sent to only you <rhiaro> I don't really understand why clients can't figure this out from the addressing and any other context they want to take into account <rhiaro> and different clients might handle it differently which is fine.. <wilkie> exactly <wilkie> clients will either ignore some measure of priority or publishers will abuse it ajordan: it's not clear when you should put individual people in the "to" field, so maybe that's where theconfusion is coming from <rhiaro> "Clients are responsible for addressing new Activites appropriately. To some extent, this is dependent upon the particular client implementation, but clients must be aware that the server will only forward new Activities to addressees in the to, bto, cc, bcc, and audience fields." ajordan: if you're trying to implement a feature that says this is a direct message, then you can say it's a direct message if there is only you in the "to" field <rhiaro> it actually says you must dereference addressed collections and individually address everything doesn't it? so maybe that's the problem.. cwebber: one more thought on this. my impression is that one thing pump.io has that activitypub doesn't have is the differentiation between a major feed and minor feed. ... it coudl be reasonable to say to the inbox give me all the stuff that's directed just to me <wilkie> rhiaro: ah typo there ... apparently "Activites" is in the document twice eprodrom: we're over our overtime rhiaro: there's a section about client addressing in the spec. whenever you find obects attached to an activity you shoudl follow these links and dereference the collections and put them in the "to" field <rhiaro> rhiaro: maybe we can't solve this now and we need to think about the wording some more cwebber: so i should remove the "postponed" flag since it seems like there is more conversation to be had eprodrom: let's wrap up the meeting since we're already over time <eprodrom> trackbot: end meeting Summary of Action Items Summary of Resolutions - Accept as minutes for previous telecon - Accept rhiaro's edit to close - Extend meeting by 30 minutes - close issue 189 by adding text from - close by adding properties with names from OAuth2 spec and revising current oauthClientAuthorize property name - close issue 198 by including text from [End of minutes]
https://www.w3.org/wiki/Socialwg/2017-04-18-minutes
CC-MAIN-2017-47
refinedweb
4,247
66.57
I need to manage my IIS7 (Windows Server 2008) remotely with a WMI IIS6 API. So I added the IIS6 WMI Compatibility and IIS6 Metabase Compatibility roles to access the root\MicrosoftIIsv2 namespace. I have a domain account which is not administrator on the remote machine ; with this right, everything is ok. I configured these rights for my domain account to access the root\MicrosoftIIsv2 WMI namespace remotely ; note that these rights work perfectly on a IIS6 and Windows Server 2003 : root\MicrosoftIIsv2 DCOM : WMI : IIS Metabase (Metabase Explorer) : I tried to give some access on C:\Windows\System32\inetsrv too ; don't know if needed. My issue is : I can't list the IIS WebSites (\root\MicrosoftIISv2:IIsWebServerSetting.Name="W3SVC/*"). I don't get an 'access denied' but nothing is returned. Get-WmiObject IIsComputer -namespace "ROOT\MicrosoftIISv2" -authentication PacketPrivacy | SELECT * Get-WmiObject IIsWebServerSetting -namespace "ROOT\MicrosoftIISv2" -authentication PacketPrivacy | SELECT ServerComment FI: I got a Warning Event 5605 with the Administrator right or not, that does not seem to have an impact : Ok, I have some more informations, when I use IIS 6 Metabase Explorer with my administrator account I can see the rights are correctly inherited for my non-administrator account. But when I try to connect using my non-administrator account, I can list the LM node, but get an "access denied, failed to get a key's data" when I try to browse the child nodes. LM I'll check further. I tried to Trace the WMI Activity, and everything seems OK ; this tends to confirm that the problem lies in IIS Rights. -authentication PacketPrivacy -authentication 6 Resolved. The WMI and IIS Metabase rights have to be set as you would do on an IIS 6. So they were correct for me. The specifity is on the IIS Metabase. First of all, in IIS 7 the W3SVC rights are completely inherited from the root while you have to set the W3SVC/AppPools rights on IIS 6 if you want to handle the application pools. W3SVC W3SVC/AppPools Since there's a 'compatiblity', the main difference resides in IIS 7 metabase file system. On IIS 6, the read rights on the inetsrv folder (which is the default for Users) and the Metabase ACLs are sufficient. Users On IIS 7, the rights have to be set on the IIS Metabase AND the IIS 7 configuration folder : %SYSTEMROOT%/system32/inetsrv/config (and .config files then). By default, only Administrators (thats why it is perfectly working with the Administrator right) and some other reserved groups can access this folder. %SYSTEMROOT%/system32/inetsrv/config Administrators Another point, if you need to execute methods like a Stop on an application pool, this feature require the Write rights on the configuration folder. Stop By posting your answer, you agree to the privacy policy and terms of service. asked 3 years ago viewed 5778 times active 2 years ago
http://serverfault.com/questions/411894/wmi-rights-required-to-read-root-microsoftiisv2-in-iis7-with-iis6-compatibility?answertab=oldest
CC-MAIN-2015-32
refinedweb
484
51.48
Missed a couple of consecutive days, but work is keeping me busy. Still, let’s talk about my second day of learning… Much of what I covered during this 1/2 hour of instruction was the installation of Django, using virtualenv, and setting up my first data model. I’m familiar with MVC frameworks; they are used all over the place. In the case of Django, it’s basically learning this design pattern all over again, though within the Pythonistic mindset. Here’s a quick look at the code: from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=200) body = models.TextField() pub_date = models.DateTimeField('date published') likes = models.IntegerField() def __unicode__(self): return self.title Basically, this code is defining the database schema that will be used to create the Article table in the backend database. We’re saying that inside the database for this Django app, we want a table called ‘Article’ that has the following fields (or columns) defined: Django converts this ‘model code’ into actual SQL statements, which are used to create the table. The syncdb command is the magic that performs this. After completing this portion of the lecture, we went into the python interactive shell, and actually created a couple of Articles (i.e row data in the table). Later today, I’ll tackle lecture 3. Night all.
https://jasondotstar.com/Day-2-Installation-and-Database-Models.html
CC-MAIN-2020-29
refinedweb
232
58.79
This article presents a neat trick allowing you to use a method of any class as a callback. In many cases, one layer of your SW needs to get services from higher layers. In order to not hurt the layering concept, the "callback" mechanism was invented: the layer which needs the service only knows (and actually declares) the prototype of the service required, not the actual service provider itself. The address of the function which will actually perform the required service is supplied at run-time, via some registration mechanism. This has been used extensively in C, and even many Win32 APIs get such callback functions as parameters (e.g. ::EnumChildWindows()). The problem presents itself when C++ class methods are the functions you would like to perform the job, not "plain" functions as is the usual case. ::EnumChildWindows() The basic reason this won't work is the fact that the this parameter in C++ is "hidden" -- it is not explicitly passed as any other "regular" argument. You cannot thus masquerade a C++ method as a plain C function. this Let's look at the type of a plain C function returning an int and receiving two ints: int typedef int (*FuncType)( int, int ); The C++ type of of a method in class CMyClass doing the same is: CMyClass typedef int (*CMyClass::MethodType)( int, int ); For the reason stated above, FuncType and MethodType are not compatible. The compiler's type-checking system will yell at you for trying to convert between the two, and no kind of cast will help. None. No, not even reinterpret_cast. In fact, some crazy attempts at static casting to "solve" this problem have been know to crash the VC++ compiler and cause internal errors. FuncType MethodType reinterpret_cast Of course, the compiler is right about this: it should not be allowed, since even if you could pass the address of a method to where a regular function is needed, the caller will not be able to specify this to the called method. Several approaches exist. The easiest is simply to avoid the problem altogether: this is sometimes even considered "pretty" C++ programming. For example: when an object wants three callbacks, it will declare an interface (a pure-abstract class with no members) and ask for an interface pointer instead of asking for the three callbacks. It is up to the implementer to implement the three methods, usually with the class-inside-class idiom, and sometimes using multiple inheritance and inheriting from the said interface (as is done in ATL, with all the fooImpl template classes). fooImpl Another approach, which I like best, calls for writing small "wrapper" functions for the methods you want to pass as callbacks and passing the wrapper functions themselves as the callback. The wrapper functions are static members of the same class as the method you originally wanted to pass as callback. This requires that the prototype for the callback function gets, on top all the application-specific parameters, some kind of "Context" or "UserData" (X11/the Motif name) parameter, so the code registering the wrapper method can also register the value of this to be later used by the static wrapper when calling the method. Since these are important ideas (both the static wrapper function and the notion of "UserData" and "Context"), I intend to elaborate on these in future versions of this article should it prove popular enough (more than 0 people read it ). Finally, there's the "dirty" approach. I assume there's more than one way, but following is how I do it. Two things need to be resolved: the first is how to get the address of the method into a void* (or for that matter: any other type which does not have the word CMyClass:: in it). The second thing is how to call the method (remember the this issue?) once we do have the address. void* CMyClass:: The first problem is solved with a trick: no cast will work, because all of them do some sort of type-checking. What is the C/C++ construct which actually screams "no type checking done here"? 2 points to anyone who guessed "Ellipses". The compiler will not do any type checking on the actual parameters passed for an ellipses argument. This way, a really small function can be made to cast practically anything into a void*. The second problem, of how to call the method once we have its address, is solved by using a "caller thunk": a function whose job it is to call the method pointed to by a void*, given the pointer and a value for this. Most methods' calling convention is __stdcall, which means amongst other things, that this is passed in the ECX register and that parameters are pushed on the stack from right to left. Using this knowledge, we can write a small function (in assembly) to do just that: invoke __stdcall methods itself. __stdcall ECX The implementation of the "caller thunk" is not portable: it should be changed for every compiler, since not all compilers pass this in ECX. (Heck, not all machines in the world even have ECX ). That's not too bad, though: I already have versions of this thunk for the ARM C++ compiler, for the TeakLite C++ compiler, and for the GNU ARM C++ compiler. You need to bear in mind that the approach works for __stdcall methods. If your method is explicitly declared to not be __stdcall, or if it has a variable number of arguments (ellipses), the trick will not work. You will simply need to replace the caller thunk to something appropriate. Again -- not too hard. Finally, please note what you are getting: you are taking the address of a method at link time, not at run-time. This means that late binding techniques (virtual function tables for virtual methods, for example) will not work. If you take the address of CMyClass::f1(), and some class derives from CMyClass and overrides f1(), you will still call CMyClass::f1(). CMyClass::f1() f1() If you think about it for a second, you will see that this is fine: you are losing nothing here. Since you gave the class name at compile time, it's the same as if you could directly call CMyClass::f1() -- you don't expect that to be late-bound, now do you? Using the "caller thunk" to call static methods and "regular" functions shouldn't work. Or should it? There's no real reason it shouldn't -- all it does is a regular call plus setting of ECX. Since such functions don't use ECX to get this, there's no harm in setting it. Thus, all we need to make sure of is that these functions (unlike the default!) will use the __stdcall calling convention. This is shown in the example. There is only one source file, demonstrating the trick. It contains a plethora of functions/methods which will be used as callbacks, a caller thunk for __stdcall, a function to convert everything into a void*, and the main driver. I demonstrate a non-virtual method (CMyClass::f1), two virtual methods (CMyClass::f2 and CAnotherClass::f2), and a regular function (MyFunc) as callback functions. CMyClass::f1 CMyClass::f2 CAnotherClass::f2 MyFunc The function to convert everything into a void* is ToVoidStar(). The caller thunk is CallThunk(). See if you can figure out why it's fine that it does not return any value! (Spoiler: it's fine since the return value is kept in EAX by the called callback, and is not changed until we get to CallThunk's caller). ToVoidStar() CallThunk() EAX CallThunk None so far This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here /***************************************************************** CFindWindowByTitle - a class to find a window handle from its title */ class CFindWindowByTitle { public: char * myTitle; // The window title required HWND myHWND; // the handle to the window found HWND Find( const char * title ); // Find the window }; /***************************************************************** CFindWindowByTitle methods */ /***************************************************************** CFindWindowByTitleCallback check if window search has found target window In: hwnd - handle to current window in search lParam - pointer to class doing search Return: 0 - keep search 1 - found it, stop searching */ static BOOL CALLBACK CFindWindowByTitleCallback( HWND hwnd, LPARAM lParam ) { // we should have been passed a pointer to the instance // of CFindWindowByTitle which started this search CFindWindowByTitle * thisCFindWindowByTitle = ( CFindWindowByTitle *) lParam; // pessimism thisCFindWindowByTitle->myHWND = NULL; // prevent infinite loops // microsoft says they won't happen with this technique // but let's make absolutely sure - search ony first 1000 windows static count = 0; if( count++ > 1000 ) { // count exceeded - stop searching count = 0; return 0; } // get string containing title of current window char buf[100]; GetWindowText( hwnd, buf, 99 ); CString swtitle( buf ); // check for target strings in window title if( (swtitle.Find(thisCFindWindowByTitle->myTitle) == -1) ) { // not this time - keep searching return 1; } // success - store handle to window found thisCFindWindowByTitle->myHWND = hwnd; //clear the count, ready for a new search count = 0; // end the search loop return 0; } /***************************************************************** Find - get handle to window with specified title In: title - title, or part title, being sesrched for Return: handle to window found, NULL on failure */ HWND CFindWindowByTitle::Find( const char * title ) { if( ! title ) return NULL; myTitle = (char *) title; EnumWindows( (WNDENUMPROC)&CFindWindowByTitleCallback, (LPARAM) this ); return myHWND; } class CCallbackWrapper { public: void *Wrapper(void *Object,...); private: unsigned char code[10]; }; void *CCallbackWrapper::Wrapper(void *Object,...) { void *Function=((void**)(&Object))[1]; code[0]=0xB9; *((int*)(code+1))=(int)Object; code[5]=0xE9; *((int*)(code+6))=(int)(((unsigned char*)Function)-code-10); return (void*)(code); } class CMyClass { public: void OnTimer(HWND hWnd,UINT msg,UINT IDEvent,DWORD dwTime); CCallbackWrapper CallbackWrapper; // ... }; CMyClass *MyTimer; TIMERPROC WrapperFunc=(TIMERPROC)MyTimer->CallBackWrapper.Wrapper(MyTimer,CMyClass::OnTimer); SetTimer(hWnd,ID_TIMER,TIMER_FREQ,WrapperFunc); General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/6731/Using-class-methods-as-callbacks
CC-MAIN-2015-35
refinedweb
1,672
56.79
DEBSOURCES Skip Quicknav sources / libidn / 1.25 Libidn NEWS -- History of user-visible changes. -*- outline -*- See the end for copying conditions. * Version 1.25 (released 2012-05-23) [stable] ** MSVC: Build fixes related to _GL_ATTRIBUTE_CONST and _GL_ATTRIBUTE_PURE. Reported by Bartosz Brachaczek <b.brachaczek@gmail.com>. ** examples: Fix compiler warning about ignoring return value from fgets. ** tests: Ship with a valgrind suppressions file for the strlen issue. See tests/libidn.supp and bottom of HACKING for discussion. ** Update gnulib files and translations. ** API and ABI is backwards compatible with the previous version. * Version 1.24 (released 2012-01-10) [stable] ** Libraries are re-licensed from LGPLv2+ to dual-GPLv2+|LGPLv3+. ** build: Fix parallel Windows builds. Reported by René Berber <r.berber@computer.org>. ** libidn: Fix potential infloop in pr29 code. Reported by Jon Nelson <jnelson@jamponi.net> in <>. ** <bittner.ede@euronetrt.hu>. ** doc: Update link to experimental TLD tables. The new link is <>. ** Update gnulib files and translations. ** QA: Improved cyclo output. Update GTK-DOC files. Various bugfixes. ** API and ABI is backwards compatible with the previous version. * Version 1.22 (released 2011-05-04) [stable] ** libidn: Add -liconv as static library requirement in libidn.pc, for MinGW. Reported by Volker Grabsch <vog@notjusthosting.com>. ** libidn: Fix memory leak in idna_to_ascii_4z when idna_to_ascii_4i fails. Reported by and tiny patch from Olga Limburg <olimburg@gmail.com>. ** libidn: Ran clang-analyze on the code. Fixed some dead assignments/initializations. ** build: Really distribute win32/libidn4win.mk. ** API and ABI is backwards compatible with the previous version. * Version 1.21 (released 2011-04-24) [stable] ** build/gettext: Demand gettext >= 0.18.1 in order to get newer M4 files. The old M4 files associated with 0.17 caused problems on Solaris, hopefully now fixed. Reported by Dagobert Michelsen <dam@opencsw.org> in <>. ** build: Improve MinGW cross-compile makefile, see win32/libidn4win.mk. ** build: Visual Studio files fixed to define LIBIDN_BUILDING. Tiny patch from Waqas Hussain <waqas20@gmail.com>. ** API and ABI is backwards compatible with the previous version. * <stepan@golosunov.pp.ru> in <>. ** tests: Added self-test tst_idna3 to catch any regression of problem above. ** idn: Only print copyright and license blurb when used interactively. Reported by "Andrew O. Shadoura" <bugzilla@tut.by> and Roman Mamedov <rm@romanrm.ru> in <> and <> respectively. ** Update gnulib files and translations. ** API and ABI is backwards compatible with the previous version. *. * Version 1.18 (released 2010-02-15) [stable] ** libidn: Put forgotten symbols under old namespace. Reverts one unnecessary change introduced in 1.17. Suggested by Marco d'Itri <md@linux.it>. ** API and ABI is backwards compatible with the previous version. * Version 1.17 (released 2010-02-05) [alpha] **. ** Really fix the link error of self-tests on MinGW. ** API and ABI is backwards compatible with the previous version. * Version 1.16 (released 2010-01-12) ** java: Add a Maven pom.xml project file. Contributed by Guus der Kinderen <guus.der.kinderen@gmail.com>. ** Fix a link error on MinGW. ** API and ABI is backwards compatible with the previous version. * <adam.strzelecki@java.pl>. **. *. * Version 1.9 (released 2008-07-01) ** idn: fix error message when NFKC fails, and some other translation fixes. Reported by Benno Schulenberg <coordinator@translationproject.org>. ** C# Libidn.dll: Work around bug that cause a failure during C# compilation. See <>. ** Remove more non-free text from doc/specifications/rfc3454.txt. The remaining data tables are not copyrightable. ** Update gnulib files, and include gnulib self-tests. ** Update translations. ** API and ABI is backwards compatible with the previous version. * Version 1.8 (released 2008-04-23) ** Translations files not stored directly in git to avoid merge conflicts. This allows us to avoid use of --no-location which makes the translation teams happier. ** Update gnulib files. ** API and ABI is backwards compatible with the previous version. * Version 1.7 (released 2008-04-10) ** idn: new parameter --nfkc to process string with Unicode v3.2 NFKC. ** Minor build fix for native Win32 builds. ** Update gnulib files. ** API and ABI is backwards compatible with the previous version. * Version 1.6 (released 2008-03-19) ** Add native Windows Visual Studio project files. Contributed by Adam Strzelecki <ono@java.pl>. ** Remove non-free portions of RFC 3454 in doc/specifications/rfc3454.txt. ** Update gnulib files. ** Doc fixes in IDNA to clarify that some functions operate on ** just one domain labels and some operate on domain name (which ** can contain several domain labels). ** API and ABI is backwards compatible with the previous version. * Version 1.5 (released 2008-02-19) ** Don't include wchar.h in idn-int.h. Fixes problems on uClibc systems which lack a wchar.h. Reported by Mike Frysinger <vapier@gentoo.org>, see <>. ** Added appendix 'On Label Separators' to the manual. Thanks to Erik van der Poel <erikv@google.com> for bringing the issue to our attention and for discussing the matter. See <>. ** Improved rendering of non-ASCII in the info manual. Done by adding a @documentencoding UTF-8. This affect how the examples are encoded, the files examples/*.c are now encoded using UTF-8 instead of a mix of ISO-8859-1 and ISO-8859-15. ** Fix non-portable use of brace expansion in makefiles. ** Update translations. ** Update gnulib files. ** API and ABI is backwards compatible with the previous version. *. * Version 1.2 (released 2007-10-01) ** Development git tree moved to savannah. See <>. ** Update gnulib files. Including mono detection fixes. ** Update translations. ** API and ABI is backwards compatible with the previous version. * Version 1.1 (released 2007-09-01) ** Fix compilation error in idn-int.h. The error would typically be 'error: no include path in which to <wich@stack.nl>, see <> and <>. ** Declare external variables with __declspec(import) for Windows. Apparently this is required for variables in DLL's on Windows. This is enabled if __DECLSPEC_SUPPORTED is defined (MinGW), or if _MSC_VER and_DLL is defined (MSVC). ** Update gnulib files. ** Update translations. ** API and ABI is backwards compatible with the previous version. *. * Version 0.6.14 (released 2007-05-31) ** Libidn is now developed using Git instead of CVS. A public git mirror is available from <>. If you have pulled from this repository before this release, you need to erase your clone because it has been re-generated from scratch. ** API and ABI is backwards compatible with the previous version. * <qboosh@pld-linux.org> and Clytie Siddall <clytie@riverland.net.au>. **. * Version 0.6.12 (released 2007-04-25) ** Use AM_JAVACFLAGS instead of JAVACFLAGS in java/misc/Makefile.am. Reported by Petteri Räty <betelgeuse@gentoo.org>. ** Update gnulib files. ** API and ABI is backwards compatible with the previous version. * Version 0.6.11 (released 2007-03-13) ** Update of the C# Libidn port, by Alexander Gnauck. The code has been refactored and the namespace has been modified to comply with .NET naming conventions. An IDNA bug was fixed. ** Update gnulib files. We now use the "striconv" module instead of the "iconvme", which causes a slight increase of code size (from 303kb to 319kb with debugging symbols on i386). The reason is the use of a new locale independent strcasecmp, which may cause faster operation in some locales where, e.g., "ASCII" and "ascii" are not treated as the same. ** API and ABI is backwards compatible with the previous version. * Version 0.6.10 (released 2007-01-04) ** Corrected year in copyright notices. ** Update gnulib files. Including the code to convert strings between different encodings (noted in case this introduces problems). ** API and ABI is backwards compatible with the previous version. *. * Version 0.6.8 (released 2006-10-18) ** The gnulib directory is separated into two directories. One gnulib directory (lib/gl/) for the LGPL library in lib/, and one gnulib directory (gl/) for the GPL tools in src/. This allows the GPL'd tools to use more gnulib modules than before, since earlier all gnulib files had to be LGPL. ** Update gnulib files. ** Some minor cleanups, like assuming locale.h and setlocale(). ** API and ABI is backwards compatible with the previous version. * Version 0.6.7 (released 2006-09-13) ** Fix build failure of idn-int.h on C99 platforms. Reported by Paul Howarth <paul@city-fan.org>. ** The manual includes the GPL license, for the command-line tools. ** The function, variable and concept index is moved to the end of the manual. ** Update gnulib files. ** API and ABI is backwards compatible with the previous version. *. * Version 0.6.5 (released 2006-06-07) ** Link the library with external libintl, for gettext. This fixes building on FreeBSD, reported by Kirill Ponomarew <krion@voodoo.bawue.com>. ** Update doxygen config file to version 1.4.7. ** API and ABI is backwards compatible with the previous version. * Version 0.6.4 (released 2006-06-07) ** Fix translation of error messages. Thanks to Joe Orton <jorton@redhat.com>. ** Fix warnings on 64-bit platforms. Thanks to Joe Orton <jorton@redhat.com>. ** The tests are run under valgrind, if it is installed. Use --disable-valgrind-tests to unconditionally disable this. It is disabled by default for cross compiles. ** API and ABI is backwards compatible with the previous version. * Version 0.6.3 (released 2006-03-08) ** Fixes for the build environment. ** API and ABI is backwards compatible with the previous version. * Version 0.6.2 (released 2006-02-07) ** Fix objdir != srcdir builds for the Java documentation. Thanks to Bernard Leak <bernard@brenda-arkle.demon.co.uk>. ** Update of gnulib files. ** API and ABI is backwards compatible with the previous version. * Version 0.6.1 (released 2006-01-20) ** Make it possible to cross-compile to mingw32. You can build Libidn for Windows by invoking `./configure --host=i586-mingw32msvc' (or similar). ** Minor changes in how the C# code is built. ** Update of gnulib files. ** API and ABI is backwards compatible with the previous version. *. * Version 0.5.20 (released 2005-10-23) ** The header file pr29.h is now installed by 'make install'. ** Translation updates. ** Update of gnulib files. ** API and ABI is backwards compatible with the previous version. * Version 0.5.19 (released 2005-09-19) ** The test for setlocale and nl_langinfo has now been separated. The autoconf script now test for locale.h, setlocale and nl_langinfo(CODESET) independently. ** Gnulib updates, fixes for getopt. ** Java manuals in doc/java/ are now generated by Gjdoc from GNU Classpath. ** Kaffe is used to link the pre-built libidn-*.jar file. ** Translation updates. ** API and ABI is backwards compatible with the previous version. * Version 0.5.18 (released 2005-07-16) ** The macro AX_CREATE_STDINT_H that is used to create idn-int.h ** has been updated. ** Fix use of 'head -1' in configure script (should be 'head -n -1'), ** thanks to Carsten Lohrke. ** Announce the help-libidn mailing list in documentation and README. ** Translation updates. ** API and ABI is backwards compatible with the previous version. * Version 0.5.17 (released 2005-05-26) ** The gnulib portability files were updated. ** The license template in files were updated with the new address. ** Translation updated. ** API and ABI is backwards compatible with the previous version. * Version 0.5.16 (released 2005-05-06) ** Mark static PR29 data tables as 'const', thanks to Joe Orton. ** Kinyarwanda translations added, thanks to Steve Murphy. ** API and ABI is backwards compatible with the previous version. * Version 0.5.15 (released 2005-03-19) ** Improvements to code to convert data between character sets. The license template was changed to the LGPL, from the GPL template that was mistakenly used in the previous two releases. Document here that cleaning up this code has solved memory allocation and arithmetic overflow problems. ** API and ABI is backwards compatible with the previous version. * Version 0.5.14 (released 2005-03-19) ** Building for srcdir != objdir from CVS now work, thanks to Linus Nordberg. ** Simplified Chinese translations added, thanks to Meng Jie. ** Vietnamese translation added, thanks to Clytie Siddall. ** API and ABI is backwards compatible with the previous version. * Version 0.5.13 (released 2005-01-29) ** The code to convert data between character encodings have been cleaned up. The stringprep_convert function has been added to gnulib, under the name iconv_string, and is now used by libidn. This should not have any user-visible consequences, though. ** It is now possible to bootstrap with unmodified Automake installations. ** Italian translation added, thanks to Marco Colombo. ** Swedish translation updated. ** API and ABI is backwards compatible with the previous version. * Version 0.5.12 (released 2004-12-04) ** Java code now support the XMPP NodePrep and ResourcePrep profiles. ** Bug fixes and improvements to Java code. The allowUnassigned flag is now respected properly. The prohibited code points check now works. Arguments are now checked. Convenience method with allowUnassigned set to false was added. ** Update getopt from gnulib. ** API and ABI is backwards compatible with the previous version. * Version 0.5.11 (released 2004-11-21) ** Fix formatting of man pages, based on warnings from Doclifter. ** Update of gnulib files to fix potential getopt problem on ELF systems. ** API and ABI is backwards compatible with the previous version. * Version 0.5.10 (released 2004-11-08) ** Libtool's -export-symbols-regex is now used to only export official APIs. Before, applications might accidentally access internal functions. Note that this is not supported on all platforms, so you must still make sure you are not using undocumented symbols in Libidn. ** API and ABI is backwards compatible with the previous version. * Version 0.5.9 (released 2004-11-07) ** Align GTK-DOC build infrastructure with GTK-DOC official recommendations. This mean that you can now browse the Libidn API manual using Devhelp. ** Update of gnulib files to fix potential problem in getopt on BSD. ** Documentation improvements. ** API and ABI is backwards compatible with the previous version. * Version 0.5.8 (released 2004-10-12) ** BidiMirroring-3.2.0.txt is now included, not only the generated source code. This allow builds to succeed after 'make realclean'. ** Generated files now have consistent 'DO NOT EDIT!' comments. ** API and ABI is backwards compatible with the previous version. * Version 0.5.7 (released 2004-10-12) ** Shared library version incremented, because new APIs were added. This was forgotten in the last release. ** French translation updated. ** Minor bug fixes. ** API and ABI is backwards compatible with the previous version. * Version 0.5.6 (released 2004-10-02) ** Added functions to convert return codes to human readable text. ** Now using GNULib in command line front end (src/) for portability code. See <> for more information on GNULib. This should make the code easier to read and maintain. ** API and ABI is backwards compatible with the previous version. idna_strerror: ADD. pr29_strerror: ADD. punycode_strerror: ADD. stringprep_strerror: ADD. tld_strerror: ADD. TLD_NO_TLD: ADD. Replaces TLD_NOTLD. TLD_NOTLD: DEPRECATED. Use TLD_NO_TLD instead. * Version 0.5.5 (released 2004-09-13) ** Hide accidentally exported variable g_utf8_skip, by marking it as static. ** Various fixes. ** API and ABI is backwards compatible with the previous version. g_utf8_skip: REMOVED. (But never meant to be used.) * Version 0.5.4 (released 2004-08-08) ** Translation updates. ** API and ABI is backwards compatible with the previous version. * Version 0.5.3 (released 2004-08-05) ** Fix crash in `idn --tld' command line tool. ** API and ABI is backwards compatible with the previous version. * Version 0.5.2 (released 2004-07-14) ** Java "make install" rules are now DESTDIR compatible. ** API and ABI is backwards compatible with the previous version. * Version 0.5.1 (released 2004-07-09) ** Cross compile builds should work. It should work for any sane cross compile target, but the only tested platform is uClibc/uClinux on Motorola Coldfire. ** The example programs now correctly invoke `setlocale (LC_ALL, "")'. ** API and ABI is backwards compatible with the previous version. * Version 0.5.0 (released 2004-06-26) ** Functions to detect "normalization problem sequences" as per PR-29 added. See the new chapter "PR29 Functions" in the manual (doc/libidn.{ps,pdf,html}) for more information and the background story. An external link that discuss the problem is <>. ** More translations. Added Esperanto (by Edmund GRIMLEY EVANS). ** API and ABI is backwards compatible with the previous version. pr29.h: ADD. Prototypes for PR29 types and functions. pr29_4, pr29_4z, pr29_8z: ADD. New API entry points for PR29 functions. Pr29_rc: ADD. New error code enum type for PR29 functions. * Version 0.4.9 (released 2004-06-11) ** The Java library (java/libidn-*.jar) is included in the distribution. ** JavaDoc manuals (doc/javadoc/) are included. ** API and ABI is backwards compatible with the previous version. * Version 0.4.8 (released 2004-06-01) ** The Java source code is actually included in the distribution. ** API and ABI is backwards compatible with the previous version. * Version 0.4.7 (released 2004-05-31) ** The Java port should now be functional, contributed by Oliver Hitz. See the new section "Java API" in the manual for more information. ** API and ABI is backwards compatible with the previous version. * Version 0.4.6 (released 2004-05-24) ** The header file idn-free.h is actually installed by 'make install'. ** API and ABI is backwards compatible with the previous version. * Version 0.4.5 (released 2004-05-21) ** In IDNA ToUnicode, a `free' on a stale pointer fixed by Ulrich Drepper. ** Several memory leaks fixed by Ulrich Drepper. ** Added more SASLPrep and NFKC test vectors. ** Automake 1.8.4 is used. ** API and ABI is backwards compatible with the previous version. idn_free: ADD. Wrapper around system `free'. idn-free.h: ADD. Prototype for `idn_free'. See idn-free.h for discussion. The interface is currently not documented. Comments and feedback is appreciated. * Version 0.4.4 (released 2004-04-29) ** Fixed two bugs in iSCSI definition, syncing with newly published RFC 3722. The first bug was an omission of prohibiting the characters in C.1.1, C.1.2 and C.7 (space characters and characters that are inappropriate for canonical representation). The second was a bug in the definition of the table, causing the entire table to be skipped, of the special prohibited output character table defined in RFC 3722 (see section 6, the characters in the table are various ASCII characters and U+3002). ** A few test vectors for iSCSI were added. ** The self tests are linked with libtool -no-install to avoid wrapper script. ** Separated self test utilities into a separate library, shared by all tests. ** More translations. Added Romanian (by Laurentiu Buzdugan). ** API and ABI is backwards compatible with the previous version. * Version 0.4.3 (released 2004-04-22) ** Fixed a bug in table processing code to prohibit control characters. The problem was that the code used a code point of 0 to indicate end of table, but if (as for table C.2.1) a range starts with 0, this logic would fail. The end-of-table test is now that both the start and end code points of the range is 0. Table C.2.1 is responsible for prohibiting non-ASCII control characters, i.e. ASCII 0-31 and 127. Before, libidn silently accepted such strings without complaining. ** A few test vectors for SASLprep were added. ** The pkg-config script no longer include a -R parameter. ** More translations. Added Dutch (by Elros Cyriatan), and German (by Roland Illig). ** API and ABI is backwards compatible with the previous version. * Version 0.4.2 (released 2004-03-20) ** A Punycode implementation in Java was added, by Oliver Hitz. Eventually hopefully a StringPrep, Nameprep and IDNA implementation will be added as well. Currently you need to specify --enable-java to enable the Java interface. The Java sources (below java/) are compiled into byte-code (not native code) into a JAR library. ** More translations. Added Danish (by Morten Bo Johansen), French (by Michel Robitaille), Polish (by Jakub Bogusz), and Serbian (by Aleksandar Jelenak). ** Norwegian TLD table added, by Thomas Jacob. ** API and ABI is backwards compatible with the previous version. * Version 0.4.1 (released 2004-03-08) ** The user messages from the command line utility are now translated. Currently English and Swedish is supported. ** Logic of stringprep_locale_charset modified. Future versions will use, in order, $CHARSET iff defined, nl_langinfo (CODESET) iff working, or fall back to returning "ASCII". Earlier it attempted to guess the system locale, in contrast with the current application's locale, via some setlocale save/set/reset magic. This change may require you to invoke setlocale() in your application, which is (should be) required for non-ASCII to work anyway. Based on discussion with Ulrich Drepper. ** The command-line utility now invoke setlocale (LC_ALL, "") at startup. ** Fixed SASLprep tables to prohibit non-ASCII space in output. Non-ASCII space has always been mapped to ASCII space, so it is not clear this really have any effect, but the specification require it. ** Building Libidn as part of GLIBC has been updated. Refer to libc/README for more information. Incidentally, GLIBC in CVS now include a copy of Libidn. ** API and ABI is backwards compatible with the previous version. IDNA_DLOPEN_ERROR: ADD. Only used internally by Libidn in libc. * Version 0.4.0 (released 2004-02-28) ** Support for TLD restrictions on IDN strings, contributed by Thomas Jacob. Many TLDs restrict the set of characters that can be used, from the full Unicode 3.2 range that is normally available. This contribution make it possible for you to test strings for TLD conformance locally. The code can be disabled by --disable-tld. If enabled (the default), the new API "tld.h" is installed which can be used to check a string for conformance to TLD specific rules. This add a new self test, and a new chapter in the manual. People responsible for maintaining TLD tables are hereby encouraged to contribute them (under reasonable licensing terms) for inclusion in future versions of Libidn. Be warned that the API for TLD checking may change throughout the 0.4.x series as we get feedback on it. ** Kerberos 5 stringprep profile macro is no longer documented. The macro itself will probably be removed in the future, if the specification is dropped from the Kerberos WG agenda. ** API and ABI is backwards compatible with the previous version. stringprep_kerberos5: DEPRECATED. Tld_table_element: Tld_table: Tld_rc: ADD. New data types. tld_get_4: tld_get_4z: tld_get_z: ADD. New functions to extract TLD from string. tld_get_table: tld_default_table: ADD. New functions to get TLD table from TLD name. tld_check_4t: tld_check_4tz: ADD. New function to provide core TLD operations. tld_check_4: tld_check_4z: tld_check_8z: tld_check_lz: ADD. New functions that combine all TLD operations in one call. * Version 0.3.7 (released 2004-01-22) ** The command line parameter '--' idiom is documented. ** The iSCSI stringprep profile now recognized as "iSCSI". The earlier name "ISCSIprep" is still recognized, for backwards compatibility. ** DocBook manuals no longer included (the tools are too unstable). ** API and ABI is backwards compatible with the previous version. * Version 0.3.6 (released 2004-01-06) ** The manual now contain a troubleshooting section for the command line tool. ** The PHP interface pass the string directly on the command line. ** The macro that create 'idn-int.h' has been updated to latest version. ** API and ABI is backwards compatible with the previous version. * Version 0.3.5 (released 2003-12-15) ** The program 'idn' accepts input strings directly on the command line. ** The program 'idn' defaults to --idna-to-ascii if no parameter is given. ** The program 'idn' now print user instructions before waiting for input. ** DocBook HTML output not included any longer. The reason is that the filenames generated by docbook2html appear to be rather random, so it is difficult to maintain the Makefile.am rules for them. ** Autoconf 2.59, automake 1.8 and libtool from CVS is used. ** API and ABI is backwards compatible with the previous version. IDNA_CONTAINS_NON_LDH: ADD. Same integer value as IDNA_CONTAINS_LDH. IDNA_CONTAINS_LDH: DEPRECATED. LDH (letter-digits-hyphens) characters are not an error, but non-LDH characters are, when IDNA_USE_STD3_ASCII_RULES is used. The logic of the mnemonic name of this error constant was reversed. * Version 0.3.4 (released 2003-11-09) ** DocBook manuals in XML, PDF, PostScript, ASCII and HTML formats included. * Version 0.3.3 (released 2003-10-18) ** Fixed list of Stringprep profiles in 'idn --help' and 'idn.php'. ** Fixed debug information in 'idn'. ** Internal improvements. Leads to reduced heap memory usage. Simplified inter-dependency among files in lib/* to make it easier to copy them into your project. ** Debugging stringprep profile 'generic' removed. ** Punycode implementation updated to rfc3492bis-00. ** API and ABI is backwards compatible with the previous version. stringprep_4i: NEW. stringprep_4zi: NEW. stringprep: CHANGED. 'profile' is marked as 'const'. stringprep_profile: CHANGED. 'profile' is marked as 'const'. stringprep_generic: REMOVED. Never meant for public use. * Version 0.3.2 (released 2003-10-07) ** SASL ANONYMOUS stringprep profile "trace" added. It is equivalent to the already supported "plain" SASL ANONYMOUS stringprep profile, except for the name. ** API and ABI is backwards compatible with the previous version. The 'in' parameter to stringprep_profile was changed from 'char*' to 'const char*'. * Version 0.3.1 (released 2003-10-02) ** Fixed handling of implicit and explicit zero-length root labels in ToASCII. ** Fixed support for Hangul Syllables during Unicode NFKC normalization. ** Fixed Unicode NFKC normalization of (some) BMP code points. This was done by syncing the NFKC code with latest GLIB, and may have fixed other bugs in the earlier versions of the updated functions. ** Added more IDNA test vectors. ** Emacs Lisp IDNA implementation now set the UseSTD3ASCIIRules flag. This is the appropriate setting for mail-related uses of IDNA. ** API and ABI is backwards compatible with the previous version. * Version 0.3.0 (released 2003-09-23) ** Ported to Mac OS X. ** Gnulib code removed, we now assume a C89 compatible environment. ** Building libidn as a libc add-on now works again. ** Man pages for all public API functions are included. ** Fixed bug in SASLprep profile. ** API and ABI is NOT backwards compatible with the previous version. All previously labeled (since 0.1.x) obsolete functions have been dropped. The use of 'enum' types instead of 'int' added in 0.2.3 reverted, it confused documentation generators and wasn't all that common practice. * Version 0.2.3 (released 2003-08-26) ** Example 4 was the same as example 3, now changed to demo ToUnicode. ** Documentation improvements. ** Prototype cleanups. The proper enum types (Stringprep_rc, Idna_rc, etc) are now used in several places where plain int where used before. String lengths are handled by (s)size_t instead of int. ** API and ABI is backwards compatible with the previous version. * Version 0.2.2 (released 2003-08-13) ** Fixed problem with strings longer than 4GB in punycode functions. The punycode code cannot handle strings longer than 4GB. The code now return PUNYCODE_BAD_INPUT on too long input, instead of failing in an unknown way. ** The "idn --idna-to-unicode" command now output locale encoded strings. ** Build fixes, bug fixes. ** API and ABI is backwards compatible with the previous version. * Version 0.2.1 (released 2003-07-04) ** Don't reject zero-length trailing labels as in, e.g., ".". The IDNA RFC is not clear on this topic, zero-length labels in general are forbidden by the ToASCII algorithm in section 4.1 step 8, but the terminology section define, inside a parenthesis, that the zero-length root label is in fact not considered a label at all in IDNA. ** Bug fixes. ** API and ABI is backwards compatible with the previous version. * Version 0.2.0 (released 2003-06-19) ** Unicode code point data is now uint32_t, defined in "idn-int.h". A header file "idn-int.h" is generated and installed to make sure the "uint32_t" data type is available on all platforms. The reason for this change is that on 64-bit platforms, the application was required to convert 32 bit integers (which is how Unicode code points are typically represented) into 64 bit integers before calling libidn functions. ** New idna_*() functions have improved flags handling. The allowunassigned and usestd3asciirules parameters were collapsed into a flags parameter, that can take on the IDNA_ALLOW_UNASSIGNED and IDNA_USE_STD3_ASCII_RULES values. This allows for easier extensions to support, e.g., Unicode 4.0 or RFC 952 ASCII rules checking. Note that the old entry points are unmodified (in this regard), and new entry points with this modification were added. ** The manual was moved into a separate directory doc/. ** Bugfixes. ** API and ABI is not backwards compatible. In punycode.h and stringprep.h the "unsigned long" data type was changed into "uint32_t", which cause a API and ABI missmatch. For idna.h, the old entry points that used "unsigned long" still exist, and new entry points that uses "uint32_t" was added. To update your application, you probably only need to change "unsigned long" to "uint32_t". As a result of these changes, the shared object version has been increased. * Version 0.1.15 (released 2003-06-07) ** Bugfixes. ** API and ABI is backwards compatible with the previous version. * Version 0.1.14 (released 2003-05-10) ** Experimental documentation generation in contrib/doxygen/. Simply invoke "doxygen" in that directory and it should build the documentation. ** Lisp API bug fixes. ** API and ABI is backwards compatible with the previous version. * Version 0.1.13 (released 2003-03-13) ** Unfinished Java *.class files implementing the libidn API. See the contrib/java/ directory. It is implemented using the Java Native Interface, and light initial testing indicate interoperability between GCJ, IBM's JDK and Sun's JDK. ** Building is now silent when gengetopt is not present. ** Bug fixes. ** API and ABI is backwards compatible with the previous version. * Version 0.1.12 (released 2003-03-06) ** Building libidn doesn't require gengetopt. Warnings are still printed though. Gengetopt will be replaced by argp eventually. ** Command line tool "idn" supports stringprep too. ** New stringprep API entry point: stringprep_profile(). It takes a name of the stringprep profile as an argument instead of the stringprep table structure. ** stringprep_*.h are deprecated and will be removed in the future. All symbols have been moved to stringprep.h. The reasons are that (1) the files typically only defined one CPP macro and exported one symbol definition, which is wasteful as it generates too much work in the manual, and (2) using one header file for all profiles allows easier access to all stringprep profiles during runtime. Note that the files are still installed, but they only #include stringprep.h now, for backwards compatibility. ** GNU Libc add-on build instructions updated to GNU Libc 2.3.2. ** SASLprep stringprep profile added. ** An online interface to libidn written in PHP added to contrib/web/. ** API and ABI is backwards compatible with the previous version. * Version 0.1.11 (released 2003-02-26) ** Command line application "idn" is included. A simple wrapper around the library that allows you to invoke punycode encoding/decoding and IDNA ToASCII/ToUnicode on the command line. ** Emacs Lisp interface for punycode and IDNA included. See punycode.el and idna.el. ** API and ABI is backwards compatible with the previous version. * Version 0.1.10 (released 2003-02-21) ** idna_*_to_ace() and idna_*ace_to_*() are deprecated in favor of ** idna_to_ascii_from_*() and idna_to_unicode_*_from_*() respectively. The reason was that the old interfaces did not accept the AllowUnassigned and UseSTD3ASCIIRules flags. Note that the old functions are not removed, but will be in the future. ** IPS iSCSI stringprep profile added. ** A new contrib/ directory added. Currently it contains a Python interface to Libidn, contributed by Stephane Bortzmeyer. ** idna.h and punycode.h are now installed by "make install". ** API and ABI is backwards compatible with the previous version. * Version 0.1.9 (released 2003-02-20) ** SASL ANONYMOUS "plain" stringprep profile added. ** XMPP nodeprep profile fixed. ** API and ABI is backwards compatible with the previous version. For future releases, the NEWS entry will specifically mention whether the C header API or library ABI backwards compatibility is affected. * Version 0.1.8 (released 2003-02-14) ** Portability fixes. This includes not building the API Reference Manual with GTK-DOC by default, if you want it use configure parameter --enable-gtk-doc after making sure your gtkdoc-mkdb accept the --tmpl-dir parameter. ** The type for string length variables is now (s)size_t. Unfortunately this means binary shared library binary backwards compatible is lost. ** New nameprep test vectors. * Version 0.1.7 (released 2003-02-12) ** Uses official IDNA ACE prefix. * Version 0.1.6 (released 2003-02-11) ** Uses tentative IDNA ACE prefix. ** Added XMPP Node/Resource Identifiers stringprep profiles. ** Fixed prohibited character checks for bid_to_ucs4_fast API entry point was removed. By accident it was never removed in 0.1.0. * Version 0.1.0 (released 2003-01-05) ** Official GNU project. ** Renamed from libstringprep to libidn. ** Supports punycode and IDNA. Caveat emptor: I don't use it myself. ** Uses "unsigned long" for Unicode code points instead of "long". Long is guaranteed to be at least 32 bits by C standards so it is always sufficiently large, no need to use uint32_t and the like. ** The obsolete stringprep_utf8_to_ucs4_fast API entry point was removed. * Version 0.0.8 (released 2002-12-13) ** Portability fixes (now works under Cygwin on Windows 2000). ** Bug fixes. * Version 0.0.7 (released 2002-12-09) ** Apply all tables to entire strings, not just first hit. ** Fix bidi infloop. * Version 0.0.5 (released 2002-12-07) ** Fix prohibited characters handling. ** Fix bidi. ** Renamed type (struct) stringprep_table_element to Stringprep_table_element. ** Renamed type stringprep_profile to Stringprep_profile. ** Renamed type (struct) stringprep_table to Stringprep_table. ** Added more self-tests. * Version 0.0.4 (released 2002-12-06) ** Add unassigned code point handling, including self test cases. ** Portability fixes. * Version 0.0.3 (released 2002-11-30) ** Exported utility function `stringprep_utf8_to_unichar', complementary to existing `stringprep_unichar_to_utf8'. ** Renamed `stringprep_utf8_to_ucs4_fast' to `stringprep_utf8_to_ucs4' to clean up API. The old entry point is maintained for binary backwards compatibility though. ** The distribution is from now on signed using GnuPG. ** Bug fixes. * Version 0.0.2 (released 2002-11-07) ** NFKC self test. ** Bug fixes. * Version 0.0.1 (released 2002-11-06) ** Add utility functions stringprep_locale_charset(), stringprep_convert() and stringprep_locale_to_utf8 () that can be used to convert text from system's locale into UTF-8, which should be done before invoking stringprep(). The functions requires iconv() in the operating system. ** An example program (example.c) that illustrates how libstringprep can be used is included. ** The pkg-config --libs output should now include necessary -R options. * Version 0.0.0 (released 2002-11-05) ** Initial release ---------------------------------------------------------------------- Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved.
https://sources.debian.org/src/libidn/1.25-2/NEWS/
CC-MAIN-2021-04
refinedweb
5,730
61.43
metaget=metahandlers.MetaData() metaget=metahandlers.MetaData(preparezip=True) Search by IMDB ID: meta = metaget.get_meta('movie', movie_name, imdb_id=imdb_id) Serach by TMDB ID: meta = metaget.get_meta('movie', movie_name, tmdb_id=tmdb_id) Search by movie name + year meta = metaget.get_meta('movie', movie_name, year=year) Search by IMDB ID: meta = metaget.get_meta('tvshow',tvshow_name, imdb_id=imdb_id) Search by name: meta = metaget.get_meta('tvshow',tvshow_name) season_list = [1,2,3] seasons = metaget.get_seasons(imdb_id, season_list) season_num = 1 episode_num = 1 episode=metaget.get_episode_meta(imdb_id, season_num, episode_num) metaget.change_watched('movie', movie_name, imdb_id, year) or metaget.change_watched('tvshow', tvshow_name, imdb_id) or metaget.change_watched('episode', episode_name, imdb_id, season) search_meta = metaget.search_movies(movie_name) Returns an array of dictionaries with the following data: - IMDB ID - TMDB ID - Name - Year IMDB ID TMDB ID Title Writer Director Tagline Cast & Role Rating Duration Plot MPAA Rating Premiered Year Genre Studio Trailer URL Thumb URL Cover URL Backdrop/Fanart URL Overlay (watched status) IMDB ID TheTVDB ID Title Rating Duration Plot MPAA Rating Premiered Genre Studio Cast & Role Trailer URL Thumb URL Cover URL Backdrop/Fanart URL Overlay (watched status) IMDB ID TheTVDB ID Season # Cover URL Overlay (watched status) IMDB ID TheTVDB ID Episode ID Season # Episode # Title Director Writer Plot Rating Premiered Poster URL Overlay (watched status) Eldorado Wrote:I thought I would get the ball rolling on getting the next piece in the proposed Video Falcon project - common meta data script I've put the initial version on git - This version was pulled from the master branch of Icefilms, I've basically put everything into it's own script folder and set it up to stand on it's own There are some to-do's left in the code as well as quite a bit of Icefilms specific coding, once that stuff is cleaned up I'm optimistic that it could be very close to being release ready Scraping of metadata for movies (TMDB) and tvshows (TheTVDB) is currently working using IMDB ID's, as an enhancement it would be nice to add ability to search based on simply movie/tv show name All welcome who are wanting to help! Quote:script.module.metahandlers Metahandlers will be the module that can get and cache metadata. As well as build/download and install metacontainers of pre-packaged metadata for sites (you provide it with a list of all content, and it will pre-make a cache of metadata for that list). Eldorado Wrote:t0mm0, this was another item on the Video Falcon list: t0mm0 Wrote:so am i right in thinking what it needs to do is... addon calls this module with a episode/movie imdb id or title module looks in its database for metadata for the required episode/movie if not found it scrapes a site for the required metadata, adds it to the database and returns it if it is found, it simply returns it from the database t0mm0 Wrote:is it possible to use the existing xbmc scraper modules rather than having separately maintained ones? (just asking the question - i know nothing about metadata in xbmc) t0mm0 Wrote:i assume the intention is to maintain a central database so that if a movie is added from one addon its metadata will be available from all others using the module? seems what is really needed is to be able to add stuff to the main xbmc library. there is also the hack that is doing the rounds at the moment with creating loads of strm files which is trying to solve the same problem i guess? also there is the mention of building pre-packaged metadata bundles - this sounds like a nightmare to me but maybe there is a particular use? there should probably be a definition of what metadata is required. does it include posters/thumbs for example? maybe this would also be a good place to track watched status (especially as it would wok across addons) while we can't do it in xbmc? (i always find it better to try and define what something is supposed to do before writing code - might save rewriting it too much later. i hope the questions above aren't too silly - as i say i don't know anything about metadata in xbmc ) t0mm0 t0mm0 Wrote:ps. eldorado you need to add .pyo (and .pyc while you are at it) files to your .gitignore file in this repo! slyi Wrote:I was also tinkering with meta data updates using asynchronous methods for icefilms see demo on I think a generic system should only download whats requested at the time and be text only (no images) as these are better stored online rather filling the limited hd of embedded devices apple tv etc... I'd be interested in helping on this aswell, can you provide a sample that works with ice films v12? from metautils import metahandlers, metacontainers metapath = xbmc.translatePath('special://profile/addon_data/script.module.metautils/meta_cache') metaget=metahandlers.MetaData(metapath,preparezip = True) meta = metaget.get_meta('tt1499658','movie','Horrible Bosses') print meta {'rating': 8.1999999999999993, 'genres': u'Comedy', 'name': u'Horrible Bosses', 'tmdb_id': u'51540', 'plot': 'Starring : \nJennifer Aniston, Jason Bateman, Charlie Day, Jason Sudeikis, Colin Farrell\n\nPlot : \nAfter three friends realize that their bosses are standing in the way of their happiness, they come up with a murderous plot, hoping to better their lives.', 'mpaa': u'R', 'studios': u'New Line Cinema', 'premiered': u'2011-07-08', 'imdb_id': u'tt1499658', 'imgs_prepacked': u'true', 'cover_url': u'', 'duration': 100, 'watched': 6, 'thumb_url': u'', 'trailer_url': u'', 'backdrop_url': u''} k_zeon Wrote:hey Eldorado. how would you intergrate this into an addon. ie where would you put the call to get the info.. and how would XBMC know there is data to show. thanks Eldorado Wrote:The call would be as you are adding either directories or video items, currently you must have a imdb id for it to scrape Using what is returned you can put it into a new dict with the proper labels eg. liz = xbmcgui.ListItem() infoLabels = [] infoLabels['genre'] = str(meta['genres']) infoLabels['duration'] = str(meta['duration']) infoLabels['premiered'] = str(meta['premiered']) infoLabels['studio'] = meta['studios'] infoLabels['mpaa'] = str(meta['mpaa']) infoLabels['code'] = str(meta['imdb_id']) infoLabels['rating'] = float(meta['rating']) liz.setInfo(type="Video", infoLabels=infoLabels) Or if you are using t0mmo's common library it looks like you can just pass infoLabels in: add_video_item({'url': url},{infoLabels},img=thumb) This is still very much in dev so just use for testing for now k_zeon Wrote:so basically add_video_item({'url': url},{genre='Action',duration='102 mins',premiered='xxxxx' etc },img=thumb) of would it be slightly different. havent tried it yet. Eldorado Wrote:Just a slight correction: add_video_item({'url': url},{'genre': 'Action','duration':'102 mins','premiered': 'xxxxx' etc },img=thumb)
https://forum.kodi.tv/showthread.php?tid=109725&page=12
CC-MAIN-2017-30
refinedweb
1,123
56.89
You can click on the Google or Yahoo buttons to sign-in with these identity providers, or you just type your identity uri and click on the little login button. If a class uses multiple inheritance, pylint 0.21 does not pick up any but the first base class, if the bases classes are in a different module. For example: ## test.py import testmodule class C(testmodule.A, testmodule.B): def __init__(self): testmodule.A.__init__(self) testmodule.B.__init__(self) self.cvar = "C" if __name__ == "__main__": c = C() print c.avar, c.bvar, c.cvar ## testmodule.py class A: def __init__(self): self.avar = "A" class B: def __init__(self): self.bvar = "B" gewoia : pylint test.py ************* Module test W0233: 7:C.__init__: __init__ method from a non direct base class 'B' is called E1101: 12: Instance of 'C' has no 'bvar' member I have various other errors and warnings as a result of this situation also. The problem disappears if you move classes "A" and "B" into the same file. It is not present in version 0.19, don't know about 0.20. Ticket #36586 - latest update on 2010/07/05, created on 2010/07/05 by gjb1002
https://www.logilab.org/ticket/36586
CC-MAIN-2018-26
refinedweb
201
77.64
Applet.getImage does not return immediately as said in the API doc The API documentation for Applet.getImage says: This method always returns immediately, whether or not the image exists. When this applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen. This is not true with Java Plug-in 1.6.0_10-rc2, as shown in the applet below. It has been tested with Java Plug-in 1.6.0_01 and Java Plug-in 1.6.0_10-rc2. The applet has been compiled with jdk1.6.0_03 and run in IE 6.0.2900.5512 SP3 on Windows XP SP3. The tests were made using a dial-up connection, the ouput shows 9 sec for getImage to return. Even on a slow connection, it should return immediately. Really inconvenient! ************ 3 tests with 1.6.0_01 *********** Java Plug-in 1.6.0_01 Using JRE version 1.6.0_01 Java HotSpot(TM) Client VM After clearing the plug-in cache getImgage(image1.jpg) took 0 millis. 2nd test without clearing the cache from previous test getImgage(image1.jpg) took 0 millis. 3rd test without clearing the cache from previous 2 tests getImgage(image1.jpg) took 0 millis. *********** 3 tests with 1.6.0_10-rc2 *********** Java Plug-in 1.6.0_10-rc2 Using JRE version 1.6.0_10-rc2 Java HotSpot(TM) Client VM After clearing the plug-in cache getImgage(image1.jpg) took 9000 millis. 2nd test without clearing the cache from previous test getImgage(image1.jpg) took 9016 millis. 3rd test without clearing the cache from previous 2 tests getImgage(image1.jpg) took 9000 millis. // --------------------------------------------------------------------- import java.applet.*; import java.awt.*; import java.awt.image.*; public class GetImageBug extends Applet implements ImageObserver { public void init() { String image1Name = "image1.jpg"; long time0 = System.currentTimeMillis(); Image image1 = getImage(getCodeBase(), image1Name); System.out.println("getImgage(" + image1Name + ") took " + (System.currentTimeMillis()-time0) + " millis."); prepareImage(image1, this); } public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { if ( (infoflags & ImageObserver.ALLBITS) != 0 ) return false; return true; } } Can anyone confirm if ImageIO.read() should return an accelerate image by default if available? as described at Should this be filed as a bug? I haven't tested if Applet.getImage() returns an accelerated image by default or not, because it's too slow to use as described above, has this been filed as a bug? Yea we had problems with getImage() within a real world situation and so stopped using it. From what I remember things seemed to lock up for periods when multiple images were being loaded at the same time. We now use our own custom MyImageLoader wrapper class that uses ImageIO.read() underneath to load images in seperate threads. This works much better, although we have a problem where ImageIO.read() is not returning accelerated images by default, so to copy each image into a newly created accelerated image. We use lots of images (socialbang.com) so this slows things down. See
https://www.java.net/node/683719
CC-MAIN-2015-22
refinedweb
509
62.44
On Saturday, Oct 11, 2003, at 16:54 Europe/Rome, Nicola Ken Barozzi wrote: >. cool. it would be piece of cake to have different *views* of the learning object's revisions so that forrest can rely on something like the above. >>. No, URI are identifiers, URL are locators. A URI *can* be used as a URL, but the results is unknown and has to be decided case by case (as for namespaces, for example). A learning object (think of it as the abstraction of what a page is) is a container of information and needs to be identified uniquely, allowing the content to evolve without require a change in identification. Versioning is an orthogonal identification axis and can be composed to provide a bi-dimensional identifier so identifies to the learning object 3984, but doesn't specify with version. specifies LO #3984 with revision 343. Note how if the URI is used as a locator, the resulting LO is immutable. don't look at the syntax of the IDs, an alternative syntax could well be and the meaning is exactly the same. The behavior of using the URI as a locator is dynamic. For example, at one point in time and might locate the same learning object, because revision "394" is the last one. How this maps to the file system is completely irrelevant because the repository represents a virtual one. > That's why the Forrest revisions have a defined date (or number) in > the name, so that that stays the same. see above, same thing, just must abstract, totally decoupled from the actually implementation of the storage. > What I would propose, and that I would like to implement, is an > indexing system that scans all source files and associates a number > with that file. that's the job that our repository would do for us transparently. > This means that a file can have a barcode attached to it, and if we > keep a repository of site barcodes, we can have a fully resolvable > barcoded page. welcome to the world of content repositories ;-) > Then, when pages are added or changed, the system would index the > files again, and add other new pages with incremented numbers. JSR 170 will allow us to do this and *much* more. >). hmmm, I have to think more about this... -- Stefano.
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200310.mbox/%3C04B5B2CF-FC01-11D7-8572-000393D2CB02@apache.org%3E
CC-MAIN-2016-40
refinedweb
385
60.75
This may be a simple fix, but I have a class for a program that contains some member functions that manipulate a vector. The vector is a private member variable, and is filled from an array using a constructor. When I try to access the member functions to manipulate the vector, the vector is empty. I have tested the constructor and member functions separately and they work fine on their own. Here is the code: class and #include directives #include <iostream> #include <vector> using namespace std; class NumberSet { public: void add (int A); //adds an element to the set if not already present NumberSet(int array1[], int size); //transfers the data from an array to a vector NumberSet( ); //default constructor int array_size_horizontal; private: vector<int> v1; int vectorsize; }; Constructor NumberSet::NumberSet(int array1[], int size) { for (int e=0; e < size; e++) v1.push_back(array1[e]); } Member Function Declaration void NumberSet::add(int A){ //need it to test for each element's value and when it gets to the end, if none are equal, then use push_back if(v1.size() == 0) v1.push_back(A); else{ bool found = false; unsigned int index = 0; while(!found && index < v1.size() ) { if(v1[index] == A) found = true; index++; } if(!found) v1.push_back(A); } } Main Function int main() { // int next; int horcounter = 0; int nextcounter = 0; int array1[6]; NumberSet runonce; cout << "Please enter 6 integers, then press return: "; for (int j=0; j < 6; j++) { cin >> array1[j]; } for (int j=0; j < 6; j++) { cout << array1[j] << endl; } NumberSet first(array1, 6); //calling the constructor int input1; cout << "To test the add function, please enter an integer and press return: "; cin >> input1; runonce.add(input1); return 0; } If anybody knows why I cannot get the function to access the vector, any help would be greatly appreciated.
https://www.daniweb.com/programming/software-development/threads/345151/class-member-functions-and-private-members
CC-MAIN-2018-47
refinedweb
303
56.79
LowRankModels.jl is a julia package for modeling and fitting generalized low rank models (GLRMs). GLRMs model a data array by a low rank matrix, and include many well known models in data analysis, such as principal components analysis (PCA), matrix completion, robust PCA, nonnegative matrix factorization, k-means, and many more. For more information on GLRMs, see our paper. LowRankModels.jl makes it easy to mix and match loss functions and regularizers to construct a model suitable for a particular data set. In particular, it supports To install, just call Pkg.add("LowRankModels") at the julia prompt. GLRMs form a low rank model for tabular data A with m rows and n columns, which can be input as an array or any array-like object (for example, a data frame). It is fine if only some of the entries have been observed (i.e., the others are missing or NA); the GLRM will only be fit on the observed entries obs. The desired model is specified by choosing a rank k for the model, an array of loss functions losses, and two regularizers, rx and ry. The data is modeled as X'*Y, where X is a kx m matrix and Y is a kx n matrix. X and Y are found by solving the optimization problem minimize sum_{(i,j) in obs} losses[j]((X'*Y)[i,j], A[i,j]) + sum_i rx(X[:,i]) + sum_j ry(Y[:,j]) The basic type used by LowRankModels.jl is the GLRM. To form a GLRM, the user specifies A(any AbstractArray, such as an array, a sparse matrix, or a data frame) losses rxand ry k The user may also specify obs obs is a list of tuples of the indices of the observed entries in the matrix, and may be omitted if all the entries in the matrix have been observed. If A is a sparse matrix, implicit zeros are interpreted as missing entries by default; see the discussion of sparse matrices below for more details. X₀ and Y₀ are initialization matrices that represent a starting guess for the optimization. Losses and regularizers must be of type Loss and Regularizer, respectively, and may be chosen from a list of supported losses and regularizers, which include Losses: QuadLoss HingeLoss LogisticLoss PoissonLoss WeightedHingeLoss L1Loss OrdinalHingeLoss PeriodicLoss MultinomialLoss OrderedMultinomialLoss Regularizers: QuadReg QuadConstraint OneReg ZeroReg NonNegConstraint(eg, for nonnegative matrix factorization) OneSparseConstraint(eg, for orthogonal NNMF) UnitOneSparseConstraint(eg, for k-means) SimplexConstraint NonNegOneReg y0 FixedLatentFeaturesConstraint(y0) Each of these losses and regularizers can be scaled (for example, to increase the importance of the loss relative to the regularizer) by calling scale!(loss, newscale). Users may also implement their own losses and regularizers, or adjust internal parameters of the losses and regularizers; see losses.jl and regularizers.jl for more details. For example, the following code forms a k-means model with k=5 on the 100x 100 matrix A: using LowRankModels m,n,k = 100,100,5 losses = QuadLoss() # minimize squared distance to cluster centroids rx = UnitOneSparseConstraint() # each row is assigned to exactly one cluster ry = ZeroReg() # no regularization on the cluster centroids glrm = GLRM(A,losses,rx,ry,k) To fit the model, call X,Y,ch = fit!(glrm) which runs an alternating directions proximal gradient method on glrm to find the X and Y minimizing the objective function. ( ch gives the convergence history; see Technical details below for more information.) The losses argument can also be an array of loss functions, with one for each column (in order). For example, for a data set with 3 columns, you could use losses = Loss[QuadLoss(), LogisticLoss(), HingeLoss()] Similiarly, the ry argument can be an array of regularizers, with one for each column (in order). For example, for a data set with 3 columns, you could use ry = Regularizer[QuadReg(1), QuadReg(10), FixedLatentFeatureConstraint([1,2,3])] This regularizes the first to columns of Y with ||Y[:,1]||^2 + 10||Y[:,2]||^2 and constrains the third (and last) column of Y to be equal to [1,2,3]. If not all entries are present in your data table, just tell the GLRM which observations to fit the model to by listing tuples of their indices in obs. Then initialize the model using GLRM(A,losses,rx,ry,k, obs=obs) If A is a DataFrame and you just want the model to ignore any entry that is of type NA, you can use obs = observations(A) Low rank models can easily be used to fit standard models such as PCA, k-means, and nonnegative matrix factorization. The following functions are available: pca: principal components analysis qpca: quadratically regularized principal components analysis rpca: robust principal components analysis nnmf: nonnegative matrix factorization k-means: k-means See the code for usage. Any keyword argument valid for a GLRM object, such as an initial value for X or Y or a list of observations, can also be used with these standard low rank models. If you choose, LowRankModels.jl can add an offset to your model and scale the loss functions and regularizers so all columns have the same pull in the model. Simply call glrm = GLRM(A,losses,rx,ry,k, offset=true, scale=true) This transformation generalizes standardization, a common proprocessing technique applied before PCA. (For more about offsets and scaling, see the code or the paper.) You can also add offsets and scalings to previously unscaled models: Add an offset to the model (by applying no regularization to the last row of the matrix Y, and enforcing that the last column of X be all 1s) using add_offset!(glrm) Scale the loss functions and regularizers by calling equilibrate_variance!(glrm) Scale only the columns using QuadLoss or HuberLoss prob_scale!(glrm) Perhaps all this sounds like too much work. Perhaps you happen to have a DataFrame df lying around that you'd like a low rank (eg, k=2) model for. For example, import RDatasets df = RDatasets.dataset("psych", "msq") Never fear! Just call glrm, labels = GLRM(df, k) X, Y, ch = fit!(glrm) This will fit a GLRM with rank k to your data, using a QuadLoss loss for real valued columns, HingeLoss loss for boolean columns, and ordinal HingeLoss loss for integer columns, a small amount of QuadLoss regularization, and scaling and adding an offset to the model as described here. It returns the column labels for the columns it fit, along with the model. Right now, all other data types are ignored. NaN values are treated as missing values ( NAs) and ignored in the fit. The full call signature is GLRM(df::DataFrame, k::Int; losses = Loss[], rx = QuadReg(.01), ry = QuadReg(.01), offset = true, scale = false, prob_scale = true, NaNs_to_NAs = true) You can modify the losses or regularizers, or turn off offsets or scaling, using these keyword arguments. To fit a data frame with categorical values, you can use the function expand_categoricals! to turn categorical columns into a Boolean column for each level of the categorical variable. For example, expand_categoricals!(df, [:gender]) will replace the gender column with a column corresponding to gender=male, a column corresponding to gender=female, and other columns corresponding to labels outside the gender binary, if they appear in the data set. You can use the model to get some intuition for the data set. For example, try plotting the columns of Y with the labels; you might see that similar features are close to each other! If you have a very large, sparsely observed dataset, then you may want to encode your data as a sparse matrix. By default, LowRankModels interprets the sparse entries of a sparse matrix as missing entries (i.e. NA values). There is no need to pass the indices of observed entries ( obs) -- this is done automatically when GLRM(A::SparseMatrixCSC,...) is called. In addition, calling fit!(glrm) when glrm.A is a sparse matrix will use the sparse variant of the proximal gradient descent algorithm, fit!(glrm, SparseProxGradParams(); kwargs...). If, instead, you'd like to interpret the sparse entries as zeros, rather than missing or NA entries, use: glrm = GLRM(...;sparse_na=false) In this case, the dataset is dense in terms of observations, but sparse in terms of nonzero values. Thus, it may make more sense to fit the model with the vanilla proximal gradient descent algorithm, fit!(glrm, ProxGradParams(); kwargs...). LowRankModels makes use of Julia v0.5's new multithreading functionality to fit models in parallel. To fit a LowRankModel in parallel using multithreading, simply set the number of threads from the command line before starting Julia: eg, export JULIA_NUM_THREADS=4 The function fit! uses an alternating directions proximal gradient method to minimize the objective. This method is not guaranteed to converge to the optimum, or even to a local minimum. If your code is not converging or is converging to a model you dislike, there are a number of parameters you can tweak. The algorithm starts with glrm.X and glrm.Y as the initial estimates for X and Y. If these are not given explicitly, they will be initialized randomly. If you have a good guess for a model, try setting them explicitly. If you think that you're getting stuck in a local minimum, try reinitializing your GLRM (so as to construct a new initial random point) and see if the model you obtain improves. The function fit! sets the fields glrm.X and glrm.Y after fitting the model. This is particularly useful if you want to use the model you generate as a warm start for further iterations. If you prefer to preserve the original glrm.X and glrm.Y (eg, for cross validation), you should call the function fit, which does not mutate its arguments. You can even start with an easy-to-optimize loss function, run fit!, change the loss function ( glrm.losses = newlosses), and keep going from your warm start by calling fit! again to fit the new loss functions. If you don't have a good guess at a warm start for your model, you might try one of the initializations provided in LowRankModels. init_svd!initializes the model as the truncated SVD of the matrix of observed entries, with unobserved entries filled in with zeros. This initialization is known to result in provably good solutions for a number of "PCA-like" problems. See our paper for details. init_kmeanspp!initializes the model using a modification of the kmeans++ algorithm for data sets with missing entries; see our paper for details. This works well for fitting clustering models, and may help in achieving better fits for nonnegative matrix factorization problems as well. init_nndsvd!initializes the model using a modification of the NNDSVD algorithm as implemented by the NMF package. This modification handles data sets with missing entries by replacing missing entries with zeros. Optionally, by setting the argument max_iters=nwith n>0, it will iteratively replace missing entries by their values as imputed by the NNDSVD, and call NNDSVD again on the new matrix. (This procedure is similar to the soft impute method of Mazumder, Hastie and Tibshirani for matrix completion.) As mentioned earlier, LowRankModels uses alternating proximal gradient descent to derive estimates of X and Y. This can be done by two slightly different procedures: (A) compute the full reconstruction, X' * Y, to compute the gradient and objective function; (B) only compute the model estimate for entries of A that are observed. The first method is likely preferred when there are few missing entries for A because of hardware level optimizations (e.g. chucking the operations so they just fit in various caches). The second method is likely preferred when there are many missing entries of A. To fit with the first (dense) method: fit!(glrm, ProxGradParams(); kwargs...) To fit with the second (sparse) method: fit!(glrm, SparseProxGradParams(); kwargs...) The first method is used by default if glrm.A is a standard matrix/array. The second method is used by default if glrm.A is a SparseMatrixCSC. ProxGradParams() and SparseProxGradParams() run these respective methods with the default parameters: stepsize: The step size controls the speed of convergence. Small step sizes will slow convergence, while large ones will cause divergence. stepsizeshould be of order 1. abs_tol: The algorithm stops when the decrease in the objective per iteration is less than abs_tol*length(obs). rel_tol: The algorithm stops when the decrease in the objective per iteration is less than rel_tol. max_iter: The algorithm also stops if maximum number of rounds max_iterhas been reached. min_stepsize: The algorithm also stops if stepsizedecreases below this limit. inner_iter: specifies how many proximal gradient steps to take on Xbefore moving on to Y(and vice versa). The default parameters are: ProxGradParams(stepsize=1.0;max_iter=100,inner_iter=1,abs_tol=0.00001,rel_tol=0.0001,min_stepsize=0.01*stepsize) ch gives the convergence history so that the success of the optimization can be monitored; ch.objective stores the objective values, and ch.times captures the times these objective values were achieved. Try plotting this to see if you just need to increase max_iter to converge to a better model. A number of useful functions are available to help you check whether a given low rank model overfits to the test data set. These functions should help you choose adequate regularization for your model. cross_validate(glrm::GLRM, nfolds=5, params=Params(); verbose=false, use_folds=None, error_fn=objective, init=None): performs n-fold cross validation and returns average loss among all folds. More specifically, splits observations in glrm into nfolds groups, and builds new GLRMs, each with one group of observations left out. Fits each GLRM to the training set (the observations revealed to each GLRM) and returns the average loss on the test sets (the observations left out of each GLRM). Optional arguments: use_folds: build use_foldsnew GLRMs instead of n_foldsnew GLRMs, each with 1/nfoldsof the entries left out. ( use_foldsdefaults to nfolds.) error_fn: use a custom error function to evaluate the fit, rather than the objective. For example, one might use the imputation error by setting error_fn = error_metric. init: initialize the fit using a particular procedure. For example, consider init=init_svd!. See Initialization for more options. cv_by_iter(glrm::GLRM, holdout_proportion=.1, params=Params(1,1,.01,.01), niters=30; verbose=true): computes the test error and train error of the GLRM as it is trained. Splits the observations into a training set ( 1-holdout_proportion of the original observations) and a test set ( holdout_proportion of the original observations). Performs params.maxiter iterations of the fitting algorithm on the training set niters times, and returns the test and train error as a function of iteration. regularization_path(glrm::GLRM; params=Params(), reg_params=logspace(2,-2,5), holdout_proportion=.1, verbose=true, ch::ConvergenceHistory=ConvergenceHistory("reg_path")): computes the train and test error for GLRMs varying the scaling of the regularization through any scaling factor in the array reg_params. get_train_and_test(obs, m, n, holdout_proportion=.1): splits observations obsinto a train and test set. mand nmust be at least as large as the maximal value of the first or second elements of the tuples in observations, respectively. Returns observed_featuresand observed_examplesfor both train and test sets. This library implements the ScikitLearn.jl interface. These models are available: SkGLRM, PCA, QPCA, NNMF, KMeans, RPCA. See their docstrings for more information (eg. ?QPCA). All models support the ScikitLearnBase.fit! and ScikitLearnBase.transform interface. Examples: ## Apply PCA to the iris dataset using LowRankModels import ScikitLearnBase using RDatasets # may require Pkg.add("RDatasets") A = convert(Matrix, dataset("datasets", "iris")[[:SepalLength, :SepalWidth, :PetalLength, :PetalWidth]]) ScikitLearnBase.fit_transform!(PCA(k=3, max_iter=500), A) ## Fit K-Means to a fake dataset of two Gaussians using LowRankModels import ScikitLearnBase # Generate two disjoint Gaussians with 100 and 50 points gaussian1 = randn(100, 2) + 5 gaussian2 = randn(50, 2) - 10 # Merge them into a single dataset A = vcat(gaussian1, gaussian2) model = ScikitLearnBase.fit!(LowRankModels.KMeans(), A) # Count how many points are assigned to each Gaussians (should be 100 and 50) Set(sum(ScikitLearnBase.transform(model, A), 1)) See also this notebook demonstrating K-Means. These models can be used inside a ScikitLearn pipeline, and every hyperparameter can be tuned with GridSearchCV. If you use LowRankModels for published work, we encourage you to cite the software. Use the following BibTeX citation: @article{glrm, title = {Generalized Low Rank Models}, author ={Madeleine Udell and Horn, Corinne and Zadeh, Reza and Boyd, Stephen}, doi = {10.1561/2200000055}, year = {2016}, archivePrefix = "arXiv", eprint = {1410.0342}, primaryClass = "stat-ml", journal = {Foundations and Trends in Machine Learning}, number = {1}, volume = {9}, issn = {1935-8237}, url = {}, } 09/27/2014 4 days ago 486 commits
https://juliaobserver.com/packages/LowRankModels
CC-MAIN-2017-30
refinedweb
2,757
55.54
SUCHETA DALAL ON: CORPORATE GOVERNANCE: A REALITY CHECK NEEDED Personal Finance Magazine THE INDIAN MEDIA IS A PAPER TIGER BRAZEN MANIPULATION, SILENT REGULATOR 11 August 2011 Rs 25 moneylife.in Stay away from glamorous sectors, promoters or companies. Here is why CURRENT ACCOUNT 13 – RCom: Cooking its Books – Sterling Holidays: Yet another fund-raising exercise Cover Page_142.indd 2 FUNDS 26 – Buying sector funds is a bad idea – Some sector funds benchmarks are opaque STREET BEAT 36 – Supreme Infrastructure – Ajanta Pharma – Andhra Petrochemicals 7/23/2011 4:53:27 PM Advertisements.indd 1 7/18/2011 2:48:03 PM Advertisements.indd 7 7/22/2011 6:14:09 PM Volume6,Issu e 12 29July–1 1 August 2011 DebashisB asu Editor& P ublisher editor@moneylife.in SuchetaD alal ManagingE ditor suchetadalal@yahoo.com EditorialC onsultant DrN itaMukher jee Editorial, Advertisement, Circulation& S ubscription Office 315,3 rdFl oor,H indS ervice Industries Premises,Of fV eerS avarkarMarg,S hivaji Park,D adar(W ),Mumbai -400028 Tel:022244410 59/60 Fax:02224442771 E-m ail:mai l@moneylife.in E-m ail: sales@moneylife.in Subscriptione-m ail subscribe@moneylife.in Pune JitendraGar sund “SANSHREY”,N anaiB augS ociety, BTK awadeR oad,Ghorpadi , Pune-41 1036 Mobile:9881309801 E-m ail:j rg.pune@gmail.com NewD elhi DDAFl ats,J-3/66,K alkaji, NewD elhi-1 10019 Chennai 14,Mi anS ahib,II ndS treet, NearMadras YouthH ostel,C hepauk, Chennai-600005 Tel:0 44 4215 5442 Bengaluru 1st Floor,13/1,7 thMai nR oad, 1 C ross,S aibabanagar,S rirampuram, Bengaluru-560 021 st Kolkata 395, Lake Gardens, Kolkata - 700 045 Tel:03324221 173/4064 4318 Hyderabad C/oR ajnidev, 15-2-16,1 stFl oor,S hop No.9, (BesideR amdasP aper Mart), GowligudaC haman, Hyderabad-500 012 Moneylife is printedandpubl ished by DebashisB asuonb ehalf of Moneywise Media Pvt Ltd and printed at MagnaGraphi cs,101C&D, GovernmentIndustri al Estate, Kandivli (West),Mum bai - 400 067 andpubl ishedat315, 3rd Floor, HindS erviceIndustri es Premises, Off VeerS avarkarMar g, Shivaji Park, Dadar(W ),Mumbai - 400 028 Editor:D ebashis Basu RNIN o:MA HENG/2006/16653 Letters to the Editor JAYA HO! Political alliances are fragile. Even as they are being conceptualised, the cracks appear. These tie-ups are just marriages of convenience. Actually, the coalition era, starting in 1989, has Write to the Editor! The only investment that brought in a phase where Win jewellery the politicians’ venality enhances your face value. has risen exponentially. In fact, the regional satraps, their cronies and flunkies are aware of their electoral prowess as legislators or MPs (members of Parliament). They take Congratulations SK Shah from New Delhi! maximum advantage of Your letter to the Editor wins a Surat Diamond gift. their electoral prowess Keep writing! Keep winning! and the existence of a government hinges, at times, on a single vote. After any election, the elected ‘Independent’ representatives are up for grabs. The narrower the margin of victory for the party voted into power, the higher the premium these fence-sitters command. Thanks to the mire that the DMK (Dravida Munnetra Kazhagam) finds itself in, the whole party is in disarray; it is demoralised and has become politically irrelevant. AIADMK (All India Anna Dravida Munnetra Kazhagam) head and Tamil Nadu chief minister J Jayalalithaa will warm up to the current UPA (United Progressive Alliance) regime. Should the PM (prime minister) bite the bait? After all, Ms Jayalalithaa has been known to switch camps whenever she knows that the going is not good. I think the Congress should tread cautiously. Now it is for the UPA (read, the Congress Party) to decide whether it wants to court imminent disaster with the AIADMK or mend fences with the DMK—a Hobson’s Choice, if there ever was one. SK Shah, New Delhi, by email GRAFT? CASH IN!! The Radia tapes have ave clearly shown that the business i iness community is calling n ng the shots in the country—by a long g margin. Pliable and weak-kneed politicians serve as agents for India Inc. c c. The super-rich havee become so powerful that no o one can stand up to their eir money power. In fact, they y are the ultimate decision-makers m makers in today’s India. They decide the `` MONEYLIFE | 11 August 2011 | 4 Letters.indd 2 7/23/2011 5:15:14 PM Advertisements.indd 2 7/18/2011 4:22:31 PM LETTERS ` structure of politics; these wealthy individuals can run India now like no politician can. Of course, like good businessmen, all their activities are either to feed their greed or boost their profits. Despite the sheer magnitude of politicians’ chutzpah and lobbying by private agents like Niira Radia—the rampaging and assertive loose-cannon journalists are merely assisting businessmen in furthering their interests. The aim of business is to place weak politicians in power—those who will let them loot the country. To loot the public sector companies and public banks; to loot the mines and oil & gas wells and loot pension funds... But the middle class should wake up. It should know where its self-interest lies. It must stop this systematic loot of the country. The super-rich make immense money by forcing politicians to hand over public assets very cheaply and by armtwisting governments to install a non-competitive monopolistic system, helping players to reap super-profits. Without these, their companies cannot show 20%-40% increase in profits every year. Should this loot continue? On a lighter note, I have a different point to make. We all know the amount of bribes these politicians make—even small fry like Madhu Koda (from Jharkhand) allegedly pocketed Rs4,000 crore while handing out mining licences in his assetrich state. But here’s the math. Big industrial houses must have benefited by at least Rs2,00,000 crore, considering the value of these mines. First, politicians do not truly realise the worth of what they are handing over. Second, they are desperate for cash—and so they are poor bargainers. These alleged bribes have actually given a great return on investment for mining companies! If the people of India have lost Rs2,00,000 crore on Mr Koda’s case, so be it. We, the middle-class (at least the brokers and market investors, that is), will make some gains. These gains would be nothing compared to what these big firms will reap, but we can surely make some money from the markets by investing in these firms! Of course, I am being sarcastic, but I feel that we should care for ourselves before we turn over- moralistic. It appears counter-intuitive, but we must all support the business community to loot this country’s wealth. Block agitations which try to stop the corporate looting. Anyway, the business community is too powerful and it cannot be stopped. If blame has to be apportioned, it should be to the politicians. The business community must be treated with kid gloves. Otherwise, all looting will stop and corporates will stop making profits; then, how will investors and brokers gain? Narsimhan Srinivasan, by email DUMB INTELLECTUALS When a number of countries made the transition from monarchy to democracy, the prevalent conventional political thinking had to be subverted. But a number of monarchs tried to hold on to power... saying that monarchy was necessary for ensuring stability. But the hollowness of this argument was exposed over time. More representative forms of government started taking root across the world. Can we not compare this movement to the attack that civil society is making on corruption? In fact, a number of ‘intellectuals’ want to retain the status quo and are working overtime to attack any change. Governments in power always use this strategy—and fire from the shoulders of these intellectuals—to undermine the wishes of the people. The civil society is a vocal minority which is expressing the views of the silent majority—a majority struggling to earn a living. This majority has no time or energy to come onto the streets. “Greed is good” seems to be the mantra now. Unregulated greed is the operative philosophy of people in power. On top of this, when the head of government is weak and permits his ministers to do as they please, corruption becomes easy. People have figured out that this unbroken sequence of scams represents a deeper structural malaise. The unregulated greedy political class is the weak spot which is being exploited by unscrupulous businessmen to grab the nation’s assets for minor considerations. One has to keep in mind that democracy has evolved `` MONEYLIFE | 11 August 2011 | 6 Letters.indd 4 7/23/2011 5:15:28 PM Here’s what is coming up! HOW TO BE SAFE & SMART WITH YOUR MONEY July 30 Seminar at the Sadhana Centre for Management & Leadership Development, Pune, exclusively for its management students 6 HOW TO USE THE RIGHT TO INFORMATION ACT EFFECTIVELY July 12 HOW TO BE SAFE & SMART WITH YOUR MONEY August These were the events Moneylife Foundation held over the fortnight A workshop on financial literacy, exclusively for the medical community in association with the Indian Medical Association Narayan Varma, ma, a chartered accountant with 55 years of experiencee addressed a packed halll on how to use the RTI Act effectively INVESTOR EMPOWER YOURSELF! July 16 First full-day seminar in Bengaluru which was also Web-casted live for the very first time UNDERSTANDING PYRAMID SCHEMES ILLEGAL MINING—BLOOD AND IRON August 12 Screening of the documentary on illegal mining—Blood and Iron by Paranjoy Guha Thakurta, an independent journalist HOW TO USE THE RIGHT TO INFORMATION ACT EFFECTIVELY September 3 Event Ad.indd 1 How to use the RTI Act effectively at the Ravindra Natya Mandir, ndir, Prabhadevi, Mumbai, by Shailesh Gandhi, Central Information Commissionerr July 23 Workshop on Understanding Pyramid Schemes by Sucheta Dalal. Ms Dalal spoke on how to invest safely by avoiding pyramid yramid schemes as well as multiltilevel marketing eting schemes Call 022-24441058-60, or email us at mail@mlfoundation.in or log on to 7/23/2011 5:18:56 PM LETTERS ` over the decades. former chairman of Bulls and bears are Write to the editor! the Atomic Energy Intellectuals are failing unpredictable. Invest in diamonds. Win jewellery Commission of India us—are they too and ex-secretary in the comfortable with the Department of Atomic powers-that-be? They are Energy), “How well are ignoring the rising tide we equipped to handle a of public opinion. People disaster in terms of fast are beginning to make response to evacuation, up their minds about Write to the editor. If your letter is the best, You’ll medical assistance this form of democracy Win Surat Diamond jewellery. and rehabilitation of which is for everyone’s the locals, in case of a benefit... except the disaster in Jaitapur?” people. When representatives can get away without Mr Kakodkar’s response was: “Unless we have this representing the people, I think the political system system in place, we will not be granted a licence to set itself should come under public scrutiny. up a nuclear power plant.” Yes, Mr Kakodkar, these Jasmeet Singh, by email clauses exist in bold letters on paper. But they have remained only on paper. Recently, a mock drill was BIG BROTHER held at Tarapur plant, but it failed. This refers to the article, “Banks & Financial The interaction with the audience at the Worli seminar Literacy—Ears to the Ground” (Moneylife, 14 July was also a disaster. Mr Kakodkar’s replies to most 2011). The article states, “We do know this; banks are questions were evasive. I feel that by conducting such quietly making plans for unique identification numbers (UINs) to be mandatory as part of know your customer discussions, nothing constructive can be generated. We have to ask ourselves a fundamental question—can (KYC) requirements without consulting the consumers we do away with nuclear power? Is it time to pass a or looking into privacy issues.” Why are the banks (at worldwide ban against nuclear power projects? a cost of millions of rupees) duplicating this process? The government is already Subrahmanian SH, by email issuing Aadhaar numbers; banks should capture this HELP US TO HELP YOU number in their existing Moneylife offers its readers a unique service—helping databases. Banks should redress grievances on a best-effort basis. However, we avoid duplication and have limited resources to devote to this effort and can further complicating the only pursue complaints that come to us by email. We issues that will arise from request readers to please send us crisp complaints, with these UINs. Aadhaar has all the facts on email (not as an attachment) and send the biometrics and PAN us the supporting documents, only if we ask for them. (permanent account We cannot handle physical letters. — Editor number) along with the address (and other HOW TO REACH US Letters to the Editor can be emailed to editor@moneylife.in or details) of a customer. can be posted to: The Editor, Moneylife Magazine, Unit No. 315, 3rd The government should Floor, Hind Service Industries, Off Veer Savarkar Marg, Dadar (W), have looked into Mumbai 400 028 or faxed to 022-24442771. Letters must include privacy issues before the writer’s full name, address and telephone number and may be edited for clarity or space. getting into this exercise. It has to ensure that any New Subscriptions & Customer Service form of wastage of funds is avoided and duplication of For new subscription requests, complaints about current processes and data is done away with. subscription and books, write to subscribe@moneylife.in or Adi Daruwalla, by email to Subscription Manager, Unit No. 315, 3rd Floor, Hind Service NUKE NUKES! At a seminar held recently at Nehru Science Centre, Worli (Mumbai), I asked Anil Kakodkar (an eminent Indian nuclear scientist and mechanical engineer; Industries, Off Veer Savarkar Marg, Dadar (W), Mumbai 400 028 or call 022-24441059-60 or fax to 022-24442771. Advertising For information and rates, email us at sales@moneylife.in or call 91-022-24441059-60. MONEYLIFE | 11 August 2011 | 8 Letters.indd 6 7/20/2011 8:15:35 PM TION MONEYLIFE FOUNDA DONATE * to help spread financial literacy & promote advocacy In just over a year since our inauguration, we have enrolled more than 4,500 members and conducted 54 workshops Hundreds have benefited from our grievance-redressal efforts. We have addressed: — Financial Issues Faced by Senior Citizens — Issues Faced by Retail Investors If you have benefited from our work, and if you would like to support our effort to educate savers, please donate to the Moneylife Foundation to help expand our nationwide financial literacy initiatives. *Donations to Moneylife Foundation are eligible for tax benefits under Sec. 80G of the Income-Tax Act 1961 (50% tax exemption). Please send a Cheque/Demand Draft in favour of ‘MONEYLIFE FOUNDATION’ accompanied by a letter indicating if it is a corpus donation. We will also need your Name, Address, Contact No., Email and PAN card details in order to send you the tax-exemption certificate..) Our Address: Moneylife Foundation, 305, 3rd Floor, Hind Service Industries Premises, Off Veer Savarkar Marg, Shivaji Park, Dadar (W), Mumbai 400 028 Tel: (022) 2444 1058/59/60 MF Trust Reg No: E-26571; MF Pan No: AACTM4377J MF 80(G) Reg No: DIT(E)/MC/80G/685/2010-11 dated 7.2.11 effective 8.9.2010 Moneylife Foundation is a not-for-profit initiative of Moneylife Magazine & Moneylife Digital, which provide fair, fearless and unbiased information on business, industry and personal finance. The Trustees are Mr Debashis Basu, Ms Sucheta Dalal, Dr Nita Mukherjee & Ms Tina Trikha. Donate Ad.indd 1 7/22/2011 8:13:03 PM LETTER ISSUE CONTENTS 11 August 2011 FROM THE EDITOR Pen Power A re you not tired with various media outlets falling over themselves to claim credit (with screaming headlines and even louder anchors) for the same exposés? But not all journalists are the same. Read about the struggle of an editor from Pune, who preferred not to unsheathe her pen, but instead used the RTI (Right to Information) Act to create civic awareness to keep eco-vandalism in check. There’s more inside this Moneylife issue about how the credibility of the Fourth Estate has been shattered recently, thanks to the politician-tycoon-media terrible troika. Our readers are aware that our markets suffer from poor participation, loose regulation and brazen manipulation. The number of instances of fraudulent manoeuvring that we have highlighted over the past five years are too numerous to be recounted here. And nothing has changed over half a decade—the situation actually seems to have taken a turn for the worse... but that only strengthens our resolve to keep unearthing situations where investors are left in the lurch. Of course, just writing about these issues that affect investors is not enough. The Moneylife Foundation held another seminar to spread consumer awareness in Bengaluru. And this event was our first attempt to reach a global audience as it was streamed live over the Internet. Apart from the 300 or more attendees, this event was watched by over 4,000 viewers. And the breaks that we had were for Q&A sessions, not advertisements. The Foundation also held its fourth seminar on the RTI Act—the focus of this event was to educate the participants on Section (4) of the Act, which involves suo moto disclosure of information by public authorities. We are also in the process of forming a Voluntary Experts Group and I invite readers to write in if they can help in pro bono work to further the activities of the Foundation. Our next stop is Chennai—another foray outside Maharashtra. Glamorous stocks grab the headlines everywhere and investors seem to be drawn to them again and again. But they will leave you with a hole in your portfolio. Read our Cover Story to know how. Debashis Basu 30 Cover Story Glamour Stocks, Ugly Returns It is easy to fall for the stocks of glamorous sectors, promoters or companies, especially since they figure prominently in the popular media all the time. This is a recipe for disaster, as Moneylife Research Desk shows 13 Current Account – Veritas Research has created history. It has alleged that Reliance Communications has been cooking its books – There is a lot of capital for the education business but student loans are elusive – The Fed Chairman thinks that the yellow metal is useless. It has stirred a huge debate – Researchers claim that googling for information affects memory – Sterling Holidays is on yet another fund-raising drive – A group of disparate entities have come up with a “superaerodynamic time trial bike” 19 LOOSE CHANGE Moneylife Quiz; Soundbites 20 Fourth Estate? Our media is a paper tiger; Vaswani’s Stock: Manipulation, time & again; Ashika Escapes: SEBI ignores machinations Disclaimer: Moneylife has a policy of not allowing its editorial staff to buy and sell stocks that are written about in the magazine. All personal transactions in individual stocks are subjected to internal disclosure rules. MONEYLIFE | 11 August 2011 | 10 Content.indd 2 7/23/2011 5:21:28 PM CONTENTS DIFFERENT STROKES EVENTS EVENT on 22 Check Misgovernance Foundation 51 Moneylife Seminars India needs to encourage proxy services to check corporate misgovernance, but ensure that conflict, regulation and compensation issues are addressed right now • • “Beware “Be of Pyramid Schemes” “Implement “Im Section (4) of the RTI Act Correctly” LEGALLY SPEAKING LEGAL STOCKGRADER 41 SMART MONEY with 24 Bond the Best Option Momentum Prime Focus jumped 18% and EID Parry climbed 2%, while Orchid Chemicals plunged 8% A few alternatives for investors who cannot directly invest in bonds either through their brokers or through other financial intermediaries Supreme Petrochem jumped 9%, while Shoppers Stop fell 5% and Asian Paints lost 2% Fund Pointers Buying sector funds is a bad idea. But if you must buy one, which should you go for? – Several funds are benchmarked to proprietary indices, making it impossible to measure their performance Long Term Amara Raja Batteries jumped 5%, while Cadila Healthcare tumbled 7% and TCS fell 4% – INSURANCE 46 Insurance Trends – – – 36 Street Beat Supreme Infra: Strong backward integration model; Ajanta Pharma: Growth drivers for the company are firmly in place; Andhra Petro: Better capacity & latest technology SAVING AND INVESTING 55 Earning Curve Never invest in something you don’t understand TRAVEL – STOCKS The d doctrine of ‘buyer beware’ applies to any transaction. You have legal recourse if you are cheated, but always keep this adage in mind before any purchase Medium Term FUNDS 26 Emptor Holds 54 Caveat Good: In all cases Guaranteed returns from Bharti AXA Monthly Income Plan: just 2.5% a year! Birla Sun Life Protector offers higher sum assured Future Generali Bima Advantage costs a packet for enhanced cover Fine Print: Motor insurance for diesel engine cars may be hiked; SBI Life fined Rs70 lakh & Nature’s 60 Mankind Grand Creations Visited by millions of people, Las Vegas and the Grand Canyon represent the grandest of spectacles that mankind and nature can provide POWER OF ONE 48 Crusading Beyond the Printed Word When governance breaks down, it is critical to empower and inspire the ordinary, faceless person, says Vinita Deshmukh based on her own experience BEYOND MONEY 66 ANewBraveLife Kripa Foundation helps people afflicted with chemical dependency and HIV infection to get back on their feet, says Disha Shah WHICH WAY 40 Follow the Price? There are too many conflicting scenarios and we know little about them—or beyond Content.indd 3 AUTO 50 Showrooms with a View Customer-oriented car firms? It’s the Japanese, finds Veeresh Malik DEPARTMENTS Letters ............................ 4 Book Review .................... 56 Money Facts .................... 63 7/22/2011 9:46:59 PM If you haven’t clicked on the Moneylife website yet, here’s why hy you sh should. news 14 reasons why you must visit the Moneylife website TOP STORIES News you should not miss >> Veritas Investment Research says RCom and RIL shortchanged shareholders by Rs25,000 crore at the time of the reorganisation of the companies >> Sector funds are overstepping their mandate by investing more than 40% of their total assets in stocks not related to their sectors, in trying to boost returns >> Asset reconstruction companies in India are very different from the global ones and have been operating contrary to the purpose they are meant to fulfil MARKET WATCH The rise and the fall S&P CNX NIFTY PTI WEB EXCLUSIVES Issues that matter to you R Vijayaraghavan MUMBAI ATTACKED, AGAIN Our commentators zero in on what is causing terror The home department has virtually conceded that it has not implemented the nearly three-yearold directive of the Supreme Court to constitute proposed security and police institutions to facilitate accountability and better governance — Vinita Deshmukh The war on terror has taught the US that technology-based intelligence alone cannot prevent terrorist attacks, as many terrorists are increasingly relying on human couriers and faceto-face communication From rampant corruption to open rebellion in the ranks after the Union Cabinet reshuffle, things seem to be falling apart for the UPA government Sudhir Badami Small things matter a lot for the safety and convenience of pedestrians. It actually requires only a little thought and a big desire to improve conditions and see the difference Anil Thakraney The Vodafone ad is simple and it is humane without using human beings. It is a good example of how even an average creative work fares well when the strategic thought is strong HAVE YOUR SAY Is the government too preoccupied with its own contradic ons to be able to deal with terrorism? 12% No — Ramesh S Arunachalam Can’t Say 5,800 88% 5,740 5,680 MONEY WISE 5,620 What’s right, what’s not 5,560 11 Jul-11 21 Jul-11 Did you know that the Sensex has gained in trading on the day after a terror attack in India over the past 20 years? on twitter NEWmoneyweb.indd 1 ML FOUNDATION Investor, Empower Yourself! 5,500 1 Jul-11 Yes If you are a tweeter, ttype. com/Mldigital to c pick up Moneylife exclusives, up-to-date e news and reports on our activities >> Insurers are focusing on single premium ULIPs for the relative ease of sale and convenience of one-time payment. But are they missing the principle of insurance? >> SKS Microfinance, the do-gooding company, is now a playground for the punter, its shares often getting locked in the circuits >> Blue Chip Infraprojects’ MLM scheme pages disappear from its website following a complaint by Moneylife to SEBI Moneylife Foundation conducted its first seminar in Bengaluru on 16 July 2011 on the basics of savings and investments for common investors. Log on to www. mlfoundation.in and register yourself as a member and you too can participate in regular programmes, free of cost TO GET THIS AND MORE... SUBSCRIBE TO OUR DAILY NEWSLETTER FOR FREE 7/22/2011 9:17:14 PM CURRENT ACCOUNT C O R P O R A T E GOVERNANC E Cooking the Books Veritas Research has created history. It has alleged that Reliance Communications has been cooking its books A Canadian firm has accused Reliance Communications (RCom) of large-scale cooking of books to boost book equity (BE). RCom came into being on 31 August 2005 at an asset value of Rs15,389 crore following a scheme of demerger from Reliance Industries Ltd. RCom’s pro-forma consolidated financial statement for 31 March 2006 lists BE at Rs11,751 crore. Subsequently, audited financial statements for the 15-month period ended 31 March 2007, shows BE at Rs22,930 crore, implying an increase of Rs11,179 crore over that of the previous 12 months. How did this come about? In FY06-07, the company reported an after-tax profit of Rs2,408 crore, and paid a dividend of Rs102 crore and a tax on dividend of Rs17 crore. On that basis, BE should have increased by approximately Rs2,289 crore. How does one account for the difference of Rs8,890 Call Drop 780 Reliance Communications 640 500 360 220 80 Mar-06 Nov-08 Jul-11 crore? This is attributable to the merger of Reliance Infocomm, Reliance Telecom, and Reliance Communication Infrastructure. According to Veritas Investment Sharp PracƟces FY Amounts booked What RCom did to reserves (Rs Cr.) 9,030 (1,986.60) Valued its subsidiaries on the account of amalgamation and arrangement in 2006, when it got demerged from RIL. The excess of fair value of assets of Rs23,207 crore over the loan liabilities of Rs7,953 crore and consideration paid in the form of allotment of equity shares of value Rs410 crore was Rs14,843 crore out of which Rs9,030 crore was transferred to the securities premium account. 2,625 (577.50) Also, a part of the above gain of Rs14,843 crore, Rs2,625 crore was transferred to the general reserve account. 2006-07 2007-08 1,287 (283.10) When it transferred passive infrastructure from RCom and RTL to RITL, the company revalued its investment in RCIL, the holding company of RITL, at its fair value by Rs4,487 crore and transferred Rs1,287 crore after adjusting the write-off of passive infrastructure assets, transferred to RITL, having book value of Rs3,200 crore. 2008-09 12,344 (2,715.60) Amalgamated its subsidiary, Reliance Gateway Net Ltd (RGNL), into itself. In accordance with this amalgamation, it valued its assets and Rs12,344 crore was transferred to general reserve. Source: RCom annual reports and Veritas Investment Research Research, “In the normal course of business, BE should grow on an after-tax, after-dividend basis from retained profits or via the issuance of securities at a premium. RCom’s BE is growing by leaps and bounds at the mere stroke of a pen. In FY08 and in FY09 the company once again undertook various reorganizations of its subsidiaries and related parties, and fair-valued its subsidiaries, booking enormous gains, thereby boosting reported BE in every instance.” Veritas concludes that, “we do not find the reported BE of the company credible. Unless RCom makes each and every one of its fair-valuation reports public, investors should be wary of the company’s claimed BE.” Not only has Veritas accused RCom of boosting its BE from dubious revaluation gains, “the company is also booking some investment gains twice on its income statement: PBT (profit before tax) in one year, and net income in another.” Veritas finds RCom’s account so smelly that is has coined a new term for it. “There are various kinds of accounting practices that Veritas has witnessed over the years: conservative, creative and aggressive. To that category we now add clandestine… to avoid paying capital gains taxes in India, the company booked income on the sale of shares in a subsidiary, through an offshore trust.” If the I-T Department gets hold of the report and takes the same view, RCom would be in trouble. It calls RCom’s position tenuous, “since it booked a capital gain on share sale and has circumvented Indian taxes. Investors should be aware that a tax liability not recognized on the books of the company could exist, and that the Indian authorities could scrutinize this transaction at any time and slap a back tax with punitive damages on the company.” 13 | 11 August 2011 | MONEYLIFE Current Account.indd 3 7/22/2011 9:10:02 PM CURRENT ACCOUNT E DU C A T I O N L OANS reported on how four pieces of legislation, which are likely to improve the current education system, such as the Education Tribunals Bill, Foreign Educational education business but Institutions Bill and two others are gathering dust. Ironically, on the one hand, students are being deprived of large in the sector, despite the fact education because of lack of funds, that banks insist on guarantees and and, on the other, we have a collaterals from the borrowers. continuous inflow of private equity In the loan category of up to Rs4 investment into the education sector lakh, defaults are especially high which is now a booming and fastand the Indian Banks’ Association growing business segment. Investors is pushing for extending the are betting on this sector as the repayment period. Banks have ‘next-big-thing’. It is probably the also asked for a mechanism which hottest sector going today. Private would rate educational institutes equity (PE) players are targeting to ensure a job guarantee to the everything—from test preparation student which, in turn, would lead to preschools, to the ‘K-12’ segment to timely repayments. Despite all these recommendations and reforms, (kindergarten to Class 12), to IT-enabled services for education. In already worried and confused students continue to be harrowed to 2010, PE investment in this sector rose to $183 million from $129 get loans approved. According to a recent media report, the government million in 2009. It may make the has asked banks to make the process sector more organised, but it will also raise user prices—to fund this of sanctioning and disbursal of hike, education loans must be made student loans ‘customer-friendly’ through a draft guideline. Banks tell available. In other fields, shortage of us that they will do things their way money is a problem. In education, and the guidelines would remain there is no dearth of money—but just that—guidelines. the structure and policies are such A number of long-term reforms that students are still getting the in education loans need to be short-shrift. undertaken. Moneylife recently More for Business, not Students There is lots of capital for the student loans are elusive W hile there is no dearth of foreign capital chasing education as a business, Indian students continue to be deprived of education loans. The education loan portfolio of public sector banks stood at Rs43,074 crore on 31 March 2011. Banks, especially public sector ones, state that they are keen to fund students. They believe that their loan books will pick up—even accelerate—with more students availing of the benefit. However, the size of the loan book is misleading. Defaults are G O L D V S P AP E R M ONEY claims that the world is flat (no, Thomas Friedman is not its chairman). David Wallechinsky cannot fill his Book of Lists with these nutty US myths. But could it be true (as one conspiracy theorist had The Fed Chairman thinks that the yellow metal is useless. it) that, if you knock on Fort Knox, it It has stirred a huge debate will not have any gold, if they open the vault? That, surely, seems to be the case. ed (Federal Reserve Board, USA) head America is a nation that cannot have its fill of conspiracy theories—UFO sightings, After all, when you can spew out a Ben Bernanke is not turning yellow. million greenbacks before you can spell Elvis spotted in a neighbourhood Ben is not bothered even when gold is ‘dollar’, Ben’s thought balloon will keep watering hole drowning his blues, or threatening to breach new levels (way saying, “What, me worry?” Money does Al Gore accidentally discovering the past $1,600/oz). The US central banker not grow on trees, but you can surely Internet… It even has a society that has told Congress, “Gold isn’t money.” `` Ben Is Not Going for Gold F MONEYLIFE | 11 August 2011 | 14 Current Account.indd 4 7/22/2011 9:10:25 PM CURRENT ACCOUNT WE B S E A R C H P E RIL S Google, and Forget Researchers claim that googling for information affects memory I t is difficult for many to imagine the pre-Google way of life; but, maybe, hitting the search button for every bit of information you need is not such a good idea. At least, that’s what a team of scientists from universities in Columbia, Harvard and Wisconsin is pointing out. According to their studies, widespread use of search engines and online databases is affecting the way people remember. The scientists arrived at the creepy conclusion after performing several memory tests, discovered that availability of a computer and access to the Internet not only determine a person’s willingness to remember information, but also what they ` chop trees to make money. But Ben’s predecessor Alan Greenspan disagrees, as he ought to. In 2010, he told a gathering that fiat money has no place to go but to gold. Ben might sorely want to raise the bar and knock back a few. (Maybe, he did that when he made the gold-is-not-money gaffe). But Greenspan had more faith in gold than in the greenback. Last year, the former Fed Chairman had said that the Allies in World War II found that it was easier for them to use gold for bribing their way through hostile land, and bills with the actually remember. The experiment explored an aspect of what is known as ‘transactive’ memory—the notion that we rely on people around us as well as reference material to store information for us. In one experiment, where participants typed 40 bits of trivia, the team found that the subjects were more likely to remember information if they thought they would not be able to find it later. In another, participants were asked to remember a trivia statement and then recall which of the five computer folders it was saved in. The researchers were surprised to find that people seemed better able to recall the folder. “That kind of blew my mind,” Dr Sparrow says. We feel that she, and we ourselves, are no less spooked. Reports on personality disorders caused by Internet addiction and use of social media are surfacing everyday. Just Google (no comments on irony here, please) Asperger Syndrome, online OCD $ sign on them were of no use. “Gold is the canary in the coal mine” is what Greenspan had said. (obsessive compulsive disorder) or intermittent explosive disorder, and you will soon have alarm bells ringing in your head every time your kid goes online or sneezes. It’s one thing to read these reports and quite another to realise that a bug is already in our brains— in our normal, social, non-psychotic, non-nerdy brains. And we don’t even feel the effect. Dr Sparrow says that her experiments have led her to conclude that the Internet has become our primary external storage system. “Human memory,” she says, “is adapting to new communications technology.” She would have meant it in a comforting way, but the imagery only adds to our paranoid imagination of a cyber zombie apocalypse. Of course, one can take Ben’s outburst with an ounce or two of salt, but he better stay well clear of Salt Lake City. Utah has declared that gold—and its fast-playing catch-up cousin, silver—to be legal tender. And not every central bank shares Ben’s sentiment on gold. They are tanking up on it like it might run out of supply tomorrow (it very well could). And, as you finish reading this, a few millions of dollars would have gushed out of Washington’s perpetual money press. — Devarajan Mahadevan 15 | 11 August 2011 | MONEYLIFE Current Account.indd 5 7/22/2011 9:10:40 PM CURRENT ACCOUNT was on the scene long before Club Mahindra emerged—but after a decade of its launch (in 1986), it has been a downhill ride for this Chennai-based company. Sterling Holidays on yet another fund-raising drive After a failed takeover deal with Days Inn, in 2006, Sterling admitted earlier, in what appears to be a case that it had accumulated debt of he troubled Sterling Holidays of insider trading and price rigging. Rs211 crore and declared a threeis looking to raise Rs120 crore year clean-up plan. In the same Sterling Holidays, which owns ($27 million) through a preferential year, it failed to raise $15 million 14 indifferently-maintained resorts allotment of shares and convertible through an issue of foreign currency in 12 destinations across India, is equity warrants to a group of convertible bonds, followed by investors. A few individual investors, in dire need of cash. The company another failed attempt to raise investment funds and the company’s Rs100 crore through the sale of promoter are going to aid in its Irrational Exuberance? timeshares and asset sales worth latest exercise, after a series of failed 120 Rs50 crore. Earlier this year, the attempts at raising money. Sterling company said that it was looking was a pioneer of time-share in India, Sterling Holidays to raise up to Rs100 crore and but poor execution and a plethora 105 it seems that the target has been of customer complaints have badly pushed up a bit. Meanwhile, the damaged its reputation—which a 90 company’s control passed into the clutch of large investors is trying to hands of private equity investors. revive. 75 In 2009, Indus Hospitality Fund, The preferential allotment will be which is now known as Bay at a price of Rs75 per share, against 60 Capital Investments, acquired over the last traded price of Rs111.50 Jul-10 Jan-11 Jul-11 15% stake in Sterling (through per share, leading to an equity preferential allotment) for around dilution of as much as 32.5%, postRs28 crore. This Fund and India conversion of warrants. As soon as reported revenues of Rs39.50 crore Discovery Fund held 19.37% stake the company announced its intent for the last financial year (ended to raise money, the scrip crashed March 2011) and has been running after the acquisition. Bay Capital, 9.28% (on 20th July). The scrip had losses for the past five years. Sterling together with India Discovery Fund, had raised its stake and, as of lost its first-mover advantage—it shot up almost 60% within a week 31 March 2011, held 22.80% in the company. Sterling has hired Ramesh Ramanathan as the new managing director, who has experience of leading Mahindra Holidays and Resorts. To invest in this company is like succumbing to a case of financial amnesia or overarching optimism. While it remains debatable how successful its clean-up operation will be, the company’s visible desperation reflects that it is still in dire straits. Add to that a limited market share and the presence of heavyweight rivals, like Mahindra Holidays and Country Club, and the company’s prospects look even bleaker. C O R P O R A T E GROW T H Desperate Measures T MONEYLIFE | 11 August 2011 | 16 Current Account.indd 6 7/22/2011 9:12:08 PM One year of financial literacy, one year of pro-investor & pro-consumer advocacy 58 SPEAKERS 5831 ATTENDEES 71 EVENTS 6054 MEMBERS 1 FOUNDATION In just one year, Moneylife Foundation has enriched many lives with unique events, opinions, actions and advocacy initiatives It’s Only the Beginning Moneylife Foundation financial literacy events have covered: • Credit Cards • Long-term Investing • Mobile Payment Systems • Consumer Banking Services • Credit Scores • Wills, Nominations & Transmission • Co-operative Housing Society Laws • Tax Returns & Scrutinies • Chain Marketing Schemes • Reverse Mortgage • Legal Compliances for NGOs • Being Financially Safe & Smart BECOME A MEMBER. IT IS FREE To become a member of Moneylife Foundation and to receive invitations to these workshops, please contact: Dione/Judith: (022 24441058-60) Or mail us at: mail@mlfoundation.in. Or visit newmlf.indd 1 7/22/2011 7:31:46 PM CURRENT ACCOUNT MI ND- C O NT R OL L ED DE V IC ES Bind over Matter BOTTOMLINE BY MORPARIA the PXP into the right gear; ‘shift up’ and ‘shift down’ will move the contraption. Of course, the first question that comes to your mind is: “Do A group of disparate entities have come up with a “super-aerodynamic time trial bike” “A computer is like a bicycle for our minds,” said Steve Jobs a few moons ago. So how about a bicycle that can be controlled by your mind? Electroencephalography (EEG) sensors have made that possible. This futuristic bike is called PXP, the brainchild of Toyota, Saatchi & Saatchi LA, Deeplocal, and Parlee Cycles (according to www. fastcodesign.com). Just slip on an EEG helmet and you do not have to bother about moving your left forearm to move you need a thought sensor to shift gears?” And of course, the second logical thought that follows is: Why does a bike need gears in the first place? Whatever happened to good old pedal-pushing? And, if somebody revisits Jerome K Jerome in the near future (wait for Spielberg to do that after he finally runs out of ideas and pre-sequels), will a futuristic machine with three men on a tricycle—with their individual EEG helmets firmly perched on their respective heads—actually be able to move... forward? And whatever will they think of next? A microwave controlled by EEG sensors? Heaven forbid, if you harbour some dark thoughts at the end of a tiring day before you even think of switching it on. And we are not even trying to imagine a future when weapons can be controlled by thought. Coming back to the current contraption, you have to be careful with this PXP, though. What if a thought like ‘slip’ slips into your mind? MONEYLIFE | 11 August 2011 | 18 Current Account.indd 8 7/21/2011 8:48:40 PM LOOSE CHANGE Surprise Gift for Quiz winners from: Moneylife Quiz - 107 Another quiz to tickle your brain. The answers to this quiz are in this very issue. The winner will be chosen by a lucky draw from correct entries. The answers will be published in the next issue. Send in your answers to quiz@moneylife.in with the Quiz no., your name, address and telephone number before 7 August 2011. 1. When did the work on building the Hoover Dam on the Colorado River start? a. 1931 b. 1938 c. 1942 d. 1956 2. With whom did Ajanta Pharma sign a deal on 3 May 2011? a. Sun Pharmaceutical b. Dabur India c. Glenmark Pharmaceuticals d. Cipla Ltd 3. With whom does Supreme Infrastructure India have a joint venture, to execute turnkey power projects for Maharashtra State Electricity Distribution Co Ltd? a. Jindal Power b. Larsen & Toubro c. Patwari Electricals d. Gammon India 4. Which prestigious award was conferred on Dr Anil K Khandelwal by Asian Banker, Singapore? a. Leadership Achievement Award b. Banking Innovation Award c. Promising Young Banker Award d. Lifetime Achievement Award 5. Who is the author of the book How a Second Grader Beats Wall Street? a. Alan Roth b. Richard Lehman c. Jim Rogers d. Michael D’souza 6. Which insurance company has launched new term plan offerings— ‘Protector’ and ‘Protector Plus’? a. New Life Insurance b. Birla Sun Life Insurance Company c. National Insurance d. Oriental Life 7. In 2008, Vinita Deshmukh was the editor of which weekly tabloid? a. Janakalyan b. Intelligent Pune c. Sakaal d. Lokmat 8. Who is the founder of InGovern Research Services? a. Kartik Narayan b. Anil Mathews c. Shriram Subramanian d. Nilesh Joshi The answers to Moneylife Quiz-106 are: • 1-a. Society for Capital Market Research & Development • 2-b. Itaewon • 3-c. Queen Munjeong • 4-d. Volzhsky Abrasive Works • 5-c. January 2010 • 6-b. Chandulal Shah • 7-c. Goa • 8-b. 12 In all, 18 readers got all the answers right last time. The winner of Quiz-106 is Alexinho Rodrigues from Mumbai. Congrats Sir! You will get a surprise gift from Surat Diamond Jewellery. Sound Bites “Curbing corruption may not make corporates prosperous, but it would definitely not let them suffer. They don’t have to worry about protecting their positions in tenders” – AM NAIK, CMD, LARSEN AND TOUBRO, in The Hindu Business Line “People I trusted—I’m not saying who, and I don’t know what level—let me down. They betrayed the company, and it’s for them to pay” – RUPERT MURDOCH, CHAIRMAN & CEO, NEWS CORPORATION, in The Washington Post “As long as the middle class remains small, there will be rampant corruption. But once it expands and jobs and services improve, patronage will die out” – DIPANKAR GUPTA, SOCIOLOGIST, in The Times of India “Large revisions in GDP estimates in recent years have led to questions on the robustness of these estimates” – ROOPA KUDVA, MD & CEO, CRISIL, in The Times of India 19 | 11 August 2011 | MONEYLIFE Loose_change.indd 3 7/22/2011 9:08:07 PM Exclusive news, the stories behind the headlines and the truth between the lines by Sucheta Dalal T H E P O L I T I C AL -M EDIA C ABAL Fourth Estate? Our media is a paper tiger “Tmedia Murdoch is sorry, but do our barons worry? that buy information and also control people’s perception by paying the media. In many ways, India currently has an advantage. Some pathbreaking. REGULATION Vaswani’s Stock Manipulation, time & again T hesubscription of the IPO in the high net-worth individuals and 6.8 times in the retail category. There was little interest from institutional investors. Immediately after the issue closed, the bulk of the subscription vanished when over 3,000 ‘investors’ issued stoppayment instructions, leaving just over a one-time subscription of the issue. Many investors bid for IPOs on the last day after watching the subscription pattern. An oversubscribed IPO requires them to bid for more shares on the expectation of a lower proportionate allotment. In this case, the fraudsters clearly `` MONEYLIFE | 11 August 2011 | 20 CROSSHAIRS.indd 2 7/22/2011 9:04:45 PM `. M ARKET MANIPULATION Ashika Escapes SEBI ignores machinations I s!” 21 | 11 August 2011 | MONEYLIFE CROSSHAIRS.indd 3 7/22/2011 9:05:07 PM DIFFERENT STROKES SUCHETA DALAL P R OXY ADVIC E Check on Misgovernance India needs to encourage proxy services to check corporate misgovernance, but ensure that conflict, regulation and compensation issues are addressed right now, while it is still a nascent business I ndian companies, or rather their owners/managers, bothered to publish InGovern’s recommendations. And, tend to be extremely touchy and thin-skinned about as far as Wipro was concerned, the recommendation any public discussion regarding board decisions, was probably just ignored. I say, probably, because a role of independent directors, auditors or retirement of day after the AGM of this blue-chip company, it had directors. Yet, a new proxy advisory firm—InGovern not reported the general body’s decisions to the stock Research Services—set the cat among our corporate exchanges. The media, obsessed only by profit numbers, pigeons by openly recommending that some big-name does not even bother with issues such as executive remuneration, appointment of independent directors independent directors do not deserve re-election. InGovern issued a press release mid-July announcing or auditors. What better signal than this about the low its vote recommendations regarding two companies— importance we accord to corporate governance and Wipro and IDFC. Just ahead of Wipro’s 19th July executive compensation issues? We will watch what Annual General Meeting (AGM), it advised against the happens at the IDFC meeting... but we are not holding re-appointment of BC Prabhakar as an independent our breath. Meanwhile, Shriram Subramanian, founder of director; and ahead of IDFC’s 27th July AGM, it has suggested that Shardul Shroff (a leading corporate InGovern, plans to watch 100 companies that are part of lawyer) and SH Khan (former chairman of IDBI) should the Nifty and Junior Nifty (two indices of the NSE) from various perspectives. And there is not be independent directors. plenty to watch. For instance, many Mr Prabhakar has been a Proxy advisory services companies like Cadila Healthcare director of Wipro for over 14 years are an important check on do not reveal the consideration which is in violation of Clause (49) publicly- listed companies at which an acquisition is made. of the recommendatory guidelines and can ensure that an Will it make a difference to how of the listing agreement of stock expert and independent institutional investors, with exchanges that favour a nine-year tenure for independent directors. firm studies and comments substantial chunks of equity, exert their rights as shareholders? After nine years, directors are as on corporate decisions More pertinently, do institutional good as married to the company. Shardul Shroff has been on the IDFC board for over investors or mutual funds really need a proxy advisor nine years and probably has plenty of other offers to be when they are already watching the companies they have an independent director. Moreover, he hasn’t found time invested in like hawks? In the US, there are proxy advisors telling institutional to attend more than 67% of IDFC’s board meetings or its AGM last year, although he is part of the audit, risk investors how to vote and proxy firms to actually cast and compensation committees. SH Khan has been on the the votes on their behalf. Will this trend catch on in India? A lot depends on the success or otherwise of board for 13 years. InGovern also points out that the fees earned by the InGovern and, reportedly, its two other competitors, audit firm Deloitte Haskins & Sells, for ‘other matters’ namely, the global giant ISS (promoted by MSCI) and is close to 80% of its audit fees. This could affect its Amit Tandon (formerly of Fitch Ratings), who are independence, it says, and suggests that investors need just setting up the proxy advisory business in India. Interestingly, the Securities and Exchange Board of India to inquire into this. So what happened? Only a couple of publications (SEBI) has created a business opportunity for them last `` MONEYLIFE | 11 August 2011 | 22 DIFFERENT STROKES.indd 2 7/21/2011 6:20:28 PM DIFFERENT STROKES SUCHETA DALAL `-sosavourterm business. Sucheta Dalal is the managing editor of Moneylife. Subscribers get free help in resolving their problems with select providers of financial services. She can be reached at suchetadalal@yahoo.com 23 | 11 August 2011 | MONEYLIFE DIFFERENT STROKES.indd 3 7/22/2011 7:57:37 PM SMART MONEY R BALAKRISHNAN BOND INVE S T M E NT S Bond with the Best Option Here are a few alternatives for investors who cannot directly invest in bonds either through their brokers or through other financial intermediaries B onds issued by companies have become attractive. We have also written about these as an investment option. Many readers have written back, saying that they are not able to buy these bonds through their brokers or through other sources. For them, here are a few alternatives. Most of the bond issuances from companies happen through ‘private placement’. An arranger or a bank ties up the demand and then there is virtually a simultaneous placement and issue. A part of it can be retained by the banker—or arranger—to create a post-issuance price benchmark. Listing is virtually certain, but trading is not. Typically, there would be an active market for a short period after the bond is issued and then liquidity dries up. So far, the largest investors, by value, in the bond markets have been banks, insurance companies, provident funds and mutual funds. This is the main class of investors that buys bonds. There are other classes of investors such as trusts, private investment companies and individuals who, typically, tend to hold the bonds to maturity. The first class of investors trades in blocks (lots) of Rs5 crore per transaction and, by default, this has become the ‘tradable’ or the ‘market’ lot. Anything outside this gets clubbed as ‘odd lots’. The institutional segment, typically, trades between themselves directly, on a platform created by the RBI (Reserve Bank of India), called the ‘Negotiated Dealing System’ (NDS). Other trades happen between a buyer and a seller through a broker note (often it is just a kind of a contract note on the plain letterhead of the parties concerned). There is some ‘reporting’ done on the debt segment of the NSE (National Stock Exchange of India) or the BSE (Bombay Stock Exchange). However, one can rarely get a trade executed on the screen, due to the lack of market-makers. There are a few players who try and sell bonds to the retail segment as well as other investors who need smaller lots of bonds (typically, between Rs5 lakh and a couple of crores). What they do is buy a single lot of Rs5 crore, and then parcel it out to smaller buyers. Most of them do not have the capacity to hold it for any length of time and endeavour to push it out as quickly as possible. In this segment, prices are higher than if one were to buy through the NDS, because the trader, who undertakes the exercise of buying a ‘market’ lot, expects some profit. The price difference could range from a few paise (if it is a large buyer, with regular activity) to a few rupees when it comes to a retail buyer, who will, typically, hold it to maturity. Institutional investors keep trading between themselves in lots of Rs5 crore, while the retail buyer has to do some hard searching with a handful of players. The sellers to the retail buyers cannot guarantee availability of all the bonds at any given time. Most likely, the retail buyer in the secondary markets can only access or get hold of the very recent issuances. It is a sale which is tagged ‘till stocks last’. Primary issues remain the best avenue for a retail buyer. However, these tend to be few and far between. A recent Rs500-crore bond issue of Shriram Transport Finance was oversubscribed by nearly 10 times in a few days! The company retained Rs1,000 crore. In this case also, it is likely that institutional investors had subscribed to the bulk of the issue. It is likely that when `` MONEYLIFE | 11 August 2011 | 24 column_Balakrishnan.indd 2 7/19/2011 8:04:57 PM SMART MONEY R BALAKRISHNAN ` trade in the secondary market starts, some retail buying Therefore, you are paying back the difference of opportunity can emerge. There are only a few players in interest and adjusting it for time value, by paying a this business—due to the need to invest large amounts of higher price for the bond. In a 10-year bond of around money to buy the bonds, hold them and then sell them. 12% coupon, and having a residual life of more than nine The absence of market-makers is the biggest deterrent to years, you would be paying an approximate premium of around Rs7. a vibrant retail debt market. Similarly, if interest rates rise, you would expect a Now, let us look at the pricing. Many retail buyers shy away from paying a ‘premium’ to the face value of yield higher than 12%. In this case, you would be buying the bonds. In a bond, there is a typical half-yearly interest the bond at a ‘discount’ to the face value. The simple payment on fixed calendar dates. For instance, if a bond rule is that when interest rates fall, the prices of bonds go has a coupon of 12% and face value of Rs1 lakh, it would up and, when they rise, bond prices fall. One important thing to note is that, currently, have interest payouts of Rs6,000 there is no TDS (tax deduction each on two dates (say, 31st March Investing in bonds in source) on bonds listed on the and 30th September each year). today’s illiquid markets at stock exchanges. So, if you are a buyer and make is a long- term play. Some People have written in and your payment on 1st July, you would be paying the agreed price brokers will help you sell asked us for names of brokers/ from where they could buy on the bond plus the proportionate them at a price, but that banks the bonds. At the risk of omitting a interest amount from 1st April (the would be a function of few names due to low awareness, day after the last interest payout) th I am listing a few of these: Karvy, to 30 June (the date up to which interest rates AK Capital, Darashaw, ICICI the previous seller had held the bonds). On 30th September, you will get the full interest Securities, Brics Securities, Religare, etc. These names payment for the period from 1st April to 30th September. are not the only ones and I hope that the brokers who So, if you buy a Rs1 lakh bond at a price of Rs1.01 lakh deal in retail bonds would write in to Moneylife for the (a premium of Rs1,000 to the face value), you would benefit of our readers. It would be nice if a platform have to pay Rs1.01 lakh plus the interest for the period can be created for price dissemination and trading for from the last date of interest payment till your date of the retail segment. Even the players that I have named purchase. In the above-mentioned example, you would do not have a national presence and are restricted to the be paying an approximate amount of Rs3,000 as ‘accrued metros and a couple of tier-II cities. Investing in bonds in today’s illiquid markets is a long-term play. Some interest’ to the seller, in addition to the agreed price. Why does the premium rise? If the bond carries brokers will help you sell them at a price, but that would interest at 12%pa for its life of 10 years, and you are be a function of interest rates. The credit rating of the willing to buy it at a yield of 11%, you have to pay issuer is important; it is perhaps the sole guide for the life the difference. It is not straight and simple arithmetic, expectancy of the bond. though. You are, in any case, going to get interest at the coupon rate of 12%. You are happy with 11%. The author can be reached at balakrishnanr@gmail.com What’s Your Bahana for Not Subscribing? I I I I I I am not interested in honest & insightful advice on money matters never have any problems with banks, credit-cards or insurance always invest on the basis of tips from friends and brokers prefer to keep my money in a bank and let it be eroded by inflation would rather spend two years of knowledge on one evening of eating out always buy from the newsstands For subscription offers that are a steal, look for a form elsewhere in this issue or our website at 25 | 11 August 2011 | MONEYLIFE column_Balakrishnan.indd 3 7/19/2011 8:05:14 PM MUTUAL FUNDS POINTERS S E C T O R F U NDS Awful Choice T he theoretical case for sector funds is strong. After all, the case can be based on two very strong tenets of investing: one, focus and concentration on a few stocks works wonders; two, identifying the right sector is an important component of stock market success. Sector funds incorporate both these aspects of investing. They focus on just one sector at a time and, if the sector does well, the fund’s performance can be among the best. Well, this is all theoretical. Firstly, fund managers have rarely proven to be smart at selecting the winning sectors. They were caught unawares by the tech bust of 2000 and also the construction boom (albeit with current unsold inventories) since 2004. That is why we believe that while the theoretical logic of sector funds is attractive, in practice, it is best to avoid them. The concentration argument cuts both ways. They are launched not when a sector is about to start a major rally but when it has already reached a peak. And, because such funds’ bets are concentrated on one sector, they carry a huge risk of underperformance. This is why they cannot beat the best of diversified equity funds or index funds. We had demonstrated this in a three-year analysis of sector funds in our 7 April 2006 issue (“Sector Funds? Bad Idea”). Here is the updated evidence. Sector funds have earned an average return of 11% since their inception. And what if you had invested your money in equity diversified funds? The average return would have been 13% since inception. But if you are hell-bent on buying a sector fund, which ones should you look at and which are the ones to avoid? Sector funds focus on the stocks of just one sector. Buying them is a bad idea. But if you must buy one, which should you go for? ML Research Desk finds out The Best Sector Funds There have been 43 sector funds with a history of three years or more. Of these, UTI Services Industries Fund and DSP BlackRock Natural Resources and New Energy Fund-Retail emerged as the best-performing sector funds with a three-year return of 20% and 13% since inception and they outperformed their respective benchmarks by 33% and 13%. Now service industry is hardly a sector and, no wonder, this UTI Services Industries Fund looks like a diversified fund. Its top five stocks are ICICI Bank, Tata Consultancy Services, Infosys, Bharti Airtel and Axis Bank. DSP BlackRock Natural Resources and New Energy Fund has only one mid-cap stock; all others are large-cap stocks. The top five picks of this Fund are Castrol India, Reliance Industries, SRF Ltd, Hindustan Petroleum Corporation and Petronet LNG. The problem is that there are few genuine sector funds. For instance, the database of Mutual Funds India puts Birla Sun Life Buy India as a sector fund. This makes no sense at all. This Fund claims to be focused on the consumer and healthcare sectors. But its investment is spread across dozens of sectors like auto ancillaries (Maruti), hotels (Taj GVK), banks (ING Vysya Bank), FMCG & food processing (ITC and United Spirits). This is really a diversified equity fund. The remaining three (of the five best performing sector funds) are power, pharma and infrastructure funds. Reliance Diversified Power Sector Fund has given returns of 31% since inception. However, while the top picks of the Fund include Torrent Power, Cummins India and Jaiprakash Associates, it also has Jindal Steel & Power and ICICI Bank in its portfolio. Almost 27% of `` MONEYLIFE | 11 August 2011 | 26 Fund pointer.indd 2 7/20/2011 8:44:34 PM MUTUAL FUNDS POINTERS ` the Fund’s assets are invested in these five stocks. Reliance Pharma Fund has earned a return of 28% since inception. Among its top picks are Divis Laboratories, Aventis Pharma, Sun Pharmaceutical, Cadila Healthcare and Ranbaxy Laboratories. HDFC Infrastructure Fund has notched up a return of 4% since inception and has outperformed its benchmark S&P CNX 500 which is down by 6%. Well, it thinks ICICI Bank, Bank of Baroda, State Bank of India, Oil and Natural Gas Corporation are infrastructure companies— as also Motherson Sumi Systems, an auto-ancillaries company. The Worst Sector Funds In terms of risk-adjusted returns among equity schemes, infrastructure funds were among the worst performers. The worst three performers include Escorts Infrastructure Fund, L&T Infrastructure Fund and Kotak Indo World Infrastructure Fund. Even if you want to invest in sector funds, you must certainly avoid these worst performers for some more time. In fact, Escorts Infrastructure Fund tops the list of the worst-performing sector funds earning a pathetic return of -9% against its benchmark Nifty which earned a return of 4% for the same period. Its five top picks are McNally Bharat Engineering, Motherson Sumi Systems, Tata Motors, Voltas and Titagarh Wagons. Out of the top five stocks of this ‘infrastructure’ fund, two are from auto-ancillaries and one from consumer durables. L&T Infrastructure Fund has ended up with a return of -10% since inception, with stocks such as ICICI Bank, Reliance Industries, State Bank of India, Bharti Airtel and Larsen & Toubro in its portfolio. ICICI Bank, State Bank of India and L&T have grown significantly in the past three years; so what was the Fund doing? Timing the market? The Fund’s size is tiny with just Rs38 crore of assets as on 31 May 2011. The Fund was launched in September 2007, at the height of the bull market. The next worst-performing fund was Kotak Indo World Infrastructure Fund. The Fund has Rs324 crore in assets, of which 15% is invested in international mutual funds. Its top five stock picks are ICICI Bank, HDFC Bank, Bharti Airtel, Reliance Industries and L&T. The Fund earned a return of -10% since inception while its benchmark S&P Nifty earned 1% for the same period. The Fund was launched in January 2008, at the peak of the bull market. And if you see the returns of its top five stocks—except Reliance—all have done very well in the past three years. So what was the fund manager doing? Performance Report Scheme# Launch Date Since Inception Benchmark BMR+ 27 May-99 20% CNX Service Sector -13% DSP BlackRock Natural 25 Apr-08 Resources & New Energy 13% BSE Metal -0.67% Reliance Diversified Power Sector 8 May-04 31% Sensex* 18% Reliance Pharma 5 Jun-04 28% BSE-HC 16% HDFC Infrastructure 8 Jan-08 4% CNX 500 -6% 6 Jul-07 -3% BSE 100 6% Best Performers UTI Services Industries Worst Performers SBI Infrastructure LIC Nomura MF Infra 24 Mar-08 -4% BSE 100 7% Kotak Indo World Infra 25 Jan-08 -10% S&P Nifty 1% L&T Infrastructure 27 Sept-07 -10% S&P Nifty 3% Escorts Infrastructure 21 Sept-07 -9% S&P Nifty 4% *Original index (India Power Index) data is not available; #All funds are growth funds; + Benchmark returns; Source: Mutual Funds India If funds from the same sector figure in the list of the top five as well as the bottom five performers, what does it indicate? Simply that fund managers do not know enough about the sector, the stocks and their possible price movements—even though such intense focus is the cornerstone of investing in sector funds. This is precisely `` 27 | 11 August 2011 | MONEYLIFE Fund pointer.indd 3 7/23/2011 5:03:13 PM MUTUAL FUNDS POINTERS F U N D B E N C HM ARKS Mutually Opaque Several funds are benchmarked to proprietary indices, making it impossible to measure their performance. SEBI remains unconcerned, so far M utual fund (MF) performance is not based on the returns that a fund earns but against an external standard called the benchmark index. MFs are supposed to be doing well, if they have beaten their benchmarks. MFs usually choose a popular benchmark like the BSE 500, the Ni y or the Sensex. The while analysing the performance of sector funds: • We found that around seven sector funds (Read “Oddball”) are benchmarked to indices which are strange constructs. • The data for these benchmarks are not available in the public domain. Oddball Scheme Launch Date Return Benchmark Reliance Diversified Power Sector 8 May-04 31% India Power Index UTI Energy (Petro) 15 Jul-99 16% UTI Energy Index Franklin Pharma 31 Mar-99 17% Lifex UTI Transportation and Logistics 9 Mar-04 15% UTI Transportation and Logistics Index Reliance Media & Entertainment 30 Sept-04 16% S&P CNX Media and Entertainment Index UTI Pharma and Healthcare 27 May-99 13% CNX Pharma Birla Sun Life New Millennium 15 Jan-00 6% BSE TECk Two funds, namely, Franklin Infotech idea is that through a process of active and Birla Sun Life New Millennium stock selection, MFs would do be er (earlier Alliance New Millennium), than their benchmarks. were launched when the data of their But what if fund companies get so respective benchmark indices—BSE IT carried away with the way they create and BSE TECk—were not available in schemes that they end up selecting the public domain. peculiar benchmarks? And what if the performance of these benchmarks • Funds also use indices like the S&P CNX Media and Entertainment Index cannot be tracked at all by retail which are paid indices. The data for investors? It makes a mockery of the these indices are accessible only very idea of benchmarks. We have tried to subscribers. How is an ordinary to bring out the difficulties one faces investor supposed to check the performance of these funds against such benchmark indices? • Many of these sector funds are products of innovative ideas of fund companies. Sector funds come in all kinds of flavours (like UTI Transportation and Logistics Fund and UTI Energy Fund) whether they make sense or not. Such ‘innovative’ sector funds demand innovative benchmarks which are customised by the fund company. • The data for these customised indices are available only on the fund fact sheet and that too, only for periods that the fund company finds appropriate for comparing the scheme with its benchmark. • When a particular scheme’s name is changed, the launch date changes to the date on which the change takes place. UTI Energy Fund was earlier known as UTI Petro Fund and the launch date was July 1999. In November 2007, its name changed to UTI Energy Fund and so the launch date changed to November 2007 which is not reasonable at all for analysing returns. • Funds which have been taken over by other fund houses also suffer from the same date change. Apple Goldshare was launched in April 1994. In November 1998, this was taken over by Birla Sun Life and the name was changed to Birla Sun Life MNC Fund– Growth, and its launch date was also changed to November 1998. So, when you look for ‘since inception’ data, be aware of these problems. ` why diversified equity funds usually do better than sector was hot in 2006 and many infrastructure funds were funds. They do so by depending less on the smartness of the fund managers and more on the performance of good companies. Sectoral schemes tend to move in cycles. And when a sector is hot, several new mutual funds are launched to cash in on the trend but you should stay away from them because that hot sector is invariably headed for a rough period. For example, the infrastructure sector launched. Their performance has been disastrous. If at all you want to invest in sector funds, choose funds that are long-term value creators. There are two such sectors: pharma and FMCG. Stocks in these two sectors have created great long-term value which is why sector funds focused on these two sectors have done exceptionally well. Keep an eye on them. MONEYLIFE | 11 August 2011 | 28 Fund pointer.indd 4 7/23/2011 5:03:27 PM Advertisements.indd 4 7/19/2011 4:00:52 PM COVER STORY It is easy to fall for the stocks of glamorous sectors, promoters or companies, especially since they figure prominently in the popular media all the time. This is a recipe for disaster, as Moneylife Research Desk shows M ix the following and shake well: glamorous businesses, dumb institutional investors, ambitious promoters and market valuation (not cash flow) as the key result area for the top management. You get a deadly cocktail that will boost your spirits for a while but could kill you in the end. This is the business of glamour stocks. We had said this about the TV18 group some time ago but the same thing applies to many such stocks. Retail investors buy them on every fall—for a while—many large institutional investors hold them for a very long time, assuming that they would come back. But glamour stocks don’t come back. They may survive and get taken over for dubious reasons; but for retail shareholders, they are an abyss. Look at glamorous businesses like New Delhi Television (NDTV), TV18, Kingfisher Airlines, SKS Microfinance and the mother of them all—the companies of Reliance group comprising Reliance Infrastructure, Reliance Communications (RCom), Reliance Power and Reliance MediaWorks. Why, even Zee Entertainment `` MONEYLIFE | 11 August 2011 | 30 Cover Story.indd 2 7/23/2011 5:26:29 PM COVER STORY ` Enterprises (Zee) and Pantaloon Retail (India) and now Sun TV Network fit into the same category. These companies are run by ambitious promoters and have a clutch of famous ‘brands’ or big projects. But either they are bad businesses or are run badly. The businesses could span infrastructure, power, finance, media, aviation and others. Most of them are losing money profusely or making too little money. Losses were a bit lower when the economy was growing fast and the market euphoria fetched these promoters, newer dumb investors and more money to keep going. But now, the losses are endemic. Their only hope is a takeover (with the promoters holding on by the fingernails till the last day) or backdoor funding for non-business reasons. These businesses are in the public eye and, if India had capitalism in the best sense of the term, they would have gone bankrupt long ago or got taken over. Instead, they lumber along, restructuring, raising more money, bending the laws and generally hanging around. These companies are traps for everyone. The promoter has to keep the show going and the music playing as investors change seats in a game of musical chairs. This means more acquisitions or expansions. This also means when promoters run out of equity money, they have to borrow. Big businesses can’t cut costs beyond a point. Indeed, to keep the show going, costs may even keep rising. Revenues may be cyclical and, therefore, variable. But the costs are fixed and growing. Meanwhile, more competition, legal issues and economic sluggishness can hurt severely. The result? Large debts and huge losses can push a company to a now-or-never situation, which is hard to decipher, looking at the glitzy exterior. Look at the shareholder returns of some of these glamour stocks over the past five years. phonetapping controversy) and its finances are in a mess. NDTV has rarely made money from operations. For the past few years, its consolidated operations have been making cash losses and it has been running on money made by selling loss-making subsidiaries to strategic investors.. Prannoy Roy, chairman, NDTV Anchored Losses 475 New Delhi Television 87% 390 305 220 135 50 Dec-07 Oct-09 Jul-11. Zee has given a compounded return of just 6% in the past five years—far lower than that of safe bank fixed deposits. Subhash Chandra of Zee pioneered cable broadcasting in India. But he is also a flamboyant businessman with a variety of other interests (lottery, cricket, fun parks and packaging). Zee is the flagship of its media business, which includes all Zee entertainment channels. Zee has done better than the others because `` 31 | 11 August 2011 | MONEYLIFE Cover Story.indd 3 7/23/2011 4:48:32 PM COVER STORY ` of controlled costs. Unfortunately, this is as good as it gets. For Zee to do far better than this, calls for sensible business practices—and selection of excellent leaders. Mr Chandra may not care much for either. The business is a family-run affair, controlled by Mr Chandra, his son and his brother Laxmi Goel. Dozens of top managers pass through the revolving door each year. Every few years, Mr Chandra announces a reorganisation and rebranding—the most recent one took place in July this year. Glamorous business, yes. Profitability? That’s another matter. Sun TV Network has 20 channels in four Indian languages and 43 FM radio stations targeted at the south Indian population globally. It also has two daily newspapers and four magazines. Sun has no long-term debt. Its standalone revenue was up 38% in FY10-11 over the corresponding year-ago period, while operating profit was up 40%. Sun’s operating margin of 81% is among the highest in India. It earns a very high RONW (return on net worth) of 32%. It gave shareholders a compounded return of 32% over the past five years. Even if genuine, this is all in the past. Sun’s business was not built on competitive advantage alone but also through strong-arm tactics and political muscle. Sun is controlled by the Maran brothers—Kalanidhi and Dayanidhi—who have been close to the ruling DMK (Dravida Munnettra Kazhagam). It has a lock on the television business in Chennai, mainly the cable business. But political connections can be fragile, as we wrote a few years ago. In 2008, the Maran brothers got into a spat with M Karunanidhi, the chief minister of Tamil Nadu, who suspected them of working against his family’s interests. Dayanidhi Maran had to give up his ministerial position at the Centre and Sun came under severe competitive threat from the new channels and the cable business backed by Mr Karunanidhi. The stock was hammered. When the Marans and Mr Karunanidhi patched up, the Sun stock went up. Investors were happy but what investors always ignored was the huge political risk attached to this glamour stock. We had pointed out that political alignments in Tamil Nadu are highly unpredictable and politicians there are crude and vengeful. In other words, Sun’s spectacular profi tability is because of a moat—but that moat can run dry anytime. This is exactly what has happened. Dayanidhi Maran ran into the 2G controversy; DMK lost the elections; Sun’s CEO was arrested; and the stock is sharply down. Glamour stocks are not run for shareholders. They are run for promoters’ egos and employees. Look at the high salaries and generous stock options, on the one hand, and low return on capital, on the other. For some employees, like Sun’s CEO, even huge salaries were not worth being arrested and jailed. That is what has also happened to three top executives of RCom, which is embroiled in the 2G scam. The telecom business is a glamorous business, but try and say that to either the shareholders of RCom or to Gautam Doshi (managing director), Surendra Pipara and Hari Nair of RCom who have been in jail since early April. Satish Seth, a close aide of Anil Ambani, told the Central Bureau of Investigation (CBI) that he was only a consultant and Gautam Doshi was responsible for all decisions relating to RCom, which Anil Ambani, chairman & CEO, Reliance group Call Disconnect 605 Reliance Communications 500 84% 395 290 185 80 Jan-08 Oct-09 Jul-11 led to the exit of Hasit Shukla, a compliance officer and company secretary of RCom. This is how glamour stocks can unravel sometimes. What has it meant for shareholders? RCom was listed at around Rs300 in March 2006, shot up to Rs844 in January 2008 and then crashed by a stupendous 90%. New research suggests that it has been cooking its books. RCom has given a TSR of negative 70% over the past five years and a compounded annual return of -21% for the same period. Reliance Power, which was listed with great fanfare on 11 February 2011, gave a negative TSR of 40% since its inception and has given a compounded return of -14% since listing. On the first day of listing, the stock opened at Rs342 and `` MONEYLIFE | 11 August 2011 | 32 Cover Story.indd 4 7/23/2011 4:48:44 PM COVER STORY ` reached its all-time high of Rs374.94 on the same day. Ever since then, it has declined, and it is now trading at Rs114.10, down by 68%. Reliance MediaWorks has given a compounded return of -7% in the past five years and a negative TSR of 31% for the same period. Reliance Infrastructure has made shareholders richer by 6% returns compounded every year over the past five years. Another glamorous business is airlines and what has made it even more glamorous is the presence of Vijay Mallya, one of the most flamboyant businessmen in India with a liquor franchise that should be the envy of everybody. His beer brand Kingfisher is one of the top brands in the world. It is so popular that Mr Mallya named his airline after this popular brand. Ironically, Kingfisher Airlines has the dubious distinction of having the maximum cases of pilots found under the influence of alcohol before take-off, in 2009. Mr Mallya, who needs lakhs of rupees a day just to maintain his stable of houses, cars, planes, horses and other assets, is determined to blow up his considerable wealth on running Kingfisher. The business has run up thousands of crores of losses and is literally running on borrowed time and money. In midJuly, a couple of Kingfisher flights were delayed by more than an hour because Hindustan Petroleum Corporation would not supply fuel unless its earlier dues were cleared. Kingfisher and Jet Airways need an unending supply of capital to stay afloat. Jet Airways needs $400 million, while archrival Kingfisher Airlines needs $300 million. But market conditions are likely to thwart their fundraising plans. Over the last year, Jet is down by 50%, Kingfisher by 60% and SpiceJet, controlled by the Marans of DMK, has dropped 66%. All of them desperately need money. What has the stock done for its shareholders? Kingfisher has given a compounded return of -15% in the past five years and TSR of -57% in the past five years, whereas Jet Airways has given a compounded return of -4% in the past five years and TSR of -18% for the same period. Shareholders of leading retail chain Pantaloon Retail should be a worried lot. The stock has fallen by a sharp 36% over the past eight months—from Rs502.25 on 1 October 2010 to Rs323.85 now. If these shareholders look a little bit closer, they will wonder for whom the company is being run—shareholders or bankers? Research analysts tracking retail stocks say that the current high interest rate regime is the key reason for the underperformance of the stock, even as the company is planning an expansion and restructuring exercise. But is there a problem with the business model itself? Pantaloon’s turnover is erratic and it is essentially pushing sales with borrowed money. A large part of the company’s operating profit has been eaten up by interest cost. Consider this. The operating profit of the company was Rs111.66 crore in the March 2011 quarter. In the same quarter, the interest cost was Rs 48.37crore. It will only get worse. Analysts tracking the stock say that interest costs will go up. The stock has given a compounded negative return of 4% in the past five years and its TSR in the past five years have been -20%. Doing good for the poor while making money is as glamorous as one can get. And there is only one listed company with such a halo—SKS Microfinance. Vikram Akula, executive chairman, SKS Microfinance Loan Crisis 1,350 SKS Microfinance 1,140 60% 930 720 510 300 Sept-10 Feb-11 Jul-11 No wonder it secured money from some of the finest investors including Catamaran of NR Narayana Murthy and Sequoia Capital, one of the world’s best private equity firms. As it happens, glamour stocks are expensive and vulnerable to disappointment easily. The share price of SKS had opened for listing at Rs1,036 in August 2010 and hit a high of Rs1,490 in the next month. From early October, however, it has declined consistently and hit a low of Rs262 in May 2011, down 75% from its listing price, causing massive losses to many smart investors. And it ‘delivered’ a total return to shareholders of -45% for the same period. Even if SKS were not involved in ugly loan recovery tactics, the suicide deaths of some of its poor borrowers in Andhra `` 33 |11 August 2011 | MONEYLIFE Cover Story.indd 5 7/23/2011 4:48:55 PM COVER STORY ` Pradesh and was not hit by laws that affect microfinance companies, rest assured that the stock would not have made much of an advance from the time it was listed. TV18 is another glamour stock. Whether it is Colors, CNBC or moneycontrol.com—TV18 touches your life daily. The group created dozens of top Web properties, TV channels for news & entertainment, print publications, is into film production, a home shopping network, events, sports and even private equity investment. The best and brightest are featured in these media properties, daily. The group has shown tremendous entrepreneurship, in Kishore Biyani, founder & CEO, Future group Uncertain Future 775 Future Capital Holdings 640 79% 505 370 235 100 Feb-08 Nov-09 Jul-11 less than a decade. Unfortunately, for the shareholders, it has been a long ride downhill ever since the stock got listed in February 2000 and hit a high of Rs781. It went through a restructuring (always the preferred option for non-performers—look at NDTV, Zee and the Anil Ambani group) a few years ago. The performance has not changed. In a year when the economy was booming (March 2011), the group reported a net loss of Rs17 crore, though it was a big improvement from the Rs114 crore loss of FY10-11. It is undergoing another round of restructuring just now. Only the diehard media watcher can keep track of the constant changes and shuffling of businesses. Usually the corporate Indian has used restructuring to effect book adjustments and asset valuation that favours promoters and short-changes minority shareholders. Attracted by the glamour, retail and institutional investors have periodically come and gone, disappointed by how difficult it has been for the group to make any money for years together. Nothing much will change now that the core business of the group—business news—constitutes only 60% of the business. This is because while revenue growth is sluggish, ET Now has made sure that TV18’s cost structure remains permanently bloated. Future Capital Holdings (FCH) went public in February 2008, raising Rs490 crore through a sale of shares at Rs765 a piece. The stock listed at Rs909. It was a glamour stock, run and partly owned (11.85%) by Sameer Sain. FCH was supposed to be Kishore Biyani’s dream financial vehicle not just to extract value from the footfalls in Pantaloon stores, but also to make money through smart investment. When Mr Sain joined FCH. The glamour faded soon after. By early 2010, Mr Sain stepped down from his position as chief executive and managing director of the company and sold his stake. Now, after three-and-a-half years of listing, the stock is quoting at Rs155, resulting in 80% erosion in investors’ wealth. We have given a small selection of stocks that are glamorous and have delivered terrible results. Admittedly, our selection is anecdotal and random, contrary to what our standard approach is—which is going by a method. The reason is, you cannot define “glamorous” in definite financial terms. But hopefully you know that a stock is glamorous if you draw from Judge Potter Stewart’s definition of pornography way back in 1964, “I know it when I see it”. The risk of glamour stocks are disproportionately higher compared to the returns you make. This is because promoters may get carried away by their own acts, the company, the sector; the promoter is constantly in the public eye giving you the impression that all is well; and of course, the media and the analysts are producing a steady stream of positive news about them. Meanwhile, if returns are poor, they constantly need capital to stay afloat—reducing the value of shareholders. Stay away. The best bets are companies that are in mundane businesses, carry a low valuation and generate high return on capital—the kind of stuff we regularly write about in our Street Beat section and occasionally in cover stories. MONEYLIFE | 11 August 2011 | 34 Cover Story.indd 6 7/23/2011 4:49:06 PM 6000 Stocks. Just 30 Minutes a Day. A Winning Edge Let us do it all for you: screening, research, analysis, grading and tracking Weekly stock letters for high profits with low-risk strategies delivered through email M oneylife magazine has been bringing you the finest approach to stock-picking—methodical, non-impressionistic and ethical. The same team that created a proven system that beats the major indices year after year now offers stock letters in different flavours for investors with different investment horizons and objectives. Here is what you get. What’s Inside: Cheetah: Short-term momentum Antelope: Medium-term growth stocks available at reasonable prices Lion: Long-term value—stocks that have a reasonable chance of beating the market over time. Only large companies are recommended Annual Price of Each Stock Letter: Rs995 Special Combo Offer for Any Two: Rs1,495 Special Combo Offer for All Three: Rs1,995 - Weekly market view - A short list of stocks to buy, with reasons - Weekly updates on all recommended stocks and clear recommendations on when to sell. the relevant investment criteria. We suggest holding at least 50 stocks in the portfolio that improves our chances of owning those rare few stocks that everyone wishes they had spotted too—earlier. How are we different from a mutual fund and your stockbroker? 1. Unlike mutual funds that hold your stock through a sharply falling market, we believe that the only objective of an investment is to earn positive returns. Buying scrips of good companies is not an end in itself. 2. Unlike mutual funds, we do not benchmark ourselves against arbitrary indices. We aim to earn positive returns under all market conditions. 3. Mutual funds say that you cannot time the market. We believe that timing is everything. The best stocks will destroy your portfolio, if you don’t sell them on time. 4. Unlike stockbrokers, we are unconcerned whether you buy 50 shares or 5,000, whether you buy/sell once a week or 20 times a week. Our income is not tied to your actions. We earn by selling ideas that we have to be responsible for. Our stock letters will survive only if you make money. In contrast, brokers earn their commissions irrespective of whether you make money or not. Cancel within four issues You can cancel your subscription within four issues. We will return your money for the remaining period of subscription. You can cancel by email or phone. Email us at mail@kensource.com for a sample Our Investment Philosophy: We believe that price is the most important information and should normally overrule most other factors. This allows us to go wherever the opportunities currently are. We do not limit ourselves to specific styles and themes. Investment Process: We crunch thousands of numbers to spot trends, unearth bargains and use our years of vast knowledge of companies to select the stocks that best meet SOME RECOMMENDATIONS Company Issue Date Recomm. Price Exit Price Return* Surya Pharmaceutical 28 Jun-10 184 294 60% Godrej Consumer Products 24 Feb-10 262 372 42% Petronet LNG 18 Apr-11 133 175 32% Titan Industries 31 Jan-11 3,468 4,560 31% Dish TV India 28 Mar-11 66 82 24% * Non-annualised; Price in Rs YES, I wish to subscribe for one year to the following winning stock letters Cheetah: Short-term momentum Antelope: Medium-term growth stocks Lion: Long-term value Annual Price of Each Stock Letter: Rs995; Special Combo Offer for Any Two: Rs1,495; Special Combo Offer for All Three: Rs1,995 NAME: ADDRESS: PHONE (Office): Phone (Resi): E-mail address: Date of Birth: (MM) (DD) (YY) (Please ensure correct date of birth if payment is by credit card) Profession : Designation: Monthly Household Income: (Please tick the appropriate) ( ) Below Rs25,000 ( ) Rs25,000 - Rs50,000 ( ) Above Rs50,000 ( ) Please find enclosed ( ) Cheque / ( ) Demand draft number favouring Kensource Information Services Pvt. Ltd. ( ) Please charge it to my ( ) /( ) /( ) My card number is & expiry date is DATE: dated (MM / YY) SIGNATURE: Please fill in this order form and mail it with your remittance to Kensource Information Services, date of birth should be mentioned. # Rates and offers are valid only in India. This offer is valid for a limited period. # All disputes shall be subject to Mumbai jurisdiction only. We do not give away your e-mail or postal address, telephone number, or any other information that you provide to us. We use this information solely to service your account Stock letter new.indd 1 7/23/2011 5:43:18 PM STOCKS STREET BEAT Unbiased & Methodical Stock Picking that Works! S U P R E ME I NF RAS T RUC T URE Concrete Structure tio n St or ies of Pr ice Ma nip ula Strong backward integration model S uprememixIndapur and Manor-Wada-Bhiwandi projects are expected to be completed by July 2013 and the Ahmednagar-KarnalaTembhurni project is expected to finish by March 2014. The Haji Malang project is a ropeway project having a construction period of two years. The Manor-Wada-Bhiwandi project—an `` Ashiana Agro Industries dustrie (Rs3) Rajasthan-based Ashiana Agro Industries was incorporated in June 1990. The company has sold its edible vegetable oil plant & machinery and has not undertaken any manufacturing activities since 2006-2007. It has primarily invested its surplus funds pending its final decision on starting a new business venture. It generates income as interest on loans and advances given during (Rs) 8 Ashiana Agro 7 6 5 59% 4 3 2 Jan-11 Apr-11 Jul-11 the year. It did not generate any revenue in the past nine quarters. On the other hand, it reported an operating loss of Rs3 lakh in each of these nine quarters. The company has no revenues and is still listed. There are days when there is no trading at all. From Rs6.15 on 20 January 2011 the stock has fallen to Rs2.55 on 15 July 2011, down 59%. It may even go up a few hundred percent. The regulators are blissfully unaware. Recommended Price Rs145 MONEYLIFE STOCK IDEAS THAT WORK Moneylife Issue 25 February 2010 109%* Exit Price Rs263 (Stop Profit triggered on 25 November 2010) (EXCEL CROP CARE) * Annualised returns MONEYLIFE | 11 August 2011 | 36 Stock-Streetbeat.indd 2 7/23/2011 5:10:52 PM STOCKS STREET BEAT Unbiased & Methodical Stock Picking that Works! ` Rs Cr. Sept-10 Dec-10 Mar-11 segment, SIIL has won Net Sales 165.71 240.48 327.96 many orders from 50.68 Mumbai Railway Vikas OP 27.77 41.36 88% Corporation. Also, in Y-o-Y Sales Growth 47% 68% 83% the building segment, the Y-o-Y OP Growth 39% 39% company has won several 15% OPM 17% 17% orders from government OP: Operating Profit, Y-o-Y: Year-on-Year, OPM: Operating Profit Margin agencies as well as private companies. Some of the Firm Ground major projects include (Rs) construction of Edge 295 Towers worth Rs255 Supreme Infrastructure crore at Ramprastha City, 270 Gurgaon, construction 245 of Hexcity worth Rs138 220 crore for Armstrong group at Navi Mumbai. 195 The company is 170 looking to expand its Jan-11 Apr-11 Jul-11 capabilities in the marine projects segment and deepening vertical strength in each state. In Kolkata, it has joined hands with Bengal Tools to undertake orders in the `` tio n St or ies of Pr ice Ma nip ula Gomti Finlease (India) (Rs29) Gomti Finlease (India) is engaged in the business of investment and investment advisory services. In FY06-07, the company focused mainly on fee-based activities as the Reserve Bank of India had rejected its non-banking financial company application in 2002-03. Since then, Gomti Finlease has not undertaken fund-based activities, except recovery of dues. Out of the past (Rs) 35 Gomti Finlease 30 25 20 15 215% 10 5 Mar-11 May-11 Jul-11 nine quarters, the company had revenues of Rs1.46 crore only in the March 2010 quarter. It reported operating losses in the past nine quarters ranging from Rs1.2 lakh in the March 2009 quarter to Rs1 lakh in the March 2011 quarter. However, the company’s stock vaulted 215%—from Rs8.90 on 31 March 2011 to Rs28 on 15 July 2011. Don’t expect SEBI or BSE to do much about this clear case of rigging. Recommended Price Rs125 MONEYLIFE STOCK IDEAS Moneylife Issue 23 September 2010 THAT WORK 109%* Exit Price Rs150 (Stop Profit triggered on 29 November 2010) (AHMEDNAGAR FORGINGS) * Annualised returns 37 | 11 August 2011 | MONEYLIFE Stock-Streetbeat.indd 3 7/23/2011 5:11:07 PM STOCKS STREET BEAT `. A J A NT A P H ARM A Health Tonic Growth drivers for Ajanta Pharma are firmly in place A janta Pharma is a small company with a presence in the anti-malarial, cardiology, dermatology, gastroenterology, musculoskeletal, ophthalmology and respiratory segments, with four manufacturing facilities in India and one in Mauritius. One of the Indian units, located at Paithan (Maharashtra), is approved by the USFDA (United States Food and Drug Administration) and health authorities of Brazil and Colombia and it also holds a WHO (World Health Organization) prequalification for one of its products. This modern manufacturing facility Unbiased & Methodical Stock Picking that Works! provides flexibility to the company, thus ensuring efficient and timely delivery of products. In the Indian market, Ajanta ranks 63rd among pharma companies in revenues. Its revenues have been growing at 27% CAGR (compounded annual growth rate) 10-12 new product launches, line extensions and therapy expansions. During FY10-11, domestic revenues contributed 37% to the company’s total revenues, while the exports business contributed 63% of the total revenues; Asia and Africa collectively contributed 95% to the export revenues and the rest was from the Latin American region. The return on equity of the company was a healthy 24.5% for FY10-11. During the quarter ended March 2011, the company’s revenue was Rs125.85 crore, a growth of 16% over Rs108.12 crore in the previous corresponding quarter. Profit after tax was Rs17.47 crore over Rs10.04 crore in the year-ago period, a jump of 74%. Operating profit for the March quarter was Rs28 crore, a rise of 32% over Rs21.15 crore in the fourth quarter of FY09-10. Mar-11 Rs Cr. Sept-10 Dec-10 Over the past five quarters, Net Sales 112.51 120.51 125.85 Ajanta Pharma has reported average 28 OP 20.91 22.80 revenue and operating profit growth 16% of 20% and 22%, respectively. Its Y-o-Y Sales Growth 19% 27% 32% operating profit margin for the Y-o-Y OP Growth 19% 31% 22% March quarter was 22%; for the OPM 19% 19% past five quarters, it was 19%. OP: Operating Profit, Y-o-Y: Year-on-Year, OPM: Operating Profit Margin On 3 May 2011, Ajanta Pharma Strong Dose signed a deal with Dabur India to offload its over-the-counter (OTC) (Rs) brand ‘30 Plus’—one of Ajanta 335 Ajanta Pharma Pharma’s key healthcare energiser 305 brands that was launched in 1990— 275 for an undisclosed amount. The company is expected to use the 245 funds generated to pay off a part of 215 its debt. The company has planned a 185 capital expenditure (capex) of Jan-11 Apr-11 Jul-11 Rs100 crore to Rs125 crore over FY13-14E to gear up for its entry into the regulated market of the US. over FY06-11 due to its strong A large part of the capex will be foothold in ophthalmology (CAGR towards setting up of manufacturing 35%), dermatology (CAGR 57%) units. The company anticipates and cardiology (CAGR 34%). The management has provided guidance 10-12 ANDA (abbreviated new for 16%-18% CAGR from domestic drug application) filings. The company has already filed two revenues over FY11-13E, driven by `` MONEYLIFE | 11 August 2011 | 38 Stock-Streetbeat.indd 4 7/23/2011 5:11:21 PM STOCKS STREET BEAT ` ANDAs, the approval for which is expected within a year’s time. Introduction of mass healthcare projects, such as the National Rural Health Mission (NRHM), and increasing rural penetration by pharmaceutical companies would contribute to the growth of domestic drug sales. The Indian pharma industry is expected to grow at a CAGR of 13.1% and would touch $11.20 billion by 2011-12. The stock is reasonably priced. Based on the annualised results for the March 2011 quarter, its marketcap to revenue was 0.72 times and market-cap to operating profit was 3.24 times. Ajanta Pharma makes a good buy at the current price. A NDH R A P et roc hem ic al s Unbiased & Methodical Stock Picking that Works! production capacity of 30,000mtpa (million tonnes per annum) of oxoalcohols which later went up to 39,000mtpa. In March 2007, APL announced its plans to expand the Rs Cr. Net Sales Sept-10 Dec-10 Mar-11 112.63 114.25 156.75 Right Equation OP 20.61 25.31 28.63 Y-o-Y Sales Growth 110% — — Enhanced capacity & latest technology Y-o-Y OP Growth 203% — — 18% 22% 18% A ndhra Petrochemicals (APL) was promoted by Andhra Pradesh Industrial Development Corporation and Andhra Sugars as a joint sector company in 1984. It makes oxo-alcohols, 2-ethyl hexanol, normal butanol and iso-butanol. These are used in plasticisers, stabilisers, solvent extractions, acrylates, finishing compounds for ink lubes & fuel additives, surfactants, adhesives, detergents, etc. APL uses naphtha and propylene as feedstock which is supplied by Hindustan Petroleum Corporation’s Vishakhapatnam refinery. APL was established with a OPM OP: Operating Profit, Y-o-Y: Year-on-Year, OPM: Operating Profit Margin Perfect Chemistry (Rs) 35 30 25 Andhra Petrochemicals 20 Jan-11 Apr-11 Jul-11 capacity of the oxo-alcohols facility in Vishakhapatnam. The expansion was completed in May 2010 at a cost of around Rs273 crore and increased the plant’s production capacity to 73,000mtpa. After the expansion, the company can meet around 55% of the country’s total demand of oxoalcohols against the earlier 27%. The enhanced capacity, coupled with efficiencies associated with the latest technology is expected to improve the bottom-line of the company. Among APL’s competitors are Tata Chemicals, Bodal Chemicals, Vision Organics, Amines & Plasticizers, Ganesh Benzoplast, etc. For the financial year ended 31 March 2011, APL reported a net profit of Rs35.63 crore against a net loss of Rs5.38 crore in FY0910. In the same period, its net revenues increased to Rs456.59 crore from Rs137.14 crore. In FY10-11, its earnings per share (EPS) stood at Rs4.19 compared to a negative figure in FY09-10. APL has recommended a dividend of Re1 (10%) on equity shares of Rs10 each for FY10-11. APL’s net profit for the March 2011 quarter increased to Rs13.62 crore from a net loss of Rs4.42 crore in the corresponding period last year. In the same period, its net revenues rose to Rs156.75 crore from Rs1.60 crore. The outlook for APL has improved substantially because of capacity expansion and technology upgradation, which have placed it in a globally-competitive position. The market for oxo-alcohols is expected to grow due to high demand from plastic and paints industries, which are growing in excess of 15% y-o-y (year-on-year). APL’s market-cap to revenues is 0.37, while its marketcap to operating profit is 2.01 times. Buy the stock at the current price. Disclaimer: Street Beat stocks are selected from over 1300 stocks in the Moneylife database. This report is for informational purpose only. None of the stock information, data and company information presented herein constitutes a recommendation or a solicitation of any offer to buy or sell any securities. Information presented is general information that does not take into account your individual circumstances, financial situation or needs; nor does it present a personalised recommendation to you. Individual stocks presented may not be suitable for you. Although information has been obtained from and is based upon sources we believe to be reliable, we do not guarantee its accuracy and the information may be incomplete or condensed. All opinions and estimates constitute our judgement as on the date of the report and are subject to change without notice. Past performance is no indication of future results. Investors must do their own research before acting on them. Exit Strategy: Please exit if the stock closes 25% below the purchase price. This is called stop loss. However, if the market price is above 50% of the purchase price, exit if the stock falls by 25%, below any day’s closing price. This is called stop profit. Data Source: Centre for Monitoring Indian Economy’s Prowess database. 39 | 11 August 2011 | MONEYLIFE Stock-Streetbeat.indd 5 7/23/2011 5:11:32 PM STREET BEAT WHICH WAY Debashis Basu Follow the Price? around the world which we cannot make sense of. And much else that we don’t know about—these will surface later. In this situation, the two things we need to look at are: price trend and valuation. The price trend, There are too many conflicting scenarios and we know little about them—or beyond as I have mentioned earlier, is strong, relative to the negative news flows. On the valuation front, we are fortnight ago, I had not in undervalued territory. We suggested that it was time still maintain that the consensus to be cautiously optimistic. earnings of analysts are too high. We Well, the market seems to have done have not seen forecasts of Sensex nothing over the past 14 days. It is earnings below Rs1,200, whereas exactly where it was. That in itself is we think that the number could well not such a bad thing. The positive be nearer Rs1,150. If this number is view is that despite a gush of correct, the Sensex starts looking negative factors, the market hasn’t Foreign Interest undervalued near 17,250—which broken down. Indeed, we have Week ending Purchase Sales Net (Rs Cr.) we almost hit in late June. We are a had two sharp dips in the past two 9,313.30 8,841.60 471.70 good 1,500 points above that. But months and each ended higher than 10 Jun-11 17 Jun-11 11,675.80 13,151.80 -1,476 there is a possibility that the Sensex the previous one. 24 Jun-11 10,400.60 11,526.70 -1,126.10 will not go down sharply—except Interestingly, during the last 30 Jun-11 13,590.80 8,990.20 4,600.60 when driven by an event. one month of sluggish market 08 Jul-11 18,470.10 12,716.20 5,753.90 What can make my optimism action and strong pessimism, 15 Jul-11 11,434.10 10,712.90 721.20 wane? New evidence that the Indian foreign institutional investors have 21 Jul-11 7,488.80 7,010.20 478.60 corporate sector will not be able kept investing in India. The table 82,373.50 72,949.60 9,423.90 to grow at 12%-15% over the next “Foreign Interest” shows the weekly three quarters and/or a hugely net inflows/outflows of the past negative global… or local event. seven weeks. Last time, I had written that after On the negative side, there are the July quarter results and the just too many high-quality experts RBI (Reserve Bank of India) policy who are warning that the largest meet on 26th July, we should have economy in the world is about to collapse into a deep slowdown, if some sense of where the market is not a recession. There are perennial headed. By the time you read this worries about China as well; and article, we would have had a sense these worries come from some of the smartest people off both. l b h Meanwhile, M hil the early signs of earnings growth in the business, such as Vitaliy Katsenelson. are not too bad. Banks like HDFC Bank and Kotak My guess is that it is impossible to Mahindra Bank have reported excellent follow the torrent of news and views and numbers and so have many consumerMedium-term: Up develop a viable investment strategy. facing companies. Long-term: — There are just too many events happening (Feedback at editor@moneylife.in) A investment that is not subject to market risks Attractive gifts, invitation for events and free online help. For a subscription offer that is unique, look for a form elsewhere in this issue or on our website at MONEYLIFE | 11 August 2011 | 40 Which way.indd 1 7/23/2011 4:59:21 PM STOCKGRADER MOMENTUM Prime Time 45% Compounded Annual Return Prime Focus jumped 18% and EID Parry climbed 2%, while Orchid Chemicals plunged 8% Gainers: Prime Focus jumped 18% in the fortnight. Sesa Goa reported a consolidated net profit of Rs840.59 crore in the first quarter ended 30 June 2011 against a consolidated net profit of Rs1,301.79 crore in the June quarter of the last fiscal. The results were not comparable consequent to merger of erstwhile subsidiary Sesa Industries with the company. The stock rose 1%. The Indian sugar industry output is expected to touch 25MT in the current season against 18.92MT in the previous season. The prices will more or less stabilise at the current level. Despite adverse climatic conditions across the world, India will end with a minor surplus over demand. EID Parry (India) rose 2% and Federal-Mogul Goetze (India) surged 6%. Bank of Baroda and Mahindra & Mahindra rose 1% each. Losers: The Q1FY11-12 results of Magma Fincorp reflected strong growth in disbursals with growth in revenues and assets under management over the corresponding quarter last year. Disbursements grew 36% to Rs1,422 crore, while revenue increased 23% to Rs221crore. Despite increasing cost of funds, the Company RS Grade Funda Grade Final Grade Entry Date Dish TV India A A A 06 Aug-10 72% Sadbhav Engineering A A A 28 Apr-11 5% Yes Bank A A A 22 Jun-11 — Return* company improved its net interest margin from 4.4% in Q4 FY10-11 to 4.6% in Q1 FY11-12. The company recorded net profit of Rs17.13 crore. The stock lost 3%. Orchid Chemicals & Pharmaceuticals’ Chennai manufacturing facility had been issued a closure notice by the Tamil Nadu Pollution Control Board (TNPCB). The Alathur facility was issued a closure notice by the TNPCB, citing non-compliance of some regulations relating to the disposal of solid waste. Orchid Chemicals said that it was in dialogue with the TNPCB; it was confident about resolving the issues and bringing the plant to a fully operational stage at the earliest. The stock tumbled 8%. Oracle Financial Services Software tanked 6%; Shree Renuka Sugars declined 1%. Changes: We are removing Oracle Financial Services and adding Punjab National Bank, Siemens Ltd and Yes Bank. Note: Please read our changed methodology for grading stocks (given below). We have also added a column showing returns since the stock’s appearance in the table. Returns from new stocks added are counted after one issue. Company RS Grade Funda Grade Final Grade Entry Date Power Grid Corp A C A 07 Jul-11 0% Balkrishna Industries A C A 07 Jul-11 -1% M&M A C A 28 Apr-11 -6% -7% Return* Bank of Baroda A B A 29 Apr-09 176% Shriram Transport A C A 18 Feb-11 Titan Industries A B A 16 Apr-10 116% Shree Renuka Sugars A D A 06 Aug-10 9% Sintex Industries A B A 01 Apr-11 16% Federal Bank A D A 13 May-11 4% Prime Focus A B A 07 Jul-11 14% EID-Parry (India) A D A 12 Nov-10 0% HDFC Bank A B A 04 Mar-11 13% Sesa Goa B A B 21 Jan-11 -15% Divi’s Laboratories A B A 07 Jul-11 2% Orchid Chemicals B A B 28 Apr-11 -28% Siemens A B A 22 Jun-11 — Bhushan Steel B B B 28 Apr-11 -16% Magma Fincorp A B A 07 Jul-11 -7% GSK Consumer B C B 29 Apr-09 186% HDFC A C A 15 May-09 83% Hindalco Industries B C B 23 Jul-10 12% Fed-Mogul Goetze A C A 28 Apr-11 18% Bank of India B C B 21 Jan-11 -10% Punjab NaƟonal Bank A C A 22 Jun-11 — Cadila Healthcare B D B 12 Nov-10 13% *Non-annualised Methodology: Momentum Stockgrader is a fortnightly ranking of stocks, based on two key factors that drive stocks—one, market-related or quantitative and, two, fundamental. The quantitative factor is the relative strength (RS), which is a stock’s relative outperformance during the past 10 weeks over select companies. For arriving at fundamental grades, we have used only operating profit growth and sales growth over three quarters. For momentum stocks, RS carries a higher weightage.. 41 | 11 August 2011 | MONEYLIFE Momentumnew.indd 2 7/23/2011 5:16:54 PM STOCKGRADER MEDIUM TERM Sun Shine 44% Compounded Annual Return Supreme Petrochem jumped 9%, while Shoppers Stop fell 5% and Asian Paints lost 2% Gainers: Supreme Petrochem’s revenues and operating profit for the June 2011 quarter rose by 11% and 35%, respectively, over the previous corresponding quarter. The stock jumped 9%. Vivimed Labs surged 9%. Kajaria Ceramics reported good June quarter results with revenues and operating profit growth of 38% and 34%, respectively. The stock gained 9%. Petronet LNG, which rose 18% over the fortnight, also had good June quarter results with revenues and operating profit growth of 83% and 77%, respectively, over the June 2010 quarter. Sun Pharmaceutical has received the US health regulator’s nod to market Alfuzosin hydrochloride tablets used in the treatment of prostatic hyperplasia. It has also received approval from the USFDA to sell a generic version of AstraZeneca Plc’s cancer drug Arimidex. The stock ended flat. HCL Technologies and Eli Lilly have signed a partnership for developing technologies and have opened a co-innovation lab in Singapore. HCL Technologies ended flat. Losers: Shoppers Stop has opened a new store in Company RS Grade Funda Grade Final Grade Entry Date Petronet LNG A A A 29 Apr-09 Return* 227% Vijayawada (Andhra Pradesh). The company now has 42 ‘Shoppers Stop’ stores in operation. The stock fell 5%. Ipca Laboratories also fell 2%. Ashwin Dani, one of the promoters of Asian Paints, has quietly consolidated his stake in Asian Paints by buying shares, thus taking his shareholding to nearly 21%. Mr Dani has bought shares with money raised by pledging his existing shares which are held by various holding companies. Asian Paints fell 2%. Robust performance of the auto sector over the past 24 months has enlarged the replacement market, mainly for tyres and batteries. Tyres are replaced around three years after the original sale, says a survey. Apollo Tyres is banking on the replacement market to ramp up growth. The stock fell 6%. Changes: We are replacing Oracle Financial Services with Praj Industries.% Return* Kajaria Ceramics A A A 26 May-11 22% Nestlé India A C A 29 Apr-09 150% Motherson Sumi Sys A A A 23 Jun-11 15% Sun Pharmaceutical A C A 29 Apr-09 104% Munjal Auto A A A 26 May-11 10% Dabur India A C A 01 Apr-10 39% Vivimed Labs A A A 26 May-11 1% Amara Raja Ba eries A C A 28 Apr-11 27% Lupin A B A 29 Apr-09 211% 3M India A C A 23 Jun-11 6% Titan Industries A B A 01 Apr-10 140% Asian Paints A C A 23 Jun-11 5% HDFC Bank A B A 29 Apr-09 125% Linc Pen & Plastics A C A 26 May-11 3% Supreme Petrochem A B A 27 May-10 72% Praj Industries A C A 21 Jun-11 Siemens A B A 27 May-10 32% Orient Paper & Inds A C A 26 May-11 -6% Supreme Industries A B A 26 May-11 24% Cadila Healthcare A D A 20 Jan-11 6% Time Technoplast A B A 26 May-11 14% Apollo Tyres A D A 23 Jun-11 2% Shoppers Stop A B A 23 Jun-11 6% Akzo Nobel India A D A 23 Jun-11 0% Ranbaxy Laboratories A D A 20 Jan-11 -5% TCS B B B 10 Jun-10 50% Ipca Laboratories A B A 20 Jan-11 4% HCL Technologies A C A 29 Apr-09 288% — *Non-annualised Methodology: Medium. Our grading methodology of fundamental factors includes two key scores, growth score (GS) and value score (VS), carrying equal weightage. We then combine the RS grade and fundamental grades.. MONEYLIFE | 11 August 2011 | 42 Medium Term.indd 2 7/22/2011 9:43:55 PM STOCKGRADER LONG TERM Strong Charge 45% Compounded Annual Return Amara Raja Batteries jumped 5%, while Cadila Healthcare tumbled 7% and TCS fell 4% Gainers: Motherson Sumi Systems (MSSL) has executed a binding agreement with Cross Industries for acquiring an 80% stake in German auto-component maker Peguform for a consideration of €141.50 million, of which MSSL’s share will be worth €72.165 million. The stock surged 5% in the fortnight. Amara Raja Batteries jumped 5%. Adani Enterprises gained 2%. Hindustan Unilever (HUL), with the largest ad spend, has cut its advertising budget for FY11-12 by Rs200-Rs300 crore. In FY10-11, HUL’s advertising & sales budget was Rs2,764 crore. Of this, advertising alone was Rs2,200 crore. The stock ended flat. Losers: Cadila Healthcare’s June quarter earnings resulted in the stock tumbling 7%. Sales growth was flat, while operating profit fell to Rs190.42 crore from Rs240.41 crore in the June 2010 quarter. Tata Consultancy Services’ (TCS) revenues and operating profit rose 34% and 31%, respectively, for the June 2011 quarter over the year-ago period. TCS stated that higher wages affected Company RS Grade Funda Grade Final Grade Entry Date Ador Fontech A A A 29 Apr-09 665% Titan Industries A A A 03 Feb-11 Emami A A A 26 May-11 Motherson Sumi Sys A A A 23 Jun-11 its operating margin. But, it expects margins to improve, going forward, and the pricing environment to remain stable. The stock was down by 4%. Ipca Laboratories, too, fell by 2%. HDFC Bank’s June quarter revenues grew by 31%, while operating profit grew by 16% over the year-ago period. The stock fell 3%. Lupin is looking for a suitor for its India formulations business. Experts say that Lupin, if it decides to dispense with its domestic drug-making venture to concentrate on its overseas business, would not settle for anything less than $3.70 billion. Billionaire investor Rakesh Jhunjhunwala has halved his stake in the drug major. His stake has come down to 1.73% (77 lakh shares) as on 30th June from 3.22% (1.43 crore shares) at the end of March 2011. The stock fell 2%.% 25% HDFC Bank A C A 29 Apr-09 125% 17% ITC A C A 27 May-10 50% 15% Godrej Consumer A C A 26 May-11 15% Return* Return* Wyeth A A A 23 Jun-11 5% Amara Raja Batteries A C A 23 Jun-11 14% TCS A B A 29 Apr-09 260% Hindustan Unilever A C A 25 Nov-10 12% Lupin A B A 29 Apr-09 211% Castrol India A C A 28 Apr-11 12% Nestle India A B A 29 Apr-09 150% Power Grid Corp A C A 03 Feb-11 10% Asian Paints A B A 27 May-10 48% Cadila Healthcare A C A 20 Jan-11 6% Petronet LNG A B A 26 May-11 26% Apollo Tyres A C A 23 Jun-11 2% Supreme Industries A B A 23 Jun-11 21% Akzo Nobel India A C A 23 Jun-11 0% Shoppers Stop A B A 26 May-11 15% Adani Enterprises A D A 29 Apr-09 241% Marico A B A 26 May-11 15% Sun Pharmaceu cal A D A 29 Apr-09 104% Ipca Laboratories A B A 20 Jan-11 4% GSK Pharmaceu cals A D A 29 Apr-09 98% Berger Paints India A B A 26 May-11 0% Ranbaxy Laboratories A D A 20 Jan-11 -5% *Non-annualised Methodology: Long. The fundamental factor includes growth score (GS) and value score (VS). GS is based on operating profit growth and sales growth. VS is calculated considering market-cap as a multiple of five quarters of average sales and operating profit, as well as latest Return on Net Worth (RoNW). The long-term list carries more large-cap stocks.. 43 | 11 August 2011 | MONEYLIFE Long Term.indd 2 7/22/2011 10:17:04 PM “You Can’t Time the Market.” Maybe. 21,100 18-31 Jan ‘08 12-25 Oct ‘07 It is easy to describe market moves. It is hard to predict them which is why fund managers tell you that you “The huge over-speculation... cannot time the market. You will get vivid descriptions should now lead to some painful correction...” of the past everyday from business channels and the 6 -19 Jun ‘08 next day from newspapers. You will get sensible and “Time for a Break?” occasional predictions from only one source. You know 2-16 Aug ‘07 what’s more valuable 9-22 Nov ‘07 17-31 Jul ‘08 15 Feb-1 Mar ‘07 17,325 “Time to Go Neutral” “The market may correct “We don’t have a forecast” 10%-15% before the next move up” “If the government moves to slay the monster of inflation, stocks will suffer collateral damage” 23 Apr-7 May ‘06 “A new downleg may start soon” 28 Mar-10 Apr ‘08 31 Aug-13 Sept ‘07 13,550 2-15 Jan “Is the market due for a fall?” “A short-term bottom may be very near” 16-29 Mar ‘07 “A Rally Now?” “Weakness has r 4-17 August ‘06 “The panic looks done for now” 9,775 Sensex “Might the markets be ready to surprise us on the upside?” “Expect another leg of stock market rally” “ 6,000 Apr-06 Aug-07 Nov-08 We have no compulsion to issue breathless market calls like TV channels or brokers, who make money by getting you to trade frequently. We are a fortnightly magazine. But we don’t issue market calls every fortnight. Moneylife market calls are infrequent. But they have been reasonably accurate so far. But, of course, the past is no guide to the future. Sensex.indd 2 7/22/2011 7:36:49 PM 13-26 Aug'10 18-31 Dec‘09 23 Apr-6 May'10 The Coming Decline Short-term Top? 4-17 Dec‘09 Time To Sell? 19 Jun-2 July ‘09 15-28 July ‘11 Headed Down? “Is the market about to crack?” Signal Yellow? 6 Nov-19 Nov ‘09 11-25 March '10 “We have no Forecast” A Buyers' Market 31 July-13 Aug ‘09 2-15 Jan ‘09 “Buy the dip” 27 Feb-12 Mar ‘09 ness has resurfaced” “A Breakdown?” 30 Jan-12 Feb ‘09 “A weak rally now” Nov-08 13-26 Mar ‘09 “Another weak rally” Mar-10 Jul-11 Moneylife Stock Analysis KNOW WHAT’S COMING Sensex.indd 3 7/22/2011 7:37:45 PM Insurance Trends New products, regulations, features and options, interpreted from your perspective T R A DI T I O N AL PL AN In the above example, the death benefit is Rs1.92 lakh (Rs2,000 monthly income for eight years). If the policyholder expires during the policy term, the monthly income Guaranteed returns from Bharti AXA Monthly Income benefit period will start immediately to pay Rs2,000 per month for Plan: just 2.5% a year! eight years. The accrued annual reversionary bonus (if declared) is paid out immediately on death. harti AXA Life Insurance— This payout is made over and above Monthly Income Plan is a the monthly income benefit made traditional policy that guarantees before the death of the life insured. a monthly income for a certain The rate of return is low from the period, called ‘monthly income investment angle, but there is an benefit period’ during the policy insurance benefit in case of death term which can be 15, 25 or 30 which has to be kept in perspective. years. For example, a policy term of 15 years has a premium payment There is a discount of 2% on the premium for monthly income of term (PPT) of seven years and Rs5,000 or more for policy term monthly income benefit period of of 15 years; discount of 4% on eight years. To get monthly income the premium for monthly income benefit of Rs2,000 for eight years, of Rs3,000 or more for policy the policyholder has to pay annual term of 25 and 30 years. There are premium of Rs23,000 (assuming optional riders like critical illness good health) for seven years. The benefit and premium waiver rider. rate of return (guaranteed) for this The minimum annual premium for example is 2.22%. There is an a 15-year policy term is Rs23,000; annual ‘reversionary’ bonus which for a 25-year policy term it is is paid at the end of the policy Rs18,000; for a 30-year policy term term. The bonus rate is declared it is Rs7,500. The PPT is seven by the company every year, but the years for a 15-year policy term; PPT policy is not eligible for any bonus is 10 years for a 25-year policy term for the first three years. The rate and PPT is 15 years for a 30-year of return (non-guaranteed) may be policy term. The minimum monthly 5.58% based on the current bonus income is Rs2,000 for a 15-year declaration of the company for policy term; Rs1,000 for a 25-year another product. Traditional plans will not give high returns as they are policy term and Rs700 for a 30-year mainly invested in debt instruments. policy term. Avoidable B TERM PLAN Expensive Flexibility Birla Sun Life Protector offers higher sum assured without increase in premium B irla Sun Life Insurance Company has launched new term plan offerings—‘Protector’ and ‘Protector Plus’. These offer flexibility to customers by giving them the option to increase their sum assured by 5% or 10% every year due to increasing responsibilities and inflation, at no extra premium. The annual premium is high, to give you flexibility. Does your term plan really need to increase sum assured every year? The insurance need will increase with dependents and inflation, but so will your income level and savings. Your need to provide a cushion for dependents should decrease under normal circumstances with financial commitments like expenses for education of children coming down, near your retirement age. So, with age, given normal earning cycles, the need for life insurance should decline and at some point, it should be zero. If not, then you have not planned for your retirement. One approach would be to go for an additional term plan when your insurance need increases and terminate the policy close to retirement when your insurance need decreases. Both these plans have a policy term of 5 to 30 years and maximum age on maturity of 75 years. The Protector plan offers a maximum sum assured of Rs49.99 lakh and Protector Plus plan Rs50 lakh. For a person aged 35 going for a `` MONEYLIFE | 11 August 2011 | 46 Insurance.indd 2 7/19/2011 8:01:53 PM INSURANCE TRENDS ` Rs20 lakh sum assured and policy term of 30 years, the premium is Rs6,060; while it is Rs13,360 if the policyholder wants flexibility of 10% increase in sum assured every year. The premium is double in this case. The company will charge the additional premium every year to be able to afford 10% annual increase in the sum assured. For added protection, both plans can be enhanced with the following riders—accidental death and disability rider, critical illness rider, surgical care rider, hospital care rider and waiver of premium rider. ULIP Expensive Option Future Generali Bima Advantage costs a packet for enhanced cover F uture Generali Bima Advantage is a ULIP (unit-linked insurance plan) that offers an option to possibly double your insurance cover if taken at inception. However, this will be suitably reduced if the enhanced insurance cover premium is in excess of 30% Fine Print Motor insurance for diesel engine cars may be hiked I nsurance companies in India are said to be considering hike in premium by 30% for diesel engine cars when compared to equivalent petrol-fuelled cars. The insurers are contemplating the premium hike for diesel cars because such vehicles are usually bought by people who drive longer distances than those driving petrol- of the basic premium. The premium for enhanced protection cover will be calculated separately and added ed to the basic premium. m. The mortality rates for the enhanced insurance nce cover are expensive. For example, the annual ual mortality charge for a 25-year-old having basic sum assured Rs10 ed of R lakh is Rs1,140 (one of the cheapest rates); the annual mortality charges for enhanced insurance cover of Rs10 lakh is Rs2,110 to Rs3,190 (depending on the policy term). The average mortality charge for ULIPs across insurers in the above case is Rs1,420. The enhanced sum assured plus basic sum assured or fund value (if higher) is paid in case of demise of the life assured. There is no option to decrease the basic or enhanced sum assured any time during the policy term. It is unclear why the mortality charges are higher for enhanced insurance cover. As such, the mortality rate for the policy term (Bima Advantage basic sum assured) is much higher than the premium for online term plans that are available in the market (for the same policy term). term This was proved in the t Moneylife Cover Story, Stor “Online Term Plans” Plan (16 June 2011). It will w not make sense to opt o for enhanced insurance cover in insu Bima Advantage. Take a term plan instead. The total charges of premium allocation h and policy administration are also expensive when compared to many other ULIPs. The premium allocation charge is 10% of basic premium in the first year, 6% in the second through fifth year and 3% from the sixth year onwards. The policy administration charge is 2% of basic premium for first five policy years and from the sixth year onwards, inflating at 5% per annum annually with a maximum of Rs6,000 per year. The policy term is 10 to 30 years and is available for customers in the age group of 7 to 65. The maximum age at maturity is 75. The minimum annualised basic premium is Rs20,000 for a policy term of 10-14 years; Rs15,000 for policy term of 15 years and above. fuelled cars, leading to higher exposure to risk. Fuel has become an important rating parameter with the growing preference for diesel vehicles. within a limit. Excess commission was paid to corporate agents which include group companies like SBI (State Bank of India), State Bank of Bikaner & Jaipur, State Bank of Hyderabad and so on; and to group master policyholders like Union Bank of India, Sundaram Home Finance, Dewan Housing Finance Corporation, Federal Bank and Kerala Transport Development Finance Corporation. Out of Rs204 crore excess commission paid over the period from 2005 to 2010, Rs186 crore was paid to State Bank group companies. SBI Life fined Rs70 lakh T he Insurance Regulatory and Development Authority (IRDA) has fined SBI Life Insurance for paying excess commission in 14 instances (Rs5 lakh penalty for each instance) to corporate agents and group master policyholders in violation of the group insurance guidelines which allow commission 47 | 11 August 2011 | MONEYLIFE Insurance.indd 3 7/19/2011 8:02:12 PM POWER OF ONE VINITA DESHMUKH P U B L I C A C T IV IS M Crusading Beyond the Printed Word S creaming headlines and follow-up stories with captions that claim ‘Impact’ or ‘Effect’ are the done thing these days and media houses often have no qualms about appropriating and claiming credit for campaigns/crusades launched by others too. I was fortunate to be part of a team headed by the late Prakash Kardaley, a stalwart journalist and activist who strongly believed that effective and relevant journalism was an integral part of a newspaper. This meant that even a neighbourhood story about a road disturbing the eco-balance by cutting through a hill wasn’t just ‘reported’ but was taken to a logical end by inspiring citizens to protest and compel corrective action. And the only appreciation one received was the reminder that “You are as good as your last story”. This grounding made one realise that however active, effective or pro-active one may be, journalism is often going to be a thankless endeavour. It is when you send out 5,000 emails urging people to attend a public meeting or rally for a cause that affects them directly and only 50 turn up that you realise that ‘citizen action’ is easier said than done. Paradoxically, while commercialisation of news has often forced journalists into submission and When governance breaks down, it is critical to empower and inspire the ordinary, faceless person, says Vinita Deshmukh based on her own experience compromise, the Right to Information (RTI) Act has allowed civil society to cut their dependence on the media for getting accurate information. Journalists too, don’t need to depend on ‘sources’ for accurate and official information; they can demand to see official documents by seeking inspection of files under Section (4) of the RTI Act. For me, the most effective demonstration of the power of this Act was in our ability to drive out a multinational company which came into Pune with all the secrecy, influence and political backing that has become the norm for mega-projects these days. In 2008, as the editor of Intelligent Pune, a weekly tabloid devoted to public causes, I was approached by a few activists to write about Dow Chemicals’ plans to set up a ‘research centre’ at Shinde Vasuli in Chakan, a suburb of Pune. They felt that Dow, which had acquired Union Carbide—and which was responsible for the world’s worst industrial disaster in Bhopal—had no moral right to enter Pune. Could my writing make a difference? I decided to investigate what Dow had planned on the 100 acres of precious land allotted to it at a throwaway price. I sought the details of permissions and clearances granted to Dow Chemicals from the member secretary, `` MONEYLIFE | 11 August 2011 | 48 Power of One.indd 2 7/22/2011 8:15:34 PM POWER OF ONE VINITA DESHMUKH ` Maharashtra Pollution Control Board (MPCB) in Mumbai. He curtly told me that he had no information and I could invoke the RTI Act to get answers. The Act was a handy tool for upright officials who didn’t want to annoy or upset their ministers by providing sensitive information to the media, but were willing to share it when officially demanded under the Act. The documents showed me that Dow Chemicals had been permitted manufacturing rights, not a mere research centre. They also listed over 60 chemicals that would be used in the plant. Of these, 24 required stringent environment clearances under the Environmental Impact Assessment (EIA) which was not adhered to. MPCB had also flouted its own River Regulation Policy under which no chemical plant can be set up within 2-km range of a major river—in this case it was the Shuda, the biggest tributary of the Indrayani River. A further inspection of files at the Maharashtra Industrial Development Corporation’s regional office at Pune revealed instructions to release land extra quickly for the Dow project. Armed with this information, I held a press conference instead of confining the findings to a report in Intelligent Pune. I wanted to motivate villagers to protest by educating them about Dow’s plans and its potential dangers. The effort paid off and the media took up the campaign when villagers protested violently and burnt equipment at the Dow plant site. Soon, Maharashtra’s warkari community staged street protests in various parts of the state. I wrote about various aspects of the Dow issue for 10 continuous months in Intelligent Pune. Finally, the then chief minister Vilasrao Deshmukh, who has signed the original memorandum of understanding with Dow, had to make a hasty call to the chemical giant, asking it to stop construction. But villagers kept up the pressure; Dow officials couldn’t visit the plant site. Ultimately, Dow dropped the Pune project plans and issued an official release. I learnt two lessons from this whole saga. First, authentic information obtained through the RTI Act is powerful ammunition for stakeholders, even if they are not literate. Second, politicians fear upsetting their vote bank more than the legality of issues or protests. I cannot take sole credit for Dow abandoning Pune, but the campaign was triggered by the might of the pen. “What’s the use of only screaming through headlines?” Prakash Kardaley was fond of saying; it inculcated an effort to be an integral part of action on the ground. Another example is our work to save the hills of Pune from being torn down by rampant construction. In true fashion, the government issued a public notice in one of the least read Marathi newspapers announcing its intention to permit 8% residential construction on the hills of 23 villages that would be included in the Pune Municipal Corporation (PMC). The state published detailed reports on the implications of the proposal and urged people to lodge complaints within the statutory 60 days of the announcement. It spurred NGOs and youth groups to initiate a campaign. An unprecedented 90,000 objections were submitted to the PMC, forcing it to announce a ‘Green DP’ (Green Development Plan) for the 23 villages (hills were declared as no-development zones and earmarked for bio-diversity parks). But the bureaucracy again tried to impose public utility and hill zones instead of residential zones. Again, I helped the Green Pune movement to get support to lodge 70,000 objections. The proposal is lying with the town planning department. Yet another effort was in connection with the haphazard detailed project report (DPR) prepared by the Delhi Metro Rail Corporation for the Pune Metro. Vijay Rane, a railway expert, analysed the DPR for me while Prashant Inamdar, a civic activist, showed me a Power Point presentation which demonstrated how the choice of an elevated metro was going to cut through the most congested streets of the city, with no benefit to citizens. I decided not to stop with writing articles. Instead, I formed the Pune Metro Jagruti Abhiyaan which brought together activists, individuals and youngsters from the railway engineering group, architects and urban planners from the Pune Technical Committee. We made a series of presentations in different neighbourhoods, organised a public rally of 350 people and held interactions with MLAs and Pune’s guardian minister. At an interaction with local politicians (‘Metro mahacharcha’), some confessed that they had voted on the metro alignment in five minutes without even reading the DPR. After persuading civic activist Aruna Roy to hold a press conference on our behalf, we forced PMC to hold the first ever jansunwai (public consultation). Ultimately, though the ruling Congress-NCP combine insisted on passing a flawed proposal, there may be a victory in this defeat, because the plans remain on paper with questions—because of doubts about its technical and financial feasibility. Rousing people into joining a public campaign is a tough and frustrating task. Often, support through emails does not translate into active participation and people are happy to suffer injustice silently even though it is clear that governments are only afraid of visible citizen’s power. 49 | 11 August 2011 | MONEYLIFE Power of One.indd 3 7/22/2011 7:55:52 PM PERSONAL BUSINESS AUTO C AR S AL ES Showrooms with aView Customer-oriented car firms? It’s the Japanese, finds Veeresh Malik F orty years ago, on my first Japanese trip, I was fascinated by their cars. I had seen these vehicles in the Persian Gulf, Europe & the US by then, but this experience was different. They seemed shinier in Japan; the locals added bells & whistles like huge tail lamps and fancy names. A Toyota Crown could be a ‘Super Deluxe Toyota Wagon Thundery’ or something even more exotic. My Japanese friends told me their manufacturers made different ‘qualities’ for different parts of the world. India was not a direct market back then—most products ‘landed’ up here through various places like Singapore, Hong Kong and the UAE. But as a seafarer, if you wanted a quality wrist-watch or 2-in-1, you bought it in Japan. It is the same with the recently-launched Toyota Etios Liva J/G/V/VX/V-SP versions in India. Suzuki tried a change with the Maruti 800, the Maruti Van and the Maruti 1000; at best, the variants were with AC. Now, Maruti Suzuki has tried to maintain ‘global’ quality; its vehicles have a range of alphanumeric suffixes. But Toyota needed the Japanese fix, with a more complicated twist, though. The Toyota Etios Liva is a low-cost challenger to the Maruti Suzuki Swift. Both cars are similar, with the ‘new’ Swift not very different from the existing one—just visit both showrooms. Again, even competitors are praising the engine inside the Etios and the Etios Liva. Especially the engine layout. But the interiors, more specifically the Etios cabin soundproofing leaves a lot to be desired. I went to a Toyota showroom, and as expected, the Liva enquirer is made aware that he is being sold Toyota’s bottom-end car in India. But at a Maruti Suzuki showroom, the potential Swift buyer is treated like a top-end customer. A Liva somehow does not give the same gut feel as does the costlier Corolla, but the SX4 has a sensory good feel—somehow like the Swift. One manufacturer gets a message across that its complete range is similar in terms of basic quality and customer experience. The other manufacturer manages to send a subtle message across that his smaller car is not just cheaper but is also for—and from—a different world. I think they should have just called it Etios Liva, instead of risking the Toyota badge, and if I had to buy a new hatchback—I would look at competition. N I S S A N ’S G A M E -P L A N Local Insight, Global Vision Making India a base for global sales makes immense sense A totally different approach seems to be Nissan’s game-plan with its Micra. It does not have too many showrooms and dealers here as yet, but the local ones are a pleasure to visit. Whether you are in the market for a small car or a large one, the approach seems similar, which is not true with many other manufacturers. The car itself looks and feels like an ‘international’ product—inside and outside. Currently exporting in its own name, as well as some amount of multi-badging for other cars, Nissan appears to be busier trying to make India a base for global production. This strategy could pay off in the ongoing slump in overall auto sales. The Maruti A-Star—also built, named and exported as the Nissan Pixo and the Suzuki Celerio, is a car that will sell well in other countries when the market goes down in India. Here, it is viewed as a premium micro-mini small car, and will likely lose sales when the slump really kicks in to the cheaper Alto. Elsewhere, it will snap up space when people stop buying bigger cars, due to rising fuel prices. Veeresh Malik started and sold a couple of companies, is now back to his first love—writing. He is also involved actively in helping small and midsize family-run businesses re-invent themselves. MONEYLIFE | 11 August 2011 | 50 Auto.indd 2 7/22/2011 8:01:08 PM ML FOUNDATION EVENTS INVESTOR, EMPOWER YOURSELF! “Beware of Pyramid Schemes” Moneylife FoundaƟon held its first seminar at Bengaluru on 16th July that 4,000 people watched live over the web T o invest in pyramid schemes like Speak Asia may seem lucrative, but their collapse is inevitable, even if it takes some years to happen, said Sucheta Dalal, founder-trustee of Moneylife Foundation and managing editor, Moneylife magazine. Ms Dalal was speaking at a seminar in Bengaluru, titled “Investor, Empower Yourself!” The seminar was organised by Indiabulls. The event was also webcast live. “Moneylife has been writing about Speak Asia-type schemes abou repeatedly, but the regulators repea keep passing the buck and we get aattacked everyday,” Ms Dalal said. “The problem is that the people who continue to attack us peop have brainwashed themselves into overlooking the fact that they are over involved with a fraud company invo which is going to take them down.” whic Citing the example of Sahara, a C participant raised a question about parti method of determining whether the m company/scheme is genuine or a com Sucheta Dalal, founder-trustee of Moneylife Foundation Fou Event.indd 2 not. Ms Dalal replied that the first step would be to check whether the scheme is registered with the regulator or not. “I am not saying that a valid registration certificate guarantees that you wouldn’t lose money and you are safe; but, in case something goes wrong, you can approach the regulator,” she said. Ms Dalal also spoke about getting the right insurance cover and warned the audience about trusting their banks unquestioningly, because relationship managers often engage in aggressive mis-selling to achieve their targets. She also spoke of the various hidden charges and riders that come attached with credit cards. Debashis Basu, founder-trustee, `` 51 | 11 August 2011 | MONEYLIFE 7/21/2011 7:13:59 PM ML FOUNDATION EVENTS ` Moneylife Foundation and editor, Moneylife magazine, told the audience that investing is really simple as long as one understood the basics of investing and stuck to them. He elaborated on the risk and returns urns of different investment products ts such as stock, mutual funds, fixed deposits eposits and insurance. ce. He explained ed why it is essentiall to know the historical al returns from differentt asset classes so that onee is not misled led by the sales pitch tch of financial ncial services companies nies and their agents. Mr Basu explained how to invest smartly in equity schemes and stocks, and pointed out the merits of compounded income over the long term. He also warned investors about sinking money into exotic ideas such as art funds and f portfolio management schemes. sc Later, he presented an exhaustive ex analysis of mutual funds fund and how to choose sensibly to maximise m gains and reduce risks. risks When he was asked about the method of choosing the t right mutual fund, he pointed out po that one must look at the l long-term record reco of the fund houses and a keep track of the fund manager. When a good fund fu manager leaves a fund, it is instantly a red flag. A participant discusses a point with the panellists Mr Basu was asked about investing in gold which is believed to be the ‘most solid’ and ‘lucrative’ form of investment. He pointed out that gold is a speculative asset. One has to buy and sell it at the right time, like any speculative asset. With data going back to 35 years, he explained that the value of gold mainly depends on the movement of the dollar and rupee. Sachin Choudhar Choudhary, director, Indiabulls Housing Housin Finance RTI “Implement Section (4) of the RTI Act Correctly” Narayan Varma addressed the fourth Moneylife FoundaƟon seminar on the Right to InformaƟon Act, saying people must build pressure so that public authoriƟes voluntarily disseminate informaƟon H It was a full-house at the workshop ow do you access information through the Right to Information (RTI) Act without filing a query? By invoking Section (4) of the Act, which allows spot inspection of files, pointed out Narayan Varma, chartered accountant and a consultant on several official committees for the effective implementation of the RTI Act. Speaking at a seminar organised by Moneylife Foundation on 12th July, Mr Varma also said that a committee has been formed at the Centre which will look at expanding the scope of Section (4) `` MONEYLIFE | 11 August 2011 | 52 Event.indd 3 7/21/2011 7:14:14 PM ML FOUNDATION EVENTS Moneylife has conducted three other seminars on RTI, where activists and journalists shared their experiences and offered tips on proper utilisation of the Act. Mr Varma focused on Section (4) which primarily involves suo moto disclosure of information by public authorities. According to this Section, all records should be maintained and indexed properly in a way that facilitates easy access to information. It further gives citizens the right to inspect files physically without making an application, and states that public authorities should disseminate as much also voluntarily disseminat information as possible and raise awareness awa through seminars. semi When asked ask about which institutions institu could be considered c public authorities, Mr autho Varma replied, “When “Wh the definition defin of public pu authority says auth that it i has to be ‘substantially ‘sub funded’ by the government, it governm opens the th ground to debate. debat But we have got information in informa many cases by c establishing that establis the institution inst concerned concern is a public pub authority.” authori However, How whether whethe a cooperative coopera society can be considered consider as a public authority or au not is debatable. deb Mr Varma said it would be different for each case, since its nature will be defined by its constitution, method of registration and way of functioning. But, he said, cooperative banks can possibly be considered public authorities. “We can say that RBI (Reserve Bank of India) rules apply to cooperative banks as well and, since RBI is definitely a public authority, the domain its jurisdiction applies to can also be classified as a public authority,” he said. Questions were asked as to why courts charge a different amount “ Unfortunately, there are a lot of public authorities who do not favour voluntary dissemination of information “ ` and its proper implementation. from the standard one and demand it in the form of court fee stamps and not postal orders in some places. Mr Varma said, “Though the RTI Act is the overarching legislation in this matter, there are individual laws formulated by states and public authorities like the Varma said, “Unfortunately, the government has failed to provide guidelines to public authorities on suo moto dissemination of information, nor do the bureaucrats have the political will to implement Section (4).” “But what do we do when the authorities reply that the records/ documents are not available?” asked a participant. Mr Varma replied that Section (4) requires the ‘reconstruction’ of lost/destroyed documents and one must go for appeal if the documents are not restored. He cited the example of a man who was entitled to a substantial estate duty (which was abolished 50 years ago) compensation from the government. Mr Varma helped the man claim his inheritance and helped the concerned government department to reconstruct the lost documents on the basis of the documents that the man had in his possession. He also spoke about other success stories. He talked about how activists had compelled governmentaided hospitals to put up information on their websites about the number of free beds reserved for the poor. “Unfortunately, there are a lot of public authorities who do A section of the audience courts. The norms and fees are also subject to such rules.” When asked as to why some public authorities have failed to come up with effective means for voluntary disclosure, Mr not favour voluntary dissemination of information,” Mr Varma said. “They think it is a nuisance. But that mindset has to change. And we must create public pressure to that effect.” Narayan Varma 53 | 11 August 2011 | MONEYLIFE Event.indd 4 7/21/2011 8:54:24 PM LEGALLY SPEAKING SD ISRANI B U Y E R B E WARE Caveat Emptor Holds Good: In all cases The doctrine of ‘buyer beware’ applies to any transaction. You have legal recourse if you are cheated, but always keep this adage in mind before any purchase H ow many times have you felt cheated while buying something tangible (a product) or intangible (securities), realising only later on that you have been taken for a ride? It has been happening over the ages; so what should the consumer or investor do to protect his own interest? Well, every consumer/investor should adhere to the old adage, ‘caveat emptor’ a Latin phrase which means ‘buyer beware’. In general, the doctrine of caveat emptor has been associated with property law. Under the doctrine of caveat emptor, the buyer could not recover from the seller for defects on the property that made the property unfit for ordinary purposes; the only exception was if the seller actively concealed latent defects. Under English Law, historically, the courts have taken the view that their function is not to protect individuals from making a bad bargain or from doing something that they later regret. English courts have seen their function as providing a ‘level playing field’ which would enable individuals and corporations to carry out their business dealings. The rule, which was a creation of the common law courts, is now circumscribed by statutory provisions. The rule of caveat emptor is quite straightforward as it implies that the buyer, while entering into a contract, has to make sure that he knows everything he needs to know about the subject matter of the contract. As far as Indian law is concerned, Section (16) of the Indian Sale of Goods Act (1930) enunciates the principle involved in the maxim caveat emptor. It states that, subject to statutory provisions, there is no implied warranty or condition about the quality of fitness for any particular purpose of the goods supplied under the contract of sale. The principle of caveat emptor lays down that it is the duty of the buyer to satisfy himself before purchasing the article—that the article which he buys, is the one he wants. So what is the effect of caveat emptor? It means that a person has no duty to disclose problems voluntarily. Thus, if one person is under a wrong notion, there is no duty on the other person to correct it. At the same time, it is not an absolute rule as it is subject to certain exceptions: • Misleading statement of truth: A statement that does not present the whole truth may be regarded as a misrepresentation. • Where a statement was true when made but, due to a change of circumstances, has become false by the time it is acted upon, there is a duty to disclose the truth. • Contracts of utmost good faith (uberrimae fidei) impose a duty to disclose all material facts because one party is in a strong position to know the truth. Examples would include contracts of insurance and family settlements. So also is the case where there is a fiduciary relationship between the parties to a contract; a duty of disclosure will arise, for example, between a solicitor and client, a bank manager and client, a trustee and beneficiary, etc. It is the primary duty of the buyer or the investor to ensure that he has made himself aware of all the facts concerning the product he intends to buy so that, later on, problems are avoided. However, at the same time, it is not that the buyer is totally at the mercy of the seller; in fact, to an extent, caveat emptor has been weakened due to certain statutory provisions, e.g., the Consumer Protection Act, etc. Today, a seller is also under certain obligations while supplying goods or materials. Similarly, a company offering its securities to the public is also subject to regulations and is duty bound to make adequate disclosures, to enable potential investors to make an informed decision. There is no doubt that, over the years, with the advent of new legislation and growing awareness of consumer rights, the rule caveat emptor has been chipped away at the edges. But remember, it is better to be safe than sorry; so at all times, caveat emptor or ‘buyer beware’ still applies. Dr SD Israni has spent over 38 years as a corporate lawyer. MONEYLIFE | 11 August 2011 | 54 Legally Speaking.indd 2 7/22/2011 8:25:25 PM Learn the basics of saving and investing Earning Curve MO N T I E R ’ S 7 L AW S OF INVES T ING Knowledge Edge Never invest in something you don’t understand A re stocks new to you? Is ‘sector funds’ a term you are hearing for the first time? Does ‘balanced funds’ make you go blank? If so, you have no business buying any of these. You are more than likely to make losses if you buy a financial product without knowing much about it. Learn the basics before investing in these assets. The guiding principle is: “Never invest in something you don’t understand.” It is the last law of James Montier’s seven immutable laws on investing. There is nothing embarrassing about not knowing and not investing in financial products you can’t understand. Warren Buffett didn’t invest in tech stocks of the late 1990s because he couldn’t understand the business. At the Berkshire Hathaway Annual Shareholders’ Meeting (1998), he said, “I could spend all my time thinking about technology for the next year and still not be the 100th, 1,000th or even the 10,000th smartest guy in the country in analysing those businesses. In effect, that’s a 7- or 8-foot bar that I can’t clear. Different people understand different businesses. The important thing is to know which ones you do understand and when you’re operating within your circle of competence.” When individuals see an ‘attractive’ stock, they invest without understanding a firm’s business. It takes discipline, like that of Buffett’s, to follow the ‘invest in what you know’ principle. By avoiding the ‘dot-com’ boom, he also avoided the ‘dot-com’ bust. “Never invest in something you don’t understand,” seems to be just good old, plain common sense, The 7 Immutable Laws of Investing 1. Always insist on a margin of safety 2. This me is never different 3. Be pa ent and wait for the fat pitch 4. Be contrarian 5. Risk is the permanent loss of capital, never a number 6. Be leery of leverage 7. Never invest in something you don’t understand according to James Montier, a member of GMO’s asset allocation team. But people tend to think that the more complicated a financial product is, the better it must be. This complexity is the cause of major fiscal disasters. “If something seems too good to be true, it probably is. The financial industry has perfected the art of turning the simple into the complex, and in doing so managed to extract fees for itself!” says Montier. Agents explain an investment product in a complicated and sophisticated manner, explaining benefits and returns with no explanation of the risks. Before investing, study the product. It’s your job to protect your savings from ‘get-rich-quick’ schemes. If you can’t see through the concept and get to the heart of the process, then you shouldn’t be investing in it. As Alan Roth, writer of How a Second Grader Beats Wall Street, says, “If you can’t explain your investment strategy and every product in your portfolio to a second grader, you are probably doing something wrong.” In stocks, ‘investing in what you know’ should not be limited to only understanding the business. There are annual and quarterly reports to be read, financial statements and ratios to be understood, the company’s competition evaluated, effects of macroeconomic factors analysed, etc. Doing this will give you an advantage over other investors who ‘invest’ in the stock market. If you want to invest in stocks and don’t want to go through the hassle of going through financial reports, etc., index funds would be the best bet. They offer you broad diversification and, going by history, are sure to make money for you in the long term, especially if you use a consistent investment strategy. 55 | 11 August 2011 | MONEYLIFE Earning curve.indd 2 7/22/2011 7:53:21 PM BOOKS Da r e t o L e ad Elephants Can Dance Dr Anil K Khandelwal scripts the story of how he turned around Bank of Baroda B ack in the days when nationalised banks dominated the industry, it was a given that these public-sector behemoths would dominate the sector. However, post liberalisation, heads of these public sector banks (PSBs) had their task cut out just to stay in business—let alone put up a fight against the new, private entrants. In Dare to Lead, Dr Anil K Khandelwal writes about how he managed to change the firmly established status quo at Bank of Baroda (BoB)—not with an iron hand, but with his ability to empathise with his employees. As Dr Khandelwal says— he speaks from his position as chairman and managing director (CMD) of BoB—his Bank was no different from other PSBs. He says in this tome, about the current banking scenario, “PSBs have begun responding to the challenges and many have DARE TO LEAD improved their financials, ANIL K KHANDELWAL adjusted to the new Sage Publications prudential norms, improved India Pvt Ltd their productivity, deployed Pages 403; Rs795 advanced technology in most of their branches, rolled out core banking, set up a vast network of ATMs, launched many innovative products and enlarged the basket of offerings to the customer. It will be quite a while before they harness their full potential and emerge as highperforming financial entities.” The author has told Moneylife earlier that the skill-sets that he had brought to run BoB were born out of empathy, observation and application of his diverse personal experiences from a tough childhood of hardship and discrimination. Dare to Lead is about how Dr Khandelwal managed to make his employees more customer-centric—and to rise to the challenge of competitive times. He has documented his achievements—which include ‘The Baroda Sun’ (the Bank’s new brand identity); achieving the magical figure of Rs2,500 billion in total business; implementing the core banking solution (CBS) in over 1,700 branches, with Internet banking; introduction of e-products, and 1,100 ATMs on a pan-India basis; ushering in 12-hour banking (8am to 8pm) and 24-hour banking with employees manning the counters, in select branches. The strength of the book is the candid description of the collective passion of the management team and its vital foot soldiers (38,000 employees). Dare to Lead is dedicated to them. Almost single-handedly, Dr Khandelwal transformed BoB on the basis of intangibles—leadership, rebranding, customer-centricity, technology and people processes. Dr Khandelwal holds a BSc, BE, MBA, LLB and PhD (in management), and post-graduate diplomas in labour law and in training & development. He has been conferred the prestigious ‘Lifetime Achievement Award’ from the Asian Banker, Singapore. For a professional The best of strategy and technology cannot help achieve business goals unless human resources of an organisation are continuously rejuvenated through new skills who has achieved a lot in life, it is his candidness that comes out in this book: “I was a mediocre student and used to get only a second class. In the kind of schools we studied, we had not heard of anyone aspiring for anything more than just passing their exams.” Dena Bank was his first brush with leadership and he made sure that the Bank emerged as a smart and strong mid-size lender. According to Pradip Khandwalla, former director, Indian Institute of Management-Ahmedabad, the ‘contingency’ model best fits Dr Khandelwal’s leadership style. He remained a transformational leader, but he also drew upon the charismatic model, the transactional leadership model and the participative model. His work philosophy was ‘tough love’, which meant toughness on performance (high standards) and compassion for people. His core strategy on trade unions was neither mollycoddling them, nor unnecessarily provoking them. Read Dare to Lead to get an insight into where the author received his inspiration both to lead BoB and to write this book. This work must be read and re-read, by leaders who want to transform their organisations. — N Madhavan MONEYLIFE | 11 August 2011 | 56 Book Review new.indd 2 7/21/2011 7:45:30 PM BOOKS T H E WA R R E N BUF F E T T S NEXT DOOR Keep It Simple Stories of individuals who have done very well in picking stocks A n average saver systematically investing in the stock market over a long period would be able to multiply his wealth hugely. However, this calls for a strong commitment to learn the basics of stock picking and an iron will to deal with internal and external demons. Investing is a difficult task. There is only one Warren Buffett. However, there are people who have been able to learn and consistently apply the simple principles of stock picking. The book provides case studies of 10 such investors. People like Michael Koza, Christopher Rees and Bob Krebs have made enough money to enjoy a lifestyle of their choice. These 10 have their own approach to investing, but they share two characteristics—hard work and discipline. They don’t rely on tips from talking heads THE WARREN BUFFETTS NEXT DOOR on TV channels or friends. While they spend hours MATTHEW SCHIFRIN searching for information and Wiley interacting with people on the Pages 194; $29.95 Web and elsewhere, they take their own decisions. Christopher Rees, who was once a vagabond, earned enough to keep him going till his next stop. Later, he became a master at understanding how to stretch a dollar. His motto is, “Don’t lose money.” An electrical engineer, Bob Krebs invests mainly in high-yielding dividend stocks, and ‘call’ and ‘put’ options. He regularly logs into ValueForum.com, to discuss investment ideas. He prefers selling naked short puts to covered call writing on stocks in his portfolio. Structural engineer Justin Uyehara also spends time each day studying his portfolio, before and after his work. Like others, Uyehara tries not to be emotionally attached to any stock. He adds, “I don’t hold anything for long. This limits my gain but also limits my loss.” A civil engineer, Michael Koza doesn’t accept company- provided figures while analysing a stock. If stocks in his portfolio either appreciate greatly or deteriorate from his estimation of their value to the point where their intrinsic value-to-price ratio goes below 1.25, he sells. Kai Petainen, a computer lab manager, is a selftaught quant. His selects his investments based on statistical models that scout for various measurable attributes in companies and stocks. He ignores stocks that get a lot of media attention. Retired educationalsoftware executive Alan Hill successfully blends ‘steadyeddy’ conservative yield-oriented picks with high-risk micro-cap stocks. His investing rules include navigating the tax code. He says that it is very important to get as much of your investment capital as you possibly can into a tax-free environment because if it is in a taxable account, the government is going to take a huge amount of your gains. Jack Weyland, 33, of Reno, Nevada, has developed expertise in healthcare and biotech stocks. He has had an average annual return of 36% since July 2002. Neither he nor Chris Rees ever completed college. Weyland has spent much of his time picking stocks—while on the road, driving a tractor-trailer. Randy McDuff, of The Pas, Manitoba (Canada), spent hours in the town library reading financial papers that were delivered once a week. This helped McDuff develop two important investing attributes: patience and discipline. He is also an avid comic book collector. True to his value-investor bias, he selects comics that he thinks are undervalued with the hope that they will become television shows or movies, causing their value to appreciate. Andrew Swann invests in commodity stocks. Besides researching online, Swann also talks to the managements whenever possible, attends mining trade shows and has travelled around the world to many of the gold mines. He says, for mining companies, cash flow is essentially a calculation of the cash costs of producing the ore subtracted from the price that the company is getting for its gold. Former radio DJ and stock broker, John Navin, is a technical analyst. Once Navin has identified a tradable pattern in a stock, he checks other technical indicators to see if they confirm the bullish or bearish pattern he sees developing. According to Navin, if your trade produces 25% gain, sell one-third of your position and, at 50% gain, sell another one-third. The 10 ‘Warren Buffetts Next Door’ investors state that the only condition for being a good investor is committing the time to educate oneself. Investing— like many of life’s endeavours—requires passion, hard work and discipline that can far outweigh theory and education. An inspiring read. — Dolly Mirchandani 57 | 11 August 2011 | MONEYLIFE Book Review new.indd 3 7/21/2011 7:43:11 PM UNIQUE CONTENT GIFTS OF KNOWLEDGE FREE SOLUTIONS Only Moneylife gives you an outstanding mix of relevant information, safe advice, sharp and unique analysis... all wrapped in world-class design. We offer you relevant and unique free books on investment and finance, not run-of-the-mill consumer items irrelevant to the world of personal finance. Got a genuine problem? Moneylife will give you free help for a solution. An exclusive & unique offer, only for our subscribers. Subscription Ad_new.indd 1 7/22/2011 11:01:03 AM Choice (Please tick) Period 12 Months 24 Months 36 Months NEW SUBSCRIBER No. of Issues 26 Issues of Moneylife Magazine 52 Issues of Moneylife Magazine 78 Issues of Moneylife Magazine Special Offer Rs455 Rs780 Rs975 EXISTING SUBSCRIBER YOUR SUBSCRIPTION NO. BASIC DETAILS NAME: ________________________________________________________________________________________________________________ ADDRESS: _____________________________________________________________________________________________________________ _____________________________________________________________________________________________________________________ PHONE: (Office):_______________________Phone (Res): _________________________E-mail address: ______________________________________ DATE OF BIRTH: _______________________(MM) (DD) (YY) (Please ensure correct date of birth if payment is by credit card) PAYMENT DETAILS PROFESSION:_________________________DESIGNATION ________________________ ( ) Please find enclosed ( ) Cash, ( ) Cheque / ( ) Demand draft number ___________ Dated: ________________________ for (tick one) ( ) Rs455 ( ) Rs780 ( ) Rs975 Favouring Moneywise Media Pvt Ltd ( ) Please charge it to my ( ) /( ) /( ) My card number is ___________________________________ & expiry date is _________ (MM / YY) DATE: __________________ DESIGNATION ________________________________ Add Rs50 extra for outstation cheques Please fill in this order form and mail it with your remittance to Moneywise Media, expiry date of card should be mentioned. # Rates and offers are valid in India only. This offer is valid for a limited period. # Please allow 4-6 weeks for the delivery of your personal copy. # All disputes shall be subject to Mumbai jurisdiction only. Introduce a friend / Fill in the details below and we will send a free copy to your friend. * Name: ___________________________________________________________________________________________________________________________ Address: __________________________________________________________________________________________________________________________ Email ________________________________________________ Tel: ___________________________ *Free copy will be sent only to addresses which can be verified prior to sending Subscription google Format.indd 1 7/22/2011 11:02:31 AM SPENDING TRAVEL BIGGER THAN THE BIG APPLE THE NEW YORK, NEW YORK HOTEL AT LAS VEGAS YON GRAND CAN E H T & S A G LAS VE MANKIND & NATURE’S GRAND CREATIONS Visited by millions of people every year, Las Vegas and the Grand Canyon represent the grandest of spectacles that mankind and nature can provide, says Jaideep Mukerji THE GRAND CANYON THE YAVAPAI POINT: NATURE DOESN’T GET BETTER THAN THIS ver the past many months, I have shared with you a number of travel destinations that may be thought of as being away from mainstream tourist trails. Las Vegas and the Grand Canyon are anything but that; both are visited by millions of people every year and each represents the grandest of spectacles that mankind and nature can provide. Experiencing the glitter of Las Vegas’ famous ‘Strip’ allows one to appreciate the solitude of a remote mountain valley `` MONEYLIFE | 11 August 2011 | 60 Travel.indd 2 7/22/2011 8:56:36 PM SPENDING TRAVEL ` from a completely different perspective. In 1829, a trading caravan of 60 men led by a Mexican merchant Antonio Armijo was charged with establishing a trade route from what was then Mexican territory to Los Angeles. By following a route through a tributary of the Colorado River, the caravan came upon a green valley amidst the arid desert. The travellers named the area ‘Las Vegas’ which was Spanish for ‘The Meadows’. Las Vegas has seen unbelievable expansion since it emerged from the desert just over 100 years ago. In the early 20th century, water from natural wells was piped into the town, providing a reliable source of fresh water as well as the means for additional growth. The increased availability of water in the area allowed Las Vegas to become a water stop, first for horsedrawn wagon trains and, later, for trains, on the trail between Los Angeles in destination. The Las Vegas Strip is where every visitor wants to go. The Strip is a nickname for the road named Las Vegas Boulevard and is ground zero for the shows, nightlife, luxurious hotels, exciting casinos and all the best things to do in Vegas that make the Strip famous the world over. Study a Las Vegas Strip map before your visit and familiarise yourself with the highlights to be found. The Stratosphere is an observation tower at the north end of Las Vegas Boulevard and has great views of the Las Vegas Strip hotels when they light up at night. It is easy to be dazzled by Vegas; the sheer number of things to see and do seems overwhelming at first. With the large number of celebrities who come to Vegas frequently, people-watching can be the main entertainment. And there are no better ‘spot people’ than the Mon Ami Gabi at the Paris Hotel, a French bistro right on the Strip, directly across the street from the famous Bellagio fountains or the Bar & Grill at Planet Hollywood, from ROOM AT THE TOP THE GRAND CANYON SEEN FROM MATHERS POINT-2 THE VEGAS STRIP THE CASINO ROYALE, PALAZZO AND THE VENETIAN HOTELS ALONG ONE OF THE GRANDEST SPECTACLES THAT HUMANKIND CAN PROVIDE California and regions to the east. In 1931, work started on building the well-known Hoover Dam on the Colorado River; the Las Vegas population increased from around 5,000 to 25,000, with most of the newcomers looking for a job on the dam building site. However, the workforce consisted entirely of males from across America and this created a market for largescale entertainment. A combination of local Las Vegas business owners, Mormon financiers and Mafia crimelords helped develop the casinos and showgirl theatres to entertain the largely male dam construction workers. Now, the sights and sounds of Las Vegas are enjoyed by millions of visitors every year. They stay in some of the most glamorous, unique, themed hotels in the world. They eat at five-star restaurants and expensive buffets. They play at casinos, pools, health spas and golf courses. The state is also relatively liberal in handing out marriage permits—Vegas is a major marriage where you can scan CityCenter, the Bellagio and the Strip all at once. Walking the Strip is a must for any first-timer and, as you cruise, check out the signs for the famous Cirque du Soleil shows. Besides being home to the top hotels, casinos and resorts, the Las Vegas Strip is a hub for other attractions like the Showcase Mall, Thomas & Mack, Sands Expo and the Fashion Show Mall that draw visitors to their world-class shops and designer boutiques. Thirty mega hotels and resorts, with a variety of themes, pride themselves on being strategically situated near the Las Vegas Strip. Billions of dollars have been invested in the creation of this hotel wonderland; each of the major Las Vegas hotels tries to outdo the other in style and magnificence. From the pirate-themed Treasure Island, the Mirage Hotel with its artificial erupting volcanoes, to the elegance of the Venetian, a walk down `` 61 | 11 August 2011 | MONEYLIFE Travel.indd 3 7/19/2011 7:34:21 PM GLITZ, GOLD & GLAMOUR YOU CAN CHECK INTO THE EXCALIBUR, MANDALAY OR THE LUXOR HOTELS SPENDING TRAVEL ` the Strip wows the visitor. The Bellagio, Venetian, Caesars Palace and the Luxor are representative of the luxury that you will find along the Las Vegas Strip. The names alone tell you what to expect; names like New York, Luxor, Paris, Orleans, Monte Carlo and Circus Circus make it clear what you can find. Other hotels have replicas of famous monuments like the Eiffel Tower, the ancient temples of Egypt, the canals of Venice or the New York skyline including a mock Empire State Building. All Las Vegas hotels feature shows with international music stars, the best of Broadway musicals and the world’s best magicians. While in Las Vegas, you almost have to gamble a little; many hotels offer free lessons for the beginner. Until recently, Las Vegas used to be famous for buffets; now, it’s more about celebrity chefs. Still, the buffet at the Bellagio with its international selections, the Cravings Buffet at the Mirage Hotel with 11 live cooking stations or the Rio Hotel’s Carnival World Buffet are experiences in their own right. Caesars Entertainment offers a 24-hour buffet pass valid at seven different hotel buffets while MGM Mirage has an allday pass valid at other hotels, all priced between $35-$45. If you are seeking adventure, then SkyJump at the Stratosphere which, at 108 stories, is the longest controlled freefall of its kind, the Fremont Street Flightlinez where you get hooked to a harness and zip right over the crowds on Fremont Street or swimming with the sharks at the Shark Reef Aquarium at Mandalay Bay, are all possibilities. Once you have had enough of the manmade attractions in Las Vegas, take the daily sightseeing coach for the five-hour long drive to the powerful and inspiring landscape of the southern rim of the Grand Canyon in the neighbouring US state of Arizona. The drive across the flat and mostly arid landscape of Arizona is dull and an opportunity to unwind from the intense experiences of Las Vegas. The Grand Canyon is considered one of the Wonders of the World, largely because of its natural features. The exposed geologic rock strata— from the bottom-most 1.8 billion years old layer called Vishnu schist—to the topmost called the Kaibab limestone, represents one of the most complete records of geological history that can be seen anywhere in the world. The Grand Canyon overwhelms your senses with its immense size—446km long river, up to 29km wide, and 1.6km deep, layer upon layer of rock seems to rise over a mile above the Colorado River. Given US government protection (in 1893) as a Forest Reserve, the Grand Canyon became a full-fledged National Park in 1919 and, today, receives close to five million visitors each year, a far cry from the 44,173 people that the Park received in 1919. Given the considerable distance from Las Vegas, a day trip allows you only a few hours at the Canyon itself split between the spectacular viewpoints at Mathers and Yavapai Points and some time at the Grand Canyon Visitor Center with its interpretive displays and exhibits. If you visit during the winter months, as I did, a passing squall can result in a dusting of snow highlighting the rock layers while shafts of sunlight breaking through the storm clouds dramatically illuminate the rock spires and canyons. If you wish to spend more time at this dramatic landscape or walk down to the Canyon floor along one of the many trails, you will have to spend a night at one of the hotels in the area. Some are located outside the National Park gates while others, operated by local indigenous people, are located within the Park boundary. Allow yourself at least three days to experience the entertainment capital of the world and see one of the world’s greatest natural wonders. — With Veeresh Malik ESSENTIAL AL FACTS Why Go There: Las Vegas is unique— there is no city in the world that can offer a grand mix of larger-thanlife experiences. Round-the-clock entertainment, the world’s best shows and hotels like you have never seen or stayed in before, Vegas has it all. The Grand Canyon is one of the world’s must-see natural wonders. Getting There: There are direct flights to Las Vegas from several European cities with convenient connections from most major metro cities in India. There are flights to Las Vegas from most major American cities. Visas: Indian nationals require US visas. Where To Stay: It is easy to book Las Vegas hotels online. The official Vegas tourism website has a wealth of information and includes a hotel booking facility:. Also, check out. com. MONEYLIFE | 11 August 2011 | 62 Travel.indd 4 7/19/2011 7:34:37 PM MONEY FACTS STOCKS INDIAN MARKET TRENDS FUND FLOWS The Sensex and the Nifty both fell 2% in the fortnight. The ML Small-cap Index gained 3%, the ML Large-cap Index rose 2%; the ML Mid-cap Index and the ML Micro-cap Index both added 1% each, while the ML Mega-cap Index lost 1%. Foreigners: Foreign institutional investors were net buyers of stocks (Rs1,199.80 crore) in the fortnight. They pumped in funds worth Rs18,922.90 crore. Share Prices, January 2011=100 700 360 115 20 110 -320 105 FII Net Investments (Rs Crore) -660 100 -1,000 11 Jul-11 95 21 Jul-11 Indians: Domestic institutional investors were also net buyers of equities (Rs835.72 crore). They sold shares worth Rs8,492.09 crore in the fortnight. 90 85 Jan-11 Apr-11 ML Mid-cap ML Large-cap ML Small-cap ML Mega-cap Jul-11 Nifty Sensex 525 DII Net Investments (Rs Crore) 345 ML Micro-cap 165 Index 8 Jul 21 Jul +/(-) MLS mall-capIndex 94.74 97.73 3% MLLarge-capIndex 110.98 113.01 2% MLMi d-capIndex 99.59 100.36 1% MLMi cro-capIndex 89.30 89.81 1% MLMega-capIndex 101.31 99.84 - 1% GLOBAL MARKET TRENDS 5,660.65 5,541.60 - 2% 12,900 18,858.04 18,436.19 - 2% Nifty Sensex Mega-cap Gainers/Losers 8 Jul 21 Jul Change PetronetLN G 142.20 168.20 18% CromptonGreav es 252.95 181.30 - 28% Large-cap Gainers/Losers 8 Jul 21 Jul Change HimadriC hemicals & Inds 44.70 51.95 16% LancoInfratech 24.50 20.95 - 14% Mid-cap Gainers/Losers 8 Jul 21 Jul Change Aptech 95.25 131.60 38% Sanwaria Agro Oils 29.85 20.30 - 32% -15 -195 -375 11 Jul-11 21 Jul-11 Dow Jones Ind Avg 12,680 12,460 12,240 Small-cap Gainers/Losers 8 Jul 21 Jul Change TTKH ealthcare 415.6 641.70 54% MudraLi festyle 42.65 25.70 - 40% Micro-cap Gainers/Losers 8 Jul 21 Jul Change SuperS pinning Mills 8.01 11.12 39% FlawlessD iamond (India) 1.49 1.19 - 20% 12,020 11,800 Jan-11 Jul-11 The Dow Jones Industrial Average gained 1% in the fortnight. The Hang Seng declined 3% and the Bovespa fell 2%. Index 8 Jul 21 Jul Dow Jones Ind Avg 12,657 12,724 1% Korean Composite 2,139 2,145 0% Taiwan Weighted 8,750 8,717 0% Nasdaq Composite 2,860 2,834 - 1% 2,798 2,766 - 1% 10,138 10,010 - 1% Shanghai Composite Nikkei FTSE (AllP ricesi nR s) Apr-11 +/(-) 5,991 5,900 - 2% Bovespa 61,513 60,293 - 2% Hang Seng 22,726 21,987 - 3% 63 | 11 August 2011 | MONEYLIFE Money Fact.indd 2 7/23/2011 5:44:13 PM MONEY FACTS STOCKS 5 What’s H T ML SECTORAL TRENDS Stocks of chemical companies were in demand during the fortnight. India Glycols soared 21%, Atul surged 18%, Himadri Chemicals & Industries climbed 16% and Gujarat Fluorochemicals rose 8%. ML Chemical Index 1,200 1,130 Companies 8 Jul 21 Jul +/- IndiaGl ycols 134.60 162.60 21% Atul 191.70 226.95 18% DeepakN itrite 185.00 218.55 18% 44.70 51.95 16% 296.55 323.25 9% HimadriC hemicals NavinFl uorineIntl 1,060 AndhraP etro 990 27.05 SOTL 920 850 Jan-11 Apr-11 Jul-11 29.45 566.55 615.80 9% BhansaliE nggP oly 30.05 32.65 9% Alkyl Amines Chem 86.25 93.50 8% GujFl uorochemicals 404.15 436.90 8% 5 Software and IT services stocks were punished. Excel Infoways tumbled 16%, Sonata Software tanked 11%, Allied Digital Services declined 10%, MphasiS fell 9%, Tanla Solutions fell 8% and Rolta India shed 7%. Companies 8 Jul 21 Jul ExcelInfow ays 25.05 21.05 -16% ML Software & IT Service Index SonataS oftware 42.90 38.20 -1 1% 425 OnmobileGl obal 107.95 96.30 -1 1% 49.70 44.65 -10% 463.90 422.05 -9% 8.92 8.12 -9% 54.90 50.10 -9% 134.60 123.65 - 8% 16.18 14.96 -8% 131.40 121.70 -7% 410 AlliedD igitalS ervices MphasiS ViseshInfotecni cs 395 380 KLGS ystel InfiniteC omputerS ol TanlaS olutions 365 350 RoltaIndi a Jan-11 Apr-11 Jul-11 AllP ricesi nR s BULK DEALS Date Company Buyer Oil& GasS ervices 9% Telecomequi p Printing& P ubl 8% Software& IT Serv - 5% - 5% Chemicals 4% Sugar - 4% Office Equipment 4% Auto - 4% BuildingMateri al 4% Odds - 3% INSIDER TRADES N T +/- ML Sectoral Trends 9% AllP ricesi nR s What’s Shares of oil & gas companies climbed 9%, printing & publishing stocks advanced 8%, chemicals and office equipment sectors gained 4% each. Telecom stocks tumbled 5%, sugar and auto sectors declined 4% each and odds fell 3% in the fortnight. Seller Rs Cr 15Jul -1 1 JagranP rakashan JagranMedi aN etworkInvtP vt MahendraMGupta 272.06 18Jul -1 1 AssamC ompanyInd ia CrestaFund InvestIndi a(Mau)Ltd-FD I 19.89 22Jul -1 1 PrajIndustri es CPRC apitalS erv CPRC apitalS erv 15.88 11Jul -1 1 OrchidC hemicals TodiS ecuritiesP vt TodiS ecuritiesP vt 10.98 22Jul -1 1 VarunInd ustries HeenaV ora HeenaV ora 6.14 13Jul -1 1 LovableLi ngerie ManishV S arvaiya ManishV S arvaiya 5.09 20Jul -1 1 EsselP ropack Ganjam TradingC oP vt LazarusInvts 4.63 Leela Lace Software Solutions Pvt Ltd bought 14,29,334 shares in Hotel Leelaventure (stake up to 5.81%). Sezal Finance bought 15,00,000 shares in Sezal Glass (stake up to 1.25%). Ekta Kapoor, joint managing director of Balaji Telefilms, bought 20,787 shares in the company (stake up to 15.78%). G Padmavathi, wife of G Bhaskara Rao, executive vice chairman of Lanco Infratech, bought 6,00,000 shares in the company (stake up to 0.22%). SPS Capital & Money Management Services Pvt Ltd bought 10,08,846 shares in Infomedia 18 (stake up to 2.01%). Pramod P Shah bought 22,10,515 shares in Infomedia 18 (stake up to 4.46%). Surana Infocom Pvt Ltd bought 33,945 shares in Surana Telecom and Power (stake up to 1.12%). The Royal Bank of Scotland NV (London Branch) sold 16,97,975 shares of Excel Infoways (stake down to 2.06%). Albula Investment Fund c/o International Management (Mauritius) sold 8,06,486 shares of Excel Infoways (stake down to 3.11%). T Rowe Price New Asia Fund sold 1,12,75,295 shares of Redington (India) (stake down to 0.60%). MONEYLIFE | 11 August 2011 | 64 Money Fact.indd 3 7/23/2011 5:44:23 PM MONEY FACTS COMMODITIES INDEX TRENDS COMMODITY TRENDS MCX Commodity Indices Rubber Particulars 8 Jul 22Jul Change 52- Week High 52- Week Low Metal 4,542.24 4,714.06 4% 4,926.75 3,274.71 Comdex 3,434.25 3,550.36 3% 3,739.05 2,682.24 Agri 2,709.78 2,791.64 3% 2,989.16 2,170.21 Energy 3,031.91 3,121.06 3% 3,585.96 2,434.89 COMMODITY FOCUS MCX Silver Futures (Rs/kg) 72,200 66,200 60,200 54,200 48,200 ndia’s natural rubber production increased by 4% to 59,200 tonnes, while consumption rose by more than 6% to 80,500 tonnes in June 2011. According to Rubber Board data, production and consumption in the year-ago period stood at 56,850 tonnes and 75,450 tonnes, respectively. But, production of natural rubber fell marginally on a month-on-month (M-o-M) basis in June to 59,200 tonnes from 59,700 tonnes in May. Likewise, the consumption of natural rubber on a M-o-M basis also declined marginally in June to 80,500 tonnes from 81,000 tonnes in May. Soyabean 42,200 Jan-11 Apr-11 Jul-11 On the Multi Commodity Exchange, silver for delivery in December rose by Rs570, or 0.95%, to Rs60,875 per kg, with a business turnover of 145 lots on 21st July. Similarly, the metal for delivery in September moved up by Rs453, or 0.93%, to Rs59,732 per kg, with a turnover of 4,694 lots. Market analysts said fresh buying by speculators in tandem with a firming global trend on concerns over Europe’s debt crisis, is fuelling demand for the metal as an alternative investment—and this has been the major factor behind higher silver futures prices. MCX PRICE TRENDS Particulars I Active Contract 5Jul2011 19Jul 2011 Change % High Low Global Commodities SilverR s/kg Sept-1 1 53,222 59,255 11.34 75,543 41,513 GoldR s/10gm Aug- 11 21,968 23,040 4.88 23,320 20,181 CrudeOi lR s/barrel Aug- 11 4,382 4,412 0.68 5,346 4,114 CopperR s/kg Aug- 11 428.05 440.45 2.90 461.10 391.60 LeadR s/kg Jul-1 1 119.85 120.10 0.21 123.40 100.30 NickelR s/kg Jul-1 1 1,044.40 1,073.40 2.78 1,237.50 974 ZincR s/kg Jul- 11 106.75 109.60 2.67 109.80 94.25 NaturalGasR s/mmBtu Jul- 11 195.50 201.70 3.17 225.80 182.50 MenthaOi lR s/kg Jul- 11 1,018.4 1,117.90 9.77 1,159.60 814.40 CPOR s/10kg Jul-1 1 474.60 482.20 1.60 538.50 466 SugarMK olR s/100kg Jul- 11 2,712 2,826 4.20 2,891 2,458 CardamomR s/kg Aug- 11 864.20 868.10 0.45 1,130 801.50 Potato Agra Rs/100kg Aug-1 1 460.80 458.30 - 0.54 480.10 415 Others A rea under coverage for soyabean has reached 9.12 million hectares so far across the country, slightly lower than the targeted 9.31 million hectares for the entire season, according to the Soybean Processors Association of India. The acreage of soyabean, which is grown only in the kharif season, stood at 9.3 million hectares and production was a record 12.65 million tonnes in the 2010-11 crop year (July-June). Rice O n 22nd July, the Ministry of Consumer Affairs, Food & Public Distribution said it is not in favour of allowing immediate export of additional quantity of non-basmati rice. Recently, the government had allowed export of 1 million tonnes (MT) at a minimum export price of $400 a tonne. The Ministry of Agriculture has recently revised upwards the projected rice output for the 2010-11 crop year (July-June) to 95.32MT from 94.11MT for the same period. Besides, government godowns are overflowing with rice stock of 27MT. 65 | 11 August 2011 | MONEYLIFE Money Fact.indd 4 7/23/2011 5:44:38 PM BEYOND MONEY a brave NEW LIFE Kripa Foundation helps people afflicted with chemical dependency and HIV infection to get back on their feet, says Disha Shah KRIPA FOUNDATION 81/A, Chapel Road, Mt Carmel Church, Behind Lilavati Hospital, Bandra (West), Mumbai 400 050 Tel: 022 2640 5411 krishna.iyer@ymail.com I AntiNarcotics Department and the NCB are referred to Kripa for rehabilitation after the raids. Over 2,700 people come to Kripa to its 19 centres in 11 states every year—and it has treated nearly 29,700 people since inception. MONEYLIFE | 11 August 2011 | 66 Beyond_money.indd 1 7/22/2011 8:58:26 PM Advertisements.indd 6 7/21/2011 6:18:14 PM REGISTERED WITH THE RNI UNDER NO. MAHENG/2006/16653. POSTED AT PATRIKA CHANNEL SORTING OFFICE MUMBAI 400001. Postal Registration No: MH/MR/WEST/184/2009-2011 Advertisements.indd 3 7/20/2011 7:07:54 PM
https://issuu.com/moneylife/docs/ml_11_august_2011
CC-MAIN-2017-30
refinedweb
32,873
60.55
Ready to learn Machine Learning? Browse courses like Machine Learning Foundations: Supervised Learning developed by industry thought leaders and Experfy in Harvard Innovation Lab. Welcome to part four of Learning AI if You Suck at Math. If you missed part 1, part 2 and part3 be sure to check them out. Maybe you’ve downloaded TensorFlow and you’re ready to get started with some deep learning? But then you wonder: What the hell is a tensor? Perhaps you looked it up on Wikipedia and now you’re more confused than ever. Maybe you found this NASA tutorial and still have no idea what it’s talking about? The problem is most guides talk about tensors as if you already understand all the terms they’re using to describe the math. Have no fear! I hated math as a kid, so if I can figure it out, you can too! We just have to explain everything in simpler terms. So what is a tensor and why does it flow? Tensors = Containers A tensor is the basic building block of modern machine learning. At its core it’s a data container. Mostly it contains numbers. Sometimes it even contains strings, but that’s rare. So think of it as a bucket of numbers. There are multiple sizes of tensors. Let’s go through the most basic ones that you’ll run across in deep learning, which will be between 0 and 5 dimensions. We can visualize the various types of tensors like this (cats come later!): 0D Tensors/Scalars Every number that goes into a tensor/container bucket is called a “scalar.” A scalar is a single number. Why don’t they just call it a number you ask? I don’t know. Maybe math peeps just like to sound cool? Scalar does sound cooler than number. In fact you can have a single number tensor, which we call a 0D tensor, aka a tensor with 0 dimensions. It’s nothing more than a bucket with a one number in it. Imagine a bucket with a single drop of water and you have a 0D tensor. In this tutorial we’ll use Python, Keras and TensorFlow, as well as the Python library NumPy. We set all of that up in my last tutorial, Learning AI if You Suck at Math (LAIYSAM) — Part 3, so be sure to check that out if you want to get your deep learning workstation running fast. In Python, these tensors are typically stored in a NumPy arrays. NumPy is a scientific library for manipulating numbers that is used by pretty much every AI framework on the planet. import numpy x = np.array(5) print(x) Our output is: 5 On Kaggle (the data science competition site) you will often see Jupyter Notebooks (also installed in LAIYSAM -Part 3) that talk about turning data into a NumPy arrays. Jupyter notebooks are essentially a markup document with working code embedded. Think of it as an explanation and program rolled into one. Why the heck would we want to turn data into a NumPy array? Simple. Because we need to transform any input of data, be that strings of text, images, stock prices, or video into a universal standard that we can work with easily. In this case we transform that data into buckets of numbers so we can manipulate them with TensorFlow. It’s nothing more than organizing data into a usable format. In web programming you might represent via XML, so you can define its features and manipulate it quickly. Same thing. In deep learning we use tensor buckets as our basic Lego block. 1D Tensors/Vectors If you’re a programmer, you already know about something similar to a 1D tensor: an array. Every programming language has arrays, which are nothing but a string of data chunks in a single row or column. In deep learning this is called a 1D tensor. Tensors are defined by how many axes they have in total. A 1D tensor has exactly one axis. A 1D tensor is called a “vector.” We can visualize a vector as a single column or row of numbers. If we wanted to see this in NumPy we could do the following: x = np.array([1,2,3,4]) print(x) Our output is: array([1,2,3,4]) We can also visualize how many axes a tensor has by using NumPy’s ndim function. Let’s try it with a 1D tensor. x.ndim Our output is: 1 2D Tensors You probably already know about another kind of tensor: a matrix. A 2D tensor is called a matrix. No, not the movie with Keanu Reeves. Think of an Excel sheet. We can visualize this as a grid of numbers with rows and columns. Those columns and rows represent two axes. A matrix is a 2D tensor, meaning it is two dimensional, aka a tensor with 2 axes. In NumPy we would represent that as: x = np.array([[5,10,15,30,25], [20,30,65,70,90], [7,80,95,20,30]]) We can store characteristics of people in a 2D tensor. For example, a typical mailing list would fit in here. Let’s say we have 10,000 people. We also have the following features or characteristics about each person: - Street Address - City - State - Country - Zip That means we seven characteristics for each of our ten thousand people. A tensor has a “shape.” The shape is a bucket that fits our data perfectly and defines the maximum size of our tensor. We can fit all the data about our people into a 2D tensor that is (10000,7). You might be tempted to say it has 10,000 columns and 7 rows. Don’t. A tensor can be transformed or manipulated so that columns become rows and vice versa. 3D Tensors This is where tensors really start to get useful. Often we have to store a number of examples of 2D tensors in their own bucket, which gives us a 3D tensor. In NumPy we could represent it as follows: [20,30,65,70,90], [7,80,95,20,30]] [[3,0,5,0,45], [12,-2,6,7,90], [18,-9,95,120,30]] [[17,13,25,30,15], [23,36,9,7,80], [1,-7,-5,22,3]]]) A 3D tensor has, you guessed it, 3 axes. We can see that like so: x.ndim Our output is: 3 So let’s take our mailing list above. Now say we have 10 mailing lists. We would store our 2D tensor in another bucket, creating a 3D tensor. It’s shape would look like this: (number_of_mailing_lists, number_of_people, number_of_characteristics_per_person) (10,10000,7) You might have already guessed it but a 3D tensor is a cube of numbers! We can keep stacking cubes together to create bigger and bigger tensors to encode different types of data aka 4D tensors, 5D tensors and so on up to N. N is used by math peeps to define an unknown number of additional units in a set continuing into the future. It could be 5, 10 or a zillion. Actually, a 3D tensor might be better visualized as a layer of grids, which looks something like the graphic below: Common Data Stored in Tensors Here are some common types of datasets that we store in various types of tensors: - 3D = Time series - 4D = Images - 5D = Videos In almost every one of these tensors the common thread will be sample size. Sample size is the number of things in the set. That could be the number of images, the number of videos, the number of documents, or the number of tweets. Typically, the actual data will be one less the sample_size: rest_of_dimensions - sample_size = actual_dimensions_of_data Think of the various dimensions in the shape as fields. We are looking for the minimum number of fields that describe the data. So even though a 4D tensor typically stores images, that’s because sample size takes up the 4th field in the tensor. For example, an image is really represented by three fields, like this: (width, height, color_depth) = 3D But we don’t usually work with a single image or document in machine learning. We have a set. We might have 10,000 images of tulips, which means we have a 4D tensor, like this: (sample_size, width, height, color_depth) = 4D Let’s look at multiple examples of various tensors as storage buckets. Time Series Data 3D tensors are very effective for time series data. Medical Scans We can encode an electroencephalogram EEG signal from the brain as a 3D tensor, because it can be encapsulated as 3 parameters: (time, frequency, channel) The transformation would look like this: Now if we had multiple patients with EEG scans, that would become a 4D tensor, like this: (sample_size, time, frequency, channel) Stock Prices Stock prices have a high, a low and a final price every minute. The New York Stock Exchange is open from 9:30 AM to 4 PM. That’s 6 1/2 hours. There are 60 minutes in an hour so 6.5 x 60 = 390 minutes. These are typically represented by a candle stick graph. We would store the high, low and final stock price for every minute in a 2D tensor of (390,3). If we captured a typical week of trading (five days), we would have a 3D tensor with the shape: (week_of_data, minutes, high_low_price) That would look like this: (5,390,3) If we had a 10 different stocks, with one week of data each, we would have a 4D tensor with the following shape: (10,5,390,3) Let’s now pretend that we had a mutual fund, which is a collection of stocks, which is represented by our 4D tensor. Perhaps we also have a collection of 25 mutual funds representing our portfolio, so now we have a collection of 4D tensors, which means we have a 5D tensor of shape: (25,10,5,390,3) Text Data We can store text data in a 3D tensor too. Let’s take a look at tweets. Tweets are 140 characters. Twitter uses the UTF-8 standard, which allows for millions of types of characters, but we are realistically only interested in the first 128 characters, as they are the same as basic ASCII. A single tweet could be encapsulated as a 2D vector of shape (140,128). If we downloaded 1 million Donald Trump tweets ( I think he tweeted that much last week alone) we would store that as 3D tensor of shape: (number_of_tweets_captured, tweet, character) That means our Donald Trump tweet collection would look like this: (1000000,140,128) Images 4D tensors are great at storing a series of images like Jpegs. As we noted earlier, an image is stored with three parameters: - Height - Width - Color depth The image is a 3D tensor, but the set of images makes it 4D. Remember that fourth field is for sample_size. The famous MNIST data set is a series of handwritten numbers that stood as a challenge for many data scientists for decades, but are now considered a solved problem, with machines able to achieve 99% and higher accuracy. Still, the data set remains a good way to benchmark new machine learning applications, or just to try things out for yourself. Keras even allows us to automatically import the MNIST data set with the following command: (train_images, train_labels), (test_images, test_labels) = mnist.load_data() The data set is split into two buckets: - training set - test set Each of the images in the sets has a label. This label gives the image the correct identification, such as the number 3 or 7 or 9, which was added by hand by a human being. The training set is used to teach a neural net and the test set contains the data the network tries to categorize after learning. The MNIST images are gray scale, which means they could be encoded as a 2D tensor, however all images are traditionally encoded as 3D tensors, with the third axis being a representation of color depth. There are 60,000 images in the MNIST dataset. They are 28 pixels wide x 28 pixels high. They have a color depth of 1, which represents gray scale. TensorFlow stores image data like this: (sample_size, height, width, color_depth). So we could say the 4D tensor for the MNIST dataset has a shape of: (60000,28,28,1) Color Images Color photos can have different color depths, depending on their resolution and encoding. A typical JPG image would use RGB and so it would have a color depth of 3, one each for each red, green, blue. This is a picture of my awesome cat Dove. It’s a 750 pixel x 750 pixel image. (Actually it’s 751 x 750 because I cut it wrong in Photoshop, but we’ll pretend it is 750 x 750). That means we have a 3D tensor with the following characteristics: (750,750,3) My beautiful cat Dove (750 x 750 pixels) Hence my Dove would get reduced to a series of cold equations that would look like this as it “transformed” or “flowed.” Then let’s say we had a bunch of images of different types of cats, (though none will be as beautiful as Dove). Perhaps we have 100,000 not-Dove cats that were 750 pixels high by 750 pixels wide. We would define that set of data to Keras as a 4D tensor of shape: (10000,750,750,3) 5D Tensors A 5D tensor can store video data. In TensorFlow video data is encoded as: sample_size, frames, width, height, color_depth) If we took a five minute video (60 seconds x 5 = 300), at 1080p HD, which is 1920 pixels x 1080 pixels, at 15 sampled frames per second (which gives us 300 seconds x 15 = 4500), with a color depth of 3, we would store that a 4D tensor that looks like this: (4500,1920,1080,3) The fifth field in the tensor comes into play when we have multiple videos in our video set. So if we had 10 videos just like that top one, we would have a 5D tensor of shape: (10,4500,1920,1080,3) Actually this example is totally insane. The size of the tensor would be absolutely ridiculous, over a terabyte. But let’s stick with it for a moment as there’s a point to doing it. Know that in the real world, we would want to down-sample the video as much as possible to make it more realistic to deal with or we would be training this model until the end of time. The number of values in this 5D tensor would be: 10 x 4500 x 1920 x 1080 x 3 = 279,936,000,000 Keras allows us to store things as floating point numbers with 32 bits or 64 bits with a data value call (dtype): float32 float64 Each of these values would be stored as a 32 bit number, which means that we multiply the total number of values by 32 to transform it into bits and then convert it to Terabytes. 279,936,000,000 x 32 = 8,957,952,000,000 I don’t even think the values would fit in a float32 (I’ll let someone else do the math on that), so get down-sampling my friend! Actually, I used this last insane example for a reason. You just got your first lesson in pre-processing and data-reduction. You can’t just hurl data at an AI model with no work on your part. You have to massage and shrink the data to make it easier to work with efficiently. Reduce the resolution, drop unneeded data (aka deduping), limit the number of frames you use, etc, etc. That is the work of a data scientists. If you can’t munge the data, you can’t do anything useful with it. Conclusion There you have it. Now you have a much better understanding of tensors and the types of data that fit in them. In the next post we’ll learn how to do various transformations on the tensors, also known as math. In other words, we’ll make the tensors “flow.”
https://www.experfy.com/blog/learning-ai-if-you-suck-at-math-part4-tensors-illustrated-with-cats
CC-MAIN-2019-35
refinedweb
2,719
70.63
A package templating system. Project description Jetpack is a package templating system based on the mustache template syntax. A jetpack template (pack) is just a directory containing subdirectories and template files. A pack might be a python package, R package, Ruby gem, anything… Packs are stored in a hanger and rendered by the jetpack utility. the Hanger A simple hanger might look like this: hanger/ pack1/ profile.md pack.json pack2/ bio.txt pack.cfg pack.json Each pack has it’s own directory in the hanger and contains all the subdirectories and template files for that pack. Additionally pack.cfg and pack.json files may exist at the hanger and/or pack level. Template Files Templates use the mustache template syntax (implemented with pystache). Partials are relative to the hanger directory. hanger/pack1/profile.md # {{team}} {{first}} {{last}} {{role}} ## Bio {{> pack2/bio.txt}} Created: {{today}} hanger/pack2/bio.txt Belichick has extensive authority over the Patriots'... Context Files Context is stored in pack.json files. hanger/pack.json { "team": "New England Patriots" } hanger/pack1/pack.json { "first": "Bill", "last": "Belichik", "role": "coach" } Built-in Context The default context includes the following tags, which can be overwritten in a context file, if desired. datetime - today: %c - year: %Y - month: %m - day: %d - hour: %H - minute: %M - second: %S Configuration Files Configuration is stored in pack.cfg files. The following options are available: A pack object can inherit the templates, contexts, and configurations of other packs. Base classes are separated by a comma. [class] base: python,generic Inheritance When base classes are specified, templates, contexts, and configurations are inherited in the following order: - pack - pack bases (recursive) - hanger Circular imports are not permitted. Set the format of built-in context tags by using the datetime directives. [datetime] today: %c year: %Y month: %m day: %d hour: %H minute: %M second: %S Installation $ git clone $ python setup.py install or $ pip install jetpack Usage jetpack provides a terminal command jetpack: $ jetpack python -s /path/to/hanger name: my_package description: The best package! try jetpack --help for additional details on usage. and a python module for interaction: import jetpack jetpack.launch(hanger='/path/to/hanger', pack='python', name='my_package', description='The best package!') Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/jetpack/0.3/
CC-MAIN-2021-43
refinedweb
399
50.43
store measured values in CSV and output chart - PSOC 5LPJaGe_4104756 Jun 14, 2019 2:40 AM Hello everybody, I am still a noobie here and hope that you can help me :-). I have written a program in which I determine a voltage drop (ADC converter) via a shunt resistor, then calculate the current for me and then output the measured value via HTerm. Now I would like to have the readings displayed in a stream-time diagram and, optimally, store the values in a .csv or .xls. I would like it if the Excel list looks like this: The final version would be to average every minute over a measurement and then every five minutes to average the previous average. So that a value is output every 5 minutes. So should be the diagram that every 5 minutes a new value is displayed. Thank you very much and sunny greetings from Germany jg.vs 1. Re: store measured values in CSV and output chart - PSOC 5LPMoTa_728816 Jun 14, 2019 7:55 AM (in response to JaGe_4104756) Hi, Sometime ago, I posted following topic. How I recycle the data (aka Return of CCS811) Can this be a hint for you? moto 2. Re: store measured values in CSV and output chart - PSOC 5LPKyTr_1955226 Jun 14, 2019 9:21 AM (in response to JaGe_4104756) I usually use RealTerm for serial logging like this, since it will automatically Timestamp your data with different choices for formatting and delimiter (comma or space) and write out to a text file log. I may have to give TeraTerm a try though. SerialPlot also looks like it could be quite handy. In any case, you can just send your data via serial, comma delimited, with a Carriage Return/Line Feed at the end of each line every 5 minutes (or whatever time period you choose). All you need then is a terminal that will log your data to a file. You may also want to print a header row before you start sending values to give your columns names, otherwise you'll have to do it manually afterward. At the end you will have a nice comma separated text file that you can just import into spreadsheet software. 3. Re: store measured values in CSV and output chart - PSOC 5LPBoTa_264741 Jun 14, 2019 9:25 AM (in response to JaGe_4104756) Jannick, I typically use a Multichart software, it is old charting tool from Cypress. It allows simultaneous input of 3 data streams using serial connection. You can find the Multicart software and some demo projects here: (in #2) Re: Best Approach: Implement DMA on 16bit Timer or 2 Status Registers? (in #3) Re: PSoC Today! - Synchronous Detection Detail /odissey1 4. Re: store measured values in CSV and output chart - PSOC 5LPJaGe_4104756 Jun 15, 2019 8:13 AM (in response to JaGe_4104756) Hello everybody, Thank you for the answers. Unfortunately, I am not quite so clear, I would like to get rid of more detailed information to describe my problem in more detail: 1. I tried to get the current date and time, code: UART_1_PutString ("Date:%s Time:%s) \ n", __DATE__, __TIME__); the compiler already shows the error: too many arguments to function call, expected single argument 'string', have 3 arguments Where is my mistake?. Thank you very much for your help. greetings jg.vs 5. Re: store measured values in CSV and output chart - PSOC 5LPLePo_1062026 Jun 15, 2019 1:55 PM (in response to JaGe_4104756) jg.vs, 1. PutString() only takes a single string for an argument. What you need to add is the following: ... // other lines of #includes. #include <stdio.h> ... // other lines of code. #define TSTR_SZ 100 // set this number to the maximum string size you expect to need. char8 tstr[TSTR_SZ]; ... // other lines of code. ... function_call(...) // Your function { ... // other lines of code. snprintf(tstr, sizeof(tstr), "Date:%s Time:%s) \ n", __DATE__, __TIME__); // format the string with the variables needed UART_1_PutString (tstr); // This will send the formatted string tstr out the UART port. ... // rest of code. One suggestion: If you format your UART text output with commas ',' separating values on each line, you can usually use the log function of most terminal programs to store as .txt or as .csv. Then as suggested earlier, you can use the charting function in Excel to display the values graphically. 2. I've never used MultiChart. Looks useful. You can trust /odissey1 (user_342122993). He is a seasoned PSoC user and has very creative ideas. Len 6. Re: store measured values in CSV and output chart - PSOC 5LPBoTa_264741 Jun 16, 2019 7:52 AM (in response to LePo_1062026) jg.vs, It looks like first ")" is unnecessary snprintf(tstr, sizeof(tstr), "Date:%s Time:%s) \ n", __DATE__, __TIME__); should be: snprintf(tstr, sizeof(tstr), "Date:%s Time:%s \n", __DATE__, __TIME__); As Motoo Tanaka pointed out, PSoC5 does not generate real time by itself. You would need some external time keeper like DS3231. Better solution was proposed by KTrenholm, as to use timestamp on the receiving side, which is available by default. So, after all, you won't need time formatting at all. /odissey1 7. Re: store measured values in CSV and output chart - PSOC 5LPBoTa_264741 Jun 15, 2019 3:06 PM (in response to JaGe_4104756)1 of 1 people found this helpful jg.vs, 2. The Multichart allows for charting/logging of the fast data streams (<10kHz), which may be overkill for your application. But there are many other options to plot/save slow data (<100Hz) using android devices and Bluetooth. For example: Visual Logger VisualLogger (Terminal/Graph) - Apps on Google Play BT Graphics BT Terminal/Graphics Full - Apps on Google Play In this case you have to attach some cheap BT dongle like HC-05 to PSoC UART, and have your data on the phone or tablet. /odissey1 8. Re: store measured values in CSV and output chart - PSOC 5LPMoTa_728816 Jun 15, 2019 2:57 PM (in response to JaGe_4104756)1 of 1 people found this helpful Hi, > 1. I tried to get the current date and time, code: The "__DATE__" and "__TIME__" gives the date and time of when the program was compiled. So it won't change every time you use it, in other words, these does not give you the "current time" To get current time, off my head there are (at least) two methods, (1) Use "RTC" component, but it requires an external 32KHz Crystal. (2) Hand craft or find unix time calendar code and keep time using some timer, this is a lot of work and very poor timer accuracy. So may be, as others suggest using PC or Host side time utility is much cheaper and accurate. Having written that the syntax error will be fixed if you write UART_PutString(__DATE__) ; UART_PutString(" ") ; UART_PutString(__TIME__) ; UART_PutString("\n") ; or use sprintf, snprintf to compose a string then use UART_PutString(str) >. IMHO, this is something you need to think and implement or pay someone to implement it for you. Have you read/tried my sample at the URL I posted earlier? > Sometime ago, I posted following topic. > How I recycle the data (aka Return of CCS811) Although not too fancy, I think it is showing one possible method to fulfill your requirement. (1) Showing real time graphics (2) Storing csv on your PC And also those suggestions from others should be help. Anyway, happy hacking ;-) moto 9. Re: store measured values in CSV and output chart - PSOC 5LPMoTa_728816 Jun 15, 2019 6:06 PM (in response to MoTa_728816)1 of 1 people found this helpful Well, after the previous post of mine, I found the following URL So I tweaked a little, schematic main.c For the fast result, I set Interval = 1, but for 5 minutes interval, please make it to 300, Meantime if you have live RTC, you don't have to call set_date_time() function. but for the realistic time, I added this function. (I was younger in 1970 ;-) ========================= #include "project.h" #include "stdio.h" #include "date_time.h" #define STR_LEN 32 #define RX_BUF_LEN 128 #define SPACE ' ' #define TAB '\t' #define CR '\r' #define LF '\n' volatile uint32_t unix_time = 0 ; volatile int pit_flag = 0 ; volatile char rx_buf[RX_BUF_LEN] ; volatile int rx_write_index = 0 ; int rx_read_index = 0 ; char str[STR_LEN+1] ; /* print buffer */ int str_index = 0 ; inline int is_delimiter(uint8_t c) ; void print(char *str) ; void init_hardware(void) ; void splash(void) ; int get_string(char *str) ; void prompt(void) ; int year = 2019 ; int month = 05 ; int day = 16 ; int hours = 8; int minutes = 32; int seconds = 36 ; float R_value = 4700 ; /* 4.7 k ohm for place holder */ CY_ISR(uart_rx_isr) { uart_rx_int_ClearPending() ; if (UART_GetRxBufferSize()) { rx_buf[rx_write_index] = UART_GetByte() ; rx_write_index = (rx_write_index + 1) % RX_BUF_LEN ; } } CY_ISR(timer_isr) { timer_int_ClearPending() ; Timer_ReadStatusRegister() ; unix_time++ ; pit_flag = 1 ; } void set_date_time(void) { DateTime date_time ; print("Enter Date (YYYY/MM/DD) > ") ; while(get_string(str) <= 0) ; sscanf(str, "%d/%d/%d", &year, &month, &day) ; print("Enter Time (hh:mm:ss) > ") ; while(get_string(str) <= 0) ; sscanf(str, "%d:%d:%d", &hours, &minutes, &seconds) ; date_time.year = year ; date_time.month = month - 1 ; /* unix time, month is 0~11 instead of 1~12 orz */ date_time.day = day ; date_time.hours = hours ; date_time.minutes = minutes ; date_time.seconds = seconds ; unix_time = convertDateToUnixTime(&date_time) ; } void measure(float *mV, float *mA) { int16_t adc_count ; ADC_StartConvert() ; ADC_IsEndConversion(ADC_WAIT_FOR_RESULT) ; adc_count = ADC_GetResult16(0) ; /* channel 0 */ *mV = (float)ADC_CountsTo_mVolts(adc_count) ; *mA = *mV / R_value ; } void print_csv_title(void) { print("Date, Time, Voltage Ush[mV], Current lpv[mA]\n") ; } void print_csv(float mV, float mA) { DateTime date_time ; convertUnixTimeToDate(unix_time, &date_time) ; sprintf(str, "%d.%02d.%4d, ", date_time.day, date_time.month + 1, date_time.year) ; print(str) ; sprintf(str, "%02d:%02d:%02d, ", date_time.hours, date_time.minutes, date_time.seconds ) ; print(str) ; sprintf(str, "%d.%04d, ", (int)mV, (int)(mV * 10000) % 10000) ; print(str) ; sprintf(str, "%d.%04d\n", (int)mA, (int)(mA * 10000) % 10000) ; print(str) ; } int main(void) { float mV, mA ; uint32_t count = 0 ; uint32_t interval = 1 ; // 300 ; /* 5 minutes */ int period = 0 ; init_hardware() ; splash() ; sprintf(str, "Interval = %d sec\n", interval) ; print(str) ; set_date_time() ; print_csv_title() ; for(;;) { if (pit_flag) { /* timer interrupt occurred */ pit_flag = 0 ; count++ ; if (count >= interval) { count = 0 ; measure(&mV, &mA) ; print_csv(mV, mA) ; } } } } inline int is_delimiter(uint8_t c) { int result = 0 ; switch(c) { case CR: case LF: case TAB: case SPACE: result = c ; break ; } return( result ) ; } void init_hardware(void) { UART_ClearRxBuffer() ; uart_rx_int_ClearPending() ; uart_rx_int_StartEx(uart_rx_isr) ; UART_Start() ; timer_int_ClearPending() ; timer_int_StartEx(timer_isr) ; Timer_ReadStatusRegister() ; Timer_Start() ; ADC_Start() ; CyGlobalIntEnable; /* Enable global interrupts. */ } void splash(void) { sprintf(str, "\nTimer Test (%s %s)\n", __DATE__, __TIME__) ; print(str) ; } void print(char *str) { UART_PutString(str) ; } void prompt(void) { print("> ") ; } int get_string(char str[]) { int result = 0 ; static int str_index = 0 ; if (rx_read_index != rx_write_index) { if (is_delimiter(rx_buf[rx_read_index])) { str[str_index] = 0 ; str_index = 0 ; result = 1 ; } else { str[str_index] = rx_buf[rx_read_index] ; str_index++ ; if (str_index >= STR_LEN) { str[STR_LEN] = 0 ; str_index = 0 ; result = -1 ; } } rx_read_index = (rx_read_index + 1) % RX_BUF_LEN ; } return( result ) ; } =============== Tera Term log Serial Plot Settings After disconnecting Tera Term, Data Format Plot (Note: I unchecked date and time ) The displayed result Getting log from Tera Term After disconnecting Serial Plot Select Menu: File > Log ... Specify log file It can be anywhere in your system with any name, but I chose log_190616.csv After logged a little I stopped Tera Term then located and opened the log file Excel showed following (I adjusted the width of columns) Attached is my sample project using CY8CKIT-059. moto
https://community.cypress.com/message/199196?tstart=0
CC-MAIN-2020-05
refinedweb
1,873
59.43
Subject: Re: [boost] [RangeEx] Range & RangeEx From: Neil Groves (neil_at_[hidden]) Date: 2008-09-12 08:28:33 On Fri, Sep 12, 2008 at 1:13 PM, Robert Jones <robertgbjones_at_[hidden]>wrote: > RangeEx appears to have the functionality I'm seeking, which is the > std algorithms > overloaded for ranges, but there's few things I'm not clear about. > > I've downloaded the range_ex.zip archive from the vault, but I'm not clear > if it replaces or extends Boost.Range. Am I now able to write things like > I intend the Boost.RangeEx proposal to replace Boost.Range. > > #include <vector> > #include <iostream> > #include <iterator> > #include <boost/range.hpp> > > void f( vector<int> const & v ) > { > using namespace std; > using namespace boost; > copy( v, ostream_iterator<int>( cout, " " ); > } This sort of thing should work, but of course it's missing closing parenthesis as posted. If you have any problems at all please let me know so that I can remedy them. I'm not getting much feedback suggesting bugs, but I am getting some feedback suggesting possible improvements to performance particularly with respect to the range adaptors and chained range algorithms. I hope this helps, Neil Groves > > _______________________________________________ > Unsubscribe & other changes: > > Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2008/09/142252.php
CC-MAIN-2021-49
refinedweb
221
64.91
Python Style Guide From OLPC Note: this document is still being discussed, and is not authoritative for the OLPC project. Also, no code has been updated to fit this style guide. No code should be updated until this is finalized. Introduction This document gives coding conventions for the Python code in the One Laptop Per Child project. This document was adapted from Guido's original Python Style Guide essay, with some additions from Barry's style guide. This guide was then modified from PEP 8 by Ian for One Laptop Per Child, to cover additional issues that are present in that environment and to make some of the language stronger.). A Note On Consistency When you are interfacing with another library and providing a Python wrapping for its functions, you should always adopt the naming style of that library. If a library is maintained or authored outside of the OLPC project, you should respect the style guidelines of that library when making edits or additions. If you are changing the style of a piece of code, this should be done all at once and no other changes should be made at the same time. Whitespace changes in particular should be done separate from even naming changes. Code lay-out Indentation Use 4 spaces per indentation level. Do not use tabs. - The number of spaces used can be easily changed with a script. I think we should give serious consideration to reducing this to 2 spaces per indentation level to minimize the number of line breaks needed and also minimize the whitespace on a screenful of code. Admittedly, lots of people, using 19 and 21 inch monitors, currently use a 4-space standard, but that can be easily fixed with a simple script. Python has a builtin parser module that can be used to do this. If all the code lives in a repository such as SVN, then this can be done as part of the code check-in process without anyone needing to think about it. However, the end-users of the laptop, working on their small screens, will thank you for it. Maximum Line Length. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended.") Blob.__init__(self, width, height, color, emphasis, highlight) Assert statements in particular tend to go over the line boundaries; so generally asserts should look like this: assert value is not None, ( "value should not be None") Blank Lines Vertical whitespace (blank lines) are not that important to readability. For the most part this can be left to the developers discretion. As a general guideline: -. Encodings (PEP 263) [note: this diverges from PEP 8] Python source for the OLPC must contain a Unicode UTF-8 encoding declaration, which looks like: # coding: UTF8 Only UTF8 should be used even if you are not using non-ASCII characters in your code. The reason is to make it easy for others to take up any Python file, make modifications and add comments in their own language. As a special case a file with the UTF8 signature '\xef\xbb\xbf' at the beginning of the file will be detected by Python as a UTF8 file. Do not use or rely on this signature since some editors will remove it. Always include the UTF-8 encoding declaration. Note that you cannot use unicode in any identifiers in Python; the encoding only applies to Unicode strings like u"a string" and comments. Long strings of text (that are not English) should be in localization files, not in the code itself. Files produced by OLPC should generally be UTF8-encoded Unicode. Even simple things like config files should be read and written as UTF-8. Imports Imports should usually be on separate lines, e.g.: Yes: import os import sys No: import sys, os it's okay to say this though: from subprocess import Popen, PIPE [note: this is a soft requirement]. [note: I don't care about the blank line, and consider the ordering to be only a suggestion] Put any relevant __all__ specification after the imports. Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. If or until we settle on Python 2.5 we cannot use PEP 328, and so cannot do explicit relative imports. "from x import *" is generally discouraged. You should only import this way from packages that are intended to be used like this (the packages generally define __all__). You should never use "import *" more than once in a file. If you use it more than once then there is no way to know (without leaving the file) exactly where a name comes from. So long as "import *" is used just once, one can assume when no other source can be found for a name that it must come from this import." [note: I hate "import foo.bar.yourclass" and prefer just "from foo.bar import yourclass" or "from foo.bar.yourclass import YourClass"; this note should probably be changed.] In summary A file should generally look like this: # -*- coding: UTF8 -*- (MUST always be used) """ docstring: may also be a unicode or 'raw' string If you are using doctest then a raw string is recommented (prefix the string with an r) [are unicode strings generally preferred for docstrings? that would give a prefix or u or ur] """ from __future__ ... import stdlib modules import external modules import internal modules __all__ = [...] # If you use __all__ constants... functions and classes... __init__.py Files __init__.py files should generally contain no substantive code. Instead they should import from other modules. Importing from other modules is done so that a package can provide a front-facing set of objects and functions it exports, without exposing each of the internal modules in the package. Note however that this causes the submodules to be eagerly imported; if this is likely to cause unnecessary overhead then the import in __init__.py should be reconsidered. Whitespace in Expressions and Statements Pet Peeves [note: if you do not put a space after a comma, it is harder to visually distinguish . from ,; e.g., foo(a,b) and foo(a.b). Please use spaces after commas!] [note: I'm soft on this one, though less soft on the others] Other Recommendations Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not). Use spaces around arithmetic operators:) [note: this is really helpful to make the code more readable; please use this convention. Keyword arguments aren't assignments, and this makes that visually clear.] Compound statements (multiple statements on the same line) are strongly discouraged. Yes: if foo == 'blah': do_blah_thing() do_one() do_two() do_three() Rather not: if foo == 'blah': do_blah_thing() do_one(); do_two(); do_three() Don't be lazy, just hit enter! if/else expressions and list comprehensions should not be deeply nested. [this needs some examples] Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes! Comments should go before the thing they are commenting on, like: # match will be the regex match object: match = None Or sometimes inside an if statement or other control structure: if match is None: # None of our attempts to match worked raise ValueError("Nothing matched!") If a comment is short, the period at the end can be omitted. Block comments generally consist of one or more paragraphs built out of complete sentences, and each sentence should end in a period. Regardless of the language you use, you should write clear and easily understandable sentences. If you use English, many readers will only understand basic English. If you use your native language, many readers will be children who are still learning their language. When choosing the language for comments, think of who will have to read these comments. If you are writing code that will be used by people in many countries, then English is probably the best choice. But sometimes, this is useful: x = x + 1 # Compensate for border Generally comments on separate lines are easier to edit: # Compensate for border: x = x + 1, and preferably preceded by a blank line, e.g.: """Return a foobang Optional plotz says to frobnicate the bizbaz first. """ For one liner docstrings, it's okay to keep the closing """ on the same line. Avoid using ''' for docstrings. Naming Conventions: Wen. Do not abbreviate names by removing vowels. Instead truncate the name. Yes: func decl No: fnctn dcln [note: these aren't very good examples, because they are just *too* ugly to be plausible...] Module Names Modules should have short, lowercase names, without underscores. This naming convention distinguishes modules from both functions and classes. This is important; consider this example from Zope 2: from DateTime.DateTime import DateTime In Zope 2 the DateTime package contained a DateTime module with a DateTime class. As a result when you see "DateTime" in the source you can't be sure if it's referring to the package, module, or class. If the module had been named datetime it would be obvious when you were referring to the module and when you were referring to the class. Similar confusion can exist with functions, which is the motivation for leaving underscores out of module names (but using them in function names). When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket). Like modules, Python packages should have short, all-lowercase names, without underscores. Class Names Almost without exception, class names use the CapWords convention. Classes for internal use have a leading underscore in addition. Exception Names Because exceptions should be classes, the class naming convention applies here. However, you should use the suffix "Error" on your exception names (if the exception actually is an error). [note: I find the Error suffix to often be redundant, but maybe it is best to use] the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public"). Many modules are not really intended to be used with "from M import *" and will export many unintended objects (like other modules). Generally you should not use "import *" unless a module is intended to be used like that, and the presence of __all__ is a good indication if a module is intended to be used that way. Function Names Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py). Function and method arguments Always use 'self' for the first argument to instance methods. Always use 'cls' for the first argument to class methods. Always use 'metacls' for the first argument to metaclass method. These are technically class methods of the metaclass, but if you don't distinguish metaclasses from classes you will confuse readers terribly. If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus "print_" is better than "prnt". (Perhaps better is to avoid such clashes by using a synonym.) Method Names and Instance Variables Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability. Use one leading underscore only for non-public methods and instance variables. Do *not* use two leading underscores. Python mangles these names with the class name: if class Foo has an attribute named __a, it cannot be accessed by Foo.__a. (An insistent user could still gain access by calling Foo._Foo__a.) If you have some reason to want to avoid name clashes in subclasses, you should use *explicit* name mangling by using an explicit prefix in front of your attributes or functions, like Foo._Foo_a. Designing for inheritance [note: this is rather complex; generally I think designing for inheritance should be avoided except in specific cases where it provides real benefits. In many cases first class functions and other techniques are easier to understand and manage than subclassing.]. Programming Recommendations Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Pyrex, Psyco, and such). For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a+=b or a=a+b. Those statements run more slowly in Jython. In performance sensitive parts of the library, the .join() form should be used instead. This will assure that concatenation occurs in linear time across various implementations. [note: I think we can be softer about this, as we need to target more than just CPython but the performance characteristics of our particular software and hardware stack.] Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators. Note is and is not compare the identity of an object. == can be overridden and does more complex comparisons, and so there is a small performance penalty. There is and only will ever by one None. class-based exceptions. String exceptions in new code are strongly discouraged, as they will eventually (in Python 2.5) be deprecated and then (in Python 3000 or perhaps sooner) removed. Modules or packages should define their own domain-specific base exception class, which should be subclassed from the built-in Exception class. Always include a class docstring. E.g.: class MessageError(Exception): """Base class for errors in the email package.""" Class naming conventions apply here, although you should add the suffix "Error" to your exception classes, if the exception is an error. Non-error exceptions need no special suffix. [note: this is a strict requirement in OLPC] When raising an exception, use "raise ValueError('message')" instead of the older form "raise ValueError, 'message'". The paren-using form is preferred because when the exception arguments are long or include string formatting, you don't need to use line continuation characters thanks to the containing parentheses. The older form will be removed in Python 3000. [note: also a strict requirement for OLPC] Use string methods instead of the string module. String methods are always much faster and share the same API with unicode strings. Override this rule if backward compatibility with Pythons older than 2.0 is required. [note: we can be strict here. string.Template is an exception, which is the only reason the string module should be used at all.] Use .startswith() and .endswith() instead of string slicing to check for prefixes or suffixes. startswith() and endswith() are cleaner and less error prone. For example: Yes: if foo.startswith('bar'): No: if foo[:3] == 'bar': The exception is if your code must work with Python 1.5.2 (but let's hope not!). [note: clearly we don't] Object type comparisons should always use isinstance() instead of comparing types directly. Yes: if isinstance(obj, int): No: if type(obj) is type(1): When checking if an object is a string, keep in mind that it might be a unicode string too! In Python 2.3, str and unicode have a common base class, basestring, so you can do: if isinstance(obj, basestring): In Python 2.2, the types module has the StringTypes type defined for that purpose, e.g.: from types import StringTypes if isinstance(obj, StringTypes): In Python 2.0 and 2.1, you should do: from types import StringType, UnicodeType if isinstance(obj, StringType) or \ isinstance(obj, UnicodeType) : [note: obviously we can just use basestring; though we need to be careful about distinguishing str and unicode. It is valid and perhaps preferred for us to be careful in distinguishing these two values. assert isinstance(value, unicode) is probably an assert we should use liberally]. [note: this only applies to multi-line/triple-quoted strings] Don't compare boolean values to True or False Using: Yes: if greeting: No: if greeting == True: Worse: if greeting is True: Strings and Unicode Generally there are three types of strings: - 8-bit strings ("str") that contain binary data - Unicode strings that contain textual data - Encoded strings, represented as 8-bit strs, that contain textual data The third form can cause problems. Python is encoding agnostic; the only encoding it does automatically is ASCII. When using ASCII text, an encoded and unicode string look very similar; they compare as equal, they hash to the same value, and str() and unicode() will convert cleanly between the two. Once non-ASCII text is introduced this all breaks. We should avoid encoded strings when possible. When we expect to receive unicode strings, it is acceptable and even encouraged to do "assert isinstance(value, unicode)". Internationalization and Localization If you are writing code for use in many countries then all user-visible strings should be in English and should be translatable. You do this like so: from gettext import gettext as _ import getpass print _("Hello %(name)s!") % {'name': getpass.getuser()} Note that string substitutions should be done after the translation via _(). Also, named values should be used. You may find string.Template preferable to %-based substitution; you can use it like: import string print string.Template(_("Hello $name!")).substitute(name=getpass.getuser()) There's a long document on internationalizing Pylons, most of which applies to any Python i18n code. [Q: are there translation domains? How does activity translation work? Are we going to monkeypatch gettext.gettext to make it work like we want for activities?] [Q: what about dates and other localized values?] [Q: Should we prefer string.Template over % substitution?] Testing The Testing Tool Taxonomy provides a long and comprehensive list of test systems available for Python. There's three core packages that can be used for testing: doctest doctest is a standard library module, and a testing system. It's probably the simplest test system to use and read. This is a common pattern for testing a package: if __name__ == '__main__': import doctest doctest.testmod() doctest.testfile('test_this_module.txt') While this works, it's very easy to forget to run tests after making changes. It's also easy to forget to test for regressions. Because of this, you should provide a way to run all of your tests. Note that you can put tests in your file's docstrings, or in an external text file. For tests that don't have documentation value an external text file is best (it won't clutter your source or the helpful information in your docstrings). For extended examples external files are also best; inline docstring doctests are mostly best to simply confirm those examples are correct, not to do extensive testing of your routines. unittest unittest is the "standard" standard library testing module. It is modeled after SUnit, JUnit, etc. Tests using this tend to be somewhat long-winded, and not very readable (this is Ian's personal opinion, but he holds it very strongly). When a project is already using unittest, you should use it for new tests to maintain consistency. Note that doctest can produce unittest-compatible tests. When creating new tests, seriously consider using doctest, as the resulting tests are usually much more readable. This is less true for tests that contain considerable logic (especially things like stress testing, or using fuzzed input). If you are using unittest-based tests you should provide a test runner as part of your code; this is a script that will run all the tests in your code. While some people use the same kind of __name__ == '__main__' trick for unittest that they do for doctest, this is not desirable (for all the same reasons). nose nose is a (non-standard) library/script for finding and running tests. It is based on unittest, and provides the tests collection that the other two modules are missing. It also can run doctests directly (without having to explicitly wrap them as unittests) and has some improved features over typical unittest test runners (like showing detail about failed assertions, and dropping into a debugger on failure). It has features very similar to py.test, but is easier to install and is more compatible with unittest-based tests than py.test. Nose also lets you use simpler tests than unittest's class-based tests. Functions with names starting with test_ will be run If you use this test runner, it is recommended that you include a shell script or Python script to run nose with your project; this will make it easy for other developers to see how you run your tests. File names Except for embedded doctests, tests should generally go in files separate from the module they are testing. This way importing the module will not load the tests and won't add any overhead unless you are actually running the tests. Tests should be named test_modulename.... You can add more to the name if you have multiple files associated with one module. Use .py for Python-based files (of course), and .txt for external doctests. Tests are sometimes put in a subpackage called tests (note that test is unfortunately used by a very boring standard library module, and it can lead to confusing situations if you use that name). It's also fine to simply put tests right beside the modules they test. External doctest files that have documentation value should be named the same as the module (with .txt), and should not have a test_ prefix; their primary value is not the testing they do, but the information they convey. Ideally all programmer documentation will use doctest, so that the accuracy of the documentation can be easily confirmed. Documentation All documentation should be provided as in an e-book format readable by Evince, the OLPC e-book reader. In particular, avoid supplying a directory tree of HTML files. Consolidate these together in a single document. One possibility is to use something based on TiddlyWiki. This is based on using Javascript to have a tree of many small documents inside a single HTML file. Since the OLPC uses xulrunner it supports Javascript in HTML. File Layout [The file layout for Python packages is pretty clear. However, where should other files go? For example, should images go beside Python code? And other declarations, like XML and the activity info file] Distribution [Something about distutils, setup.py, setuptools, etc. Should we have a single author, an author list? Should the author email point to a support address or developer discussion list?] Deprecations and Warnings When other people use code of your, you will have to support them as you update your code. Even if you mark your package as being "version 0.1", it doesn't matter -- if your code is useful, and someone uses it, then you'll need to start thinking about backward compatibility, or else make life difficult for your users. Deprecations and warnings are specifically meant to deal with this. Warnings should seldom go in new code. For instance, you could do: def send_content(dest, data): if not isinstance(data, str): warnings.warn('You should only send str data') data = str(data) But because there are no current users (if this is new code), this should simply be an error: def send_content(dest, data): assert isinstance(data, str), ( "data should be a str, not %r" % data) Then callers will see this error and call str(data) on their end, removing any potential ambiguity. When you want to use warnings is when in the past you've allowed non-str data, and you want to change that. There is no firm rule about when you should simply turn something into an error, and when you should provide warnings. If you provide a warning, it should be in this form: import warnings def send_content(dest, data): if not isinstance(data, str): # Deprecated since 2005-05-01 warnings.warn('send_data(dest, data=%r) should only be passed a str value for data', DeprecationWarning, stacklevel=2) data = str(data) DeprecationWarning is a category of warnings. You can disable warnings by category, or turn them into errors. stacklevel=2 means that the bad behavior happened at stack level 2 (the immediate caller of this function). This will show the caller's filename and line number in the warning. You might have to increase this number if you are using more indirection in your code. Including the date of the deprecation in a comment makes it easier to determine when the deprecated usage should be turned into an error (after some time one can assume all callers have fixed their code). When a function has been moved or removed, you should start with a warning and then turn it into an error like: def send_content(dest, data): # Moved on 2005-07-10 raise NotImplementedError( 'The send_content function has been moved to mypkg.content_sending.send_content') You should not simply remove a public function; by putting in an error you tell callers exactly how they should update their code. Like warnings, these should eventually be removed. There should always be a stage where you make it an explicit error, as some users may ignore warnings entirely until it is turned into an error. str, unicode, and repr There are three ways to coerce an object to text: str(obj), unicode(obj) and repr(obj). str coerces an object to its non-unicode textual representation. Though this is very commonly used, unicode(obj) should be preferred as it creates unicode text. As an example, here's code that can cause a problem: class User(object): def __init__(self, name): self.name = name def __str__(self): return 'User %s' % self.name u = User(u'Iñtërnâtiônàlizætiøn') # This works fine: print repr(unicode(u)) # This won't work: print str(u) # This won't work either: print u # This won't work either: 'Hi ' + str(u) So what happened there? Well, self.name was a unicode string. When you do 'User %s' % self.name it returns a unicode string as well (str strings are turned into unicode when used with % -- this itself is a little scary). Then str() calls u.__str__(). It sees unicode, and it tries u'Iñtërnâtiônàlizætiøn'.encode('ascii') ('ascii' is sys.getdefaultencoding()). What is scary is here is that if you do your testing with this: u = User(u'Bob') then everything will work, because u'Bob'.encode('ascii') succeeds. The moral of this story? If you had implemented __unicode__ there would have been no problem. (Well, calling code could still be broken, but your code would not be broken.) So: - If you are dealing with textual data, use __unicode__ and unicode(obj). - If you are really just dealing with binary data, __str__ is okay to use, but it is usually preferable to just use another method that returns the string/binary form of the object. It is not necessary to overload every magic method just because you can. repr() The repr(obj) form (and its __repr__ magic method) are intended for Programmer representations of objects. These are handy representations that you can use to see what kind of object it is. Sometimes it is true that eval(repr(obj)) == obj, but this should never be relied upon (in fact eval() should generally never be used). More to the point, the repr() of an object should show useful or interesting information about an object. It should never be confused for a textual description. It should never be shown to a user (unless that user is acting as a programmer). If you want to override the default repr() for an object (and that is encouraged!) The general form for this method is: class User(object): def __init__(self, name): self.name = name def __repr__(self): return '<%s %s name=%r>' % ( self.__class__.__name__, hex(id(self)), self.name) Note: we use self.__class__.__name__ so that subclasses won't lie about their class. We use hex(id(self)) so that two similar objects will look distinct (it is often important when there are two different objects with the same data). The id is not necessary for Value Objects. Lastly, any instance variables you want to expose are done through %r, which puts the repr() of those objects into the string. This is very helpful when, for instance, a newline is embedded in the value. Because repr() is most useful when there are bugs, you shouldn't assume all instance variables contain well formed data. It is also acceptable (especially for Value Objects) to use: def __repr__(self): return '%s(name=%r)' % (self.__class__.__name__, self.name) You should be careful that repr() return values are not too long. If you sometimes have long data in a value, you might do this: def __repr__(self): bio_repr = repr(self.bio) if len(bio_repr) > 20: bio_repr = bio_repr[:15]+'...'+bio_repr[-5:] return '<%s bio=%s>' % (self.__class__.__name__, bio_repr) Portions of this text are from PEP 8 are in the public domain. Other portions are under a CC-Attribution license.
http://wiki.laptop.org/index.php?title=Python_Style_Guide&oldid=36317&redirect=no
CC-MAIN-2013-20
refinedweb
4,855
64.1
13 August 2010 16:17 [Source: ICIS news] LONDON (ICIS)--Sasol-Huntsman has restarted its maleic anhydride (MA) plant at ?xml:namespace> Originally expected to last 10 days, the company stopped production at the plant on 9 August and restarted it during the evening of 12 August, the source said. “Everything went well and today our plant is running at full capacity,” the source added. Sasol-Huntsman shut down the plant as part of necessary construction to bring on stream 45,000 tonnes/year of capacity in January 2011. The plant’s current capacity is 60,000 tonnes/year. For more on maleic anhydride
http://www.icis.com/Articles/2010/08/13/9385158/sasol-huntsman-restarts-moers-ma-plant-ahead-of-schedule.html
CC-MAIN-2015-22
refinedweb
104
55.54
Introduction Javascript is usually considered as an untyped or weakly-typed language. I will not go into the discussion about this topic in this article. You can check out for example this StackOverflow thread for more information. We currently cannot prove the correlation between using statically/dynamically typed languages and number of defects in the system, but there are some evidences that errors occur less when using statically typed language. You can go more deeply into the topic in the following study. In addition statically typed languages can offer smart tooling integrated in your IDE, which enables you to perform more complex autocompletion and linting. Javascript is one of the most widely spread and demanding language. You can use it for frontend, backend or even mobile development. Javascript has definitely a lot of advantages, but as it is untyped it does not support static typings by default. Fortunately, we can enhance the Javascript language using the following tools to add static typings to our project: Flow is open-sourced by Facebook and we are able to perform type checking with a Flow server while coding. On the other hand, TypeScript is maintained by Microsoft. TypeScript is older then Flow and seems to me that the ecosystem is much better. TypeScript has better support with typings for more libraries, especially on the backend. In this article we will use solely TypeScript in our examples. Model example of manual static typing for GraphQL queries Let’s first take a look at how to define our static typings manually. We will start with this simple schema: type Subscription {id: ID!email: String!}input SubscribeInput {email: String!}type Mutation {subscribe(input: SubscribeInput!): Subscription!}type Query {subscriptions: [Subscription]} We would like to fetch the list of subscribed users. If you have your development server running you can move to GraphQL Playground. We can then execute the following GraphQL document: query getSubscriptions {subscriptions {id}} Now if you use our example repository. Let's say we would like to include generate our TypeScript types each time we change our GraphQL schema and propagate these changes to your development workflow, so that you can use it directly in your frontend components We can execute this query in GraphiQL and we will receive something like this {"data": {"subscriptions": [{"id": "02b7d240-0d44-11ea-bbff-1b2383f1b30b","email": "david@atheros.ai"}]}} Then we will start writing our TypeScript type definitions. We will first need to manually check the schema so that our definitions are in sync with the data from the GraphQL server. We can write the definition for Subscriptions query as follows: export interface Subscribe {id: string;email: string;}export interface GetSubscriptions {subscriptions: Subscribe[];} We need to manually check our schema to see what each type represents so that our static typings are in sync. Let’s say we want to add the required field source that will be typed as an enum value. The updated Subscription type in SDL (Schema Definition Language) will then be as follows: enum SourceEnum {ARTICLEHOME_PAGE}type Subscription {id: ID!email: String!source: SourceEnum!} In order to fetch this field we will need to update our GraphQL query as well: query getSubscriptions {subscriptions {idsource}} But what about our typings? We need to update the affected typings wherever they are being used. I believe that the biggest trade off for static typing is the increased time for development, the duplication of data structure and the possible friction that can occur with versioning our APIs. We cannot only update our code; we also need to add our typings manually and then update them after each change. It can lead to wrong typings and false errors if developers do not sync up immediately. These problems can be solved with automatic generation of types with GraphQL. Our GraphQL gateway will serve as our single source of truth, and static typing will be synced immediately on both the frontend and backend. How would we achieve that with GraphQL? So now that we have talked about adding typings in our TypeScript code manually, how can GraphQL help us automate that? As we mentioned, one of the biggest problems when defining typings is that the manual static typing can get too time-consuming and it is hard to keep everything in sync through versioning. We could already notice the connection between GraphQL type system and either the TypeScript or Flow type systems. GraphQL’s type system is strongly typed, and we can perform transformations from GraphQL type system to TypeScript type systems. To get a better idea of how this works in practice let’s visualize how to transform the GraphQL types into TypeScript types. First let’s take a look at this graph We will first define our GraphQL schema on our server. Then we need to generate static typings on the frontend to type the results and arguments for queries and mutations. We also need to generate separate static typings on the backend for our resolvers. Every time our GraphQL schema changes we also need to update our affected static typings. The GraphQL gateway is now the single source of truth for typings, but in order to remove the friction between definitions we need to introduce automation. This way we will not have to keep everything in sync manually. Generating types on the frontend with GraphQL CodeGen Let’s generate TypeScript types for our responses from the GraphQL server. We will use a library called GraphQL CodeGen. We will use our example repository. In order to execute the code you can clone the repository with git clone git@github.com:atherosai/next-react-graphql-apollo-hooks.git install dependencies with npm i and start the server in development with npm run dev GraphQL CodeGen yaml file GraphQLCodeGen works on modular bases. There is a lot of plug-ins that enables you apply GraphQL CodeGen library to many different applications. For now we will use just two plug-ins - TypeScript operations plugin: enables to generate types for mutations and queries - TypeScript plugin: generate basic types from the schema schema: 'server/schema/typeDefs.ts'documents: 'components/**/*.graphql'generates:generated/typescript-operations.ts:- typescript-operations- typescript We can see that we need to first define a way how to retrieve the information about the schema. This is done in the schema field and in our case we used typeDef file, where schema in SDL is written. GraphQLCodeGen will then apply schema introspection and uses the results to generate TypeScript types. If your GraphQL server is running on port 3000, you can also perform introspection directly on the endpoint. Please note that for security purposes you should disable introspection in production; it should therefore only work in a development environment. We have also defined our path to GraphQL documents. In the example repository we store our GraphQL queries and mutations at our React component and the pattern above will validate all of them against our GraphQL schema and then generate TypeScript types for frontend. The last lines in the our GraphQLCodeGen config defines output path of the generated types and plug-ins used. If you have installed graphql-codegen globally and you are in the folder of our example repository you can just execute: graphql-codegen otherwise you can use our npm script command: npm run gen:schema This command will run a schema introspection query, take every *.graphql file that matches the specified pattern and validate it with our GraphQL schema. Based on each GraphQL file we will generate a new TypeScript types. TypeScript output and how to use it in your React components GraphQLCodeGen generated .ts, .d.ts files with types for each *.graphql requests into generated folder and we are able to import them into our React-Apollo components. Please note that for the sake of simplicity we did not implement React components in the repository. If you would like to generate Flow types or other supported types you can only change --target parameter. The following TypeScript file for the getUsers query should now be available in the queries/generated export type Maybe<T> = T | null;export type SubscribeMutationVariables = {input: SubscribeInput};export type SubscribeMutation = ({ __typename?: 'Mutation' }& { subscribe: ({ __typename?: 'Subscription' }& Pick<Subscription, 'id' | 'email' | 'source'>) });export type SubscriptionsQueryVariables = {};export type SubscriptionsQuery = ({ __typename?: 'Query' }& { subscriptions: Maybe<Array<Maybe<({ __typename?: 'Subscription' }& Pick<Subscription, 'id' | 'email' | 'source'>)>>> });/** All built-in and custom scalars, mapped to their actual values */export type Scalars = {ID: string,String: string,Boolean: boolean,Int: number,Float: number,};export type Mutation = {__typename?: 'Mutation',subscribe: Subscription,};export type MutationSubscribeArgs = {input: SubscribeInput};export type Query = {__typename?: 'Query',subscriptions?: Maybe<Array<Maybe<Subscription>>>,};export enum SourceEnum {Article = 'ARTICLE',HomePage = 'HOME_PAGE'}export type SubscribeInput = {email: Scalars['String'],source: SourceEnum,};export type Subscription = {__typename?: 'Subscription',id: Scalars['ID'],email: Scalars['String'],source: SourceEnum,}; I believe that the best way to operate is to generate type definitions every time you change your GraphQL schema. This will make your types up-to-date and you will avoid mismatches on your frontend. Now let's use our generated types for our React components in the repository. In our project we have one query for fetching subscriptions query getSubscriptions {subscriptions {idsource}} On the client we are rendering our results in the table with two columns email and source. We use Apollo client and React Hooks for our data fetching. React component is written; Apollo client is written in TypeScript so it has good support for handling your types. We are passing our generated types in the useQuery hook. Our second GraphQL operation is subscribe mutation. Our component is written as follows: /* place-holder text commonly used in the graphic, print, and publishingindustries for previewing layouts and visual mock-ups.<; In this case we used useMutation hook and again passed our generated types into useMutation function. These steps enabled us to use generated types on the client and each time we will change our GraphQL schema we will get up to date TypeScript suggestions. Generating typed-safe resolvers on your server with GraphQLCodeGen In order to generate server-side typings for your resolvers we need to use additional plugin. After updating our codegen.yaml we will get the following: schema: 'server/schema/typeDefs.ts'documents: 'components/**/*.graphql'generates:__generated__/typescript-operations.ts:- typescript-operations- typescriptserver/__generated__/resolver-types.ts:- typescript- typescript-resolvers We can generate our types again with: npm run gen:schema Now we have generated also types for our resolvers to server/generated/resolver-types.ts. We can now type all of our resolvers as follows: import { getSubscriptions, createSubscription } from '../requests/subscription-requests';import { Resolvers } from '../__generated__/resolver-types';interface StringIndexSignatureInterface {[index: string]: any;}type StringIndexed<T> = T & StringIndexSignatureInterfaceconst resolvers: StringIndexed<Resolvers> = {Query: {subscriptions: () => getSubscriptions(),},Mutation: {subscribe: async (__, args) => createSubscription({}, args),},};export default resolvers; How to take it even further? But what about not just generating static types? What about generating your own code? This is something the GraphQLCodeGen library can also accomplish with plug-ins. For our project the most relevant plugin is for React Apollo. This can help you to skip one additional manual step of creating React Apollo components for mutations and queries. Summary I believe that automatic type and code generation is one of the biggest trends in GraphQL ecosystem. We are having great ecosystem for development especially for TypeScript and GraphQLCodeGen. You can use our starter project to speed up your set-up. This will help you diminish unnecessary friction between your static typing on the frontend with the GraphQL API. You can inject the command to regenerate types after each change in your GraphQL schema files. This way you will have your types automatically in sync with your API. A further advantage is that no extra communication between backend and frontend team members is required, since frontend engineers are notified about the changes in their types. We are additionally able to validate your queries and mutations in CI to avoid deploying queries and mutations on the frontend that do not comply to the current GraphQL schema. There is definitely space for improvement in libraries, especially for server side typings, but current implementations using GraphQLCodeGen is a promising step for more efficient work-flows. I believe that automatic type generation of static types using GraphQL not only in TypeScript has a bright future. It will allow us to spend less time writing boilerplate code and updating our types and more time on shipping high-quality typed products. Did you like this post? You can clone the repository with the examples and project set-up. Feel free to send any questions about the topic to david@atheros.ai.
https://atheros.ai/blog/generate-javascript-static-types-from-graphql-typescript-and-flow
CC-MAIN-2022-40
refinedweb
2,092
54.02
Provided by: manpages-dev_4.13-3_all >>IMAGE_HUGE_2MB, SHM_HUGE_1GB (since Linux 3.8)). On success, a valid shared memory identifier is returned. On error, -1 is returned, and errno is set to indicate the error. ERRORS On failure, errno is set to one of the following: EACCES The user does not have permission to access the shared memory segment, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.-wide POSIX.1-2001, POSIX.1-2008, SVr4. SHM_HUGETLB and SHM_NORESERVE are Linux extensions. shmflg and creates a new shared memory segment. Shared memory limits The following limits on shared memory segment resources affect the shmget() call: MB). memfd_create(2), shmat(2), shmctl(2), shmdt(2), ftok(3), capabilities(7), shm_overview(7), svipc(7) COLOPHON This page is part of release 4.13 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
http://manpages.ubuntu.com/manpages/artful/man2/shmget.2.html
CC-MAIN-2019-39
refinedweb
163
58.18
Right-to-Left text - Flex 3 and 4 problems with TextFieldozDiGennaro Jun 1, 2010 5:34 PM I have an application that requires exact location of mouse clicks in text. TextField support this, but I cannot find another text class that does. The application also requires European languages and Semitic languages (right-to-left). Usin Flex 3 or Flex 4, I can display right-to-left text and find the click locations, although I have to add a workaround in Flex 3 (at least) for locating the char index from the mouse click location (x,y). Problem: If the TextField is selectable (which is desirable for my application) and the user selects text, the sequence of characters is scrambled. Problem: If the method setTextFormat is used on a subset of the characters, the sequence of characters is scrambled. Big Problem: There were verbal promises that this would be fixed in Flex 4, but it fails for me. Failing code: <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="" xmlns:s="library://ns.adobe.com/flex/spark" xmlns: <fx:Script> <![CDATA[ import mx.charts.BubbleChart; import mx.containers.Canvas; import mx.controls.Button; import mx.core.UIComponent; var tf:TextField = new TextField(); public function creationComplete():void { tf.x = 100; tf.y = 50; tf.width = 500; tf.text = "א בְּרֵאשִׁית בָּרָא אֱלֹהִים אֵת הַשָּׁמַיִם וְאֵת הָאָרֶץ"; var tformat:TextFormat = new TextFormat(); tformat.size = 30; tformat.align = "right"; var l:int = tf.getLineLength(0); tf.setTextFormat(tformat,0,l); var tb:UIComponent = new UIComponent; tb.addChild(tf); var c:Canvas = new Canvas(); c.addChild(tb); this.addElement(c); var b:Button = new Button(); b.label = "switch"; b.x = b.y = 20; b.addEventListener(MouseEvent.CLICK,buttonSwitch); c.addChild(b); } private function buttonSwitch(e:MouseEvent):void { trace("button"); var tformat:TextFormat = new TextFormat(); tformat.size = 30; tformat.align = "right"; tformat.color = 0xFF0000; tf.setTextFormat(tformat,0,10); } ]]> </fx:Script> </s:Application> 1. Re: Right-to-Left text - Flex 3 and 4 problems with TextFieldFlex harUI Jun 1, 2010 10:11 PM (in response to ozDiGennaro)1 person found this helpful TextField doesn't support RTL, only TLF/FTE based controls like Spark RichText, Label, TextInput and TextArea, and full support requires Flex 4.1 which is available in the nightly builds and is scheduled to ship "soon". Inside those controls are one or more TextLines and TextLines have APIs to find characters based on x,y (the API uses the term "atoms"). 2. Re: Right-to-Left text - Flex 3 and 4 problems with TextFieldozDiGennaro Jun 2, 2010 6:26 AM (in response to Flex harUI) Thank you. I'll try out your suggestions. 3. Re: Right-to-Left text - Flex 3 and 4 problems with TextFieldozDiGennaro Jun 15, 2010 5:38 PM (in response to ozDiGennaro) I've had a lot of success with EditableRichText, with only moderate effort. It's quite pretty. However, the method var p:Point = new Point(xStage,yStage); // coordinates of mouse click in stage reference frame richText.getObjectsUnderPoint(p) does not work for me. Sometimes, I get objects returned, but not related to my textFlow (no textLines). And I often get no objects, even though the click was well within the RichText area. Do I have to move to the Beta version (4.1)? So far, I'm using only left-to-right text. Please help me determine my direction. Thanks. 4. Re: Right-to-Left text - Flex 3 and 4 problems with TextFieldGordonSmith Jun 16, 2010 2:00 PM (in response to ozDiGennaro) Interesting. Perhaps the documentation is wrong and foo.getObjectsUnderPoint() expects a Point in the coordinate system of foo rather than in global coordinates. Or do global coordinates work in other situations that don't involve RichEditableText and TextLines? Gordon Smith Adobe Flex SDK Team 5. Re: Right-to-Left text - Flex 3 and 4 problems with TextFieldozDiGennaro Jun 17, 2010 5:46 AM (in response to GordonSmith) Your answer gives me a clue to the status of the release. I felt that the documentation might not match the code, which clearly says "use a point in global (stage) coordinates". I'll try other coordinates and see. Thanks. I'll also try RTL text soon. The moment of truth. Oz 6. Re: Right-to-Left text - Flex 3 and 4 problems with TextFieldozDiGennaro Jun 17, 2010 11:09 AM (in response to ozDiGennaro) Opps. My error. I was providing the point in the wrong coordinate space. No known problems. Thanks for you help. Oz 7. Re: Right-to-Left text - Flex 3 and 4 problems with TextFieldozDiGennaro Jun 17, 2010 11:10 AM (in response to ozDiGennaro) I suspect there will be other questions when I pursue RTL in RichEditable classes. 8. Re: Right-to-Left text - Flex 3 and 4 problems with TextFieldGordonSmith Jun 17, 2010 2:22 PM (in response to ozDiGennaro)1 person found this helpful If you think the problem is likely to be in the underlying TLF library, you should ask your question on the Text Layout Framework forum at. The TLF engineers monitor that forum. If it seems to be in how Flex's <s:RichText>, <s:RichEditableText>, <s:TextInput> or <s:TextArea> use TLF, then ask it here in the Flex forum. Gordon Smith Adobe Flex SDK Team 9. Re: Right-to-Left text - Flex 3 and 4 problems with TextFieldgauravk.pandey Oct 28, 2010 4:59 AM (in response to ozDiGennaro) Hi All , Firstly i would thanks to all of you for sharing knowledge . I have one query I make a text area that is mx TextArea and a devider on divider relese i changes the width of text Area. Within the text area i have rtl text which direction is set as "RTL". now my question is if the width of text area is not sufficent to accomedate a complete line of text then how that mx textArea resize the text to fit the text into that text area. Any help on this would be highely appreceated. Thanks & Regards Gaurav Kumar Pandey 10. Re: Right-to-Left text - Flex 3 and 4 problems with TextFieldozDiGennaro Jan 13, 2011 2:14 PM (in response to gauravk.pandey) I have moved on to using TextFlowLayout. All problems are solved there. I recommend it. Use Flash Builder Hero, since it support TLF 2.0 out-of-the-box. The InlineGraphics support several valuable attributes, including float="left" etc. Beautiful.
https://forums.adobe.com/thread/651099
CC-MAIN-2018-30
refinedweb
1,090
67.55
Windows Phone 8: Networking, Bluetooth, and NFC Proximity for Developers - Date: October 31, 2012 from 1:45PM to 2:45PM - Day 2 - B92 Nexus/Normandy - 3-047 - Speakers: Tim Laverty - 29,708 session on connecting Windows Phone applications using the new API's. Great content. Could you put your demo source somewhere we can take a look. Thanks @snekithan, Tim has now posted his samples for this session, here: Hi, Indeed a great presentation on Windows Phone 8 Networking. Just need to ask you that since IPv6 is now supported on Windows Phone, can it be also used at socket level to communicate to remote server over IPv6, as well as creating listening sockets over IPv6? Waiting for reply... Thanx Uday Gupta @Uday- you can use IPv6 to create/listen/accept w/ sockets. In my samples I use IPv4 but don't need to. Code samples are posted here:. How to create httpclient in WP8 C++ ? Hi know where i can get samples for PBAP sample for WP8 Bluetooth So what about Bluetooth Low Energy / Smart??? It's really REALLY needed for a lot of serious accessories. Right now only iOS got support for it, not quite a big enough market. Please add it as soon as possible! Android at least HTC are coming soon with API's as well. The video talks about socket communication between connected apps on different devices. Can I use sockets for the following scenario: 1. Use Winsock/Managed/WinRT sockets to communicate between ISV Application and OEM services which runs on the same device? 2. What is the best way to communicate between Foreground ISV application and service (OEM service) which runs on the same device? 3. Can I use sockets in the background agents to communicate with foreground application? When I try to build above given code sample , follow error is generated Error 5 The type or namespace name 'CWinsockListener' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Shafiq\Downloads\Windows Phone 8 Networking Samples\C#\SimplePhoneSocketListener\SimpleSocketListener\MainPage.xaml.cs 36 39 SimpleSocketListener Please help I am trying to run this sample without windows phone via emulator in 2012 visual studio. It is not going to run. please guide me about steps needed to build this app via emulator Remove this comment Remove this threadclose
http://channel9.msdn.com/Events/Build/2012/3-047
CC-MAIN-2014-35
refinedweb
391
64.41
Dj. Why Django? Why Not X? As stated above, Django follows the batteries included philosophy. PHP frameworks such as Code Igniter try and strip all of the "unnecessaries" out for maximum performance; but Django can include all of these out of the box and still be high performance because of its modular design (If you don't call include feature XX then it isn't included; so it doesn't slow the script down). Here are some of the most notable features: - User/Authentication system - Automatic RSS generation - GIS - Automatically generated Admin interface - Generic views (more on this later) - Three level caching system - Powerful template system MTV Django runs on an MTV (Model Template View) system (Not the television channel). This is different from MVC. - Model. The model sets out the schema for our database. Unlike PHP frameworks, you don't write your queries here. Using Django's ORM you declare the fields, field types and any additional data such as Meta information. - View. In the View, you set all of your code logic. You may need to pull some results from the database or manipulate some strings. The view expects a request and a response. The response is typically an http redirect, http error (404), or a call to load a template. When loading a template you usually pass some data through - most likely, results from a database query. - Template. The template is the plain HTML code with Django's custom Template 'language' (similar to smarty) in it. You look and iterate just like you would with any other language. Creating Our To-Do List We are going to create a very simple application, a to-do list, to showcase how to get started with Django. We'll use the automatically generated admin interface to add, edit and delete items. The ORM will be used to query the database. The view will pull get the to-do items and pass them onto the template where they are shown. I'm going to assume you have Django installed and running. First, we need to create our project. To do this, we need to use the command line. django-admin.py startproject todo That should have created a directory called todo. Go into that directory. (cd todo) manage.py startapp core Yours should look similar to the image below. Now that we have created the project, we need to input some settings. Open up todo/settings.py with your favorite text editor. Django supports a wide range of databases - MySQL, Postgres and Oracle, to name a few. Since we are only developing, we are going to use SQLite. SQLite only requires the name of the database to be specified. Change Line 12 to: DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. Change Line 13 to: DATABASE_NAME = 'to-do.db' # Or path to database file if using sqlite3. With the database set up. we only need to do a couple more edits in the settings file. On line 69, we need to set a full path to the templates directory where all of our HTML templates will be stored. Create the directory in /todo/core/ and then specify it on line 69. My template directory and installed apps tuple: Finally, we need to add our application and the admin application into the INSTALLED APPS tuple. So on line 81, insert: 'django.contrib.admin', 'todo.core', After 'django.contrib.sites', That's it for the settings.py file. Model Now we need to specify our model. Open /todo/core/models.py with your text editor. As I said above, models define the structure of the database. There's no need to run raw CREATE TABLE.. SQL queries, Django can do all of this for us. We just need to specify what we want. Since its a to-do list - each to-do will have a title, some content, and the date it was published. It's very easy to represent this in Django. from django.db import models class todo(models.Model): #Table name, has to wrap models.Model to get the functionality of Django. name = models.CharField(max_length=100, unique=True) #Like a VARCHAR field description = models.TextField() #Like a TEXT field created = models.DateTimeField() #Like a DATETIME field def __unicode__(self): #Tell it to return as a unicode string (The name of the to-do item) rather than just Object. return self.name Now that we have defined the database, we need to tell Django to sync all of the tables. We can do this by calling the syncdb command in the command line. Open up the command line and navigate to todo/. manage.py syncdb You should get some output for the tables created, as well as a prompt for creating a super user. Create the user and make a note of the username and password, as we'll use them to login to the admin area. For this tutorial we are going to use Django's test server to test our application. It is strongly advised that you do not use the test server in deployment, but instead use apache + mod_python or FastCGI. To start the test server, we again call manage.py but with the argument of runserver. We can additionally provide a port for it to run on. By default it runs on port 8000. manage.py runserver 9090 To view the results we can go to . todo/urls.py Now we need to set up our URLs. Unlike PHP all URLs in Django are routed. That simply means we specify them ourselves. If a user tries to navigate to a page that isn't set, it simply returns a 404. Since this is a simple to-do application, we only need to set one URL, the index page. We are also going to enable our admin panel so that we can add, delete and edit our to-do items. from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), #Lets us access the admin page (r'^$', 'todo.core.views.index'), #Our index page, it maps to / . Once the page is called it will look in /todo/core/views.py for a function called index ) The final thing we need to do before we can use the admin panel is to register the model with it. Create todo/core/admin.py and set the contents to: from django.contrib import admin #Import the admin from models import todo #Import our todo Model. admin.site.register(todo) #Register the model with the admin Now that the URLs are set, the database is synced, and the model is registered, we can access our administrator panel. Start the test server if it isn't already and navigate to . Login with the super user details you created. You can see under the core heading there is "todo" - the name of the model. By clicking on this, we can see all of the "to-dos" we have made. The admin interface for making new to-dos is below. Now that creating, updating and deleting the to-do items are finished, all we need to do is display them. If you navigate to you will see an error saying that "the view called index does not exist". Remember - in the urls.py file, we specified that if the user visited the index, then it would load /todo/core/views.py with the function index()? We're going to specify that now. We write index() just like any other Python function, except it has to accept a request and return a response. from models import todo from django.shortcuts import render_to_response def index(request): #Define our function, accept a request items = todo.objects.all() #ORM queries the database for all of the to-do entries. return render_to_response('index.html', {'items': items}) #Responds with passing the object items (contains info from the DB) to the template index.html Now all that's left is to create our template in the todo/core/templates/ directory. In this template, we want to iterate through all of the items (in the object items) and display them on the page. All of the Django logic is wrapped with curly braces; if it's a variable, then it is wrapped with two curly braces. <h2>todo</h2> {% for x in items %} <p>{{ x.name }} - {{ x.created|date:"D d M Y" }}</p> <p>{{ x.description }}</p> <hr /> {% endfor %} You're finished! Add a few to-do items in the admin panel, and then go to . Your layout should look similar to the image below. Further Reading I encourage you to learn more about Django if you're intrigued. Feel free to tweet me with any questions that you might have.
http://code.tutsplus.com/tutorials/intro-to-django-building-a-to-do-list--net-2871
CC-MAIN-2014-15
refinedweb
1,460
67.55
Red Hat Bugzilla – Bug 165932 Review Request: msmtp - An SMTP Client Last modified: 2010-11-02 12:49:48 EDT Spec Url: SRPM Name or Url: Description: In the default mode, msmtp. Why not use gnu sasl? It brings more features. Is it because gnu sasl doesn't work on Fedora? I cannot find it in fedora, if it isn't submitted somebody would have to, however... Until GNU SASL is published in Fedora, this package work and can be included IMHO. * Name is OK * Source msmtp-1.4.3.tar.bz2 is the same as upstream * The BuildRoot is the preferred one * Spec looks OK * rpmlint looks OK * File list looks OK * Seems to work fine One thing though : please change into so that the tarball can be downloaded automatically. If GNU SASL is published, please remember to update your package. Does it work with Cyrus SASL ? Thanks for the comments. "prdownloads" has been changed to "dl" in the new spec and SRPM at and I have been unable to find information on interoperability with Cyrus SASL and am inclined to believe that it is not possible. I'll be working on a GNUSASL spec file in the mean time, though it is not my forte. (assigned to myself for clarity, package already approved) Ping ? The only diff between release 2 and release 1 is the fixed source URL, so it's still approved. If you're still interested in this package, please go ahead and import it. I'm not an Extras Contributor and thus cannot commit it, but anybody who has commit access is welcome to import it. (In reply to comment #6) > I'm not an Extras Contributor and thus cannot commit it, but anybody who has > commit access is welcome to import it. You can become a contributor by going through the process outlined in. Since you submitted the package for review, this would be a good starting point. What does msmtp bring in terms of functionality that is not already supplied by esmtp (which uses libesmtp, and is available in extras)? Is it worth duplicating functionality? Also, it may be worth using the alternatives system to set this as the system mailer - see the esmtp spec for an example. But then again, given that neither msmtp and esmtp do local delivery, I wonder if this breaks things. . Any particular reason why this package is not yet imported and built ? This package is already approved and has not been imported for a long time. I am going to close this in a week if this is not imported within that time frame. And eight months later this package still isn't in. I'm removing FE-ACCEPT and closing this ticket. *** This bug has been marked as a duplicate of 243631 *** Package Change Request ====================== Package Name: msmtp New Branches: EL-5 Owners: turki Sorry about this wrong bug number.
https://bugzilla.redhat.com/show_bug.cgi?id=165932
CC-MAIN-2017-30
refinedweb
484
72.66
- Author: - zain - Posted: - March 10, 2009 - Language: - Python - Version: - 1.0 - pagination paginator filtering - Score: - 9 (after 9 ratings) This allows you to create an alphabetical filter for a list of objects; e.g. Browse by title: A-G H-N O-Z. See this entry in Yahoo's design pattern library for more info. NamePaginator works like Django's Paginator. You pass in a list of objects and how many you want per letter range ("page"). Then, it will dynamically generate the "pages" so that there are approximately per_page objects per page. By dynamically generating the letter ranges, you avoid having too many objects in some letter ranges and too few in some. If your list is heavy on one end of the letter range, there will be more pages for that range. It splits the pages on letter boundaries, so not all the pages will have exactly per_page objects. However, it will decide to overflow or underflow depending on which is closer to per_page. NamePaginator Arguments: object_list: A list, dictionary, QuerySet, or something similar. on: If you specified a QuerySet, this is the field it will paginate on. In the example below, we're paginating a list of Contact objects, but the Contact.email string is what will be used in filtering. per_page: How many items you want per page. Examples: >>> paginator = NamePaginator(Contacts.objects.all(), \ ... on="email", per_page=10) >>> paginator.num_pages 4 >>> paginator.pages [A, B-R, S-T, U-Z] >>> paginator.count 36 >>> page = paginator.page(2) >>> page 'B-R' >>> page.start_letter 'B' >>> page.end_letter 'R' >>> page.number 2 >>> page.count 8 In your view, you have something like: contact_list = Contacts.objects.all() paginator = NamePaginator(contact_list, \ on="first_name", per_page=25) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: page = paginator.page(page) except (InvalidPage): page = paginator.page(paginator.num_pages) return render_to_response('list.html', {"page": page}) In your template, have something like: {% for object in page.object_list %} ... {% endfor %} <div class="pagination"> Browse by title: {% for p in page.paginator.pages %} {% if p == page %} <span class="selected">{{ page }}</span> {% else %} <a href="?page={{ page.number }}"> {{ page }} </a> {% endif %} {% endfor %} </div> It currently only supports paginating on alphabets (not alphanumeric) and will throw an exception if any of the strings it is paginating on are blank. You can fix either of those shortcomings pretty easily, though. Very useful. I've made it unicode-safe (replace all str()with unicode()and the __repr__()with __unicode__(), iterate on chunks sorted by key instead of iterating on string.ascii_uppercase, don't use str().upper()but <obj>.upper()instead) and more complete. Working on putting objects starting with numbers or symbols (in the unicode sense) in their own chunk too. # Thanks for the snippet and thanks to HM for the unicode-ification. Said that, there are a couple of typos in the template: need ifequal instead if and p instead of page. Should be: {% ifequal p page %} <span class="selected">{{ page }}</span> {% else %} <a href="?page={{ p.number }}">{{ p }}</a> {% endifequal %} # How hard would it be to change the pagination a little to offer 26 pages, 1 per letter, instead of x pages, 25 (or y) entries per page (across letters)? Is this a good place to start, or should I be using another alg? # @datakid23 what You talking about is not a pagination but a filtration # You can look at #2025 ;] # HM, just curious if you ever finished working on your version of the code? If so, would you ever consider posting it for others to learn from? # Hi It would be good to have a configurable parameter which if specified would accordingly paginate alphabetically or in groups For example I want the whole letters to be displayed (Even return blank page if there are no objects for the alphabet searched ) # @HM it is possible to you to update the unicode stuff?? It would be nice ;) # Please login first before commenting.
https://djangosnippets.org/snippets/1364/
CC-MAIN-2017-22
refinedweb
654
58.99
Hi Thank you for requesting me First I need to know if this is a registered Partnership, or if you were just going to file 2 Schedule C's (Sole proprietor) Hi I see you stepped in Can you please tell me if this is a registered Partnership? It is a registered LLC. Supposed to file 1065. ok........what entity is it registered as? An LLC can be anything from Sole Proprietor to Partnership ok........you're a partnership Do you want to know the easiest way to do this? The best way to be compliant and legally minimize taxes. Ok......you have 2 choices. The easiest one is to cancel the EIN# XXXXX the IRS (and cancel the Partnership at the same time by telling the IRS that this is no longer a partnership) Election for Husband and Wife Unincorporated Businesses The IRS ruled a few years back that husband/wife businesses do NOT have to be a Partnership, that they could each claim their portion of income/expenses This removes your wife from having to report 40% of the income and pay SE tax You also don't have to file a separate return. You would only need to file Form 1040 (Schedule C) which is part of your Federal tax return If you decide to leave this as a Partnership, then you will file a Partnership return (The form 1065 you mentioned) and you and your wife will get a K1 showing your share of income/expenses based on the 60/40 split Since you are doing the work, you must be a General Partner, which means that you will have to pay SE tax on your 60% Your wife could be a Limited Partner (meaning she invests in the company but does not work for it, and she will not need to file any SE tax) You would have to keep track of the $ your wife puts into the company (if she purchases supplies, gave start up money, etc) You have to keep track of how much money Limited Partners put into a company because they can never take more of a loss than what they invested (or paid tax on in the years the company makes a profit) If it were me, I would use the election for husbands/wives each filing a Schedule C However, you would have to let the IRS know that the Partnership is canceled, or else they will be looking for a Form 1065 for you. This makes your book keeping much more simple, and who ever earns the money pays on the money. However, either way is "politically" correct I got the message you were typing, but nothing appeared on my end. Did you have a comment or question? Ok. Thanks for the detailed response and links. I understand the 2 choices. Do draws from the company have to be in proportion to the 60/40 split? From the partnership? No, but unless you are reimbursing someone for a company expense, the draw is considered to be income Ok. I think that answers my questions. Thanks for all the help and recommendation! You're most welcome Please come back here if you have any follow up questions Ok. This was my first time using this. I appreciate you making it a pleasant experience. I'm glad it was a pleasant experience. It helps when the customer is as informed as you are You may come back even after you rate and pay if you have follow up questions. Thanks so much! You're most welcome. Thank you very much for requesting me!
http://www.justanswer.com/tax/7ywdu-husband-wife-llc-setup-bookkeeping-business-one.html
CC-MAIN-2014-52
refinedweb
603
67.08
PHP Interview Questions – Part 5 1. What is PHP stands for?. Why is PHP-MySQL used for web Development? We use PHP-MySQL in web development because both are open source means both free to use. Both when MySQL work with PHP it gives result much faster than when MySQL work with Java/.Net/Jsp. 12. What function we used to change timezone from one to another ? I have given you a function using them we can change a timezone into another timezone. date_default_timezone_set() function Example: date_default_timezone_set(‘India’); And we use date_default_timezone_get() function to get the entered date. 13. How do you understand about stored procedure,Triggers and transaction in php? Below I have given how stored procedure,Triggers and transaction work in PHP: 1.Stored Procedure: It is combination of some SQL commands it is stored and can be compiled.Suppose that when user is executed a command than user has don’t need to reissue the entire query he can use the stored procedure.Basically main reason to use the stored procedure is that using this we can decrease the time of reissue of that query. Because work done on server side is more than the work done on application side. 2.Trigger: Trigger is a stored procedure.This is used to work stored procedure effectively.It is invoked when a special type of event comes.For effectively understand this i have given you a example. When we attach a trigger with stored procedure than when we delete a record from transaction table than will automatically work and delete the respective client from client table. 3.Transaction: Transaction is that in which particular amount of data goes from the a client to the another client.We maintain the transaction record into a table called transaction table. 14.How we can upload videos using PHP? When want to upload videos using PHP we should follow these steps: 1.first you have to encrypt the the file which you want to upload by using “multipart-form-data” to get the $_FILES in the form submition. 2.After getting the $_FILES[‘tmp_name’] in the submition 3.By using move_uploaded_file (tmp_location,destination) function in PHP we can move the file from original location. 15. How can we create a database using PHP and myqsl? I have given you a example using this you can create a database. <?php $con =mysql_connect(“localhost”,”vivek”,”vivabh”); if (!$con) { die(‘Could not connect: ‘ . mysql_error()); } if (mysql_query(“CREATE DATABASE my_db”,$con)) { echo “Database has been created”; } else { echo “Error to create database: ” . mysql_error(); } mysql_close($con); ?> 16. What do you understand about Joomala in PHP? Joomala is an content management system who is programmed with PHP.Using this we can modified the PHP sit with their content easily. 17. How you can differentiate abstract class and interface? There are some main difference between abstract and interface are given below: 1.In an abstract we can use sharable code where in the case of interface their is no facility to use sharable code. 2.In which class we implement an interface class. All method that we use should be defined in interface. Where as class those extending an abstract while a class extending an abstract class their is no need to defined methods in the abstract class. 18. What do you understand about Implode and Explode functions? The main difference b/w Implode and Explode functions is that We use Implode function to convert the array element into string where each value of array is separated by coma(,). Example: <?php $array = array(‘First_Name’, ‘Email_Id’, ‘Phone_NO’); $comma_separated_string = implode(“,”, $array); echo $comma_separated_string; ?> output: First_Name,Email_Id,Phone_No We use Explode function to convert the string value those are separated with coma(,) into array. Example: <?php $comma_separated_string = string(‘First_Name,Email_Id,Phone_No’); $array = Explode(“,”, $coma_separated_string); echo $array; ?> output: Phone_No 19. Can we submit a form without submit button? Using JavaScript we can submit a form without submit button. Example: document.FORM_NAME.action=”Welcome.php”; document.FORM_NAME.submit();//this is used to submit the form 20. Can I develop our own PHP extension?if yes,how? Yes,we can develop a PHP extension like that, Example: <? echo ‘PHP’; ?> To save this file as .php extention 21. What do you understand by nl2br()? nl2br() function is stands for new line to break tag. Example: echo nl2br(“R4R WelcomesnYou”); output: R4R Welcomes you 22.How function strstr and stristr both work in PHP? Generally, Both function strstr and stristr are same except one thing stristr is a case sensitive where as strstr is an non-case sensitive.We use strstr to match the given word from string. Syntax: syntax: strstr(string,match word) Examle: <?php $id_domain = strstr($email_id, ‘@’); echo $id_domain; ?> output: @xyz.com 23. In PHP can I get the browser properties? Using get_browser function we can get the browser properties in PHP. Example: $browser_properties = get_browser(null, true); print_r($browser_properties); 24. How we can increase the execution time of a PHP script? I have given you some function using them you can increase the execution time of a PHP script.Default time for execution of a PHP script is 30 seconds. These are, 1.set_time_limit()//change execution time temporarily. 2.ini_set()//change execution time temporarily. 3. By modifying `max_execution_time’ value in PHP configuration(php.ini) file.//change execution time permanent. 25. How we can get the value of current session id? We can get the value of our current session id by using session_id().It returns the value of our current session id. 26. How we use ereg_replace() and eregi_replace()in PHP? The main difference b/w ereg_replace and eregi_replace() is that,eregi_replace is case sensitive. Example:In eregi_replace() it think both ‘welcome’ and ‘WeLCome’ are different. where as ereg_replace() is not case sensitive. Example:In ereg_replace() it think both ‘welcome’ and ‘WeLCome’ are same. 27. Which type of inheritance exists in PHP? PHP supports Multi-level inheritance.It doesn’t support multiple inheritence.But using interface we can achieve multiple inheritance in PHP. 28. What do you understand about pear in PHP? Basically PEAR is stands for PHP Extension And Repository.PEAR is a framework and distribution system using that we can make PHP component reusable.It has huge collection of different classes.We use this for advance scripting.Example: Database,Mail,HTTP etc. 29. Tell me how to use COM components in PHP? We use COM component in PHP by using that manner, Example: <?php $objCom = new COM(�AddNumber.math�); $output = $objCom ->AddTwoNum(4,5); echo $output; ?> 30. Tell me default session time in PHP and how can I change it? The default session time in PHP is 14400.We can change it like that manner, Synatx: $session_time_Limit=”14400″; ini_set(session.gc_maxlifetime,$session_time_Limit); 31. How we use copy() and move() file uploading functions in PHP? When we use copy function it copy the file from source location to destination location and keep original file to the source location. Syntax: copy($_FILES[‘uploadedfile’][‘tmp_name’], $destination_path) Where as when we use move function it copy the file from source location to destination location and delete original file from source location. Syntax: move_uploaded_file($_FILES[‘uploadedfile’][‘tmp_name’], $destination_path) 32. How can we find out the name of the current executing file? I have given you a example that gives you the name of current executing file, Example: <?php $File_Name = $_SERVER[“SCRIPT_NAME”]; echo $File_Name; ?> 33. What is the main difference b/w include_once() and require_once() in PHP? The main difference b/w include_once() and require_once() is that, In PHP if file is not exist and specified with include_once() it gives show warning message.Where as if we specified file as require_once() it giver a fatal error. 34. what are the constant value in PHP?can we write them without $ symbol? We can’t change the value of constant.Yes,we can write constant value in PHP.Below I have given you a example: define(“CONSTANT”,”R4R Welcomes You”); echo “CONSTANT”; 35.) 36. What is session hijacking? Session hijacking is the misuse of a valid computer session. It is used to attain unauthorized and illegal access to a system. This access is attained using the “brute force” attack where in he tries multiple id’s to login in a system while the session is in progress. The most common method of session hijacking is IP spoofing where an attacker uses source-routed IP packets to insert commands into an active communication between two systems on a network and pretending itself as one of the authenticated users. 37. How session will work when we disable cookies of client browser? Session is kind of cookie who is work on server side.For working of session on server side cookies should be enable on server side and also on client side browser.But session will also work when cookies are disable on client side by using URL session passing. 38. Explain about PHP cookies? A cookie is a small piece of information that is generated by the server but stored on the client. In php $_COOKIE[‘name’] is used to access a particular cookie. 39.What is a PHP accelerator? PHP accelerator increases the speed of applications written in PHP. This boost of performance can be around 2-10 times. PHP accelerator increases the speed of the applications by decreasing parsing each and every time a PHP application runs. It depends upon factors such as time taken for execution of the PHP script and the actual percentage of the source code requested. 40.Explain about the data types in PHP? Actually we have 7 data types are there in php. 1.Integer 2.Float 3.String 4.Object 5.Array 6.Boolean 7.Resource 41. What is Object Oriented Programming? This is usually a pretty open ended question. You should understand classes (objects are instantiated classes), abstract classes, interfaces, methods, properties,inheritance, multiple inheritance as well as why OOP is helpful as compared to procedural programming. 42. In PHP what is the difference between a Class and an Interface? decided not to use an interface for cars, but then some types of cars are not forced to have a “stop” method. 43.What is MVC? jobs. Model – Usually contains data access code and all of you business logic code. View – Contains markup/design code, generally html,xml, json. Controller – Usually contains very little code, just whatever is needed to call the Model code and render the View code. 44.Explain how a PHP session works?. 45. What are some of the big changes PHP has gone through in the past few years? There are a number, but the big ones people are looking for are: a. PHP 5.0 realised the object model (AKA OOP). b. 5.1 added PDO – for accessing databases. c. 5.3 – added namespace support and late static bindings. 46.What is the difference between $_GET and $_POST This is a great question because an interviewer can tell how deeply you understand HTTP and the request/response. If you don’t have good understanding of HTTP protocol, google around and get a grasp on it. 47. In a PHP class what are the three visibility keywords of a property or method? public, private and protected. The default is public. Public -> Any class may instantiate the class and call the method or property. Protected -> Only the class itself or inherited (children) classes may call a method or property. Private -> Only the class itself may call a method or property. 48. What is Polymorphism? Don’t get scared by the big word. It’s simply the idea that one object can can take on many forms. So in PHP OOP one class “cars” may have two classes that extend it, for example a “Honda” class and a “BMW” class. 49. How do you load classes in PHP? They are trying to gauge your understanding of how class auto loading works. Review the “autoload” and “spl_autoload_register” function (note:you should us the later). The autoload function basically triggers a function when a class is instantiated, you can put whatever logic you like in it but generally you want to include the class file based on some sort of naming convention. 50. What is the value of “$day” in the below code? $wed= 1; $day = ($wed==1) ? ‘today’ : ‘tommorrow’; // $day is now set to ‘today’ Companies often ask about the ternary operator (?). which is simply a shorthand for if else statements. 51.What is the Scope Resolution Operator? “::” double colons is the scope operator it is used to call methods of a class that has not been instantiated. You should also understand static methods and how they differ from regular methods. 52. What are some PHP Design patterns you have worked with? Design patterns are simply commonly used techniques within your code, they often are implemented in different ways so they can be a bit tricky to grasp without writing them yourself. If you are unfamiliar with them I would start by learning the Singleton Pattern and the Strategy Pattern. 53. What is the difference between single quotes and double quotes? Great answer at below link. 54. What does ob_start do? Makes it so PHP does not output anything. Companies ask this because many large frameworks wrap a bunch of code in ob_start() and ob_get_clean(). So understanding how that function works is pretty important. 55. What does “&” mean in ‘&$var’ ? ‘&’ indicates a reference 56. What is the meaning of a final class and a final method? Final keywords indicates that the class or method cannot be extended. 57. Does PHP support multiple inheritance? No. You should understand what multiple inheritance is. 58. What are some magic methods in PHP, how might you use them? Magic methods are basically triggers that occur when particular events happen in your coding. __GET, __SET are magic methods that are called (behind the seen) when you get or set a class property. 59. What is the difference between $var and $$var? $$var sets the value of $var as a variable. $day=’monday’; $$day=’first day of week’; echo $monday; //outputs ‘first day of week’ 60.What is the difference between the functions unlink and unset unlink() is a function for file system handling. It will simply delete the file in context.unset() is a function for variable management. It will make a variable undefined. 61.What are encryption functions in PHP Discussion CRYPTO(), SHA1(), MD5()- 62.What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row().). 63. How can we find the number of rows in a result set using PHP Here is how can you find the number of rows in a result set in PHP:$result = mysql_query($any_valid_sql, $database_link);$num_rows = mysql_num_rows($result);echo “$num_rows rows found”; 64.How do you call a constructor for a parent class parent::constructor($value) 65.How To Assigning a New Character in a String using PHP we can use str_replace function. Ex: $string = ‘Hello’; $alteredString = str_replace(‘e’, ‘i’, $string); echo $alteredString; O/P : Hillo 66.How can we encrypt and decrypt a data present in a mysql table using mysql AES_ENCRYPT() and AES_DECRYPT() 67. How can we find the number of rows in a result set using PHP Here is how can you find the number of rows in a result set in PHP:$result = mysql_query($any_valid_sql, $database_link);$num_rows = mysql_num_rows($result);echo “$num_rows rows found”; 68. How do you call a constructor for a parent class parent::constructor($value) 69. How many values can the SET function of MySQL take MySQL SET function can take zero or more values, but at the maximum it can take 64 values. 70. What is meant by nl2br() Discussion nl2br() inserts a HTML tag <br> before all new line characters n in a string.echo nl2br(“god bless n you”);output:god bless<br>you 71. How To Check Your PHP Installation DiscussionPHP 5.2.2 (cli) (built: May 2 2007 19:18:26)Copyright (c) 1997-2007 The PHP GroupZend Engine v2.2.0 Copyright (c) 1998-2007 Zend TechnologiesC:>phpphp-cgi -vPHP 5.2.2 (cgi-fcgi) (built: May 2 2007 19:18:25)Copyright (c) 1997-2007 The PHP GroupZend Engine v2.2.0 Copyright (c) 1998-2007 Zend Technologies 72.. 73.temp; Maximum allowed size for uploaded files.upload_max_filesize = 2M 74. How can we change the name of a column of a table This will change the name of column:ALTER TABLE table_name CHANGE old_colm_name new_colm_name 75. How can we create a database using PHP and MySQL? We can create MySQL database with the use of mysql_create_db(“Database Name”) 76. How can I execute a PHP script using command line? Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. 77. what is meant by nl2br()? Inserts HTML line breaks (<BR />) before all newlines in a string. 78. How can we encrypt and decrypt a data present in a MySQL table using MySQL? AES_ENCRYPT () and AES_DECRYPT () 79. How can we encrypt the username and password using PHP? The functions in this section perform encryption and decryption, and compression and uncompression: 80 What are the differences between PHP3 and PHP4 and PHP5 ? what is the current stable version of PHP ? what advance thing in php6 The current stable version of PHP is PHP 5.4.11 on 2013-01-17 as still waiting for PHP6 with unicode handlig thing There are lot of difference among PHP3 and PHP4 and PHP5 version of php so Difference mean oldest version have less functionality as compare to new one like 81.How we get IP address of client, previous reference page etc ? By using $_SERVER[‘REMOTE_ADDR’],$_SERVER[‘HTTP_REFERER’] etc. 82. 83.What is the difference between the functions unlink and unset? unlink() deletes the given file from the file system. unset() makes a variable undefined. 84 .How can we register the variables into a session? $_SESSION[‘name’] = “sonia”; 85 86 .How can we increase the execution time of a PHP script? by changing the following setup at php.inimax_execution_time = 30; Maximum execution time of each script, in seconds 87. 88. How To Run a PHP Script Discussion A standard alone PHP script can be executed directly with the PHP Command Line Interface (CLI). Write the following script in a file called hello.php:<?php echo “Hello world!”; ?>This script can be executed by CLI interface like this:phpphp hello.phpYou should see the “Hello world!” message printed on your screen. 89.. 90.. 91.. 92. What is the functionality of the function htmlentities htmlentities() – Convert all applicable characters to HTML entitiesThis function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities. 93. How…?> 94. How can we destroy the cookie in PHP Set the cookie with a past expiration time. 95. How can we get second of the current time using date function $second = date(“s”); 96. How To Create a Table using PHP If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script:<?phpinclude . 97. How can we get second of the current time using date function $second = date(“s”); 98.()”> 99.What type of inheritance that php supports Discussion In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword ‘extends’ 100.How To Convert″);print(“”);?>This script will print:-13005Price = $99.9931 + 2 = 31 + 2 = 3The″+2, which will cause the string to be converted to a value 1. 101.What Is the Best Way to Test the strpos() Return Value in PHP Because strpos() could two types of values, Integer and Boolean, you need to be careful about testing the return value. The best way is to use the “Identical(===)” operator. Do not use the “Equal(==)” operator, because it does not differentiate “0” and “false”. Check out this PHP script on how to use strpos():<?php$haystack = “needle234953413434516504381640386488129”;$pos = strpos($haystack, “needle”);if ($pos==false) { print(“Not found based (==) test”);} else { print(“Found based (==) test”);}if ($pos===false) { print(“Not found based (===) test”);} else { print(“Found based (===) test”);}?>This script will print:Not found based (==) testFound based (===) testOf course, (===) test is correct. 102.How to reset/destroy a cookie in PHP Reset a cookie by specifying expire time in the past:Example: setcookie(‘Test’,$i,time()-3600); // already expired timeReset a cookie by specifying its name onlyExample: setcookie(‘Test’); 103.What Is a Persistent Cookie in PHP. 104.How many ways can we get the value of current session session_id() returns the session id for the current session. 105.How To Protect Special Characters in Query String If you want to include special characters like spaces in the query string, you need to protect them by applying the urlencode() translation function. The script below shows how to use urlencode():<?phpprint(“<html>”);print(“<p>Please click the links below”.” to submit comments about GlobalGuideLine>”);?>
https://www.lessons99.com/php-interview-questions-5.html
CC-MAIN-2020-05
refinedweb
3,502
67.55
History Way back in 2001 I wanted to be able to query Google automatically. Since Google did not provide an official API, I developed a small simple Google Search “NoAPI” scraper and published it as Googolplex. Google launched a SOAP based API but on December 20, 2006 they stopped accepting signups for the API1 and suspended it on August 31, 20092. This shows that creating a service or product based on web APIs is a very risky business without an SLA contract. Google soon launched another API called Google Ajax Web Search API3 under a different license. This second API was suspended on November 1, 20104. You may wonder if Google is a bipolar creature. You can see the latest post at Fall Housekeeping.. It’s not clear why Google vacilates over what could be an additional source of revenue, but it is clear that we should expect Google to provide an official and easy to use API. There are ways Google could restrict abuse of their APIs by third parties. It’s very common to offer a free alternative for low volume searches and charge for more intensive uses like Yahoo BOSS does. In this article we’ll examine one way of crawling information in AJAX/Javascript based sites. Crawling Google As A Browser If you go to Google and look at the html source code you’ll be astonished to see pure Javascript obfuscated code. Even after searching the source is not clearer. So, here is our code to get Google’s results using htmlunit/jython,we don’t have any affiliation with them,jwejust like it!). Look at our Web Scraping Ajax and Javascript Sites for more information. google.py import com.gargoylesoftware.htmlunit.WebClient as WebClient import com.gargoylesoftware.htmlunit.BrowserVersion as BrowserVersion def query(q): webclient = WebClient(BrowserVersion.FIREFOX_3_6) url = "" page = webclient.getPage(url) query_input = page.getByXPath("//input[@name='q']")[0] query_input.text = q search_button = page.getByXPath("//input[@name='btnG']")[0] page = search_button.click() results = page.getByXPath("//ol[@id='rso']/li//span/h3[@class='r']") c = 0 for result in results: title = result.asText() href = result.getByXPath("./a")[0].getAttributes().getNamedItem("href").nodeValue print title, href c += 1 print c,"Results" if __name__ == '__main__': query("google web search api") run.sh /opt/jython/jython -J-classpath "htmlunit-2.8/lib/*" google.py Alternatives The following search engines provide official APIs for search: - Yahoo Search API - Blekko Search API: Ask for a key or use the RSS search feed. - Duck Duck Go API. - Bing Search API - Twitter Search API Homework - Write a clean function/class to do Google queries and handle exceptions. - Modify the function to handle nested and paged results - Modify the function again, this time to include descriptions. Final Notes The approach taken by Mario Vilas is more API like, our approach here is a defensive measure against NoAPIs. This is another good example where HtmlUnit does its job. BTW the noapi.com domain is available5 See Also References - Beyond the SOAP Search API - A well earned retirement for the SOAP Search API - Google AJAX Search API beta Version 1.0 Available - Fall Housekeeping - The noapi.com domain is available at the time of writing of this article. Register it now! (Disclaimer: affiliate link). Additional Resources - Google Search API? - Google Deprecates Their SOAP Search API - Google Search API Dropped - Is this API going to be closed down? - Yahoo BOSS Switching To Paid Model In Early 2011 - Thoughts on Yahoo! BOSS Monetization Announcement - Google to Start Charging for Prediction API - Update on Whitelisting (Twitter API policies discussion) - From “Businesses” To “Tools”: The Twitter API ToS Changes
http://blog.databigbang.com/tag/deprecated/
CC-MAIN-2022-33
refinedweb
601
67.55
:-. ' . . .. .. ' | ' ' ' ' ''''''' '"'^ '''' "'''r' ' ''' ~~*-~r^--*~r-; - rj*j ry - NIGHT THE DAY, frlfiU ??N0T NOT THEN BE FALSE TO ANY MAN ? v M BV KEITH, SMITH & CO. AV A LH ALL A, SOUTH CAROLINA THURSDAY, JUNE 7, 1877. .'i }.i i . . frit">i >r .Mitf-i " ,?w.'.M ! S):!. VOLUME XII-NO. 29. LIM ? H?H*imd?Ji?i ItlJllMMtVU THU NUW ? Barn? IK. BY-PHILIP J. BULL. Tho dcdioutiou's ovor, wifo; wo gavo tho ohuroh to God \Vith Dot ooo oout's indebtedness from floor to lightning rod; I But 'twas a struggle long and flcroct tho hours droggod slowly on, .Before wo took Thorinopykc, or crossed our Rubicon. At Inst it was decided that, whntovor clso befalls, .Tho Sherill's hammer shull not souud within thoso frescoed walls; And so Tm living o'er, to night, tho months nf snn aud ruin That brought this towering oak troo from thc acorn of my brain. You recollect tho meetinghouse I preached in for a while; Some culled it au "old rookery," and porno '.tho old etouo pile;" And when wo prayed tho Lord to ootnc, it seemed a deep disgracu To ask tho King of Glory iuto such a poor old placo. Tho smoky walls were cracked with ogc, and when tho cold winds blow, They rovod around in searoh of rents, and then cumo rushing through; And I'm convinced that, many a soul, from where our uew ohuroh stands, lias taken death's express train for tho houso not made with bauds. So when wc carno upon tho ohargc-'twas early in tho fall I called a meeting of tho board; thrco an swered to tho oall. They thought tho times too hard to build, and lumbar was too dear; With whioh "whereas," it wa?? "licsolvcd to put it off u year." Hut on one Sabbath ovouing thc people gave u shout; I looked from parsonngo to ohuroh and saw tho Hames leap out; Hut from thc lire a pheonix grand arose to faith's clear view, And all because they hadn't fixed nn old defective Quo. I drafted a subscription roll; ull in duo form of law, And shook it in tho faoo and eyes of every man I saw; Sotno gave it tho cold shoulder, and thus left us in a lurch, But othcrfcoamo up nobly, wife, and built our nico new church. And neighbor Smith, who wouldn't sign becauso ho mount to sell, Tho bruthen? Brown, who could not give becauso they'd dug tho well, And Thompson, too, and I lobins?n, nil came around at last; Li ko meu who board tho hinder car as it is moving past, If they could only feel tho weight of all my sad alarms, They'd bo moro ready, Aaron-liko, to hold up ?Moses' arms; They know how tho cold sleet cuts tho faoc, and how tho North wind bites, But only God can count (iud weigh a pastor's sleepless nigh tal But now tho struggle's ended,. and tho victory is reached; Aud wasn't it n grand discourse our good old Bishop preached? But when ho had thc Israelites a-crossing tho Ked Sea From wilderness to promised land, I thought ho just meant mo. Well, when' tho next now proaohor comos, to hold instead of build, I hopo tho finished fort may bo with valiant soldiers filled; And os our members, ouo by one, aro oarriod to thoir graves, Jd ny others clasp thc chancel-rail, and Jcaru how Jesus saves! ?tn(?ti itigiitM-TIIO ?ouim t or Jurisdiction. Tho tyrannical administration of tho knited States Govornmont by Gen. Grant, as moro etpcoially cvidoucod in his support of worthless men in office at tho South, tundo tho Govornmont service, in this ficotion, no odious, that few respectable moil would consent to work for tho Government on any terms Naturally, tho ovil multi plied itself indefinitely. Tho ohiof offices, thoso from whioh largo profits wero to bo dorivod aud which stamped thoir oharaotor on tho looal administration of tho Govern ment, wcro mostly in tho hands of Northern poi it iou I trumps or Southern ronogudos, and sn Booking for sabord imites thoso mon usu ally appointod others of thoir kind, gene rally from a principle of natural affinity, but somotimcs from sheer want of ohoioo. J1 or, occasionally, it would happen that ono of these principal nd von turora had sufiloiout regard for pubiio opinion to wish to givo a color of doconoy to his ofUoo by tho appoint* mont of honest and capable subordina ten, but honest and oapablo mon had too muoh regard for their reputation to desire to bo found in suob company, and, consequently, unworthy mun woro omployed. _ Tho dienstrous result of this stato of things was moro particularly manifested in tho Stato8 of North Carolina and Georgia, in tho mountainous distrio'.s of whioh poor 1* I and ignorant- persons woro engaged iu tho manufacturo of ardent spirits contrary to tho provisions of tho rcvonuo laws of tho United Stuten. Tho manufacture of liquors had boou tho pursuit of their lives, and on it thoy depended for making a subsistoneo. Tho regulations established by tho Govern ment were such that they could not bo complied with except by persons having a largo amount of espita!; tho impecunious distiller must givo up his business altogether, or run tho risk of being detected and pun ished. Nino tenths of them preferred tho lutter alternativo. Hero there was a delicate problem presented to tho Government*, to enforce, tho laws and yet neither oppress nor irritate tho people. At least each is tho problem that would hayo been considered by wiso rulers. Grant's satraps, however, were bent only on enforcing tho laws', they neither thought nor oared about tho unfor tunate pooplo upon whom tho laws were an unjustifiable hardship. They filled tho mountains with unprincipled ruffians armed with tho authority of the law, who, under tho sacred namo of justice, committed robbery, arson and murder. Tho people in Georgia begged for morey, aud President Grant, in tho last days of his reign, yielded it, but in such a manner ns to fill thc pockets of his minions. In North and South Caro lina tho people have sought tho aid of thc State Courts to punish tho perpetrators of tho outrages upon thom, and tho criminals hnvo sought refuge in tho United States Courts. Uenoo has arisen a conflict ot I jurisdiction, tho deoision of which will mark out anew tho boundary between State and Federal authority, and show whether tho citizens of a State have nny rights which the officers of tho National Government arc bound to respect. Judgo Sohcnck, ono of tho Superior Judges of North Corolino, has recently decided that the act of Congress authorizing tho romoval of criminal prosecutions ot United States employees from tho State to tho Federal Courts is unconstitutional, aud now comes tho Hon. Thompson H. Cooke, Judgo of tho Eighth Circuit of thc State, who, in a charge to tho Grand Jury of Greenville Inst week, says: "Thcso officers of the Government, be lieving that when proceeded against foi violations of tho Stato laws they oan move their coses into tho United States Court, one go unwhipped of justice, havo no doubl grown rcoklcss as to how they disohurgt their duties, os well as emboldened to op press tjnd outrage tho citizen. If, upor investigation, you should find this charge sustained, you will present all persons wh< may havo engaged ir?, oppressing youl pcoplo, aud I undertake to say two vorj important things will bo accomplished First, this class of United States officer: will soon learn they cannot longer violate thc Stato law with impunity. Secondly that they will bo tried in thc State Courts regardless of tho cet of Congross, whicl authorises thom to transfer their cuso to titi United States Cuurts. "Io saying this, I am not unmindful o my oath of ollioo, to wit: That I reeogniz tho supremacy of tho Constitution am I laws of tho United States over thc con stitulion and laws of any State.. Tho prac tioal effect of thc oct of Congress refcrro j to is to prevont tho trial of ??ICHO o??icci? let thc grado of their crime bo never s infamous, oiid to encourage tho comtnissio of crime. In tho oaso of tho Stato vi Mallison, indicted for tho murder of Davit in thc County of Anderson, Judgo Hon held that Mallison was a revenue officer i tho discharge of his duly, and thnt th killing of Davis was a necessity, incident t thc discharge of his duties, and turned hit looso without ii trial hy jury, in violation c i paragraph o, Suction 2, Article 3 of th Constitution of tho United Stntcs, wino reads as follows: 'The trial of all crime except in oases of impeachment, shall bo ti jury,' &. Tho not of Congress coofors ii jurisdiction upon tho United States Coui to try and dctormino a prosecution bogu in thc Stuto Courts for misdemeanors < crimes, by virtue of statutes or iudictib at commun law. "Tho jurisdiction of tho Stato Courts i all matters of crime at common law an statute law, not in violation of tho Constiti lion of tho United States, has bcou concede by tho General Government for nearly or hundred yours, I may say without qucstic or debato, and, in fact, from tho laying i tho foundation stone of tho Republic, uni ovon long after tho llepublionn party guim tho ascendency in tho Union; and I a uttorly at a loss to know how, when or who tho Stato lost her jurisdiction iu such case I sholl, therefore, disregard tho said act Congress, andrflireot Mr. Solicitor to procec with all prosecutions against rcvonuo off oors charged with violating tho laws of tl Stato." I Judgo Cooke makes tho issue squnrcl Tho determination is, to teach United Stat officers that thoy oatt no longer violato Stn laws with impunity, and to try suoh offene ors in tho Stato Courts, regardless of tl immunity attcmptod to be scoured thom I an unconstitutional Aot of Congress. It n patriotio work, and comes with good grn from n Republican Judgo. Without deco trnlization and States' Rights, in thc fullest sonso/ tho llopublio cannot stand. [News and Courier. WASHINGTON, July 10.-Ry a genet order issued from the War Dopartmont, t Statos of Louisiana, Arkansas, Mississi?] Alabama and parts of Kcntuoky and To nesseo lying west of" tho Tenn essen Riv? and which comprises tho military dopai mont of tho Gulf, lin vo been ic assign cd 1 tho military division of tho Atlantic. Fence or No Fence. Jlfcssrs. Editors: As tho question, fenoo or no fence, appears to bo open for discus sion, if it will not bo considered inappropri ate, I propose to offer a fow thoughts relativo to this question. 1st. 1 sin iu favor of tho chango, if it could bo adoptod by tho wholo country and not restricted to townships; though to fcn foroo tho law ou tho pooplo at prosont will not do. Let us wait for other sections who may bo moro interested to try tho experi ment. Then it will bc time for us to try it. 2d. J?yyoutlcavo E will givo you somo of my exporienoo in feucing stock. Some timo ago, in tho spring of tho year, wo had a cow which wont bock to her old range, and if wo got hor milk it was ueccossory to conlluo her and keep her at home. There foio, having a little broom sedge old hold enclosed with water in it, tho cow was promptly put iu it to starve, I thought. Thero she stayed until fall without any thing to cat oxcept said grass and a lick of salt now and then. Instead of starving wo obtained plenty of good rich milk, tho cow continually improving and becoming fat in tho fall. So with this and similar expon monta wo conclude il is better to fence tho stock, us splitting rails is hnrd wotk, old fenoo rows good soil, and tho cattlo, &?., in n better condition. Wc might bring other proofs to show thc nd vantage to our pooplo in adopting tho law, but will forbear at present, ilowovcr, as I said at first, let us not bo too hasty in making tho change; for our present condi tion also has its advantages in having a groat deal of forest land whioh is now worth less for cultivation, affording an inexhausti ble; supply of rich grazing material for our stock, which never fails to pay our people in fut beeves, hogs, ?fee This groat help tho poor man, whoso only sourco of profit is his fow cattlo, &c, cannot easily dispcuse with. I could say moro on thia subject, but lest I weary your patience, 1 will desist und respectfully leave to abler writers to argue ibis question, so as to do thc most good for our country. Respectfully submitted. CITIZEN. better ii om K?!&cilcl<1. EUOEFIKM) C. Ii,, July 6th, 1877 Messrs. Editors: Having just returned from your delightful town, you, in all probability, would liko to know tho dots from ridgefield. Judge Kershaw opened n new ern in this County by bringing tho recollections of a glorious past aud tho beacon light of as happy a future Ile gave us two weeks court, holding duily sessions from 10 A. M. and adjourning about li o'clock of euch day Tho docket was cleared of much Criminal Bcrubbisb. That noted burglar and pest of thc citizens, Aggrippa Wigfull, colored, was convicted at this term of tho court for cottcn stealing. Tho hearts of Edgclicld throb mere easy than before court adjourned last week. A now Rifle Club under title of ''Tho Edgofield Rifled," J nines Bonham, oaptaio, was lately"organized with nn activo member ship of 00. Thc organization will bc .sent in for recognition in a day or HO. lion. George D. Tillman was in town tho other day in high spirits. Tho venerable "Congressman" has shaved his fuco and cut his hair ncaily us cloon as ho will oust Smalls out of his pretended seat next fall. Mr. Till man is iu good spirits, and told mc that ho bad more than 4,500 of Smalls' votes in o bad condition in Aiken, while ho (Smalls) had made no impression in Edgcfiold where ho mado bis great effort. Ile says to secure his scat will bc a oertointy. Tho nogrocs, deadened by thc great defeat at tho last clcotion, aro so heartbroken that thoy give vent to their foolings by a pro posed removal to Liberia. 1 havo conversed with several upon tho subject, and find their ignorant minds carried away with tho idea that thero is a treo in that Paradise whoso fruit is largo nuts, about tho sizo of a peck mensuro, containing puro flour, whilo n mero gimlet hole bored through tho bork of tho same will exudo puro molasses until stopped. This is no fiction to them, but their oondid belief. Poor things! always toady to be tho dupes of some spec ulator. Tho criminals convicted at tho Inst court hero will bo hung on tho 31st proximo. Crops aro vory good. I will give moro os nowa ooour. J. Vi II. Tho African Exodus. THE LEADERS CLAIM THAT 40,000 NEUROES WIM. LEAVE Tina STATE. Inquiry was mado yestorday at tho oflioo tho Lihoritiu Excursion-pardon, Exodus Assoointiou os to tho number of names en rolled for tho trip. Tim answer received was that from 2,000 to 3,000 mon, womon and children in and about this oily hod put down their names. Outside tho city, it is stated, that somewhoro botweon 30,000 and 40,000 have expressed thoir determination of omigrotiog, and havo handed in thoir names. Thoy consist of all olasses and conditions ol'colored society, including some persons of moans and influence Tho largo majority, liOWOVOr, aro laborers and incohnn los. Thoso having thc matter in ohargo aro enthusiastic, aud oxprcsstheir confidence of Buoooss. Thoy say that thoy lately ro ooivod information whioh induced thom to botiovo that a largo number of om ?grants will bo enabled to loavo boro this fall? Thoy Boom to havo figured olosoly on thoir routo and bayo it ail laid out. Tho voyago from this city to Monrovia will bo a ton day ooo and from that place they will go by inland water twonty tbrco miles to whoro tho country begins to riso. Thoro thoy will settle) and work up tho hills iuto tho Country* Gcorgo Curtis, who seems oepooially en thusia8tio, says that thoy will bo beyond tho malarial belt. Ho says also, that mon of prominonoo and wealth in Eugland havo become interested in tho matter, and that tho association has recently received en couraging letters from suoh sources. His idea ia that tho proposed exodus will bo for tho benefit of both races, and is anxious to have it udorstood thal ho advocates it for that roason, and not in any unfriendly spirit towards tho white peoplo. His ideas on tho subjeot aro worth publishing. Ho says that tho prcsont agitation to havo tho machinory brought to tho cotton is bound to secure that result. That wheu that is doue that Char leston's export trade iu raw cotton and her import trado io fabrics is bound to suffer. That if tho emigrants oro treated kindly and assisted by Charleston, they will natu rally send bock their products to bc manu factured hore, this placo being only a day or two further fr?in thom than London. That this would givo this city nu immense import trade, and furnish food for unnum bered looms and factories. Tho last words heard by tho reporter 03 he withdrew were: "Wo cnn no moro bc stopped thau tho children of Israel could bc stopped from coming out of Egypt." [iVctfs and Courier. What Mimi bo ?one for Hie Co lored People? This is a groot question, and should not bo lost sight of, and tho Southern peoplo must not allow themselves to be provoked into unfriendliness to tho colored man by tho many unkind things said of thom by rash and foolish mon in tho North. Wo know our duty, and wc must dare to do it. If thc Northern people will help us to do it, well; if not, thc obligation must bo dis charged. Tho Southern Presbyterian Church has taken a noble stand on the qucstiou of the education of colored mon for tho ministry, and wc have no doubt they will bo prospered. Their school at Tuska loosa is already doing a good work, and is" gaining favor. Dr. Adgcr, who was thc Del?galo from thc Southern Presbyterian Church io thc Reformed (Dutch) Synod, which met in New York, called tho attention of thc latter body to what his Assembly was doing for tho colored peoplo, and asked Iiis Northern brethren of tho Dutch Church for help. Of this matter ho writes in thc Southern papers sinco his return, and also touching thc relations of tho churches, North and South: Just before thc close of tho Synod's pro ceedings, I was kindly iuvitod to say a few farewell words. After expressing tho senti ments of esteem and affection with whioh I was filled, J. told them that I had "only ono thing moro to say, and that 1 wan glad of the opportunity to say it. That ono thing was thut, when tho South asked tho North* to help her in doing good to tho colored man it was not possible, after all that has hap poncJ, that she should refuse. 1 knew well how much their various objects of church interest were pressed with tho nood of money; but still when my Church said to their Church, 'Help us, brethren, to do tho duty which wo both owe to tho poor, help loss, dependent race in question,' it was not possible, after all that had taken placo, for tho Reformed Church oit her to rcfuso or neglect thc appeal." I thought I could seo that I had touched their heurts, and it was very pleasant afterward to havo two mon amongst tho foremost in tho body, who lind seemed all along to bo giving uio a little of tho cold shoulder, to como up to mc and oxtoud their hands with marked cordiality, wishing mo farewell; and ono of them said with truo Holland warmth, "I am going right homo, and will immediately toko up a oollection for your objcot aud forward it to yon." 1 wondered o little what it WOB that so commended my objcot POW to thoir kind regards, because in my former address I had, from loiters sent mo by Dr. Stillman and Mr. Dickson, detailed a number of moving pnrtioulnrs, and no snob effort appeared to follow. My conclusion was, that it was tho oppoal made for tho poor, helpless, depen dent raco. Our brethren of tho North do not know how wo feet toward tho negro. And suoh words from mo, of kiud, Chris tian consideration, astonished and delighted and drew forth tho sympathy of thoso Itc formcd of tho North. Thcro aro bad mon in both sections. What a pity that tho good men in both could not know ono another better! I look upon our relations with tho Reformed os of groat vallie to both tho parties and to tho country too. F'om tho Northern Presby terians wo seem to bo further ?part by thoir Into action at Chioago than ever. Dut hero aro Presbyterians in tho North, of tho truo blue jun; iii rino soi t, with whom WO have come to occupy dose oo-oporativo union. Hore is tho undeniable proof that wo aro not governed by sectional prejudices. And herc is tho ooolcsiastioal bond, HO far os Presbyterians aro concerned, that gives proniiso of poaoo and good will for tho future betweon, tho estranged North aud South.-Due West Presbyterian. OKAVELTJBD HORSES.-Qivo two-thirds pf a tablespoonful of ?altpotro in a littlo salt for throo oonscootivo days? Jorueolom has 8,000 Christians, 13,000 Jowsj ?nd 15,000 Mohammedans. A Genuino Uoforincr. Wo copy tho following briof biographical ?kctchof tho HOD. W. C. Browu, of Ander son, from tito Charleston Journal of Com merce. Dr. Brown ia ono of tho marked mon of tho Hoaso. His coarso has mot with tho unqualified approval of his con stituents and haB brought down upon his hoad tho doep ourses of parvenu patriots and journalistic blackguards. Tho biogra pher says: Tho IJon. W. 0. "Brown, of Anderson, is one of tho mnrkod men of tho Huuso. ile is now forty-six years of ago, and was boru in Oconco County. Wliou ho was a lad his father removed to Georgia and settled in thu mountain region of that State, whero tho fumily still reside. Ex Governor Joe Brown, is o distinguished mom boc of tho family, cud a brother of our Representativo. ])r. Brown is emphatically a self-mndo tuan, aud got a liberal nud practical ?ducation, contending against poverty and many other difficulties. No combination of difficulties, however, could dishearten him, but with untiring determination bo prosecuted his studies, and in 1851 ho graduated in medi cine in Philadelphia with thc highest honors of a largo and brilliant class; ilo then located nt Belton, and for years pursued his profession with conspicuous success. In it Ito amassed a handsome fortune and retired from his profession only to become a largo, successful and prosperous planter. Thc Doctor is of a modest and rotiriug disposi tion, and lins always been averse to public lifo. Ile was, however, almost unanimously elected President of thc Tax payers Uuiou for his county in 1873, which position ho Glied with distinguished ability and honor. Last summer ho was provailed upon to allow his nomo to bo used ns a candidato for tho Legislature, and entered upon tho canvass with all tho eagerness and energy of his enthusiastic nature, displuying marked ability as a political speaker, Ho headed thu ticket in tho primary ck ?tions. This is tho first term of tho Doctor, and he has already taken a prominent place among the best mon of thc House. J lo is remarkable for tho clearness of his views and tho honesty of his purposes. Ho has a perfect conception of tho issues now before tho country, and truly roprcseuts Ina i constituency. Ho is actuated by thc highest .standard of morals and is untcrr?icd by opposition in thc ndvooaoy of his views. Ho is a shining light, and by his bold and determined oourao has won tho respcot and admiration of tho whole House. dio Um lt. To the young man with his hair parted in tho middle, who is about to put his college education and his sole leather trunk on tho Texas bound train, wo say, Itopl To thc clever artisan and tho honest mechanic who thinks ho will fly from tho bard times where ho is, to imaginary well paid employment in tho Lone Star State, wo also say-slop! To tho adventurous rustic who wishes to leave hoeing tho turnips of soma New York farm to find a soft thing in this land of prairies, wc omphn'tionlly repeat atay where you arc! Wo would that wo inhabited the earthly Elysium that some Texas papers say we do, but wo aro afraid wo don't. From tho bottom of our hearts wc should bc glad to think that there was plenty and prosperity for overy one who sacks to settle among us -but all tho same, thcro isn't. Wo do possess something of an approach to tho eternal summer and tho marvelous growth of tho Eust is so tired of hearing us brag about, and that is all. Sooth to say, thcro is no chanco hore for men without money, oil tho eager, now arrivals to tho contrary notwithstanding. In plain English, tho paper that speaks of tho magnificent opportunities this State presents to tho new comer, lion, and Hos in a very gratuitously criminal way indood. The unvarnished troth is that our labor market is stookod to overflowing, and ovory frosh arriviug train but adda to the misora blo multitude in our midst that waits, suffern, starves and finally fights its desperate way back East again. Before thc door of nearly every houso in this oily, there daily begs a hollow-eyed swarm that would sadden the heart of o satyr. Men of brains and culture, good clerks, oxcoHcnt accountants, business men of undeniable oncrgy, mechanics of abili ty, walk the streets in dum despair, and finally ttiko those that lead to tho chain gang nnd workhouse. Tho writer of this cannot remember one evening for very many that bohns not been roked for monoy to buy a meal, or a bod by men who would have sooner died on tho rook than asked alms in tho light of day. And eomo of thom do die on thc rack thc rack of bitter disappointment and con tinued misery. Vet still somo journals calmly sing tho rumo old siren song, and still thia overcrowded, ovcr-troded and financially prostrated community is held up willi fatal persistence ns tho proper Mcoca of tho American youth. Wo hog tho journals in tho East nnd North to copy this ortiolc. Wo ask that tho truth and tho wholo truth bo told thcro ns a simplo duty to humanity. In tho nnmo of tho distress wo seo around us, aud aro powerless to relievo, in the nomo of tho tramps and vagrants that fill our cities and towns, wo solemnly warn intending immi grants of all classes, except farmers and mon with money to invest that wo aro overstock ed with labor, ?nd will bo for tho noxt four or fivo yoars? Though his tiflkot may bo pur ohasod and his trunk packed, wo say to tho man looking hither for em ploy m cut-Go baoki-Tcxa* Intelligence. Goodness ia beaut v vi iii hc,t cst***. WASHINGTON, July 12.-Tho notion with regard to Speoinl Treasury Agonts Bracket! nod Mooro is tho sensation of tho day. An importance attaches to theso agents which noithor their pay nor their known fuuotions Warrant?. Tho Atlantio Con Ht Lino, via Wilmington, tho Piedmont Air Lino, via Richmond and Cbarlotto, and tho Kcnnesaw, via Lvnoh borg, Knoxville and Atlanta, aro makiug a dosperato fight for tho great Southern mail, lt ia carriod at presont over the Konneaow routo, and tho indications aro that it will continue to go over that linc. Private advices from Jackson, Missis sippi, state that thc Republican committee of that State met on Saturdny und passed, by a more majority, a resolution of con? - denco in Prcsidont Hayes. Thc cominittco resolved to make uo nominations for tho Stale tiokot nt the election next foll, for tho reason that thc President's civil service letter forbidding Federal officials to engage in campaign work left them without organi zation, a majority of thc committee being officeholders. A vote vtas passed to adjourn sine die, which was couivalent to disbanding tho Republican party in Mississippi. Thc home subscription to the hew four per cent, loon has reached SI8,00,000. Acting Scorctary McCormick has advices fror Louden that they are being placed by thc syndicate ut par in London. Thc Department of Justice disavows any intention of arresting Marshal Douglas, of North Carolina. Thcro is nothing to warrant ptoooodings against him on ?Io ia thc deportment. Hon. Stanley Matthews, of Ohio, has authorized an interviewer to say that ho hos "uover made any bargain with auybody about anything, at any timo, connected with Louisiana affairs," and that all assertions to thc contrary arc pure inventions. A BE?UBLTOAN ORATOR ADDRESSES SOUTHERN COLLEGIANS.-(Jcnoral Stowart L. Woodford, of New York, a lending Re publican orator during tho recent Pr?sidons tinl campaign, delivered tho address at tho commencement of tho Mississippi University nt Oxford, in that State, lost week before a very largo audience. Among tho auditors wcro Governor Stone nnd two or three ex Governors, judges of thc Supremo Court and tho Federal Court, members of the Leg islature, and tho most distinguished men from nil parts of thc State Ho WBB con ducted to thc rostrum by Senator Lamar, and introduced to tho audience by tho chnncollur. His appearance was greeted with cordial applause Ho made very feeling allusion to tho post, wbioh he de clared wo could not shut from thought; to tho oourngo shown by thc young men invit ing him, and to tho hearty courtesy of his welcome. Ile would speak "not of student themes, but of public duties, the common need of tho republic and thc common duties of young men. I say oom mon duties, for wo arc ono. (Applause.) Wo aro bound together in tho holy wedlock of on enduring nationality. (Prolonged applause) Tho three essential needs of the rcpublio seem to bc, first, tho general and systematic educa tion of our people; second, the thorough, abiding and effcotivo respect for tho lav? such respect us heartily recognizes ita au thority and obeys and enforce? its mandates; third; toleration by all to all." Kalah of those proposition bc urged elaborately and earnestly. "Eoforeo a good law aud tho community sccs and knows that it is good, und will look to its rctcntiou. Enforce a bad law, nnd tho pcoplo will awaken to tho need of its rcpoal. Tho man who substi tutes his own will for tho will of tho many and takes tho law in his own hand is a bad citizen nod he is who acquiesces in the violence of his neighbor is a wonk citizen." (Applause). During tho dolivory froquont bursts of applauso interrupted theapoakor, and at tho close round ofter round of cuthusiastio ohoor8 groctod him. NEW YORK, July 10.-A spocial from Stn Antonio says, tho train cn routo from Chihuahua to San Antonio, laden with specie, was attacked Sunday evening by thirty-five white and Mcxiouu highwaymou on Seco oreck, fifty two miles from Sau Antonio. Tho traiu contained* twolvo wagons, and thcro wcro twenty mon with it. After a despcrato fight tho robbers wcro driven off, losing aovoral, killed nnd woun ded. Tho Mujor Domo in th,e troin, Frank Grimsiger, and a Mexican were killed, and several others of tho train pceplo wounded. No tooti outrage has occurred since tho war. THE OHIO CONVENTION.-- Wa$hiflaton? Juhj 9.-Information received hero from Ohio, warrants tho prediction, whioh is positively made, that tho Deuocrats will elect a mr.jority of tho mombors of tho next Legislature of that State, nnd thus scouroa Domocrntio Senator in place of Mr. Stanloy Matthowfl, whose term will expiro in Maroh, 1S78. Matthews is so unpopular, that thor? is talk of passing a resolution in tho Ropublibsn Stato Convention on July 81, whioh shall opcrato as a oonsuro upon him. Thoro is now groat intorost hore concerning this convention, and many Republicans hore aro preparing tb attend it. In a certain bffioo tho following notice U nostod, "Shut the door, and when you havo dono talking on business, Borve your mouth tho aamo way." Mon who travol barofootod around a newly onrpcted bedroom often find thorn sol von on tho .?ror?<-? frick. xml | txt
http://chroniclingamerica.loc.gov/lccn/sn84026912/1877-07-19/ed-1/seq-1/ocr/
CC-MAIN-2016-36
refinedweb
5,608
65.66
The following paragraph contains my main problem, though I have four others that I am unable to find help with in simple tutorials at the bottom of this post, I will greatly appreciate any help. Hello, I'm relatively new to c++ and may therefore may have a few foolish questions while I am attempting to work on a program that is a sort of basic AI interface. I would like to know how to have the program respond to user input that is set to a string variable as an entire sentence, or rather, how to equate an entire sentence with a string. As the user inputs data, I use cin >> my_string to attempt to set the sentence or words input as my_string. Then, when I tell the program to evaluate the string, it has no problem if it is a single word if I have already set this specific character arrangement to a string it should be looking for... If will almost certainly be easier for the problem to be seen in my block of code, which is only a very basic structure at present. it is as follows: when I input something other than Hello or goodbye if gives me a number of copies of the error sentence corresponding to the number of words.when I input something other than Hello or goodbye if gives me a number of copies of the error sentence corresponding to the number of words.Code: #include <cstdio> #include <cstdlib> #include <iostream> #include <string> using namespace std; int main (int nNumberofArgs, char* pszArgs[]) { //define some strings (present tense) //punctuation string period = "."; string comma = ","; string semicolon = ";"; string sp = " "; //greetings (meant to be single line or sentence) string Hello = "Hello"; string hello = "hello"; string Good_morning = "Good morning"; string good_morning = "good morning"; //dismissals string Goodbye = "Goodbye"; string goodbye = "goodbye"; //articles string a = "a"; //nouns string cat = "cat"; //verbs string jump = "jump"; //sentences (need to determine classes, and how to select from classes) //unser input sentences string s1; string s2; string s3; string s4; string s5; string s6; string s7; string s8; string s9; string s10; //output sentence strings string o1 = Hello;//tell to choose random greeting eventually (non-time based) string o2; string o3; string o4; string o5; string o6; string o7; string o8; string o9; string o10; // loop ints and such int l1 = 0; //begin program cin >> s1; //a newline must not be started until the first cin is reflected upon. if (s1==Hello+period||s1==Hello||s1==hello+period||s1==hello) //if s1 is a greeting, then output nothing additional, otherwise reflect. (move to loop below) { cout << Hello+period << endl; } else { cout << Hello+semicolon; } //must insert something similar to loop here, to finish else statement evaluation of input while ( l1 < 10 ) {// loop stops if l1 is greater than 10 cin >> s2; s3=s2; s4=s3; s5=s4; s6=s5; s7=s6; s8=s7; s9=s8; s10=s9; if (s3==Goodbye+period||s3==Goodbye||s3==goodbye||s3==goodbye+period) // begin with the most common input type. { l1 = 11; } else { cout << "I am quite sorry, but I am unable to understand your sentence, either\n"; cout << "because of too great a number of grammatical errors, or because I simply\n"; cout << "am unable to comprehend the structure or intent of the sentence input.\n"; }// I now need to move to a whole bunch of if/then statements. inside a loop, these }// statements must be able to reflect upon every possible instance of input in // reasonably correct english. (FUN!) cout << Goodbye+period <<endl; system ("PAUSE"); return 0; } I would also like to ask: 1. are classes able to be refrenced like strings, for example, if I tell the program to respond to the word "animal", and I have a class animal, subclasses dog and cat, would there be any way to take the highest order class, and tell the program to ask which of the sub branches that user wishes to speak about? (other than directly writing a response, which cannot automatically update itself as more subclasses are added) 2.how can I tell the program to create new subclasses based on the input of the user, or is not classes, then strings atleast, for whords which are not already placed into a class (at this point i only want the program to be able to catagorically sort words based on classes I create, or tell it to create) 3.as for the refrence mentioned in 1, how would I tell the program to respond to a single word input in a sentence, or several words when found togther, not necessarily in the exact same order and syntax as used every time. 4. How would I tell the program to look for relative symmetry between strings (where a one letter mistake per five words perhaps might seem reasonable in human error, the program only knows exeact symmetry, or none at all, this is usefull in many aspects, but can become (though less than a major concern) a minor annoyance in my particular instance. 5.where I have s3=s2,s4=s3 and such, should I reverse those? I just realized, that while I meant to keep some eight sentences in a sort of short-term memory, that line of equation may just be immediately putting the value of s2 in all of those variables, and resetting each time the loop makes a...loop. (by reverse I mean to put s10=s9 first, s9=s8, etc.) I appreciate the time of anyone who helps to answer any of the preceeding questions.
http://cboard.cprogramming.com/cplusplus-programming/90697-string-issues-printable-thread.html
CC-MAIN-2016-40
refinedweb
924
52.87
Type: Posts; User: AwkwardRaven so void calculateParkingHours () { enteringMins += ( enterY * 365 * 29 * 60 ); enteringMins += ( enterM * 12 * 29 * 60 ); enteringMins += ( enterD * 29 * 60 ); enteringMins += ( enterH *... I'm writing a program to calculate a fee based on the time that a car is parked in a theoretical garage. But my time function doesn't seem to be giving me the correct number of minutes... I would... so if I extrapolated separate integers from a stream MM/DD/YY hh:mm what would be the exact syntax to use to convert that into a time format C++ can recognize and contrasts between two different... then how would I specify the time for difftime from a string formatted in MM/DD/YY hh:mm? Why do I need .c_str() also if I use difftime can I define my own times? thank you for replying but that's not what I would hope to do. This is what I have so far: #include <iostream> #include <string> #include <iomanip> #include <cmath> #include <cstring> Hello, I'm trying to read in two instances of date and time (from user input) into a string value (MM/DD/YY hh:mm). I need to be able to calculate the difference between the two in order to...
http://forums.codeguru.com/search.php?s=00307e971b5cde438824b6077fb6a7bc&searchid=7002451
CC-MAIN-2015-22
refinedweb
206
60.35
DEBSOURCES Skip Quicknav sources / cduce / 0.4.1 0.4.1 - Tools: * Error message when using --mlstub without the built-in OCaml interface * Improvements to the type pretty-printer * "include" uses the -I options - Language: * New Caml_int builtin type * The // construction no longer stops at the first matched subtree on each branch * New "dump_xml" and "dump_xml_utf8", equivalent to the composition of print and print_xml, but more efficient - Implementation: * New subtyping algorithm * Small improvement to the pattern matching compiler * Improve type-checking time for map * Improve type-checking of record expressions * Don't display warnings for unused branches in ghost (generated) pattern matching - Bug fix: * "eval" can now be called several times and use the toplevel environment * use "open_out_bin" (needed for Cygwin installation) * "open" allowed as tag name * exceptions raised by the expat parser and by the dump_to_file primitives are now catchable * work-around the double close bug in OCaml 0.4.0pl1 - Packaging bug 0.4.0 - Adapted to OCaml 3.09. - To build the OCaml/CDuce interface, OCaml sources are now needed. 0.3.92 - Tools: * Build and install dtd2cduce when PXP is available. * Display of location for errors and warnings compatible with OCaml. - Language: * Better error messages for xtransform. - Bug fix: * Forgot PLIST.godi in the package. 0.3.91 - Tools: * Get rid of cdo2ml and mlcduce_wrapper. Now included in cduce. - Bug fix: * Internal uid collision when using OCaml externals. * Makes "String.length" works (String used to resolve to the CDuce type). 0.3.9 - Language: * Added split_atom, make_atom. Removed atom_of. * Added char_of_int built_in function. * Now int_of also accepts octal binary and hexadecimals. * The field access also works for XML element attributes. * More catchable exceptions (for load_xml, load_file, etc). * namespaces, schemas, "using" identifiers are now exported. * "open" statement. - Implementation: * More efficient implementation of records at runtime. * Clean-up of the internal representation. * The XML Schemas are now parsed only at compile time. * The automata for pattern matching are now produced at compile time. - Tools: * The functionality of cdo2ml is now assured by cduce itself, with the --mlstub option. * Remove the --dump option (which was deprecated). * Remove support for sessions in the web prototype. - Bug fixes: * Correct handling of external references with expat. * Installation problem under some BSD (using "install -c"). 0.3.2 * Bug fix in configure 0.3.1 - Bug fix: * configure must not require pxp * inclusion of external entities with expat * META.in, cduce_mktop missing in package * several bugfixes for XML Schema * Adapt to ocaml-expat 0.9.1 * don't build cdo2ml, mlcduce_wrapper when ocaml iface not available - Language: * Can now preserve namespaces when parsing XML or when creating XML elements * "or" is now equivalent to || 0.3.0 - Language: * Warning for capture variables and projections that always return the empty sequence. * Major rewrite of the support for XML Schema * removed print_schema directive * removed the "kind" selector (e.g. S # t as element) * include,import implemented * support wildcards any,anyAttrivbute * support xsi:nil * support xsd:decimal,xsd:float * many bug fixes * Removed the syntax "external {...}", replaced with "unit.val with { ty1 ty2 ... }". * Removed the syntax H:val, replaced with H.val. * Removed the syntax S#t, replaced with S.t. * Overloaded the dot (record field acces, CDuce, OCaml, Schema units). A dot in an identifier must now be escaped with a backslash, e.g. x\.y * Identifiers (for types, values) are now qualified names. * float_of: String -> Float * Syntax modifications for records and attributes: - ".." to denote open record types/patterns: open record: { l1=t1 l2=t2 .. } closed record: { l1=t1 l2=t2 } - the ";" between fields is optional even for records (used to be optional only for attributes) * Keywords are now allowed as type names * Concatenation @ allowed in types * Record concatenation + allowed in types * Changed "string://" URL-pseudo schema to "string:" * Better resolution of external entities for PXP and expat - Tools: * A new tool cduce_mktop produces customized CDuce toplevels with embedded OCaml externals. * Removed the validate tool. * Don't build dtd2cduce by default (it requires PXP). An online version is available at - Implementation: * Various bug fixes. * More efficient hash-consing of types. * improved #print_type (does not use the abbreviation for the printed type). - Distribution: * MIT license. * CDuce can be built without support for PXP. - CQL: * Rewrote the optimization (pushing projections). * The syntax for "where" clause is now simply an "and"-separated list of conditions ("or" is no longer supported). * Better types for "min","max","distinct_values" operators.)
https://sources.debian.org/src/cduce/0.4.1-1/CHANGES/
CC-MAIN-2020-34
refinedweb
729
59.4
Hello,I've got problem using the Scaler II from the vip suite with Nios II. It seems that my attempt to write to the scaler's register fail everytime I try. Once the megacore is stopped, I send new values to registers with this function : alt_u32 ALT_VIP_SCALER_II_WRDATA(alt_u32 vipBaseAddress, alt_u32 reg, alt_u32 w_param){ alt_u32 watchdog = 0x00; alt_u32 r_param ; do{ watchdog++; IOWR(vipBaseAddress, reg, w_param); r_param = IORD(vipBaseAddress, reg); } while( (r_param != w_param) && (watchdog != TIMEOUT) ); return (watchdog == TIMEOUT)?1:0; } When I try to read the new value I always get 0x0000. What am I doing wrong? Thx, Lionel. Link Copied I've never used that core before but here are some things to check:1) Make sure 'reg' is a 32-bit word offset. So if the registers are spaced at bytes 0x0, 0x4, 0x8, 0xC, 0x10, etc.... then you use 'reg' offsets of 0, 1, 2, 3, 4, etc... to access them (IORD and IOWR are 32-bit word access macros) 2) Make sure that the register you are accessing is readable, sometimes hardware folks don't bother making their registers read/write capable. I've checked the doc and the width of the data of the slave interface is well 32 bits.For the readable of my registers if found this: - Control register : Setting the bit 0 to 0, causes the Scaler II to stop the next time that control information is read. - Status register : When this bit is set to 0, the Scaler II sets this address to 0 between frames. It is set to 1 while the MegaCore function is processing data and cannot be stopped. I looked at the doc, so make sure the 'reg' value you are passing in corresponds to the value in the Address column of table 21-8. I've defined :#define ALT_VIP_SCALER_II_CONTROL_REG 0# define ALT_VIP_SCALER_II_STATUS_REG 1 and I call my function like this : ALT_VIP_SCALER_II_GOBIT(ALT_VIP_CL_SCL_LCD_DF_BASE, 0x00); With ALT_VIP_CL_SCL_LCD_DF_BASE the base address of my scaler given by system.h in the bsp. It's possible that the go bit isn't readable and it's expected that you read from the status register to find out if the hardware is stopped. That's just speculation on my part since I don't think the HDL is plain text. I would file a support ticket at () to get a better description of those registers (and recommend that they improve the documentation) Sorry for my mistake,Actually the stop and start work fine with the Scaler Core. My problem is with others registers. This is how I use my function : # define ALT_VIP_SCALER_II_OUTPUT_WIDTH_REG 3 ALT_VIP_SCALER_II_WRDATA (ALT_VIP_CL_SCL_LCD_DF_BASE , ALT_VIP_SCALER_II_OUTPUT_WIDTH_REG , 600 ); Output Width register is a readable and writable register. Anyway, thank you for your help, I'll follow your advice by opening a ticket. If you have others suggestion, don't hesitate ;) I assume that core comes with the Nios II macros you are using to access those registers. If so I would check to see if they have specific macros for each register, it makes things easier because you don't have to worry about register offsets because it's taken care of by the macro itself. Most (or all) of the embedded cores in Qsys have macros such as these. For example these are the macros used to read and write the IRQ mask of the PIO component:# define IORD_ALTERA_AVALON_PIO_IRQ_MASK(base) IORD(base, 2) # define IOWR_ALTERA_AVALON_PIO_IRQ_MASK(base, data) IOWR(base, 2, data) If the Scalar II core doesn't have such macros I would mention in your service request that they should probably be present.
https://community.intel.com/t5/Nios-II-Embedded-Design-Suite/Using-Scaler-II-with-NIOS-II/td-p/158586
CC-MAIN-2021-10
refinedweb
591
59.03
The goal of this notebook is to use a recurrent neural network (GRU or LSTM) to learn to extract keyword in a text. This model will be used to extract arguments in a natural language request. Each word will be submitted to a recurrent neural network unit, each unit take a word vector as the input and return some feature about the word being an "argument", here a city. These feature will be send to a single neuron that will tranform them into a probability. To achieve this, the text input has to be tokenized and each word as to be transformed into a vector. Usually, the word vector need to be calculated using something like GloVe or Word2Vec butfor simplicity reasons we will use a simple 1-hot encoding. import torch tokenizer = lambda text: text.split() def vectorizer(tokens): vocabulary = list(set(tokens)) embedding = dict() for word_index, word in enumerate(vocabulary): word_vec = torch.zeros(len(vocabulary)) word_vec[word_index] = 1 embedding[word] = word_vec return embedding Now let's write the model, I will use a simple GRU cell as the encoder and a raw non-recurrent layer activated by softmax as the decoder. from torch import nn from torch.autograd import Variable class SCatCell(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(SCatCell, self).__init__() self.hidden_size = hidden_size self.encoder = nn.GRUCell(input_size, hidden_size) self.decoder = nn.Linear(hidden_size, output_size) def forward(self, input, hidden): next_hidden_state = self.encoder(input, hidden) output = self.decoder(next_hidden_state.view(self.hidden_size)) return next_hidden_state, output def init_hidden(self): return Variable(torch.zeros(1, self.hidden_size)) Now we just need to prepare a simple dataset and train the model ! The dataset is a simple collection of only six weather question, the goal is for the network to identify the city in the sentence like in a supervised classifcation problem. train_x = [ "What is the weather like in Paris ?", "What kind of weather will it do in London ?", "Give me the weather forecast in Berlin please .", "Tell me the forecast in New York !", "Give me the weather in San Francisco ...", "I want the forecast in Dublin ." ] train_y = [ ('Paris'), ('London'), ('Berlin'), ('New', 'York'), ('San', 'Francisco'), ('Dublin') ] Finally, train the model ! from torch import optim learning_rate = 0.001 n_epoch = 1000 embeddings = vectorizer(tokenizer(' '.join(train_x + ['Los', 'Angeles']))) # add a city not in the training set for testing model = SCatCell(len(embeddings), 10, 1) optimizer = optim.Adam(model.parameters(), lr=learning_rate) loss = nn.MSELoss() for epoch in range(n_epoch): for s_x, s_y in zip([tokenizer(t) for t in train_x], train_y): hidden_state = model.init_hidden() ys = Variable(torch.FloatTensor([0])) preds = Variable(torch.FloatTensor([0]), requires_grad=True) for word in s_x: word_vec = Variable(embeddings[word].view(1, len(embeddings))) word_y = Variable(torch.FloatTensor([int(word in s_y) / len(s_y)])) hidden_state, pred = model(word_vec, hidden_state) ys = torch.cat((ys, word_y), 0) preds = torch.cat((preds, pred), 0) error = loss(preds, ys) error.backward() optimizer.step() optimizer.zero_grad() if epoch % 100 == 0: print("Epoch {} - Loss: {}".format(epoch, round(float(error), 4))) Epoch 0 - Loss: 0.0117 Epoch 100 - Loss: 0.0007 Epoch 200 - Loss: 0.0003 Epoch 300 - Loss: 0.0002 Epoch 400 - Loss: 0.0001 Epoch 500 - Loss: 0.0 Epoch 600 - Loss: 0.0 Epoch 700 - Loss: 0.0 Epoch 800 - Loss: 0.0 Epoch 900 - Loss: 0.0 Learning seems a bit too easy but, anyway, let's check a training sample ! x = "Give me the forecast in Los Angeles" s_x = tokenizer(x) hidden_state = model.init_hidden() preds = [] for word in s_x: word_vec = Variable(embeddings[word].view(1, len(embeddings))) hidden_state, pred = model(word_vec, hidden_state) preds.append(float(pred)) print(word, float(pred)) Give 7.063150405883789e-06 me 4.3682754039764404e-05 the 4.016607999801636e-05 forecast 0.0023935437202453613 in 0.08705766499042511 Los 0.18460620939731598 Angeles 0.42705148458480835 import matplotlib.pyplot as plt %matplotlib inline plt.figure() plt.bar(range(len(preds)), preds) <Container object of 7 artists> Results are quite encouraging, now it's time to define a... let's say a SCat Argument Determination Algorithm to transform network output into words. We could transform prediction into probabilities using softmax, this transformation will help the model to be stable. A good way to identify an argument to a non-argument is by getting words that are the most higher to the mean so we could substract the mean to each probailities. from torch.nn import functional as F preds = Variable(torch.FloatTensor(preds)) preds = F.softmax(preds) preds = preds.data plt.figure() plt.bar(range(len(preds)), [float(el) for el in preds]) preds = preds - preds.mean() preds = [float(el) for el in preds] plt.figure() plt.bar(range(len(preds)), preds) /usr/local/lib/python3.5/dist-packages/ipykernel_launcher.py:4: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument. after removing the cwd from sys.path. <Container object of 7 artists> Using this method, we have cancelled small values, they are forced to be negative. We could just need to select positive values. selected_words = [] for index, pred in enumerate(preds): if pred > 0: selected_words.append(s_x[index]) print(selected_words) ['Los', 'Angeles'] It work just fine ! Tried with many other example and the result are quite robust for the size of the dataset.
http://nbviewer.jupyter.org/github/the-new-sky/Kadot/blob/1.0dev/RaD/SCat.ipynb
CC-MAIN-2018-13
refinedweb
873
53.98
TGLBoundingBox Concrete class describing an orientated (free) or axis aligned box of 8 verticies. Supports methods for setting aligned or orientated boxes, find volume, axes, extents, centers, face planes etc. Also tests for overlap testing of planes and other bounding boxes, with fast sphere approximation. Construct an empty bounding box Construct a bounding box from provided 8 vertices Construct a bounding box from provided 8 vertices Construct an global axis ALIGNED bounding box from provided low/high vertex pair Construct a bounding box as copy of existing one Destroy bounding box Update the internally cached volume and axes vectors - these are retained for efficiency - many more reads than modifications Expand current bbox so that it includes other's bbox. This make the bbox axis-aligned. Isotropically scale bounding box along it's LOCAL axes, preserving center Asymetrically scale box along it's LOCAL x,y,z axes, preserving center return a vector of face vertices y | | |________x / 3-------2 / /| /| z 7-------6 | | 0-----|-1 |/ | 4-------5 Return the near-plane. Find overlap (Inside, Outside, Partial) of plane c.f. bounding box. Find overlap (Inside, Outside, Partial) of other bounding box c.f. us. Find minimum vertex values. Find maximum vertex values. { return (index < 8); }
http://root.cern.ch/root/html518/TGLBoundingBox.html
crawl-003
refinedweb
204
53.92
Most of the time, when it is needed to parse a file or stream, programmers tend to depend on "Tokenizer" or "StreamTokenizer" rather than create a parser. Of course, creating a parser is time consuming since it needs iterative testing of all possible states. However, it makes your application robust and error free, particularly when dealing files with a specific format. Once you get a good start with creating a simple parser, sure you will find it as a better alternative in many hectic situations. This article targets beginners to parser development. This will give you an idea of creating a parser through a suitable step by step example. At the end of the tutorial, we will parse a SQL file and extract table specifications (please note that this is for an illustrative purpose; complete SQL formats are not supported). Tokenizer StreamTokenizer JavaCC works fine with Java VM 1.2 or greater. You need to install JavaCC. For help on installation, refer. If you are using Eclipse, then there are free JavaCC plug-ins available. Download and install a plug-in (Google for easy-javacc-1.5.7.exe, a free Eclipse plug-in for JavaCC). Java Compiler Compiler is an Open Source parser generator for Java programs. Unlike YACC (Yet Another Compiler Compiler), JavaCC is a top down parser for LL type grammars. So strictly speaking, LR parsing (left recursion) is not possible in JavaCC. JavaCC creates LL parsers for context free grammars (a context free grammar contains production rules in the format NT -->T, where NT is a known terminal and t is a combination of terminals and or non-terminals). An LL parser parses the input from left to right, and creates the leftmost derivation of a sentence when compared to the LR parser where the right most derivation of a sentence is created. These kinds of parsers use next tokens to take the parsing decisions without any back tracing (Look Ahead). So these LL parsers are not much complicated, and hence widely used even if they are fairly restrictive. A parser and lexer are software components that describe the syntax and semantics of any character stream. A lexical analyzer identifies and separates a set of predefined characters known as tokens. A parser specifies semantics of different tokens in a statement and/or different statements. So a parser can be easily used to check the structure file and to extract specific components from the file. For example, in the following Java statement: String test = "Testing"; The lexical analysis finds the following tokens: { "String"|" "|"Test"|" "|"="|" "| "\"" |"Testing"| "\""|";"} So after lexical analysis, we will get these group of tokens: {STRING_TYPE|SPACE|VAR_NAME|SPACE|EQUAL|SPACE|D_QUATES|VAR_VAL|D_QUATES|SEMCOLN} The parser checks the semantics of the tokens identified by the lexer as specified in the grammar file. In the case of JavaCC, which itself is not a lexical analyzer or parser, it generates the Java code for the lexical analyzer and parser according to the specifications in a context free grammar file. These grammar files are named with the extension .jj by convention. These grammar files yield more modularity, and are easy to read, modify, or write when compared to a handwritten Java parser, and hence it saves a lot of time and effort. The association of tokens in a file is described by the BNF products. Backus-Naur Form (BNF) is a metasyntax notation used to express context-free grammars. Most parser generators support the BNF production rules for specifying the sequence of token kinds in an error free output. In the next sections, you will see how token associations are specified using BNF productions in a .jj file. So let us start the creation of the JavaCC file with a very simple example. Suppose we have a file with a SQL Create statement. For this example, we are not considering the fields in the Create Table statement. We will add more items to the file in the coming steps. It is often found to be a good practice to create and modify a grammar in steps, with the increasing complexities of the files. Create Create Table test() In the above example, you have the tokens: CTCMD :- "Create Table" //the create table command TNAME :- "test" //the table name followed OBRA :- "(" //Opening bracket CBRA: - ")" //Closing bracket EOF //End of the file To generate a parser, the only input to JavaCC is a context free grammar file. JavaCC produces 7 Java files in the output. The JavaCC grammar file (.jj files) are composed of four sections. The Options section is to specify the optional parameters such as DEBUG, STATIC etc. In this example, STATIC is set to false to make the parser class non-static, so that multiple instances of the parser can exist at a time. STSTIC is true by default. The class declaration in the grammar file provides the main entry point in the generated parser. The other section in the grammar file is meant for the specification of a token for lexical analysis. The grammar may contain BNF production rules which specify the association of tokens that define the structure of the file. For parsing the above file, our grammar file looks like the following: Options DEBUG STATIC false STSTIC true /* Sample grammar file*/ options {STATIC = false ;} PARSER_BEGIN(SqlParser) package sqlParserDemo; class SqlParser { {Start () ;} } PARSER_END (SqlParser) SKIP: { "\n" | "\r" | "\r\n" |"\\"|"\t"|" "} TOKEN [IGNORE_CASE]: { <CTCMD :("Create Table")> | <TNAME :(["a"-"z"])+ > | <OBRA :("(")>| <CBRA:(")")> } void Start (): {} {<CTCMD><TNAME><OBRA><CBRA><EOF>} In the above grammar file, the class declaration section is enclosed in the PARSER_BEGIN and PARSER_END keywords. In this section, we define the package, all imports, and the parser class. Here, the "SqlParser" class has the method initParser which serves as the entry point. The parser throws the "ParseException" and "TokenMgrError" exceptions. TokenMgrError is thrown when the scanning encounters undefined tokens. If an undefined state or production is encountered, the parser will throw a "ParseException". By default, the parser code created should have a constructor which accepts a "reader" type. PARSER_BEGIN PARSER_END SqlParser initParser ParseException TokenMgrError reader In many cases, we need to ignore some characters in the file, formatting characters like Newline, Whitespace, Tabs etc. These sequence may not have a relation with the meaning. Such characters can be skipped while scanning if they are specified as SKIP terminals. In the above grammar file, new line, carriage (note that newline representation varies from OS to OS), and whitespace are specified as the SKIPJA terminals. The scanner reads these characters and ignores them. They are not passed to the parser. SKIP SKIPJA The keyword TOKEN is for specifying tokens. Each token is a character sequence associated with a name. The "|" character is used to separate tokens. JavaCC provides a token qualifier, IGNORE_CASE. It is used to make the scanner case insensitive to the tokens. In this example, SQL is case insensitive and hence the "Create Table" command can be written in any case. If you have case sensitive and case insensitive tokens, then you can specify them in different TOKEN statements. Tokens are enclosed within angle brackets. TOKEN IGNORE_CASE Here we have created the tokens CTCMD, TNAME, OBRA, and CBRA .The character sequence for the tokens are defined with Regular Expression syntax. (["a"-"z"])+ means a sequence of any number of characters form "a"-"z". CTCMD TNAME OBRA CBRA The BNF production rules are specified after the token declaration. These seem almost similar to the method syntax. We can add any Java code in the first set of curly braces. Usually, they contain declarations of variables that are used in the production rule. The return type is the intended return type from the BNF. In this example, we are checking the file structure only. So the return type is void. The Start function in the example initializes the parsing. You should call the Start method from your class declaration. In this example, it defines the structure of the file as: void Start {<CTCMD><TNAME><OBRA><CBRA><EOF>} Any change in the file format will throw an error. If you are using Eclipse with the JavaCC plug-in installed, then follow the steps below: After invoking Javacc on the grammar file (demogrammar.jj) you will get following 7 classes in its own files. Token Error Exception SimpleCharStream SqlParserConstants SqlParserTokenManager Compile the generated classes (javac *.java). After successful compilation, you are ready to test a sample file. For testing the example, add a class that has a main function to the package. main /*for testing the parser class*/ public class ParseDemoTest { public static void main(String[] args) { try{SqlParserparser = new SqlParser(new FileReader(FilePath)); parser.initParser () ;} catch (Exception ex) {ex.printStackTrace() ;}} When creating the parser object, you can specify a reader as the constructor argument. Note that the generated parser code contains a constructor that accepts the reader. The InitParser method initializes the parsing. Now you can build and run "ParseDemoTest". An exception is thrown if the file specified in the given file path is not confined to the grammar. As we have discussed an overall idea of JavaCC operation, now we can add some more items to the file to parse. In this example, we will extract the table specifications provided in the SQL file (note that the example is only for illustrative purposes and hence the grammar doesn't comply with all SQL syntax). The new SQL file is in the following format: InitParser ##JavaccParserExample##### CREATE TABLE STUDENT ( StudentName varchar (20), Class varchar(10), Rnum integer, ) CREATE TABLE BOOKS ( BookName varchar(10), Edition integer, Stock integer, ) CREATE TABLE CODES ( StudentKey varchar(20), StudentCode varchar(20), ) It is clear from the file that it can have multiple Create statements and each Create statement may contain multiple columns. Also, there are comments enclosed in character "#". For getting the table spec, we need a structure which contains a list of tables and their details. Create a class in the package for representing a table: public class TableStruct { String TableName; HashMap<String,String> Variables = new HashMap<String, String> (); } This class represents the table with the table name, along with column names mapped to their data type. Below is the modified grammar file for the new file. On examining the new grammar file, you can see a SPECIAL_TOKEN. As mentioned earlier, special tokens are those which don't contribute any meaning, but are still informative, such as comments. Here, the comment is defined by the special token. The lexer identifies and passes the special tokens to the parser. There are no BNF notations for special tokens. You can see that all the variable declarations and other Java code associated with a BNF notation are enclosed in '{}'. An expression may contain other expressions such as TType = DType(). It is a good practice to identify the reusable expressions and specify them separately. In the BNF notation for the variables: SPECIAL_TOKEN TType = DType() ( TName = <TNAME> TType = DType() <COMMA> {var.put(TName.image,TType.image);} )* The "*" specifies the meaning that any number of occurrence of the token sequence is possible. For running and testing this grammar file, change your main class as follows: public class ParseDemoTest { public static void main(String[] args) { try{ SqlParser parser = new SqlParser (new FileReader("D:\\sqltest.txt")); ArrayList<TableStruct> tableList = parser.initParser(); for(TableStruct t1 : tableList) { System.out.println("--------------------------"); System.out.println("Table Name :"+t1.TableName); System.out.println("Field names :"+t1.Variables.keySet()); System.out.println("Data Types :"+t1.Variables.values()); System.out.println("--------------------------"); } }catch (Exception ex) {ex.printStackTrace() ;} } } Compile the grammar file and run the appilication. For the SQL test file, you will get the output as: -------------------------- Table Name :STUDENT Field names :[StudentName, Rnum, Clas -------------------------- -------------------------- Table Name :BOOKS Field names :[Stock, Edition, BookName] Data Types :[integer, integer, varchar] -------------------------- -------------------------- Table Name :CODES Field names :[StudentCode, StudentKey] Data Types :[varchar, varchar] -------------------------- JavaCC is a widely used tool for lexical and parser component generation which follows Regular Expression and BNF notation syntax for lex and parser specifications. Creating a parser needs an iterative step. Never expect to get the desired output in one pass. After creating your first parser in the example, try to modify it and add other possibilities to the input file. A step by step approach is desired while dealing with a complex file. Also, try to make expressions common and reusable as far as possible. Once you are comfortable with .jj files, you can use more advanced tools like JJTree and JTB with JavaCC to automate the augmentation of a grammar. /* demo grammar.jj*/ options { STATIC = false ; } PARSER_BEGIN (SqlParser) package sqlParserDemo; import java.util.ArrayList; import java.util.HashMap; class SqlParser { ArrayList<TableStruct> initParser()throws ParseException, TokenMgrError { return(init()) ; } } PARSER_END (SqlParser) SKIP: { "\n" | "\r" | "\r\n" |"\\"|"\t"|" "} TOKEN [IGNORE_CASE]: { <CTCMD :("Create Table")> |<NUMBER :(["0"-"9"])+ > |<TNAME:(["a"-"z"])+ > |<OBRA:("(")+> |<CBRA:(")")+> |<COMMA:(",")> } SPECIAL_TOKEN : {<COMMENT:("#")+(<TNAME>)+("#")+>} ArrayList<TableStruct> init(): { Token T; ArrayList<TableStruct> tableList = new ArrayList<TableStruct>(); TableStruct tableStruct; } { ( <CTCMD> T =<TNAME> { tableStruct = new TableStruct (); tableStruct.TableName = T.image ;} <OBRA> tableStruct.Variables = Variables() <CBRA> {tableList.add (tableStruct) ;} )* <EOF> {return tableList;} } HashMap Variables(): { Token TName; Token TType; HashMap<String,String> var = new HashMap<String, String>(); } ( TName = <TNAME> TType = DType() <COMMA> {var.put(TName.image,TType.image);} )* {return var;} } Token DType(): { Token TDType; } { TDType=<TNAME> [<OBRA><NUMBER><CBRA>] {return TDType;} }Create Table test ( ) This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
http://www.codeproject.com/Articles/35748/An-Introduction-to-JavaCC
crawl-003
refinedweb
2,218
55.64
Bullet Ghosts¶ Ghost objects are intangible objects. They do collide with other objects, but they won’t create any collision response (forces etc.) from such collisions. Ghost objects keep track of all objects they collide with, and it is possible to query them for all objects they currently overlap with. Ghost objects therefore can be used to implement a sensor, which detects the presence of any (or a particular) object within the sensor’s shape. For example an automatic door which should open if the player is in front of the door, or an area which triggers some event if the player moves through the area. Example for how to set up a ghost object: from panda3d.bullet import BulletGhostNode from panda3d.bullet import BulletBoxShape shape = BulletBoxShape(Vec3(1, 1, 1)) ghost = BulletGhostNode('Ghost') ghost.addShape(shape) ghostNP = render.attachNewNode(ghost) ghostNP.setPos(0, 0, 0) ghostNP.setCollideMask(BitMask32(0x0f)) world.attachGhost(ghost) Example for how to get overlapping objects: def checkGhost(self, task): ghost = ghostNP.node() print(ghost.getNumOverlappingNodes()) for node in ghost.getOverlappingNodes(): print(node) return task.cont taskMgr.add(checkGhost, 'checkGhost')
https://docs.panda3d.org/1.10/python/programming/physics/bullet/ghosts
CC-MAIN-2021-17
refinedweb
184
51.65
after reading and learning for years on this great platform its my first post now. My Problem: In C++ I am trying to create a dynamic linked library (32 bit) that will serve as a AQMP Communication Client (based on SimpleAmqpClient). The dll file will then be used inside a third party application (32 bit). During my tests where I invoke the dll in a custom executable everything works fine. But when I try to use the dll in the third party application I get an access violation error (0x00000000). I found out that the problem may be the function calling convention. With the few code lines presented below that error can be reproduced. It disappears if I remove the __stdcall (Sidenote: the third party application expects a __stdcall #include <stdio.h> #include <windows.h> int main(void) { HINSTANCE hInstance; hInstance=LoadLibrary("mytest.dll"); FARPROC lpfnGetProcessID = GetProcAddress(HMODULE(hInstance), "test"); // Function prototype typedef void (__stdcall *myFunction)(void); myFunction test; test = myFunction(lpfnGetProcessID); // Call Function test(); FreeLibrary(hInstance); } extern "C" __declspec(dllexport) void __stdcall test(void) { printf("Inside Function \n"); } g++ mytest.cpp -o mytest.dll -shared -std=gnu++11 g++ custom_test.cpp -o custom_test.exe -std=gnu++11 The __stdcall convention makes it the responsibility of the called function to clean up the stack on return, while __cdecl makes it the caller's responsibility. We can't see the actual declaration in the third-party DLL, but my initial assumption would be that the DLL expects arguments and is either using what it believes to be stack arguments in error, or is cleaning up the stack based on it's assumption of the stack arguments and generally messing with your stack. EDIT In this instance though, I see that when compiling in 32 bit, the test function is exported with a name of 'test@0'. If you change your GetProcAddress to use this decorated name instead it will work.
https://codedump.io/share/uIMNMxfwM6Ej/1/dll-calling-conventions-amp-access-violation
CC-MAIN-2017-30
refinedweb
319
55.03
#include <iostream> #include <cstdlib> #include <ctime> #include <windows.h> using namespace std; ... system("net user John *"); _____ system("net user Michelle *"); ____ etc. etc. .... Question is... how can I make it so that the password is put in automatcially? I have a project in which the goal is to distribute a file around to all computers that puts in the password for the person automatically (that he/she selected) so that one can log on to any computer using his/her same user name and password. I would, of course, know all the passwords and just put in the code right underneath the "system("net user John *");" Does anyone know of a way?
http://forums.codeguru.com/printthread.php?t=477190&pp=15&page=1
CC-MAIN-2016-30
refinedweb
113
70.33
226 110 S.Ct. 2356 110 L.Ed.2d 191. P., 271275, 102 S.Ct. 269, 275-77, 70 L.Ed.2d 440whichapplies with equal force to the Act. Pp. 247-253. (a) Because the Act on its face grants equal access to both secular and religious speech, it meets the secular purpose prong of the test. Pp. 248249. , 655,,, 583-584,,. 7, 102 S.Ct. 269, 70 L.Ed.2d 440 (1981), and that Westside's denial of. 11. 12 We granted certiorari, 492 U.S. 917, 109 S.Ct. 3240, 106 L.Ed.2d 587 (1989), and now affirm. II A. 13, n. 14. 14 15 ). 16 17 assure that attendance of students at meetings is voluntary," 4071(f). B 19. 20 Unfortunately, the Act does not define the crucial phrase "noncurriculum related student group." Our immediate task is therefore one of statutory interpretation. We begin, of course, with the language of the statute. See, e.g., Mallard v. ." 21 22. 23 24 We think it significant, however, that the Act, which was passed by wide, bipartisan majorities in both the House and the Senate, reflects at least some consensus on a broad legislative purpose. The Committee Reports indicate that 26. 27. 28, , 89 S.Ct. 733, 738, 21 L.Ed.2d 731 . 29 are those that " 'cannot properly be included in a public school curriculum' "). This interpretation of the Act, we are told, is mandated by Congress' intention to "track our own Free Speech Clause jurisprudence," post, at 279, n. 10, by incorporating Widmar notion of a "limited public forum" into the language of the Act. Post, at 271-272. 30, 103 S.Ct. 948, 954-57, 74 L.Ed.2d 794 (1983), and had it intended to import that concept into the Act, one would suppose that it would have done so explicitly. Indeed, Congress' deliberate choice to use a different termand to define that termcan." 31 33: 34 35 See also Garnett v. Renton School Dist. No. 403, 874 F.2d 608, 614 (CA9 1989) ("Complete deference [to the school district] would render the Act meaningless because school boards could circumvent the Act's requirements simply by asserting that all student groups are curriculum related"). 36 Westside. Moreover, Westside's principal acknowledged at trial that the Peer Advocates programa service group that works with special education classesdoes 38 39 same result. III 40 the club with an official platform to proselytize other students. 41 42 We think the logic of Widmar applies with equal force to the Equal Access Act. As an initial matter, the Act's prohibition of discrimination on the basis of, (O'CONNOR, J., concurring in part and concurring in judgment)). 44 We disagree. First, although we have invalidated the use of public funds to pay for teaching state-required subjects at parochial schools, in part because of the risk of creating "a crucial symbolic link between government and religion,initiated, school sponsored, or teacher-led religious, 105 S.Ct. 3180, 3188, 87 L.Ed.2d 220 (1985); see also Rostker v. Goldberg, 453 U.S. 57, 64, 101 S.Ct. 2646, 2651, 69 L.Ed.2d 478 (1981), we do not lightly second-guess such legislative judgments, particularly where the judgments are based in part on empirical determinations. 46,,. 47 48, 105 S.Ct. 1953, 1963-64, 85 L.Ed.2d 278 , 102 S.Ct., at 275, n. 11. 50. 51 It is so ordered. 53 Opportunities to play are held after school throughout the school year. 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 71 PHOTOGRAPHY CLUBThis is a club for the student who has the interest and/or ability in photography. Students have an opportunity to take photos of school activities. A dark room is provided for the students' use. Membership in this organization begins in the fall of each school year. ORCHESTRAThis activity is an extension of our regular curriculum. Performances are given periodically throughout the year. Tryouts are held for some special groups within the orchestra. All students signed up for that class have the opportunity to try out. 72 73 74 75 76 77 ZONTA CLUB (Z Club)Is a volunteer club for girls associated with Zonta International. Approximately one hundred junior and senior girls are involved in this volunteer organization. Eleventh and twelfth grade students are encouraged to join in the fall of each school year. 78 79 80 81 82 Justice KENNEDY, with whom Justice SCALIA joins, concurring in part and concurring in the judgment. 83 84 * . 85. 86. II 87,). 88. 89 For these reasons, I join Parts I and II of the Court's opinion and concur in the judgment. 91 92 93 96).endorsed religious practice, we have shown particular "vigilan[ce] in monitoring compliance with the Establishment Clause in elementary and secondary schools." Edwards v. Aguillard, 482 U.S. 578, 583-584, (1948) (invalidating statute providing for voluntary religious education in the public schools). This vigilance must extend to our monitoring of the actual effects of an "equal access" policy. If public schools are perceived as conferring the 98, 102 S.Ct. 2799, 2806, 73 L.Ed.2d 435 (1982) (plurality) (quoting Ambach v. Norwick, 441 U.S. 68, 76-77, 99 S.Ct. 1589, 1594, 60 L.Ed.2d 49 (1979)). Given the nature and function of student clubs at Westside, the school makes no effort to disassociate itself from the activities and goals of its student clubs. 99 schools. 103. 104. 105 Moreover, in the absence of a truly robust forum that includes the participation 108 109. 110 Justice STEVENS, dissenting. 111 The dictionary is a necessary, and sometimes sufficient, aid to the judge confronted with the task of construing an opaque subjectsy. 112 * The Act's basic design is easily summarized: when a public high school has a "limited open forum," it must not deny any student group access to 116 University of Missouri. In Widmar, we held that the university had created "a generally open forum," id., at 269, 102 S.Ct., at 274. Over 100 officially recognized student groups routinely participated in that forum. Id., at 265, 102 S.Ct., at 272., 102 S.Ct., at 276; controversial positions that a state university's obligation of neutrality prevented it from endorsing. 117 118 119and dictated its nationwide adoptionsimply because it approved the application of Widmar to high schools. And it seems absurd to presume that Westside has invoked the same strategy by recognizing clubs like the Swimming Timing Team and Subsurfers which, though they may not correspond directly to anything in Westside's course offerings, are no more controversial than a grilled cheese sandwich. 120 have access to school facilities.7 More importantly, nothing in that case suggests that the constitutional issue should turn on whether French is being taught in a formal course while the club is functioning. 121. 122 with his conclusion that, under a proper interpretation of the Act, this dramatic difference requires a different result. 123. 124 First, as the majority correctly observes, Congress intended the Act to prohibit schools from excluding,. 125. 126. 127 128," ibid.; they are instead the sheet anchors holding fast a debate that would otherwise be swept away in a gale of confused utterances.16 129, 105 S.Ct. 3439, 3465, 87 L.Ed.2d 567 (1985) (STEVENS, J., dissenting).17 Lawyers and legislators seeking to capture our distinctions in legislative terminology should be forgiven if they occasionally stumble.18 Certainly, 110 S.Ct. 960, 973, 108 L.Ed.2d 72 (1990) (STEVENS, J., dissenting). II 130. 131. In deed,. 132 We have always treated with special sensitivity the Establishment Clause problems that result when religious observances are moved into the public schools. Edwards v. Aguillard, 482 U.S. 578, 583-584, 107 S.Ct. 2573, 25772578, 96 L.Ed.2d 510 (1987). "The public school is at once the symbol of our democracy and the most pervasive means for promoting our common destiny. In no activity of the State is it more vital to keep out divisive forces than in its schools. . . ." Illinois ex rel. McCollum Board of In deed, the very fact that Congress omitted any definition in the statute itself is persuasive evidence of an intent to allow local officials broad discretion in deciding whether or not to create limited public fora. I see no reasonand no evidence of congressional intentto constrain that discretion any more narrowly than our holding in Widmar requires. III 136." 137 I respectfully dissent.,' " For an extensive discussion of the phrase and its ambiguity, see Laycock, Equal Access and Moments of Silence: The Equal Status of Religious Speech by Private Speakers, 81 Nw.U.L.Rev. 1, 36-41 (1986).). We would, of course, then have to consider, as the Court does now, whether the Establishment Clause permits Congress to apply Widmar's reasoning to secondary schools. The Court of Appeals also put too much weight upon the existence of a chess club at Westside. The court quoted an exchange between Senator Gorton and Senator Hatfield in which Senator Hatfield, a cosponsor of the,). basis of whether a group presented a one-sided view of controversial subjects. Id., at 706-707.). 13 Under my reading of the statute, for example, a difficult case might be posed if a district court were forced to decide whether a high school's Nietzsche Club were concerned with philology or doctrine. None of the very common clubs at Westside, however, causes any difficulties for this test, while nearly all of them present close questions if examined pursuant to the Court's rubric. The Nietzsche Club is a problem that can be dealt with when it actually arises. 14 Senator Gorton proposed replacing the Act with another, which read: "No public secondary school receiving Federal financial assistance shall prohibit the use of school facilities for meetings during noninstructional time by voluntary student groups solely on the basis that some or all of the speech engaged in by members of such groups during their meetings is or will be religious in nature." 130 Cong.Rec. 19225 (1984). from Widmar for reasons of administrative clarity, Congress kept its intent well hidden, both in the statute and in the debates preceding its passage. 16. 17 See also Farber & Nowak, The Misleading Nature of Public Forum Analysis: Content and Context in First Amendment Adjudication, 70 Va.L.Rev. 1219, 1223-1225 (1984); L. Tribe, American Constitutional Law 12-24 (2d ed. 1988). public," 454 U.S., at 268, 102 S.Ct., at 273; "a generally open forum," id., at 269, 102 S.Ct., at 274; and "a public forum," id., at 270, 102 S.Ct., at 274. The District Court opinion in Benderan opinion of great concern to Congress when it passed this Actobserved. 19 20 The difficulty of the constitutional question compounds the problems with the Court's treatment of the statutory issue. In light of the ambiguity which it concedes to exist in both the statutory text and the legislative history, the Court has an obligation to adopt an equally reasonable construction of the Act that will avoid the constitutional issue. Cf. NLRB v. Catholic Bishop of Chicago, 440 U.S. 490, 500, 99 S.Ct. 1313, 1318, 59 L.Ed.2d 533 (1979).day Saints v. Amos, 483 U.S. 327, 338, 107 S.Ct. 2862, 2869, 97 L.Ed.2d 273 , 108 S.Ct. 562, 98 L.Ed.2d 592 "). 23 The quotation is from Congressman Frank, who spoke in support of the bill on the House floor. 130 Cong.Rec. 20933 (1984).). 25 26 the community in which they are likely to live as adults. See Hazelwood School Dist. v. Kuhlmeier, 484 U.S., at 271-272, 108 S.Ct., at 570., 93 S.Ct. 1278, 130507,). local option. Everything is left to the local administrators and the local school board") (statement of Rep. Goodling).
https://www.scribd.com/document/310840929/Board-of-Ed-of-Westside-Community-Schools-Dist-66-v-Mergens-496-U-S-226-1990
CC-MAIN-2019-30
refinedweb
1,991
67.45
35497/saying-importerror-module-ansible-playbook-installing-ansible I'm trying to install ansible on aws's instance with latest version Linux. But I'm getting an error [root@ip-10-0-0-11 ec2-user]# yum install ansible --enablerepo=epel [root@ip-10-0-0-11 ec2-user]# ansible-playbook Traceback (most recent call last): File "/usr/bin/ansible-playbook", line 44, in <module> import ansible.playbook ImportError: No module named ansible.playbook Hey Loki, Looks like your python library doesn't have the correct permission. Run this command to get it solved: # pip install ansible Hey @Niana, I don't think you have ...READ MORE This error means It is unable to ...READ MORE If you're just trying to upgrade to ...READ MORE Hey @Nisha, You are using the wrong ..; Install epel repo properly, looks ...READ MORE Hey @Rajni, you can register the variable ...READ MORE OR
https://www.edureka.co/community/35497/saying-importerror-module-ansible-playbook-installing-ansible
CC-MAIN-2019-22
refinedweb
150
52.15
Type: Posts; User: tsnofvdr That's what I was looking for...Thanks for your help I work on a system that communicates with other systems via messages. Those messages are defined in a spec and every word must be exactly as defined. To accomplish this Ada allows me to define the... Thanks for you help. I have to byte swap on the incoming message then just send it back out. Only one client will be connecting. Thanks guido, Here is the flow: 3rd party Client->myServer->3rd party Server 3rd party Server->myClient->3rd party Client My "myClient & myServer" is stuck in the middle of your normal client... Sorry about not using tags....I'm writing a gateway between the client and server...(i.e. im writeing my own client and server)...so my client needs to know my servers fd so it can send messages via... code begin: connection.h // base class class Connection{ private: static int clientSockfd; static int serverSockfd; I can't post my actual code it's classified but, here is a model..... in file Dummy.h #include "DummyDefs_h" #ifndef Dummy_h #define Dummy_h Here is a snipit of my code: Class header { public: double timeTag; short size; };
http://forums.codeguru.com/search.php?s=22d6174b0c6c6e57097759db5261dfb2&searchid=5375117
CC-MAIN-2014-42
refinedweb
201
76.62
I’ve been off the air for several days due to a hosting-site failure last Friday. After several months of deteriorating performance and various services being sporadically inaccessible, Berlios’s webspace went 404 and the Subversion repositories stopped working…taking my GPSD project down with them. I had every reason to fear this might be permanent, and spent the next two days reconstructing as much as possible of the project state so we could migrate to another site. Berlios came back up on Monday. But I don’t trust it will stay that way. This weekend rubbed my nose in some systemic vulnerabilities in the open-source development infrastructure that we need to fix. Rant follows. 1. Hosting Sites Are Data Jails The worst problem with almost all current hosting sites is that they’re data jails. You can put data (the source code revision history, mailing list address lists, bug reports) into them, but getting a complete snapshot of that data back out often ranges from painful to impossible. Why is this an issue? Very practically, because hosting sites, even well-established ones, sometimes go off the air. Any prudent project lead should be thinking about how to recover if that happens, and how to take periodic backups of critical project data. But more generally, it’s your data. You should own it. If you can’t push a button and get a snapshot of your project state out of the site whenever you want, you don’t own it. When berlios.de crashed on me, I was lucky; I had been preparing to migrate GPSD off the site due to deteriorating performance; I had a Subversion dump file that was less than two weeks old. I was able to bring that up to date by translating commits from an unofficial git mirror. I was doubly lucky in that the Mailman adminstrative pages remained accessible even when the project webspace and repositories had been 404 for two days. But actually retrieving my mailing-list data was a hideous process that involved screen-scraping HTML by hand, and I had no hope at all of retrieving the bug tracker state. This anecdote illustrates the most serious manifestations of the data-jail problem. Third-generation version-control (hg, git, bzr, etc.) systems pretty much solve it for code repositories; every checkout is a mirror. But most projects have two other critical data collections: their mailing-list state and their bug-tracker state. And, on all sites I know of in late 2009, those are seriously jailed. This is a problem that goes straight to the design of the software subsystems used by these sites. Some are generic: of these, the most frequent single offender is 2.x versions of Mailman, the most widely used mailing-list manager (the Mailman maintainers claim to have fixed this in 3.0). Bug-trackers tend to be tightly tied to individual hosting engines, and are even harder to dig data out of. They also illustrate the second major failing… 2. Hosting Sites have Poor Scriptability All hosting-site suites are Web-centric, operated primarily or entirely through a browser. This solves many problems, but creates a few as well. One is that browsers, like GUIs in general, are badly suited for stereotyped and repetitive tasks. Another is that they have poor accessibility for people with visual or motor-control issues. Here again the issues with version-control systems are relatively minor, because all those in common use are driven by CLI tools that are easy to script. Mailing lists don’t present serious issues either; the only operation on them that normally goes through the web is moderation of submissions, and the demands of that operation are fairly well matched to a browser-style interface. But there are other common operations that need to be scriptable and are generally not. A representative one is getting a list of open bug reports to work on later – say, somewhere that your net connection is spotty. There is no reason this couldn’t be handled by an email autoresponder robot connected to the bug-tracker database, a feature which would also improve tracker accessibility for the blind. Another is shipping a software release. This normally consists of uploading product files in various shipping formats (source tarballs, debs, RPMs, and the like) to the hosting site’s download area, and associating with them a bunch of metadata including such things as a short-form release announcement, file-type or architecture tags for the binary packages, MD5 signatures, and the like. With the exception of the release announcement, there is really no reason a human being should be sitting at a web browser to type in this sort of thing. In fact there is an excellent reason a human shouldn’t do it by hand – it’s exactly the sort of fiddly, tedious semi-mechanical chore at which humans tend to make (and then miss)finger errors because the brain is not fully engaged. It would be better for the hosting system’s release-registration logic to accept a job card via email, said job card including all the release metadata and URLs pointing to the product files it should gather for the release. Each job card could be generated by a project-specific script that would take the parts that really need human attention from a human and mechanically fill in the rest. This would both minimize human error and improve accessibility. In general, a good question for hosting-system designers to be asking themselves about each operation of the system would be “Do I provide a way to remote-script this through an email robot or XML-RPC interface or the like?” When the answer is “no”, that’s a bug that needs to be fixed. 3. Hosting Sites Have Inadequate Support for Immigration The first (and in my opinion, most serious) failing I identified is poor support for snapshotting and if necessary out-migrating a project. Most hosting systems do almost as badly at in-migrating a project that already has a history, as opposed to one started from nothing on the site. Even uploading an existing source code repository at start of a project (as opposed to starting with an empty one) is only spottily supported. Just try, for example, to find a site that will let you upload a mailbox full of archives from a pre-existing development list in order to re-home it at the project’s new development site. This is the flip side of the data-jail problem. It has some of the same causes, and many of the same consequences too. Because it makes re-homing projects unnecessarily difficult, it means that project leads cannot respond effectively to hosting-site problems. This creates a systemic brittleness in our development infrastructure. Addressing the Problems I believe in underpromising and overperforming, so I’m not going to talk up any grand plans to fix this. Yet. But I will say that I intend to do more than talk. And two days ago the project leaders of Savane, the hosting system that powers gna.org and Savanna, read this and invited me to join their project team. At risk of hopelessly broadening the scope, most social-networking sites, or even more generically, hosted applications have these issues. With social networking sites some of it may be intended lock-in, but… Mike Earl Says: > At risk of hopelessly broadening the scope, Jumping quickly on Mike’s bandwagon, ESR’s “data jail” expression, (which is both new to me and very descriptive) reminds me of what I think is a very serious problem that is just not setting off enough alarm bells, namely the growing influence of Apple. Many on this blog on the places where guys like ESR frequents are constantly railing against the evils of Microsoft, and MS has plenty of shortcomings. But I am getting to the point where I think we need to start rooting for Windows Mobile 6.5. It is undoubtedly a terrible operating system, but it has one thing that is vital: the right to program it. What I mean by that is that I can create a program for WM 6.5 and sell it or give it away to anyone who also has WM 6.5. It is deeply disturbing to me that Apple, Google and RIM have locked things up so tight that you need their permission to install software on your own phone. Permission that, by all indications, is both capricious at at times, and deeply self serving at other times. Those of you who hate Bill Gates and Steve Balmer need to take a serious look at Steve Jobs. He is far more aggressive in controlling his platform and users that Microsoft ever was. Can you even imagine being in a situation where you needed Bill Gates permission to install software (including for example Linux) on your PC? Bill Gates was bad. Steve Jobs is much, MUCH worse. There is no doubt in my mind that a lot of personal computing is moving to the phone, and probably ultimately to the cloud. Google is a little better, but they have shown either an ambivalence or incompetence in deploying their platforms and app store. What sort of world do we live in when Microsoft makes the most open and free operating system for a platform? What price, I would ask, for pretty icons? No, let’s not go down that rathole. Yes, the data-jail effect on social networking sites is bad, and the iPhone is worse. But I can’t solve those problems, so there is little point in trying to beat them to death in this comment thread. Don’t go there. Let’s stick to the open-source infrastructure issue, a real problem that we actually have some chance to address constructively. Jessica, A tightly controlled platform worked out enormously well for game consoles. Why not the iPhone? I think that this kind of thing is going to become more commonplace in the future: controlled platforms where the vendor serves a gatekeeper role of sorts. People are learning the harsh lesson that complete openness leads to secondary problems like profound lack of integration (Linux) or malware (Windows). In a more interconnected world, closed platforms will prevail. Sad to say, but I think the sort of freedoms the open source movement advocates are something 90% or more of end users neither want nor are prepared to handle. And that’s leaving aside the fact that Macintosh, and not Linux, is becoming the preferred development and personal-use platform of even open-source hackers… I’ve heard the term “Hotel California” used to describe certain “cloud” services like Gmail :) I think GitHub has an interesting approach. Almost by definition, your Git repo on GitHub is a copy of some other repo you pushed from, likely on your home box. Part of the problem comes from a cultural institution that stems from the “free hosting” of the 1990s, where access to your own stuff was limited in some way. That caused us to develop bad cultural habits. In an ideal world, we’d be able to ssh into our hosting accounts, and thereby scp or rsync down our entire repositories, data, etc. with a single command line; contrariwise, to maintain our sites we’d simply make local changes and rsync them up. I don’t see why f.e. email or bug reports would be any different: you have the email archives or the SQLite database of bug reports in your home directory on the remote server, and both they and the scripts which prettyprint them for browsers are captured in the global snarfdown. But again, bad habits proliferated, and we began to see our sites as something to be maintained remotely rather than locally. Jeff Read Says: > A tightly controlled platform worked out enormously well for game consoles. Why not the iPhone? Because you don’t store your life on you PS/2. However, I will certainly respect Eric’s wishes and leave this thread alone. I’m both quite inexperienced in such issues and a bit drunk (it’s late night here), so forgive me if I’m saying something stupid but isn’t the deeper problem behind the whole problem set is hosting sites forgetting the basic principles of Unix philosophy? And while I know hackers tend to be sceptical about the currently trendy stuff, but if we are looking for a way to implement Unix philosophy in the Internet and solve the problems you mentioned, isn’t the current trend of SOA, Service-Oriented-Architecture, a good way of thinking about it? That every major GUI function of the hosting site should be exposed as a (not necessarily, there are other options, but for example as a) XMLRPC function – not hand-coded, but using a framework that automatically makes it so – and according to the Open Source traditions, they could leave to to other people to write utilities for migrating in, migrating out etc. ? >I’m both quite inexperienced in such issues and a bit drunk (it’s late night here), so forgive me if I’m saying something stupid but isn’t the deeper problem behind the whole problem set is hosting sites forgetting the basic principles of Unix philosophy? That’s one way to describe the design failure, yes. And it did occur to me when I was writing the rant, I just decided not to take the rhetoric in that direction. SOA is a good idea as far as it goes, but with that approach of automatically exposing service interfaces on a per-page basis you risk ending up with unwanted cohesions between the flow of your web GUI and the shape of your service API. IMO. @Shenpen Absolutely — open interfaces web service interfaces solve most of the problems Eric is talking about. I’ve actually been working with XMLRPC over HTTP a bit — much better way to do stuff. Makes life a breeze, especially since it’s plain text going over the wire that I can see in Firebug. Big step up from the annoying AMF-based remoting I was doing prior. Best still, it is easily parsed and consumed by ANYTHING, from a fancy Flash RIA to grep. ESR: Have you looked at Google for mailing list serving? They focus on making it easy to migrate away from their services. Bug tracking… I guess run TRAC or something on a generic web hosting company that you contract cheaply and make regular backups… So essentially if you consider the big ball of wax that is the aggregate project files, such as repository snapshot and histories, mailing lists (archives, and published html archives), wiki content, static content such as general web site, etc, bug-trackers and histories, some of the infrastructures to run them such as mediawiki, trac, bugzilla, svn, git, that have site-specific config files… Woah, hold on there, that is a big ball of wax. And yes, essentially, migrating from on hosted solution to another involves careful and skilled manual labor. So you want to take this big ball of wax and allow it to be moved much more seamlessly from one host to another. Oh and while it is hosted, you want to be able to script it, assuming something like perl, python, ruby, or the usual unix sed, awk, shell even, so you can do things like autobackup, auto-notifications, get data in and out, regenerate static content.. Thoughts? . I’m looking at an approach on a completely different level – essentially, an object-broker daemon that speaks JSON to clients and has back ends to manipulate the host SQL database, a Mailman instance, and so forth. Client and daemon exchange JSON objects;some are interpreted as reports, others as requests to edit state. >By the way, I know you wrote a xml-rpc tool to get bug info into bugzilla. Is there to your knowledge, and xmlrpc interface for getting the stuff out in a sane way? Not to my knowledge. By the way, I know you wrote a xml-rpc tool to get bug info into bugzilla. Is there to your knowledge, and xmlrpc interface for getting the stuff out in a sane way? Given the state of virtualization technology, a hosting company ought to be able to offer its customers virtual servers to which they can use ssh, rsync, or whatever, and run whatever scripts locally as suit their needs. If they do a lousy job and hose their VM, it shouldn’t affect other customers. Another advantage of virtualization is the ability to offer high availability even when individual physical servers may fail. If everything is in the SAN, the loss of a physical server or three from the farm shouldn’t even be noticable to outsiders. And customers whose needs must be scaled up can be given bigger time slices and more bandwith with no changes on the customers’ side. So hosting companies should be doing it anyway. Apologies in advance but I wonder what RMS would think about this thread? What are the chances that the technical solutions being discussed here might be developed sufficiently to respond to the RMS concerns about the cloud? The suggestion that project hosting sites offer full-blown VPS misses the point of project hosting: Hackers don’t like to be admins; it’s boring. A project called Bugs Everywhere, , could solve (or work around) part of the problem. It incorporates the bug tracker in the vcs (multiple vcs supported) so pulling your code also gets you the bug history and outstanding bug list. Given the state of visualization technology and the fact there is a rapid commoditization of computer resources driven by multiple economic factors, you are receiving the exact quality you are paying for. The issues here are not about technology, but governance and trust. Your data, your business and other aspects of our lives we share in this electronic media are now surrendered to others. Many facets of our lives are held digitally and many times are held hostage by the partners we select to proxy our relationship with others. You are effectively “relying on the kindness of strangers” to promote and help manage your relationships. We rely on them to be a trusted custodian of the data that represents our parts of our lives. When something goes wrong, very wrong, most people feel violated. You should feel violated, they are violating your trust. How did we put ourselves in this position ? We blindly relinquished our sense of responsibility to others, whether it be teachers, doctors, day care centers, lawyers, clergy, political representatives and appointees, other civil servants, and salesmen. We find ourselves repeating these same patterns with hosting providers or cool looking web presences. Shouldn’t we stop handing over the value our relationships and many times the ability to earn a living to the untrustworthy ? How do we ensure the once trustworthy are still trusted ? What should we look for ? We entrust our partner/provider-proxy with many important aspects of our lives, why isn’t there transparency to ensure what we share is cared for the way we expect it should be. More times than not, governance is not about making data available, but denying access to it. It often said “possession is 9/10s of the law” the same is true for denying access to data. If you have a website that you are conducting business on, many providers will permit you to upload all the data you would like for free… Getting that data back, however, is another issue. Depending on providers, you may have to run a gauntlet of unclear fees and other costs. Cloud computing, the panacea of low cost compute are riddled with these practices. Its like an child’s amusement park where you pay on the way out, they don’t tell you about the fees and the fees can change while your in there. If you don’t pay, they keep your children. Does it really matter whether the the tech is corba, rcp, xml, webdav or the next grand pooba of tech ? All the protocols and technology in the world won’t help you if the provider denies you access to your data. It don’t matter whether its because they can’t manage the scale of their business or they are holding your data for ransom, you still can’t get your data which can stall portions of your life or income. Some hosting providers actually do make a commitment to provide you with all your project data upon request; I think the issue in many cases is not malicious intent, but simply one of resourcing, because designing and maintaining a full import-and-export system is a lot of work, and existing users often put more energy into asking for features and bugfixes than immigration insurance. >Why JSON, as opposed to XML? Unless I’m using a dynamic language that can handle the stuff natively (JavaScript, ActionScript) it’s really not that convenient. I’ve used both and found JSON pleasantly lightweight and easy to work with, even in C. I can’t sat the same thing about XML. @esr: Why JSON, as opposed to XML? Unless I’m using a dynamic language that can handle the stuff natively (JavaScript, ActionScript) it’s really not that convenient. I agree that exposing interfaces on a per-page basis is silly; one has to come up with an interface on the service level, and have the pages or other UI consume said services. I wonder if distributed bug / issue trackers, such as mentioned BugsEverywhere, or ditz, TicGit, CIL, Gerrit Code Review (I’m sorry for pro-Git bias here) which store bug / issue info inside distributed version control system repository, and wiki / blog / CMS engines such as ikiwiki, wikiri, WiGit, Nuki, Tekuti, Chuyen etc. (again I am sorry for pro-Git bias in this list) which store / can store revision information in distributed version control system can help here. For example with (proprietary and closed-source) GitHub you have (at least) two out of three (four): code is in distributed version control system (Git), and Git Pages solution uses either specially named repositories or specially named branches for storage of web pages in distributed version control system repository. I don’t know about built-in issue tracker, as I have not used it; I also think that wiki pages are not stored in git repository. What would be the currently best platform ? What would be the platform the most willing to implement the changes you (esr) advocate ? I have a question for this very knowledgeable group. Why wouldn’t you just keep an image of your system and if your current provider becomes unreliable just migrate the entire image, OS and all ? Eric, You might be interested to read the blog article “Time and space tradeoffs in version control” on Eric Sink’s blog (ericsink dot com — sorry I could never work out how to embed links in wordpress comments.) It discusses the effectiveness of different methods of storing multiple revisions of the same source code in minimal space and with respect to retrieval efficiency. Eric runs a company selling a source code control system, so his insight in interesting. Besides the version-ed source code, surely all you need is a SQL data dump, including a database schema and you are done? Add a cron job and an ftp server and no administration is required. It’s probably because there aren’t as many Apple users, but people like Mark Pilgrim have written about the data format problem for Apple’s closed formats. The thing is, there really aren’t that many (for instance) bug-tracking systems out there; the total amount of code change to provide import/export functionality is relatively small. Launchpad contains pointers to all manner of trackers, but the vast majority of them are Trac and Bugzilla. (Debian’s BTS and Sourceforge have only one instance each, but each instance is very large.) The problem isn’t so much that hosts don’t provide these services; it’s that the trackers don’t. Extending Savane in this way is a very good start. Have you considered looking at Launchpad’s “Malone” tool? It does a lot of automated bug-status fetching; it’s not a full importer, but it looks like they’ve already done a considerable portion of the work you’re facing. I want to mirror from a number of different repositories, but I am not the owner of the code, or a developer. I read your post with interest because I can say that trying to script regular updates from the popular repos has been unworkable. For instance, for those sites only giving access via HTTP, of course, HTTP doesn’t give a directory listing or date, and version numbers cannot be parsed, or relied on. Further, download pages can’t be reliably scraped (as though that were a solution) because they change often. Some access of this kind, such as being able to rsync the latest bundle, would be a big help. Indeed. One of Apple’s more boneheaded moves — a display of sheer fucktardedness rooted in the software fashion industry — was deprecating the NeXTSTEP proplist format (which resembles but JSON in all but superficial syntax details) in favor of an XML format for Mac OS X. “The Unix Philosophy” by Mike Gancarz, Chapter 4 “The Portability Priority”. “Choose Portability over Efficiency” “Store Numerical Data in Flat ASCII Files” Google seems to be doing something about this with their Data Liberation Front. Here’s the DLF page for Google Code. JSON is a better match for this task. Consider a bug report. A minimal common set of attributes can be specified, but beyond that, there’s a lot of differences between bug reports. An easy invariant is that exporting the project, then re-importing the project into the same project framework/service should be a no-op, so each service’s exact definition of a bug report is going to be fairly different at the protocol level. XML has all the necessary support to handle this, but it’s locked up in the XML namespace mechanism. The XML namespace mechanism is, in my experience, very powerful, very well thought-out, very expressive, and pretty much botched up by every single “in-the-wild” programmer who ever touches it, which unfortunately really kills it for interop. You’re going to end up with XML soup on this project no matter what you do. You might as well cut straight to JSON. You’ll still have “JSON soup”, but the odds of a “normal” programmer being able to deal with it are much higher. Much, much higher. The simpler serialization format will help guide programmers down the same paths, whereas XML offers a bit too much power and freedom here, and my own experience shows few people know how to use it safely. XML would probably be a better choice for enterprise software where half your design involves defending yourself from the hordes of mediocre programmers working on the problem, where the validation tools XML has would be helpful (for suitable definitions of “helpful”), but I think it’s a poor match for open source. (The only caveat I have for JSON is that you need to be strict about it; loosey-goosey parsers are a terrible idea. The spec is simple and clear; do not violate it. This is not targeted at esr in particular, just a general observation.) This is why I’ve never hosted at a site that didn’t give me ssh access and let me see the raw data files. If you have access to these, replicating your site at a similar host is pretty simple. I opt for VPSs now though.. OT: Eric, Obama won the nobel peace prize! Is it worth a new post on that? “absurd decision on Obama makes a mockery of the Nobel peace prize” There’s one other tricky bit of structured data there I haven’t seen discussed yet; developer accounts (identities, rights). Who has rights to check in code, or update/delete/add bugs, or make an official release? Even once you define a format for that data you have a bit of a problem in that some of the identify information possibly shouldn’t be available even to project administrators. Maybe this should tie into something like OpenID, with some kind of project-specific databaes handling authorizations seperate from the actual identify verification? The web-services solutions people are talking up here are fine, but for bug-tracking data I’d prefer to nuke the problem from orbit and solve it the same way that distributed version control systems solve it for source repositories: Allow me to simply have a full snapshot and history on my machine at all times. Something like JIRA backed by something like git would be a truly excellent piece of technology for those of us who do more coding than we like in remote and data-starved places (airplanes, vacations, etc.). ESR wrote: > No, let’s not go down that rathole. Yes, the data-jail effect on social networking sites is bad, > and the iPhone is worse. But I can’t solve those problems… Respecting your desire not to discuss that in depth here, but I just want to refute the notion that we can’t solve those problems in 2010. The solution will revolve around providing a more popular set of services that are open and are more generally re-useable, giving rise to a proliferation of integration momentum. I also want to underpromise and overperform, so I will just say I am in Asia now and deeply focused on this work… What’s funny is that old projects like Savane and Gna precisely appeared when similar hazards happened with the FSF’s savannah platform outage (bits of this history in). Then 6 years later, esr you have same concern … welcome on board. I should also point, being an oldtimer in this field, that as early as 2001, there were already discussions about the CoopX project () that actually has never really delivered. Now, the subject comes to the front again : glad to feel less alone. I should introduce the COCLICO project () which we have just started, which intends to help address these concerns too. I hope we can join forces (as discussed on IRC yesterday). Sorry, not all workpackage descriptions translated yet, bur babelfish is your friend. The interoperability one () precisely addresses such import/export tools to diminish projects lock-in to the forges. We’re just started for a few days and are funded to work for next 2 years… so expect more news from us soon. We started a project in New Orleans after Katrina and being able to move our data from one host to another, and having daily rsync backups was a first-order issue, but it’s very much solvable. The one thing I would say is that Apple’s time machine has rsync beat when it comes to space-conserving backups. Rsync writes hardlinks of your entire filesystem every time it runs backups. After 180 days of daily backups, the app server had grown from 8 GB to 8.1 GB, yet the backup (essentially /home, /var, /usr, and /etc) took up 100GB of space. >A project called Bugs Everywhere, , could solve (or work around) part of the problem. It incorporates the bug tracker in the vcs (multiple vcs supported) so pulling your code also gets you the bug history and outstanding bug list. I’ve looked at this. It appears to me to be an extremely clever solution to the wrong problem. As in – what if you just downloaded a binary, not the source repo? It looks to me like you don’t get to use Bugs Everywhere. Bug reports can be stripped off trivially from any of the major sites via their APIs. While youre correct about the mailing lists, youd be tied into the mailing list no matter where you hosted it. I dont honestly see that as being any more of an armed-and-dangerous risk at a hosting site than at Google Code or your friend Bobs mail server down the hall. That’s all right — projects can simply adopt the Ulrich Drepper approach: a big fat middle finger to users unwilling to check the latest source out of version control. The obvious solution is an open source mailing list manager and bug database manager that is driven by a bunch of XML or JSON files that grow incrementally and a database. Download the files and database, and you can host the mailing list and bug database on any computer. Sounds like a lot of work. I fully support someone else doing that work, and if someone else did that work would assist by using the product and submitting bug reports. ‘I’ve looked at this. It appears to me to be an extremely clever solution to the wrong problem. As in – what if you just downloaded a binary, not the source repo? It looks to me like you don’t get to use Bugs Everywhere.’ Hmm…. not sure why you think not, just post a bug to the main/central repo or use the web interface (in developemnt). This aside, the point was that the bug tracker state becomes a function of source control and you just need a copy of the source to also have the bug tracker state. In the post you mention that modern distributed version control has solved the problem for source but bug tracker state and mailing lists are still data jailed. A tool like bugs everywhere solves the bug tracker state and the source control (particularly when using git/hg/bzr as the source repository). Thus one only has to worry about the mailing list state being data-jailed. This idea could of course probably be extended to the mailing list but it might not be a good fit, having the source, bug reports and mailing list in the same data store. Sharesource addresses (some) of these. 1 – All project wiki pages use Wiki Creole, which is easily ported to anything else. We should probably offer project administrators some kind of ‘download dump’ link to let them keep off site backups. 2 – The code that runs sharesource is open source. You can download it and run your own copy for your own project(s). Its then your diligence, not ours to keep the data safe. We only require that your changes be made public. Otherwise, yet-another-sucky-forge.com will pour in tons of venture cap, fix everything wrong and the patches will never see the light of day. The idea of dumping mailman archives is a good one and I plan to bring it up. Currently, our bug system sucks .. so that’s something we’ll address after our bug system stops sucking :) As for the code .. we support Mercurial and soon Git. However, providing a snapshot for SVN users might be a good idea. A project using a DVCS has no need for repo snapshots. Sorry to comment in reverse order, thanks for your thoughts. They clearly point out room for improvement. Most effort lately has gone into a Xen based compile farm for projects, so repo heads can be built and tested on many operating systems. Should you check it out, please realize that its a very part time effort. There’ s another approach to bugs in a DVCS: Integrated issue tracking with Ikiwiki. This makes the BTS a structured section of the project wiki, editable from the web or using the DVCS. So a user of a distribution’s’t been pulled yet. >There’ s another approach to bugs in a DVCS: Integrated issue tracking with Ikiwiki. This makes the BTS a structured section of the project wiki, editable from the web or using the DVCS. So a user of a distribution’s’t been pulled yet. That is really, truly elegant — the most convincing attack on that specific problem I have seen yet. If I do end up building a forge system, this will quite likely be one of the components. A bit late, but I’d like to mention that ticgit solves the centralized issue tracker by including issues in a branch in your git repo. With using that and Github’s Pages (essentially, storing the webdocs for a project in another branch), I can have everything essential to my project mirrored on half a dozen of my computers, and potentially on thousands of others worldwide. Pingback: Links collection about software forges: status, criticism and new ideas « Libre Software People's Front Pingback: Apache OpenOffice turns to SourceForge for Distribution | Linux-Support.com Great article, I wholeheartedly agree that not being able to write your own script is starting to become part of new technology, especially in terms of Apple. And Xiong Chiamiov, thank you for explaining that, I now am backed up 200% and am feeling secure :) P.S. If you are having problems with your host-site, sign up with Little Nimbus! I have no affiliation with the site except that I recently signed up and am extremely happy with it. No more slow uploads, no more waiting for support that doesn’t even help, and no more BS. I hope you guys switch or at least find a host-site that helps you as much as I have been helped.
http://0-esr.ibiblio.org.librus.hccs.edu/?p=1282
CC-MAIN-2017-47
refinedweb
6,289
59.53
David Gristwood Developer & Platform Group, Microsoft August 2005 Applies to: Microsoft ASP.NET 2.0 Summary:. (16 printed pages) Download the sample from here. Introduction Understanding the Navigation System in ASP.NET 2.0 The Navigation Controls Working with the Navigation System Implementing Your Own Site Map Provider A Folder Site Map Provider Conclusion Most web sites employ some form of visual navigation to help users move around the site easily, and find the information and Web pages they require. Though the look and feel can vary widely from site to site, the same basic elements are usually present, in the form of navigation bars, or menu lists, that direct users to specific parts of the web site. ASP.NET 1.x out of the box provided little in the way of support for site navigation, leading many developers and web designers to either build their own navigation system, or buy third-party controls to meet their requirements. All this changes with ASP.NET 2.0, which introduces a navigation system that uses a pluggable framework for exposing the site hierarchy, and controls that plug into this new model, making it easy to build a high quality menu and navigation system. This paper describes how the navigation system in ASP.NET 2.0 works, and shows how it can be extended beyond simple XML files, which is the default mechanism used in Visual Studio 2005.. The ASP.NET 2.0 navigation framework can be broken down into a couple of areas: This layered architecture creates a looser coupling between the underlying site hierarchy and the controls on the web site, provides greater flexibility, and makes architectural and design changes easier as sites evolve. The diagram below shows the relationship between the provider and the controls. Figure 1. Navigation architecture In the case of the navigation system, the data source describes the hierarchy of the web site pages that users can navigate to, and how this information should be displayed to the users. It is referred to as a site map. The layout for a simple web site might be: Products Product A Product B Product C Latest Offers Visit us Before delving down into the inner working of the navigation system, it is important to understand how developers interact with it. The most common way is through the three new navigation controls in ASP.NET 2.0. Multiple Web navigation controls can exist on a single site or page—it's not uncommon to have the main menu control on the left-hand side of a page and another menu across, say, the top of the page, and it's possible to have one navigation control programmatically control another on the page, or to have them operate independently. The navigation system is commonly used in conjunction with the Master Pages capabilities that are also new in ASP.NET 2.0. By placing the navigation controls on the site's master page, it ensures a consistent look and feel across the entire site. However, the navigation and master page capabilities are orthogonal and independent of each other. The three new web controls are: Figure 2. Menu control Figure 3. TreeView control Figure 4. SiteMapPath control (click on the graphic for a larger image) From an architectural perspective, the Menu and TreeView controls are somewhat similar, the main differences being in the way they are programmed and render themselves, each having its own distinctive look and feel. For a more detailed look at these two controls, see the MSDN article Introducing the ASP.NET 2.0 TreeView and Menu Controls. It is worth noting that, although the most common scenario for the Menu and TreeView controls centers around site navigation, they can also be used in non-navigation scenarios, letting users make selections. The SiteMapPath (or "breadcrumb") control is a little different. It works directly with the SiteMapProvider, not through the SiteMapDataSource control that the Menu and TreeView controls use. This reflects its more focused role within the navigation system, so there is less rationale to try to expand its functionality to non-navigation scenarios. One of the easiest ways to gain an understanding of how site navigation works is to access it directly from within an application, rather than through a Web control. The following sample shows how to interact with the SiteMap object model to display part of the hierarchical site information. <%@ Page Language="C#" %> <script runat="server"> private void Page_Load(object sender, System.EventArgs e) { this.Label1.Text = "Current Page Title : " + if(SiteMap.CurrentNode.ChildNodes > 0) { this.HyperLink1.NavigateUrl = this.HyperLink1.Text = } } </script> <html> <head> </head> <body> <form id="Form1" runat="server"> <asp:Label</asp:Label><br /> First Child Node: <asp:HyperLinkHyperLink</asp:HyperLink> </form> </body> </html> The navigation system models the site map as a series of nodes, known as SiteMapNodes, within a tree-like structure, each of which typically represents a page on the web site that a user can navigate to (it is possible to have nodes that are simply place holders for subpages and that, as such, have no Web page themselves). The SiteMapNode class has several properties and methods, but the most important ones are: The SiteMapNode class also has a number of properties that hold the links between the individual SiteMapNodes that describe the site map structure (ChildNodes, NextSibling, PreviousSibling, ParentNode, and so on). As mentioned, ASP.NET 2.0 ships with a navigation data store provider called the XmlSiteMapProvider, and this is the default provider that most developers are familiar with. This provider consumes data from an XML file that represent the SiteMapNodes. When using Visual Studio 2005, if you add a new site map to a Web project, by default, it will create a Web.sitemap file within the project and populate it with the following template. You can immediately see that the core SiteMapNodes properties covered earlier (title, url, and description) are attributes in the Web.sitemap XML schema, and that the tree structure (parent, child, and so on) is expressed by nesting SiteMapNodes. This is a simple and elegant way of handling the site map information, and, for many Web designers, it more than suffices. However, the extensibility of the ASP.NET provider model does mean you can write your own provider. There are perhaps three primary reasons for considering creating a custom site map provider: To implement your own site map provider, you need to derive a custom provider class from the SiteMapProvider abstract class in the System.Web namespace. Although the SiteMapProvider class has some twenty or so abstract or virtual methods, only a small number need to be overridden and implemented in your custom site map provider. If your custom site map provider uses a data store that is similar to the default XmlSiteMapProvider's Web.sitemap XML schema, you could choose to derive from the StaticSiteMapProvider class, which provides a partial implementation of the SiteMapProvider class, and which is, in turn, the base class for the actual XmlSiteMapProvider class. As a minimum, the following methods must be implemented by your class: You should also override the SiteMapProvider Initialize method and perform your own initialization there, after calling the base class Initialize. You can optionally override some of the properties that relate to the nodes, if required, to enable you to build more sophisticated models to represent the site map: These properties and methods represent the contract between the SiteMapProvider and the Menu / TreeView controls (through the SiteMapDataSource) and the SiteMapPath control. This interaction occurs as the controls make requests for information that is needed to populate the display and, as the user navigates through the site, to track the current position within the site navigation. It's an event-driven model, with the navigation system calling into the provider throughout the interactions. If you write your own provider, you need to decide whether the SiteMapNodes are read-only or whether they are writeable—if they are writeable, you need to take into account thread safety and ensure that the implementation is thread safe, locking update code where appropriate, because ASP.NET dispatches requests across a thread pool, so a singleton will be accessed by multiple threads. A more subtle issue is around performance and scalability. It's not unusual for a web site to use a couple of navigation controls, or for the underlying navigation data store to be quite large; therefore, you need to ensure your provider is responsive, which will impact design issues around the best algorithms to store and retrieve the data, and the potential role of caching. There is also the issue of security to take into account. A common requirement for web sites is to allow only some members or other authenticated users to see certain pages, and ASP.NET 2.0 role management provides a well defined way to restrict access to Web files based on security roles. This extends through to the site navigation system by means of a mechanism known as security trimming. Security trimming enforces the Url and File Authorization rules that also apply when attempting to access a page. Defining a roles attribute on a node serves to widen the access to the node—if you are in one of the roles defined in the roles attribute, then the node is returned; if you are not in one of these roles, then the Url and File Authoriation checks are performed. In the case of the XmlSiteMapProvider, adding a roles="managers" style attribute to a SiteMapNode entry will determine whether the user sees that node in the site map. When writing your own site map provider, this is surfaced throught the IsAccessableToUser method, which returns a Boolean to indicate whether that node is available to the user, based on his or her role. There is a default implementation in the base SiteMapProvider class that derived providers can use. If security is to be supported, the site map must provide some way to store this information. The sample in this article exposes the subdirectories within a web site as the actual site map, enabling the web site navigation to map directly onto the folder structure, a not uncommon model for a web site structure. The focus for this sample is to show how to design and build a site map provider, and, as such, it doesn't aim to provide industrial-strength coverage of all the possible "edge conditions." These trade-offs are highlighted within the article, where appropriate. The sample provider recursively enumerates through the subdirectories of the web site and, for each folder (apart from the App_* and bin directories, which are special directories used by ASP.NET 2.0), checks for the existence of a default.aspx file. If this file is present, the sample provider adds it to the site map, using the name of the containing folder as the menu description. It would be relatively easy to extend this sample to support more than the one default.aspx entry for each directory, or to store a ToolTip date in a text file within the directory, if required. The core code for the provider is as follows. [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)] public class FolderSiteMapProvider : SiteMapProvider { private SiteMapNode rootNode = null; // root of tree private Hashtable urlHash = null; // hash table based on URL private Hashtable keyHash = null; // hash table based on key string defaultPageName = "Default.aspx"; // only look for this file in each subdirectory string defaultTitle = "Home"; // description of root node // override SiteMapProvider Initialize public override void Initialize(string name, NameValueCollection attributes) { // do base class initialization first base.Initialize(name, attributes); // our custom initialization urlHash = new Hashtable(); keyHash = new Hashtable(); // get web site info string startFolder = HttpRuntime.AppDomainAppPath; string startUri = Uri.EscapeUriString(HttpRuntime.AppDomainAppVirtualPath); // want canonical format of URI // Create root node string key = startFolder; string url = startUri + @"/" + defaultPageName; rootNode = new SiteMapNode(this, key, url, defaultTitle); RootNode.ParentNode = null; urlHash.Add(url, rootNode); keyHash.Add(key, rootNode); // populate entire site EnumerateFolders(rootNode); } // Retrieves a SiteMapNode that represents a page public override SiteMapNode FindSiteMapNode(string rawUrl) { if (urlHash.ContainsKey(rawUrl)) { return n; } else { return null; } } // Retrieves the root node of all the nodes //currently managed by the current provider. // This method must return a non-null node protected override SiteMapNode GetRootNodeCore() { return rootNode; } // Retrieves the child nodes of a specific SiteMapNode public override SiteMapNodeCollection GetChildNodes(SiteMapNode node) { // look up our entry, based on key return n.ChildNodes; } // Retrieves the parent node of a specific SiteMapNode. public override SiteMapNode GetParentNode(SiteMapNode node) { // look up our entry, based on key return n.ParentNode; } // helper functions . . . // . . . } The sample provider builds up a list of folders when the provider is called through its Initialize method, and doesn't refresh that list, so it won't detect new folders added on the fly, which is not unreasonable for a production web site. It doesn't implement security trimming, so all subdirectories are visible, but it would be simple to implement this by adding a call to the base class IsNodeAccessible method inside of the FindSiteMapNode, GetChildNodes, and GetParentNode methods, which would automatically get the benefit of any file authorization rules configured for the web site. Internally, a provider can represent the underlying store in any number of ways; however, because it interacts with the navigation system through SiteMapNode classes, in this case it makes sense to uses these internally, especially because a directory hierarchy so closely matches the node hierarchy. It also maintains two hash tables, one of which is keyed on the node URL, and the other of which is keyed on the node key (which is the folder name), to allow rapid lookup of nodes. For this sample, holding all this information in memory makes sense, because it keeps the programming model simple and the lookup very fast; however, for a very large site, with thousands of folders, it may be worth investigating a mechanism that doesn't hold them all in memory. In order to keep the code simple, the nodes are not handled as read-only. In a true industrial-strength provider, when the application is not allowed to add or amend the internal list of site map nodes, mark the individual nodes and the collection as read-only. Private helper functions are used to build up the folder hierarchy, as shown in the following code sample. private void EnumerateFolders(SiteMapNode parentNode) { // create a node collection for this directory parentNode.ChildNodes = nodes; // get list of subdirectories within this directory string targetDirectory = parentNode.Key; // we use the key to hold the file directory string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory); foreach (string subdirectory in subdirectoryEntries) { string[] s = subdirectory.Split('\\'); string folder = s[s.Length-1]; string tmp = String.Copy(folder); tmp = tmp.ToLower(); // avoid any case sensitive matching issues // check for App_ and bin directories, and don't add them if (tmp.StartsWith("app_")) continue; if (tmp == "bin") continue; string testFileName = subdirectory + @"\" + defaultPageName; if (File.Exists(testFileName)) { // create new node string key = subdirectory; string url = CreateChildUrl(parentNode.Url, folder); string title = folder; n.ParentNode = parentNode; // add it into node collection and table nodes.Add(n); urlHash.Add(url, n); keyHash.Add(key, n); // and enummerate through this folder now EnumerateFolders(n); } } } As the provider enumerates over the subdirectories, it creates a SiteMapNode class for each valid subdirectory, setting its key, url, and title properties. It also populates the ChildNodes property, which is a SiteMapNodeCollection, with each of the child nodes, and the ParentNode property points back up to the parent node. It also adds each of the nodes to the hash tables, for rapid lookup. Once complete, the provider needs to be configured using the web.config file. The following entry needs to be added under <system.web>. <system.web> . . . <providers> <add name="SimpleProvider" type="Test.SimpleProvider"/> </providers> . . . </system.web> The goal of this article was to give you an insight into, and appreciation of, the ASP.NET 2.0 site navigation system and how the different elements work together. The code sample shows how it is possible to extend the architecture by building your own site map provider that uses an arbitrary source to define the site hierarchy. David Gristwood works for Microsoft in the Developer and Platform Group in the UK, where he spends most of his time working with customers and partners, helping them design and build solutions that make the most of the Microsoft .NET platform. He is also a regular speaker at events and seminars.
http://msdn.microsoft.com/en-us/library/aa479338.aspx
crawl-002
refinedweb
2,732
50.46
Created on 2019-11-03 16:15 by gvanrossum, last changed 2019-11-11 04:11 by gvanrossum. This has always bothered me, and it shouldn't be necessary. This session: >>> #foo ... >>> should really have been >>> #foo >>> It's confusing that the REPL prompt switches to "..." here, for no good reason. It should just treat the line as empty. Ditto if you enter a space (there's an invisible space after the first prompt): >>> ... >>> As a person without much experience, it sounded like a simple enough task, but having dug a bit, I found it quite complicated. It seems to me that the interpreter loop (in the standard REPL, that you get when you start ./python, blocks for input somewhere inside a massive function called 'parsetok' (in Parser/parsetok.c). Now, I could maybe investigate further, to have it return to the interpreter loop if it reads a comment (or empty line), but I'm afraid to mess up something. From my understanding, there aren't that many other choices, because parsetok() doesn't return before you finish the statement (in other words, it does not return if you type a comment line or a blank line - it instead waits for more input, as indicated by the '... '). Am I way off in concluding that this would be a change to the parser? Yes, that's likely where the change should be made. I think if the *first* token encountered is either NL or COMMENT the parse should be abandoned by the tokenizer. Entering 'pass' or a completely blank line results in a new primary prompt, at least on Windows. The Windows REPL otherwise prints ... even for effectively blank lines. IDLE usually prints a new prompt for effectively blank lines. >>> >>> #a >>> # a >>> #a >>> I agree that these look better. This behavior comes from code.InteractiveInterpreter and ultimately codeop. def _maybe_compile(compiler, source, filename, symbol): # Check for source consisting of only blank lines and comments for line in source.split("\n"): line = line.strip() if line and line[0] != '#': break # Leave it alone else: if symbol != "eval": source = "pass" # Replace it with a 'pass' statement As noted above, 'pass\n' is treated the same as '\n' The first line above originally had a space, but IDLE appears to strip trailing whitespace also, even outside of comments. (For an ending '\ ', this prevents SyntaxError, but maybe this is a bad lesson for beginners.) However, I did find a case with an unnecessary continuation line. >>> # a >>> This puzzles me, as it should be treated exactly the same as without the space after '#'. ast.dump(ast.parse(' # a\n', '', 'single')) gives the same result, 'Module(body=[], type_ignores=[])', as without. Regarding the IDLE mystery, *if* there's a difference between how it treats " # a" and "# a", this must be due to some part of the code that's invoked before _maybe_compile() is called, right? But that's immaterial to this bug -- I'm only complaining about the "builtin" REPL. Fix corner case bugs in IDLE would definitely be a separate issue. But is the 'fix' in _maybe_compile at all applicable to the REPL? Or might a parser change REPL fix make the code in _maybe_compile unneeded? > But is the 'fix' in _maybe_compile at all applicable to the REPL? Or might a parser change REPL fix make the code in _maybe_compile unneeded? I don't know. Most of the contortions in code.py codeop.py are meant to emulate what the parser does without help in the REPL: keep asking for input until one of the following happens: - a syntax error is found; - a simple statement is parsed till completion; - an empty line is found at a point where a compound statement is potentially complete. The bug here is that apparently the above conditions aren't quite enough, and it seems we need to add: - a line that contains just whitespace and/or a comment is seen before anything else. The reason that IDLE has to reimplement similar logic is that the parser (actually, the tokenizer) isn't written as a coroutine to which you send lines you read -- it's written as a blocking function that you pass a file and the function will attempt to read lines from the file. The function returns a parse tree or raise an error. That model doesn't work in IDLE, which needs to stay reactive while the shell window is in the middle of a statement. I think we'll find that the bug is *very* old. IIRC the initial releases of Python didn't have the rule that indentation is ignored between matching parentheses/brackets/braces. In those days the tokenizer also didn't gracefully skip blank lines, or lines with comments that weren't aligned with the current indentation level. So then checking for empty lines was good enough.
https://bugs.python.org/issue38673
CC-MAIN-2019-47
refinedweb
802
72.76
C++: Write a Class Coord that Includes Degrees In ocean navigation, locations are measured in degrees and minutes of latitude and longitude. For example, 149 degrees 34.8 minutes west longitude, and 17 degrees 31.5 minutes south latitude, to be written as 149°34.8' W, 17°31.5' S. There are 60 minutes in a degree. Longitudes are measured from 0 to 180 degrees, east or west from Greenwich, England. Latitude is measured from 0 to 90 degrees, north or south from the equator to the poles. Write a class Coord that includes the members: degrees (int), minutes (float), and the direction character (N, S, E, or W) to represent both latitude and longitude (altogether 6 members). The class must have a constructor accepting 6 parameters and a toString() method that returns a string representation of the coordinate as a C++ string (not C string). The main () program must allow the user to enter the coordinates one-by-one, create the Coord object, and apply its toString() method for displaying. You can use hex character constant 'xB0' for printing the degree symbol (°). Solution Preview Please see the attachment. // Navigation.cpp #include <iostream> #include <sstream> #include <string> using namespace std; class Coord { public: int longtitude_degree; float longtitude_minute; char longtitude_direction; int latitude_degree; float latitude_minute; char latitude_direction; Coord(int, float, char, int, float, char); // Constructor to accept 6 parameters string toString(); // method for ... Solution Summary The solution writes a class Coord that includes degrees and minutes of latitudes and longitudes.
https://brainmass.com/computer-science/cpp/cplusplus-write-class-coord-includes-degrees-240966
CC-MAIN-2017-13
refinedweb
249
55.34
Hi, I’ve got a script that sends reports by email using Net::SMTP. Occassionally I get errors from the mail server (normally rejected addresses) which causes an exception which I catch with rescue. This is in a class derived from Net::SMTP: def send (to, subject, data) retries = 0 @count += 1 to_array = to.split(/\s*,\s*/) hdrs = <<HDRS To: #{to} Subject: #{subject} Date: #{Time.now.strftime("%a %b %e %T %Y %z")} Message-Id: <selms-#{@time}-#{@count}@selms> From: #{@from} HDRS send_message( hdrs + data.join("\n") + ".\n", @from, *to_array) rescue Net::SMTPFatalError, Net::SMTPSyntaxError if $! =~ /virtual alias table/ then retries += 1 STDERR.puts “mail failed #{retries} for #{to}:#{$!}” spleep(10) retry if retries <= 2 end STDERR.puts “mail failed for #{to}:#{$!}” false end I wish to ‘reset’ the smtp session so that I can continue sending email without doing a finish and another start (i.e. before I retry). Is this possible? I’ve looked through the docs for net::smtp and not found anything obvious. I have not looked at the source yet. Russell
https://www.ruby-forum.com/t/recovering-from-errors-in-net-smtp/71724
CC-MAIN-2021-21
refinedweb
176
78.04
#include <Amesos_Merikos.h> Inheritance diagram for Amesos_Merikos: <br /><br /> Merikos partitions the rows of a matrix into two or more disjoint submatrices. i.e. if rows i and j are in different submatrices, A[i,j] == 0 == A[j,i]. Rows/columns not in any of the submatrices, i.e. the rows/columsn of the separator, are permuted to the bottom right. <br /><br /> Merikos factors each of the disjoint submatrices in parallel, (potentially by calling Amesos_Merikos() recursively), updating the rows and columns of the separator which belong to it and forming the schur complement of those rows and columns of the separator. <br /><br /> Merikos updates the trailing block of the matrix and then factors it. <br /><br /> Merikos is a Greek word for partial, reflecting the fact that Amesos_Merikos uses a series of partial LU factorizations, performed in parallel, to piece together the full LU decomposition.
http://trilinos.sandia.gov/packages/docs/r5.0/packages/amesos/doc/html/classAmesos__Merikos.html
CC-MAIN-2014-35
refinedweb
148
51.28
Deterministic, Finite State Machine. Project description Deterministic, Finite State Machine Contents Installation python setyp.py install StateMachine blueprint This is a propery with a getter and setter that defines the state machine. Setting the blueprint will also reset the state machine. { "initialState": state, "initialContext": dict(), "alphabet": set(), "validStates": set(), "acceptedStates": set(), "finalStates": set(), "transition": lambda state, context, event: new_state, "lifecycles": dict() } Initial Context An optional dictionary, which can be used to share information between states and updated during state transitions. Alphabet A set of events, which are used to drive state transitions. Initial State The starting state. Must be a valid state. Valid States A set of valid states. Accepted States A set of accepted states. Final States A set of final states, once reached, new transitions will raise StopMachine. Transition A function, which takes state, context and event as parameters and returns the next state. The event must be a member of the alphabet and the new state must be a valid state. Lifecycles Lifecycle actions can be ran before or after specific events. Events A set of events, which are used to drive lifecycle actions. Actions A list of functions, which take state, context and event as parameters. { "lifecycles": { "before": [{ "events": {0, 1, 2, 3}, "actions": [before_any] }], "after": [{ events: {3}, "actions": [after_three] }, { "events": {2, 3}, "actions": [action1, action2] }] } } - before_any executes before events 0, 1, 2 & 3 transitions are executed - after_three executres after event 3 transition is executed - action1, then action2 executes after events 2 & 3 transitions are executed state The current state of the state machine. context The current context of the state machine. initial True or False if the current state is the initial state. accepted True or False if the current state is an accepted state. final True or False if the current state is a final state. Methods reset() Resets the state machine's state and context to their initial values defined in the blueprint. The initial state must be a valid state. ValueError- Invalid initial state set_state(state, context) Set the state machine's state and context. The state must be a valid state. ValueError- Invalid state transition(event) Transitions the state machine to the next state by executing the transition defined in the blueprint. The event must be a valid member of the alphabet defined in the blueprint. The state must be a valid state. StopMachine- Current state is final ValueError- Invalid event is_initial(state) -> True | False is_valid(state) -> True | False is_accepted(state) -> True | False is_final(state) -> True | False is_event(event) -> True | False Usage Create a state machine with a blueprint and transition from the initial state 1 to accepted, final state 2. from dfsmpy import StateMachine machine = StateMachine({ "alphabet": {1, 2}, "initialState": 1, "validStates": {1, 2}, "acceptedStates": {2}, "finalStates": {2}, "transition": lambda a, c, e: e }) machine.transition(2) Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/dfsmpy/
CC-MAIN-2022-21
refinedweb
496
56.15
Opened 11 years ago Closed 16 months ago #11154 closed Bug (fixed) Inconsistency with permissions for proxy models Description Summary: The content type framework treats proxy models and their parent as the same model. The permissions framework treats them as separate models. This is complicated, and best explained by example. First of all, create this model: class UserProxy(User): class Meta: proxy = True app_label = "foo" This will result in three new permission objects being created: "auth.add_userproxy", "auth.change_userproxy", "auth.delete_userproxy" However, when the admin site checks for permissions for this model, it will be looking for permissions called: "foo.add_userproxy", "foo.change_userproxy", "foo.delete_userproxy" The inconsistency lies in that permissions are created using the ContentType of the proxy model's parent class. However, permissions are checked using the app_label of the proxy model itself. In order to reconcile this, there appear to be two options: - Allow each proxy model to have it's own ContentType. - Make ProxyModel._meta.app_label return the app label of the parent model. Personally, it makes sense to me that each proxy model has its own ContentType. Since proxy models can represent subsets of the parent model, they require different admin permissions. In order to have different admin permissions, they need to have their own content types. The current situation is a horrible mess of both approaches. The content type framework treats proxy models as being the same as their parent model. The permissions framework treats them as different. I realise that this is something of a design decision for the framework. I leave it up to greater minds than mine to come up with a solution! Attachments (1) Change History (70) comment:1 Changed 11 years ago by comment:2 Changed 11 years ago by comment:3 Changed 11 years ago by Unfortunately, it's not that simple. Setting the app_label is not required to replicate this bug. All you need to do is create a new application with a proxy model that references a model in another application. The two models then have different app_labels, and the problem occurs. For example: # staff/models.py class UserProxy(User): class Meta: proxy = True This is a pretty trivial use of proxy models, yet it does not work with the admin system. Not good. comment:4 Changed 10 years ago by comment:5 Changed 10 years ago by This really isn't a multidb problem. Changed 10 years ago by Workaround for issue 11154 comment:6 Changed 10 years ago by We've successfully employed the workaround as found in osso.core.management.init.py on django-1.1. Regards, Walter Doekes OSSO B.V. comment:7 Changed 10 years ago by (Although I must add that we do not use the admin interface for users, so I cannot confirm or deny that it solves issues in the admin interface.) comment:8 Changed 10 years ago by It may be obvious how to implement this, but for the rest of us a quick rundown. - paste patch in my_app/init.py - run ./manage.py syncdb comment:9 Changed 10 years ago by We've lived with this for the duration of 1.2; it can wait a little longer. comment:10 Changed 10 years ago by comment:11 Changed 10 years ago by Proxy models should also proxy the permissions of the model they are shadowing. So any app_label check should first check if the instance is a proxy and look in the parent's app_label instead. comment:12 follow-up: 13 Changed 10 years ago by Proxy models should also proxy the permissions of the model they are shadowing Are you sure about that Malcolm? Proxy models could be quite useful for limiting permissions to a subset of objects. For example, I could make a Student proxy for User with a manager whose get_query_set returns only Users in the "student" Group, and a save method which automatically assigns Users to that group. What if I'd then like to restrict Teachers to only being able to add/change/delete Students and not Users in general? comment:13 Changed 10 years ago by comment:14 Changed 9 years ago by comment:15 Changed 9 years ago by This patch worked well for me, successfully using it in a production website where we needed a proxy on the User model without breaking the admin site. comment:16 Changed 9 years ago by comment:17 Changed 9 years ago by comment:18 Changed 9 years ago by comment:19 Changed 9 years ago by comment:20 Changed 9 years ago by comment:21 Changed 9 years ago by Milestone 1.3 deleted comment:22 Changed 9 years ago by comment:23 Changed 9 years ago by I also think that Proxy models should have their own permissions. The current problem seems to lie in the way that ContentTypeManager determines the app_label of a model: ModelBase will - proxy or not - report the app_label either as explicitly specified or from the parent's module name. if getattr(meta, 'app_label', None) is None: # Figure out the app_label by looking one level up. # For 'django.contrib.sites.models', this would be 'sites'. model_module = sys.modules[new_class.__module__] kwargs = {"app_label": model_module.__name__.split('.')[-2]} else: kwargs = {} However, ContentTypeManager._get_opts() traverses proxies up to the non-proxy model and then uses the entire meta of that model, incl. app_label. def _get_opts(self, model): opts = model._meta while opts.proxy: model = opts.proxy_for_model opts = model._meta return opts This is where app_label needs to be preserved. Maybe just put it aside, traverse, then readjust: def _get_opts(self, model): opts = model._meta # Preserve proxy model's attr_label attr_label = opts.attr_label while opts.proxy: model = opts.proxy_for_model opts = model._meta opts.attr_label = attr_label return opts comment:24 Changed 9 years ago by Hmmm, on second thought - looking at what parts of _meta are actually used by ContentTypeManager - maybe it shouldn't traverse at all, just stick with the proxy model itself... comment:25 Changed 9 years ago by comment:26 Changed 9 years ago by I'm working in polymorphic models (django_polymorphic) and I'm adding proxied polymorphic models... this is also a problem in this case, where I'm in the need to have content types for proxied models as well. comment:27 Changed 9 years ago by I think that allowing `ContentTypeManager.get_for_model` to return a proxy model (using a boolean kwarg to bypass the ContentTypeManager._get_opt part) could fix issues. Defaulting this boolean flag to false would preserve backward compatibility. The auth framework could then use that flag to create the missings permissions for proxy model. Plus it would allow polymorphic solutions that saves the object ct to be retreived calling ContentTypeManager.get_for_model('app', 'label', True). I think the addition of this new feature/approach should be discussed on django-dev since it involves a design decision. comment:28 Changed 8 years ago by I would consider it a bug if two different places give two different app_label's for the same model, and fixing it _will_ break backwards compatibility. Imho the only question is for which of the two. comment:29 Changed 8 years ago by comment:30 Changed 8 years ago by I have found a permission on proxy models related bug, the admin back end fails to display the administrative options for proxy models. I have a proxy model extending the Flatpage model, I unregistered the ModelAdmin for it and registered my custom one. I assigned 'change_myflatpage', and 'edit_myflatpage' (and even 'change_flatepage'/'add_flatpage') to the user. Howeverr the django admin fails to have any options for my custom flatpage model; If I make the user a super user the edit options appear. Attempting to access the url directly (/admin/flatpages_ext/projectflatpage/) throws a 403 error. If there is anything else that you guys need please advise. comment:31 Changed 8 years ago by @danols: That's exactly the inconsisteny described in this ticket. The "change_myflatpage" permission has the app label of your class ("yourapp.change_myflatpage") but when django admin checks it will use the app_label of the parent class ("contrib.change_myflatpage"). Look at the database tables "auth_permission" and "django_content_type". In the latter, your proxy model is listed with "myapp" as the app_label. When django admin checks the permission though, it traverses up to the parent of myflatpage and then uses _that_ app_label, and a combination of "contrib" and "change_myflatpage" is not in your permissions table. comment:32 Changed 8 years ago by Just wanted to add that etianen the ticket reporter is the author of django-reversion and this inconsistency breaks real-life use cases, e.g. It may be a matter of discussion whether proxy models should have their own permission or not (though I personally find that a no-brainer), but really the issue is that two different vital locations report two different "app_label" for the same class. I don't see a valid argument for an explicitly specified "app_label" of a proxy model being reported as its parent (root) model's "app_label". comment:33 Changed 8 years ago by comment:34 Changed 8 years ago by comment:35 Changed 8 years ago by Here's the actual approach I was talking about at comment:27. It solves the issue but proxy_for_model kwarg is really an odd name, anyone thinking of something better? It doesn't introduce any backward incompatibly issues since the admin relied on the opts of the proxy for the has_perm checks. In other words, ModelAdmin registered with a proxy model couldn't be accessed at all if you weren't a superuser thus approach such as this one wouldn't actually work. It might also be worth documenting that new kwarg since it can be quite useful when using the ContentType framework. The fact that you can now add permissions for proxy models can be quite handy (see comment:12) and IMHO is also worth documenting. All those features need extra testing and doc that I'll be happy providing if I can get some feedback toward my approach. comment:36 follow-up: 37 Changed 8 years ago by follow_proxy, traverse_proxy? (or even _proxies) The default behaviour would still be "broken" - ModelBase and ContentManager would still be giving different stories regarding app_label comment:37 follow-up: 38 Changed 8 years ago by Replying to danny.adair@…: follow_proxy, traverse_proxy? (or even _proxies) The default behaviour would still be "broken" - ModelBase and ContentManager would still be giving different stories regarding app_label Defaulting follow_proxy (like that one :) to False would unify both API but would break backward compatibility. I ran the test with follow_proxy=False as default and only two tests breaks. However apps relying on contrib.ContentType in the wild could break badly. i.e. (django-taggit) If you defined a TaggableManager() (uses GenericForeignKey internally) on a proxy model then all tags will be associated with the concrete model ContentType in the db. If we release follow_proxy=False as default then the generic relation between the proxy model and the tags will be broken since they were never associated with the proxy's ct. We can either break the API to unite them or offer the user to opt-in in order to maintain backward compatibility. But this whole discussion is getting bigger then the ticket itself. We should maybe open another issue to fix the ContentType proxy issue that blocks this one and then, once it's fixed, use the new hooks to fix this one with: diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index 78a51cf..a1d2d9e 100644 --- a/django/contrib/auth/management/__init__.py +++ b/django/contrib/auth/management/__init__.py @@ -31,7 +31,8 @@ def create_permissions(app, created_models, verbosity, **kwargs): searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() - ctypes_for_models = ContentType.objects.get_for_models(*app_models) + ctypes_for_models = ContentType.objects.get_for_models(*app_models, + follow_proxy=False) for klass, ctype in ctypes_for_models.iteritems(): ctypes.add(ctype) for perm in _get_all_permissions(klass._meta): comment:38 follow-up: 39 Changed 8 years ago by [...]. comment:39 Changed 8 years ago by Replying to danny.adair@…: [...]. I'm in the process of writing a new ticket describing the issue in which I'll suggest a design decision is taken toward breaking backward compatibility. comment:40 Changed 8 years ago by comment:41 Changed 8 years ago by While this gets fixed I wrote down a snippet that creates permissions without modifying django's code base. comment:42 Changed 8 years ago by Now that #18399 is fixed, I created a pull request that fixes this bug and bring back the get_for_models permission creation optimization reverted back in #17904. I'm still wondering if this needs any doc? I guess a release note wouldn't hurt? comment:43 Changed 8 years ago by I would really like to see a release note for this. I am currently looking at the pull request and wondering what exactly will change. I am going to close the pull request (per the policy of commit or close on review). Reopen with the added docs. I have a suspicious feeling I should know by now what this changes, but can't remember... comment:44 Changed 8 years ago by hi, after reading all the comments, i'm not sure if this is fixed or not in 1.4, however i have found another issue with this. I have tracked it to sites.py line 338 has_module_perms = user.has_module_perms(app_label). The problem is that the admin site won't even start to look for model_admin.get_model_perms(request) because i don't have permission to the "foo" module (as the permissions created are under "auth". I know you busy, but this I think is a serious issue if someone has to make use of the build in admin site, and won't have an superuser (because an superuser is very evil). Thank you. comment:45 Changed 7 years ago by Has a fix for this made its way into 1.5? I'm still using 1.4 ATM, and have just had this bug smack me upside the head. comment:46 Changed 7 years ago by No fix made it to 1.5. I'll try to rebase the patch and add a release note. I'll have to test possible issues with this, to make sure this doesn't introduce security issues related to permissions. As far as I can see there should be none in the admin since no permissions were created for proxy models, I'll have to checkout the other various permission API. We should also document how to create those missing proxy model permissions by running syncdb. comment:47 Changed 7 years ago by comment:48 Changed 6 years ago by comment:49 Changed 6 years ago by Seems like not fix in 1.6 still. Just encountered this bug. Any idea if it could be fixed in 1.6 point releases? comment:50 Changed 6 years ago by Using 1.6 and can confirm this is still an issue. Any idea what's the latest on this? Thanks, comment:51 Changed 6 years ago by comment:52 Changed 6 years ago by comment:53 Changed 6 years ago by Hi @jorgecarleitao, unfortunately don't have time to work on this ticket in the next few weeks so I'll deassign myself. Feel free to assign it to yourself. I think the biggest part of this patch is to figure out how to enable proxy models permissions in a backward compatible way without introducing any security issues in applications relying on the existing behavior. Since this ticket has been opened for 5 years it wouldn't hurt to document the actual caveats of the implementation meanwhile. Even if the ticket gets fixed in this release cycle we should backport the documentation for all supported versions. comment:54 Changed 5 years ago by comment:55 Changed 5 years ago by I requested better documentation on the latest pull request. comment:56 Changed 4 years ago by The pull request was closed as the submitter couldn't address the security concerns raised there. Someone else is welcome to follow up and try to address them. comment:57 Changed 4 years ago by For anyone else struggling with this, we've solved it by writing migrations to add the permissions (django 1.8) by creating the 'model': migrations.CreateModel( name='XYZUserProxyModel', fields=[ ], options={ 'verbose_name': 'User (XYZ User)', 'managed': False, 'proxy': True, 'verbose_name_plural': 'Users (XYZ Users)', }, bases=('proxyapp.user',), managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), comment:58 follow-up: 59 Changed 2 years). I don't know the framework well enough to assess the actual security impact of the original change, but would like to propose the following as a less risky path forward: - Update the patch so that, by default, proxy models have no permissions. This default would be baked into the logic of proxy = Trueand override anything inherited from a parent Model. - If a user provides permissions, we assume the user wants permissions for the proxy model and create them (i.e. otherwise using the patch as-is) - (Optionally) The next time Django puts out a major release (too bad this missed 2.0!) change the default to always create permissions. This proposal reduces the risk for users: - If you're not providing permissions on a proxy model -- explicitly or via a Meta inheritance chain -- you will be unaffected. I assume most users fall into this category. - If you're intentionally adding permissions (indirectly!) by exploiting this bug, something should break when you upgrade Django. This provides sufficient warning of a change to discover the other effects. - To be affected but not notified, you need to be including duplicate (or otherwise unused) permissions in the Meta class of your proxy model. This should be rare and mostly arise from inheritance in your Meta class (where the duplicate permissions aren't explicit). comment:59 Changed 21 months). If I'm not mistaken, I don't think it's entirely true. The patch was designed to recreate permissions using the content type of the proxy model instead of the one of the concrete model. The permissions for the proxy models are already automatically generated. For example, if you proxy a model in the same app (i.e. with the same app_label), you can create and admin page for it and use its permissions just fine. It's only if you create a proxy model in a different app (most common use case is to proxy auth.User), that you can't use the admin + permissions, because of that app_label mismatch when the admin is building the string to lookup the permission. In order to reconcile this, there appear to be two options: - Allow each proxy model to have it's own ContentType. - Make ProxyModel._meta.app_label return the app label of the parent model. The first approach would fix it altogether but is a larger discussion that I think is preventing this ticket to be closed (it's the approach used by the patch). Instead, I think we should focus on the second recommandation (with some slight modifications) so that the ticket can be closed and the discussion about content types can happen separately. To help understand the original problem and some of the approaches we can take, I want to make some clarifications with a simple example: # myapp/models.py from django.db import models from django.contrib.auth import get_user_model class Vehicle(models.Model): pass class Car(Vehicle): class Meta: proxy = True class Driver(get_user_model()): class Meta: proxy = True The current behavior is to use the concrete model content type to generate the default permissions, so for view it would be: myapp.view_vehicle myapp.view_car auth.view_driver As you can see the permission for driver is what makes the admin fail to lookup the correct permissions for the admin page of Driver, only a superuser would be able to access it. What I suggest is to refactor django/contrib/admin/options.py to use the following function, that builds the proper app_label from an opts parameter (to follow the same pattern as get_permission_codename). # django/contrib/auth/__init__.py def get_permission_app_label(opts): """ Return the app_label of the permission for the specified model. Proxy models use the content type of the concrete model. """ return opts.concrete_model._meta.app_label # django/contrib/admin/options.py # Replace the many similar calls ('view', 'change', 'add', 'delete', etc.) - codename = get_permission_codename('add', opts) - return request.user.has_perm("%s.%s" % (opts.app_label, codename)) + app_label = get_permission_app_label(opts) + codename = get_permission_codename(action, opts) + return request.user.has_perm("%s.%s" % (app_label, codename)) By looking at the concrete model ( opts.concrete_model._meta.app_label. as opposed to opts.app_label), it would keep the existing behavior intact for other models (For a concrete model, opts.concrete_model._meta == opts), and make the admin work with proxy model inheriting concrete models from a different app (i.e. with a different app_label). The other benefit of using this approach as first step to fix the broader issue, is that it centralizes where the change would occur if we decided to go with having a ContentType per proxy model and using that to generate the initial permissions instead of the one of the concrete type. Finally, regarding the security concerns previously raised, the only scenario that I can think of is the following: Pre-conditions: - You have a proxy model whose concrete model has a different app_label - You gave the permissions for that proxy model to a user - You registered the model on the admin Before the patch: The user wouldn't see or be able to access the admin page, only superusers could. After the patch: The user would be able to access the admin page based on its permissions. I will create a PR with this approach, let me know if there are any corner case or security concerns I'm missing. comment:60 Changed 21 months ago by comment:61 Changed 21 months ago by comment:62 Changed 21 months ago by As mentioned on the pull request, I moved away from my initial comment because: - It's only a temporary fix and we would still need to address the bigger issue about how permissions are created for proxy models. - It makes it actually more risky in terms of security as users with proxy permissions would suddenly be able to access the admin pages they couldn't see before (even though they should have been in the first place...) I think I'm pretty close to wrapping up the code changes and I'd love some feedback before I start writing up the docs and the release notes. You can check the pull request for more details about the current state of things and how this patch would impact permissions. For 1.1 we're going to need to simply say "don't do that" -- setting a different app_label is confusing things. For 1.2 we'll need to work this out better.
https://code.djangoproject.com/ticket/11154
CC-MAIN-2020-24
refinedweb
3,829
54.52
Here's a problem from HackerRank (rated Medium): When Daenerys, got her new phone there were no games in it. So she went to the play store and downloaded one of the top rated game called Princess and Angels. In the game princess starts with 0 total strength. there are N angels before princess and her castle. And each i th angel give Ai strength. but some of the angels are actually evil wearing angel clothes and they give negative strength trying to fight with Princess. The game can be won if Daenerys can get through all the N angels without dying. Princess will die if her total strength ever gets less than 0. fortunately Princess has a special power. she can fight with an angel and reverse it's strength atmost once. if she use that power on i th angel with x strength, She can apply this power and make it to -x. Daenerys can foresee the strengths of N angels. when passing through each angel, the strength is added to total strength. Princess can also reverse the strength of that angel before adding, but only once. Given N Strengths of angels, can u help Daenerys figure out the best possible result she can have?. print "She did it!" (without the quotes ) if she can win the game. Otherwise print the maximum position up to which she could reach (i.e. the position at which she died due to the negative total strength). Input Format First line of input contains T , number of testcases. Each testcase have two lines, N in the first line and N space separated integers in the next line. Constraints 1<=T<=1000 1<=N<=100000 -1000<=strength<=1000 Output Format For each test case, print a single line denoting the answer to the problem. And this is my attempt at the solution: #include <iostream> using namespace std; int main() { int strength, power, n, t, count = 1, i, pos; cin>>t; while(count <= t) { strength = 0; power = 1; cin>>n; int a[n]; for(i = 0; i < n; i++) cin>>a[i]; for(i = 0; i < n; i++) { if((strength + a[i]) < 0 && power == 1) { strength -= a[i]; power = 0; } else if((strength + a[i] < 0) && power == 0) { if(strength >= 0) { pos = i + 1; strength += a[i]; break; } } else if((strength + a[i]) >= 0) strength += a[i]; } if(strength >= 0) cout<<"She did it!"<<endl; else if(strength < 0) cout<<pos<<endl; count++; } return 0; } I think: Imagine the following input: 5 6 -5 -2 -2 -2 Your algorithm will encounter the 6 and add it, so strength becomes 6. Next we encounter the -5. Since this will not kill us we accept that loss. Strength becomes 1. Next we come to the -2. This will kill us (takes us to -1) so we flip it using the power. Our strength becomes 3. The following two -2s will therefor kill us. However if you had used the power on the -5 bringing the total strength to 11 at that point, you would have got to the end, so in this case your answer is incorrect.
https://codedump.io/share/59DtnClaNS9D/1/mistake-in-this-solution-for-hackerrank
CC-MAIN-2021-25
refinedweb
521
81.33
I'm trying to strip the code of all comments. However, as you can see, it doesn't work right. Anyone know the problem? I'm running it with this as file.txt:I'm running it with this as file.txt:Code:#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string str = "", main = ""; ifstream in("file.txt"); int pos; while(!in.eof()) { in.getline((char *) str.c_str(), 255); pos = str.find("//"); if(pos != string.npos) { main += str.erase(pos, str.length()); } else { main += str; } main += '\n'; } cout << main << endl; in.close(); cin.get(); return 0; } Code:one; // comment 1 two; r; four;
http://cboard.cprogramming.com/cplusplus-programming/51467-problems-stripping-comments.html
CC-MAIN-2015-48
refinedweb
106
80.88
Get the highlights in your inbox every week. Why I switched from Java to Kotlin | Opensource.com Why I switched from Java to Kotlin Kotlin is a cross-platform, general-purpose programming language and an easy move for anyone familiar with Java. Subscribe now After years as an educator, I became a professional software developer. That brought me to Java, but recently, I began enjoying a totally different but compatible programming language called. Variables Variables in Kotlin will feel familiar. Here are a few examples of creating basic integers: var I = 5 val j = 7 var k:Int = 8 There's a subtle and important difference between var and val assignments: var is used when the variable you defined can be reassigned, and val is used for local scope values that will not be changed. Each variable's type is optional because the type can be inferred, similar to the dynamic assignment in JavaScript. There are also nullable assignments that use syntax like: var f: Int? = 9 This means the assigned value can be equal to null. The reason for using null is outside the scope of this article, but it's important to know that a variable can only equal null when explicitly defined to do so. If you plan to define a variable with no initial instantiation (value), you must place the type after the variable name: var s: Int Strings are composed similarly, with the type after the variable name: val a:String = "Hello" Strings have superpowers in Kotlin. They include awesome string template functions that you can explore. Arrays Another basic type is the array. It can store a pre-determined amount of objects of the same defined types. There are a few different ways to create arrays in Kotlin, such as: val arrA = arrayOf(1,2,3) val arrB = arrayOfNulls<Int?>(3) val arrC = Array<Int?>(3){5} The first creates an array with a length of three and the elements 1, 2, and 3; the second creates an array of nulls of type nullable integer; and the third creates an array of nullable integers with each of the elements equaling 5. To retrieve one of the elements, use bracket notation, starting with zero. Therefore, to retrieve the first element in the first array, use: arrA[0]. Collections Other ways to group objects in Kotlin are generally referred to as collections. There are a few types of collections in Kotlin. Each can either be mutable (changeable/writable) or immutable (read-only). - Lists: An ordered group of items can contain repeated items and must be of the same type. Mutable lists can be formed like this:var mutList = mutableListOf(7,5,9,1) val readList = listOf(1,3,2) - Maps: Maps, similar to HashMaps in Java, are organized by keys and values. Keys must be distinct. They are instantiated like:var mapMut = mutableMapOf(5 to "One", 6 to "Five" ) val mapRead = mapOf(1 to "Seven", 3 to "six") - Sets: Sets are a data structure where each object in the group is unique. They are created like this:var setMut = mutableSetOf(1,3, 5, 2) val readSet = setOf(4,3,2) Whenever you try to reassign an immutable object, you will get a syntax error stating Val cannot be reassigned. This behavior comes in handy when you have a collection that you never want to be edited by any part of the program. Functions Functions are the foundation of a well-formed software program. Repeatable bits of code stored as functions can be reused without rewriting the same commands over and over again. In Kotlin, the standard syntax for creating a function is: This example function accepts a string as the only parameter; as you can see, the parameter type is placed after the name of the parameter. The Unit object is the Kotlin equivalent to Java's void when a function does not return a value (although Unit is one value—and only one value—because it is a singleton). Kotlin functions work much as they do in Java and some other languages. Classes Classes in Kotlin are very similar to classes in other object-oriented programming (OOP) languages that consider the object/class the foundational building block. Classes are created using the syntax: class ExampleClass{} By default, classes possess a primary constructor that can be used to set object properties without writing code for getters/setters (accessors/mutators). This makes it easy to create an object and begin using it without much boilerplate code. The primary constructor cannot contain implementation code, only parameters: public class ExampleClass constructor(type:String) To write primary constructor implementation, you can use init within the classes: init{ val internalType:String = type } Or you can initialize it in the constructor by placing val or var in front of each parameter: public class ExampleClass constructor(var type:String, var size:Int) Although this didn't go deep into classes, properties, and visibility modifiers, it should get you started creating objects in Kotlin. The "main" point Kotlin files have .kt file endings. To begin running a Kotlin file, the compiler looks for a main function within the file; therefore, a basic "Hello World" program would look like this: fun main(args:Array<String>){ println("Hello World") } Easy peasy, right? Kotlin is an advanced—but intuitive—OOP language that simplifies and streamlines Java development for mobile devices, server-side, web, and data science applications. I find its syntax and configuration much simpler than Java's. For example, compare the System.out.println("Hi") Versus Kotlin's syntax: println("Hello") In addition, getters and setters don't require additional libraries for simple implementation. In Java, libraries like Lombok simplify class/object property setting through annotation. In Kotlin, a class can be implemented with properties easily: These properties can be retrieved or set using the syntax: var me = Person() me.firstName = “Stephon” me.lastName = “Brown” Kotlin's simplicity and Java interoperability equate to little risk that you will spend time learning something that isn't useful. After taking your first steps into Kotlin, you may never look at your Java code or the JVM the same way again. 7 Comments Why I will stick with Java? What Stephon Brown said :D Hi Stephon, I really liked the article. I have a question. Is prior Java programing knowledge required to learn Kotlin ? I learned Java in college but never worked with it professionally. If I want to develop Android apps, can I start with Kotlin ? Thanks Ciao! In my opinion, I would have to say no. Java is not a prerequisite to learning Kotlin. Knowing Java will demystify a lot of architectural aspects related to the JVM and provide you with extended libraries within Java, but it is not necessary to have a complete and deep understanding to use Kotlin. Jet Brains even offers very thorough walkthroughs called Koans: I fail to see the property getters and setters in the last paragraph? Actually I have a feeling that the author has no idea what they are. Otherwise, I'm very unimpressed by Kotlin. var or val, keyword for everything, unclear typing... this thing is a mess. If you want a nice language, look at Typescript. Hi Milan, The getters/setters are automatically implemented once you declare a property within a class; therefore, using the example from the article, me.firstName can be used to both retrieve and set the property "firstName." Moreover, you can make more complex implementations of the property with different syntax outlined here:. While I agree some aspects of Kotlin may be a bit unclear/complex at first glance, I don't agree that Typescript is as easy to grasp transitioning from Java, an OOP language, provided its subset is the prototype-based language Javascript. Great article!! One question, what about abstractions like interfaces, abstract classes to support Design Patterns, everything is supported with Kotlin? BTW, why not Scala instead of Kotlin? Cheers, Hi Bruno, Abstractions are backed right into Kotlin: They use some of the same keywords as Java, and you could just make a POJO if you want to shy away from the Kotlin syntax and create your abstractions that way. As for Scala, I honestly didn't look too much into it. After programming in Java, I was really drawn in by the succinct and simple syntax of Kotlin. I did see Scala is a JVM compatible language and the syntax is very reminiscent of Java, but I wanted to try something different.
https://opensource.com/article/20/6/java-kotlin
CC-MAIN-2020-29
refinedweb
1,412
61.87
SCons compatibility package for old Python versions 26 27 This subpackage holds modules that provide backwards-compatible 28 implementations of various things that we'd like to use in SCons but which 29 only show up in later versions of Python than the early, old version(s) 30 we still support. 31 32 Other code will not generally reference things in this package through 33 the SCons.compat namespace. The modules included here add things to 34 the builtins namespace or the global module list so that the rest 35 of our code can use the objects and names imported here regardless of 36 Python version. 37 38 Simply enough, things that go in the builtins name space come from 39 our _scons_builtins module. 40 41 The rest of the things here will be in individual compatibility modules 42 that are either: 1) suitably modified copies of the future modules that 43 we want to use; or 2) backwards compatible re-implementations of the 44 specific portions of a future module's API that we want to use. 45 46 GENERAL WARNINGS: Implementations of functions in the SCons.compat 47 modules are *NOT* guaranteed to be fully compliant with these functions in 48 later versions of Python. We are only concerned with adding functionality 49 that we actually use in SCons, so be wary if you lift this code for 50 other uses. (That said, making these more nearly the same as later, 51 official versions is still a desirable goal, we just don't need to be 52 obsessive about it.) 53 54 We name the compatibility modules with an initial '_scons_' (for example, 55 _scons_subprocess.py is our compatibility module for subprocess) so 56 that we can still try to import the real module name and fall back to 57 our compatibility module if we get an ImportError. The import_as() 58 function defined below loads the module as the "real" name (without the 59 '_scons'), after which all of the "import {module}" statements in the 60 rest of our code will find our pre-loaded compatibility module. 61 """ 62 63 __revision__ = "src/engine/SCons/compat/__init__.py 5357 2011/09/09 21:31:03 bdeegan" 64 65 import os 66 import sys 67 import imp # Use the "imp" module to protect imports from fixers. 6870 """ 71 Imports the specified module (from our local directory) as the 72 specified name, returning the loaded module object. 73 """ 74 dir = os.path.split(__file__)[0] 75 return imp.load_module(name, *imp.find_module(module, [dir]))7677 -def rename_module(new, old):78 """ 79 Attempts to import the old module and load it under the new name. 80 Used for purely cosmetic name changes in Python 3.x. 81 """ 82 try: 83 sys.modules[new] = imp.load_module(old, *imp.find_module(old)) 84 return True 85 except ImportError: 86 return False87 88 89 rename_module('builtins', '__builtin__') 90 import _scons_builtins 91 92 93 try: 94 import hashlib 95 except ImportError: 96 # Pre-2.5 Python has no hashlib module. 97 try: 98 import_as('_scons_hashlib', 'hashlib') 99 except ImportError: 100 # If we failed importing our compatibility module, it probably 101 # means this version of Python has no md5 module. Don't do 102 # anything and let the higher layer discover this fact, so it 103 # can fall back to using timestamp. 104 pass 105 106 try: 107 set 108 except NameError: 109 # Pre-2.4 Python has no native set type 110 import_as('_scons_sets', 'sets') 111 import builtins, sets 112 builtins.set = sets.Set 113 114 115 try: 116 import collections 117 except ImportError: 118 # Pre-2.4 Python has no collections module. 119 import_as('_scons_collections', 'collections') 120 else: 121 try: 122 collections.UserDict 123 except AttributeError: 124 exec('from UserDict import UserDict as _UserDict') 125 collections.UserDict = _UserDict 126 del _UserDict 127 try: 128 collections.UserList 129 except AttributeError: 130 exec('from UserList import UserList as _UserList') 131 collections.UserList = _UserList 132 del _UserList 133 try: 134 collections.UserString 135 except AttributeError: 136 exec('from UserString import UserString as _UserString') 137 collections.UserString = _UserString 138 del _UserString 139 140 141 try: 142 import io 143 except ImportError: 144 # Pre-2.6 Python has no io module. 145 import_as('_scons_io', 'io') 146 147 148 try: 149 os.devnull 150 except AttributeError: 151 # Pre-2.4 Python has no os.devnull attribute 152 _names = sys.builtin_module_names 153 if 'posix' in _names: 154 os.devnull = '/dev/null' 155 elif 'nt' in _names: 156 os.devnull = 'nul' 157 os.path.devnull = os.devnull 158 try: 159 os.path.lexists 160 except AttributeError: 161 # Pre-2.4 Python has no os.path.lexists function
http://www.scons.org/doc/2.1.0/HTML/scons-api/SCons.compat-pysrc.html
CC-MAIN-2016-26
refinedweb
773
56.15
User Details - User Since - Jan 16 2020, 9:13 AM (52 w, 1 d) Thu, Dec 17 Patch against main Rebase on master I don't have commit access. Please, commit when ready. Thank you! Dec 14 2020 I don't have commit access to the repository. Please, commit when ready. Reorder operations and initializations alphabetically Removed useless code Clean up unnecessary 'auto' declartion Fixed namespace usage Dec 11 2020 Align test syntax style with common practise Rebased on top of D92171 Dialect syntax homogenized with ArmNeon dialect Naming convention aligned with ArmNeon dialect File location aligned with ArmNeon dialect Conversion code aligned with ArmNeon dialect Improved type checking Added extra scalable vector type traits Dec 8 2020 Improve documentation around signedness of operations. Fixed default value for enabling ArmSVE extensions in vector Dec 7 2020 Fixed lint problems. Improved documentation. Merged with D92614, doesn't require it's own lowering pass anymore. Dec 3 2020 Make operations signless. Rename dialect and move it to a different namespace. Nov 27 2020 Switching to ODS for type generation Fixed issue with doc formating. Changed name of vector scale size operation to a better suited one, fixed documentation accordingly. Nov 26 2020 Added missing documentation for SVE intrinsics Remove commented code Change to comply with header guard naming style Feb 5 2020 Brilliant! Thanks, Nicholas. This will indeed be a helpful reference for "close-to-ISA" dialects in general :-) Jan 29 2020 LGTM.
https://reviews.llvm.org/p/jsetoain/
CC-MAIN-2021-04
refinedweb
241
53.21
Using in order showed on each page in your store. When the customer reaches the checkout the current code will be applied.. It's really simple in the url:[YourDiscountCode] Our app will work with most stores even if they have a custom theme. But there are cases where a store can have other apps or scripts that might interfere with out app and that might cause it not to work. If you have any issues then let us know and we'll find out what the issue is. Had an issue with this to begin with - developer put in a fix and seems to be working now. will update as time goes on This app works and is a much needed addition to the stock discount code. I just need some more controls so that I can set {% if cart.total_price >= 20000 %} <form action="/cart/?discount=over2" method="post" id="cart_form"> {% else %} <form action="/cart" method="post" id="cart_form"> {% endif %}
https://apps.shopify.com/autofill-discount-from-url
CC-MAIN-2017-17
refinedweb
161
81.73
LIBPIPELINE(3) BSD Library Functions Manual LIBPIPELINE(3) libpipeline — pipeline manipulation library #include <pipeline.h> arguments command. void pipecmd_fchdir(pipecmd *cmd, int directory_fd) Change the working directory to the directory given by the open file descriptor directory_fd while running this command. environment_pre_exec(pipecmd *cmd, pipecmd_function_type *func, pipecmd_function_free_type *free_func, void *data) Install a pre-exec handler. This will be run immediately before executing the command's payload (process or function). Pass NULL to clear any existing pre-exec handler. The data argument is passed as the function's only argument, and will be freed before returning using free_func (if non-NULL). This is similar to pipeline_install_post_fork, except that is specific to a single command rather than installing a global handler, and it runs slightly later (immediately before exec rather than immediately after fork). descriptor.. See pipecmd_pre_exec for a similar facility limited to a single command rather than global to the calling process. void pipeline_start(pipeline *p) Start the processes in a pipeline. Installs this library's SIGCHLD handler if not already installed. Calls error (FATAL) on error. The standard file descriptors (0, 1, and 2) must be open before calling this function. int pipeline_wait_all(pipeline *p, int **statuses, int *n_statuses) Wait for a pipeline to complete. Set *statuses to a newly- allocated array of wait statuses, as returned by waitpid(2), and *n_statuses to the length of that array. The return value is similar to the exit status that a shell would return, with some modifications. If the last command exits with a signal (other than SIGPIPE, which is considered equivalent to exiting zero), then the return value is 128 plus the signal number; if the last command exits normally but non-zero, then the return value is its exit status; status, calculated as for pipeline_wait_all(). int pipeline_run(pipeline *p) Start a pipeline, wait for it to complete, and free it, all in one go. void pipeline_pump(pipeline *p, ...) Pump data among one or more pipelines connected using., returning potentially calling parent processes which may exit while a pipeline is running, the program is not guaranteed to be able to collect exit statuses of those processes.. If the PIPELINE_DEBUG environment variable is set to “1”, then libpipeline will emit debugging messages on standard error. If the PIPELINE_QUIET environment variable is set to any value, then libpipeline will refrain from printing an error message when a subprocess is terminated by a signal.); fork(2), execve(2), system(3), popen(3). Most of libpipeline was written by Colin Watson <cjwatson@debian.org>, originally for use in man-db. The initial version was based very loosely on the run_pipeline() function in GNU groff, written by James Clark <jjc@jclark.com>. It also contains library code by Markus Armbruster, and by various contributors to Gnulib. libpipeline is licensed under the GNU General Public License, version 3 or later. See the README file for full details. Using this library in a program which runs any other child processes and/or installs its own SIGCHLD handler is unlikely to work. This page is part of the libpipeline (pipeline manipulation library) project. Information about the project can be found at. 2020-11 October 11, 2010 GNU
https://man7.org/linux/man-pages/man3/libpipeline.3.html
CC-MAIN-2021-25
refinedweb
528
56.55
XML::Essex - Essex XML processing primitives TODO The return value will be returned to the caller. For handlers, this is usually a "1" for success or some other value, such as a data structure that has been built or the result of a query. For generators and filters, it is important that the result of the next filter's end_document() is returned at the end of your Essex script, so that it may be used upstream of such modules as XML::Simple. Errors should be reported using die(). Essex is designed to Do The Right Thing for the vast majority of uses, so it manages result values automatically unless you take control. Below is a set of detailed rules for how it manages the result value for a filter's processing run, but the overview is: result()with it, or returnthat result normally, just like a handler. result()with it, or returnthat result normally. Generators and filters generally should not return a value of their own because this will surprise calling code which is expecting a return value of the type that the final SAX handler returns. These are exported by default, use the use XML::Essex (); syntax to avoid exporting any of these or export only the ones you want. The following export tags are also defined: :read get read_from parse_doc isa next_event path type xeof :rules on :write put write_to start_doc end_doc start_elt chars ... so you can use XML::Essex qw( :read :rules ); for an Essex script that just handles input and uses some rules, or even: use XML::Essex qw( parse_doc :rules ); for a purely rule-based script. Importing only what you need is a little quicker and more memory efficient, but it cal also allow XML::Essex to run more efficiently. If you don't import any output functions (see :write above), it will not load the output routines. Same for the input and rule based APIs. my $e = get; Returns the next SAX event. Sets $_ as an EXPERIMENTAL feature. Throws an exception (which is silently caught outside the main code) on end of input. See isa() and type() functions and method (in XML::Essex::Object) for how to test what was just gotten. read_from \*STDIN; ## From a filehandle read_from "-"; ## From \*STDIN read_from "foo.xml"; ## From a file or URI (URI support is parser dependant) read_from \$xml_string; ## From a string. read_from undef; ## STDIN or files named in @ARGV, as appropriate Tells the next get() or parse_doc() to read from the indicated source. Calling read_from automatically disassembles the current processing chain and builds a new one (just like Perl's open() closes an already open filehandle). Adds an output filter to the end of the current list (and before the eventual writer). Can be a class name (which will be require()ed unless the class can already new()) or a reference to a filter. Parses a single document from the current input. Morally equivalent to get() while 1; but exits normally (as opposed to throwing an exception) when the end of document is reached. Also slightly faster now and hopefully moreso when optimizations can be made. Used to read to the end of a document, primarily in rule-based processing ("on"). TODO: Allow parse_doc to take rules. Output one or more events. Usually these events are created by constructors like start_elt() (see XML::Generator::Essex for details) or are objects returned get() method. write_to \*STDOUT; ## To a filehandle write_to "-"; ## To \*STDOUT write_to "foo.xml"; ## To a file or URI (URI support is parser dependant) write_to \$xml_string; ## To a string. Tells the next put() to write the indicated source. get until isa "start_elt" and $_->name eq "foo"; $r = get until isa $r, "start_elt" and $_->name eq "foo"; Returns true if the parameter is of the indicated object type. Tests $_ unless more than one parameter is passed. Like get() (see below), but does not remove the next event from the input stream. get "start_document::*"; get if next_event->isa( "xml_decl" ); ...process remainder of document... get "start_element::*" until path eq "/path/to/foo:bar" Returns the path to the current element as a string. get until type eq "start_document"; $r = get until type $r eq "start_document"; Return the type name of the object. This is the class name with a leading XML::Essex:: stripped off. This is a wrapper around the event's type() method. Return TRUE if the last event has been read. If this section doesn't make any sense, see for your next dose of XML koolaid. If it still doesn't make any sense then ding me for writing gibberish. Element names, attribute names, and PI targets returned by Essex are generated in one of three forms, depending on whether the named item has a namespace URI associated with it and whether the filter program has mapped that namespace URI to a prefix. You may also use any of these three forms when passing a name to Essex: If an attribute has no NamespaceURI or an empty string for a NamespaceURI, it will be returned as a simple string. TODO: Add an option to enable this for the default namespace or for attrs in the element's namespace. If the attribute is in a namespace and there is a namespace -> prefix mapping has been declared by the filter If the attribute is in a namespace with no prefix mapped to it by the filter. Namespace prefixes from the source document are ignored; there's no telling what prefix somebody might have used. Intercept the start_prefix_mapping and end_prefix_mapping events to follow the weave of source document namespace mappings. When outputting events that belong to a namespace not in the source document, you need to put() the start_prefix_mapping and end_prefix_mapping events manually, and be careful avoid existing prefixes from the document if need be while doing so. Future additions to Essex should make this easier and perhaps automatic. Essex lets you manage namespace mappings by mapping, hiding, and destroying ( $namespace => $prefix ) pairs using the functions: aka: ns_map my $map =. It is often advantageous to declare exceptional events that should be processed as they occur in the stream rather than testing for them explicitly everywhere they might occur in the script. This is done using the "on" function. on( "start_document::*" => sub { warn "start of document reached" }, "end_document::*" => sub { warn "end of document reached" }, ); This declares that a rule should be in effect until the end of the document For now, this must be called before the first get() for predictable results. Rules remain in effect after the main() routine has exited to facilitate pure rule based processing.. These are exported by :write (in addition to being available individually). aka: characters aka: end_document aka: end_element aka: start_document aka: start_element XML::Essex is a source filter that wraps from the use line to the end of the file in an eval { ... } block. Stay tuned. You may use this module under the terms of the BSD, Artistic, oir GPL licenses, any version. Barrie Slaymaker <barries@slaysys.com>
http://search.cpan.org/~rbs/XML-Filter-Essex/lib/XML/Essex.pm
crawl-002
refinedweb
1,168
61.67
C++11 support in ODB One of the major new features in the upcoming ODB 2.0.0 release is support for C++11. In this post I would like to show what is now possible when using ODB in the C++11 mode. Towards the end I will also mention some of the interesting implementation-related issues that we encountered. This would be of interest to anyone who is working on general-purpose C++ libraries or tools that have to be compatible with multiple C++ compilers as well as support both C++98 and C++11 from the same codebase. In case you are not familiar with ODB, it is an object-relational mapping (ORM) system for C++. It allows you to persist C++ objects to a relational database without having to deal with tables, columns, or SQL, and manually writing any of the mapping code. While the 2.0.0 release is still a few weeks out, if you would like to give the new C++11 support a try, you can use the 1.9.0.a1 pre-release. While one could use most of the core C++11 language features with ODB even before 2.0.0, what was lacking is the integration with the new C++11 standard library components, specifically smart pointers and containers. By default, ODB still compiles in the C++98 mode, however, it is now possible to switch to the C++11 mode using the --std c++11 command line option (this is similar to GCC’s --std=c++0x). As you may remember, ODB uses GCC as a C++ compiler frontend which means ODB has arguably the best C++11 feature coverage available, especially now with the release of GCC 4.7. Let’s start our examination of the C++11 standard library integration with smart pointers. New in C++11 are std::unique_ptr and std::shared_ptr/ weak_ptr. Both of these smart pointers can now be used as object pointers: #include <memory> class employer; #pragma db object pointer(std::unique_ptr) class employee { ... std::shared_ptr<employer> employer_; }; #pragma db object pointer(std::shared_ptr) class employer { ... }; ODB now also provides lazy variants for these smart pointers: odb::lazy_unique_ptr, odb::lazy_shared_ptr, and odb::lazy_weak_ptr. Here is an example: #include <memory> #include <vector> #include <odb/lazy-ptr.hxx> class employer; #pragma db object pointer(std::shared_ptr) class employee { ... std::shared_ptr<employer> employer_; }; #pragma db object pointer(std::shared_ptr) class employer { ... #pragma db inverse(employer_) std::vector<odb::lazy_weak_ptr<employee>> employees_; }; Besides as object pointers, unique_ptr and shared_ptr/ weak_ptr can also be used in data members. For example: #include <memory> #include <vector> #pragma db object class person { ... #pragma db type("BLOB") null std::unique_ptr<std::vector<char>> public_key_; }; It is unfortunate that boost::optional didn’t make it to C++11 as it would be ideal to handle the NULL semantics ( boost::optional is supported by the Boost profile). The good news is that it seems there are plans to submit an std::optional proposal for TR2. The newly supported containers are: std::array, std::forward_list, and the unordered containers. Here is an example of using std::unordered_set: #include <string> #include <unordered_set> #pragma db object class person { ... std::unordered_set<std::string> emails_; }; One C++11 language feature that comes really handy when dealing with query results is the range-based for-loop: typedef odb::query<employee> query; transaction t (db->begin ()); auto r (db->query<employee> (query::first == "John")); for (employee& e: r) cout << e.first () << ' ' << e.last () << endl; t.commit (); So far we have tested C++11 support with various versions of GCC as well as VC++ 10 (we will also test with Clang before the final release). In fact, all the tests in our test suite build and run without any issues in the C++11 mode with these two compilers. ODB also comes with an example, called c++11, that shows support for some of the C++11 features discussed above. These are the user-visible features when it comes to C++11 support and they are nice and neat. For those interested, here are some not so neat implementation details that I think other library authors will have to deal with if they decide to support C++11. The first issue that we had to address is simultaneous support for C++98 and C++11. In our case, supporting both from the same codebase was not that difficult (though more on that shortly). We just had to add a number of #ifdef ODB_CXX11. What we only realized later was that to make C++11 support practical we also had to support both from the same installation. To understand why, consider what happens when a library is packaged, say, for Ubuntu or Fedora. A single library is built and a single set of headers is packaged. To be at all usable, these packages cannot be C++98 or C++11. They have to support both at the same time. It is probably possible to have two versions of the library and ask the user to link to the correct one depending on which C++ standard they are using. But you will inevitably run into tooling limitations (e.g., pkg-config doesn’t have the --std c++11 option). The situation with headers are even worse, unless your users are prepared to pass a specific -I option depending on which C++ standard they are using. The conclusion that we came to is this: if you want your library to be usable once installed in both C++98 and C++11 modes in a canonical way (i.e., without having to specify extra -I options, defines, or different libraries to link), then the C++11 support has to be header-only. This has some interesting implications. For example, initially, we used an autoconf test to detect whether we are in the C++11 mode and write the appropriate value to config.h. This had to be scraped and we now use a more convoluted and less robust way of detecting the C++ standard using pre-defined compiler macros such as __cplusplus and __GXX_EXPERIMENTAL_CXX0X__. The other limitation of this decision is that all “extra” C++11 functions, such as move constructors, etc., have to be inline or templates. While these restrictions sound constraining, so far we didn’t have any serious issues maintaining C++11 support header-only. Things fitted quite naturally into this model but that, of course, may change in the future. The other issue that we had to deal with is the different level of C++11 support provided by different compiler implementations. While GCC is more or less the gold standard in this regard, VC++ 10 lacked quite a few features that we needed, specifically, deleted functions, explicit conversion operators, and default function template arguments. As a result, we had to introduce additional macros that indicate which C++11 features are available. This felt like early C++98 days all over again. Interestingly, none of the above mentioned three features will be supported in the upcoming VC++ 11. In fact, if you look at the VC++ C++11 support table, it is quite clear that Microsoft is concentrating on the user-facing features, like the range-based for-loop. This means there will probably be some grief for some time for library writers.
http://codesynthesis.com/~boris/blog/2012/03/27/cxx11-support-in-odb/
CC-MAIN-2013-20
refinedweb
1,222
61.87
How to find Maximum Pairwise Product in Java using Naive approach In this Java tutorial, we will learn how to find the maximum pairwise product using Java. Maximum Pairwise Product in easy words you can say that it is the product of those two numbers present in an array from which we get the highest value possible. What is the meaning of Maximum Pairwise Product? It means that we have to find the maximum product of two distinct numbers in a given array of non-negative numbers. Input: A sequence of non-negative numbers. Output: The maximum value that can be obtained by multiplying two different numbers from the input sequence. =>, For example, I’m giving you a sequence of non-negative numbers: a1 . . . . an Input format: The first line contains a single number whose value is equal to n. The next line contains n non-negative numbers a1 . . . . an. Output format: The maximum pairwise product. Sample 1 Input : 3 1 2 3 Output : 6 Sample 2 Input: 10 7 5 14 2 8 8 10 1 2 3 Output: 140 Naive Method : A naive approach is to solve the Maximum Pairwise Product Question is to find all the possible pairs from the sequence which is inputted by the user. A[1 . . . . n] =[a1 . . . . an] and then we have to find the largest product value. Logic : First, we have to find the two largest values from the inputted sequence. Because we know that the product of the largest value is the maximum product we can get. Note: All inputted numbers in the sequence is must be non-negative numbers. Find Maximum Pairwise Product in Java using Native Approach import java.util.*; import java.io.*; public class MaxPairwiseProduct { static long getMaxPairwiseProductFast(int[] numbers) { int n_Size = numbers.length; int max_index1 = -1; for (int p = 0; p < n_Size; p++) { if ((max_index1 == -1) || (numbers[p] > numbers[max_index1])) max_index1 = i; } int max_index2 = -1; for (int k = 0; k < n_Size; k++) { if ((k != max_index1) && ((max_index2 == -1) || (numbers[k] > numbers[max_index2]))) max_index2 = j; } return (long)numbers[max_index1] * numbers[max_index2]; } public static void main(String[] args) { FastScanner scanner = new FastScanner(System.in); int n = scanner.nextInt(); int[] numbers = new int[n]; for (int i = 0; i < n; i++) { numbers[i] = scanner.nextInt(); } System.out.println(getMaxPairwiseProductFast(numbers)); static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } } } We have used StringTokenizer class here. You can also read, - Frequency of Repeated words in a string in Java - Working with HashMap (Insertion, Deletion, Iteration) in Java
https://www.codespeedy.com/find-maximum-pairwise-product-in-java/
CC-MAIN-2020-40
refinedweb
455
56.96
@stencil/router is the NPM package to use with Stencil to make it easy to define routes for your web component-powered PWA. The API for the router is very similar to React Router’s, so you may already be familiar with the syntax. In this post we’ll build a simple example where we have global components for an app shell, header and menu, as well as 3 routes: home, about and contact. Setup & Configuration First, make sure you have the @stencil/router package installed in your project: $ npm install @stencil/router # or, using Yarn $ yarn add @stencil/router Next you’ll want to make sure that your Stencil config file’s config object contains a collections array with the router package: stencil.config.js exports.config = { bundles: [ { components: ['app-shell', 'app-header', 'app-menu'] } ], collections: [ { name: '@stencil/router' } ] }; // ... If you're using Stencil's starter app to initiate your project, the @stencil/router package and proper config will already be in place. Defining Routes Routes are defined in a global <stencil-router> element that contains <stencil-route> elements for each individual route definition. Routes will be rendered inside the stencil-router element. The <stencil-router> should have an id that the <stencil-route> elements can refer to. Here’s a simple example with our 3 routes: <stencil-router <stencil-route <stencil-route </stencil-router> Notice the use of exact={true} on the root / url to match only the root path to the home component. We would place such route config in our app’s top level component, here app-shell. Here, our whole app root component could look like this: /components/app-shell/app-shell.tsx import { Component } from '@stencil/core'; @Component({ tag: 'app-shell' }) export class AppComponent { render() { return [ <app-header, <app-menu />, <stencil-router <stencil-route <stencil-route </stencil-router> ]; } } The render method returns multiple top level elements. This can be done using an array of top level elements, like in the above example. Or, it can also be done by wrapping the 3 top level elements in a wrapping div element. Linking to a Route To link to a route with the app, use the <stencil-route-link> element with the id of the router and the url. Here for example, here’s the render method of our app-menu component: /components/app-menu/app-menu.tsx (partial) render() { return ( <ul> <li> <stencil-route-link About </stencil-route-link> </li> <li> <stencil-route-link Contact </stencil-route-link> </li> </ul> ); } Here we’re also using the activeClass property to set a class name on active routes. The root route also has its exact property set to true so that the active class gets added only on an exact match of the url. Passing Data to a Route You can also pass props to a route in its configuration using the componentProps property: <stencil-route url="/contact" component="app-contact" router="#router" componentProps={{ method: 'Walkie-talkie' }} /> And then in the component it can be accessed using using the @Prop decorator: app-contact.tsx import { Component, Prop } from '@stencil/core'; @Component({ tag: 'app-contact' }) export class ContactComponent { @Prop() method: string; render() { return <p>📞 Getting in touch by {this.method}</p>; } } 👷 The Stencil router is in heavy development and the API is bound to change rapidly. Refer to the official repo for the latest changes.
https://alligator.io/stencil/routing/
CC-MAIN-2019-09
refinedweb
557
50.16
In dynamic programming, a problem may be broken down into smaller subproblems and solved more efficiently, since the optimum solution to the core problem is dependent on the optimal solution to each of the smaller subproblems. Richard Bellman came up with the idea for the method back in the '50s. The DP method only computes the answer to each subproblem once and then remembers it, saving time by not recomputing it for subsequent appearances of the same subproblem. By the end of this tutorial, you will better understand the recursive and dynamic programming approach to find the Longest Increasing Subsequence with the necessary details and practical implementations. Problem Statement for the Longest Increasing Subsequence Problem The Longest increasing subsequence (LIS) problem involves finding the length of the longest increasing subsequence inside a given sequence. All items within it are sorted in ascending order of increasing length. As an example, the length of LIS for the set {10, 15, 13, 9, 21, 22, 35, 29, 64} is 6 and LIS is the set {10, 15, 21, 22, 35, 64}. Now, look at the recursive solution to solve the Longest increasing subsequence. Recursion-Based Solution to Find the Longest Increasing Subsequence This recursive approach is more of a brute force approach. You will follow the below steps to find LIS length: - You will search for an increasing subsequence for every element and then pick the one with the maximum length. - You will start with fixing the ending point first and then go from there. - You will decrease the indices and look for the second last element, and so on. - Finally, you will select the subsequence with the highest length and declare it as LIS. And this is how you find the Longest increasing subsequence using recursion. Now, implement this solution through a simple C++ code. Implement the Recursion-Based Solution to Find the Longest Increasing Subsequence You will be provided with a set with elements {10, 15, 13, 9, 21, 22, 35, 29, 64}. Now, you are to find the longest increasing subsequence in this set, which will come out to be the LIS{10, 13, 21, 22, 29, 64} and of length equal to six. Code: /* A C++ program to implement recursive solution of LIS problem */ #include <bits/stdc++.h> using namespace std; /* To make use of recursive calls, this the function will return two things: 1) We use curmaxending to get Length of LIS ending with element arr[n-1] 2) Overall maximum as the LIS may end with an element before arr[N-1]. maxref is used this purpose. The value of LIS of a full array of size n is stored in *max_ref, which is our final result */ int _lis(int arr[], int N, int* maxref) { /* Base case */ if (N == 1) return 1; // 'curmaxending' is length of LIS // ending with arr[N-1] int res, curmaxending = 1; /* Recursively get all LIS ending with arr[0], arr[1] ... arr[n-2]. If arr[i-1] is smaller than arr[N-1], and max ending with arr[N-1] needs to be updated, then update it */ for (int i = 1; i < N; i++) { res = _lis(arr, i, maxref); if (arr[i - 1] < arr[N - 1] && res + 1 > curmaxending) curmaxending = res + 1; } // Compare curmaxending with the overall // max. And update the overall max if needed if (*maxref < curmaxending) *maxref = curmaxending; // Return length of LIS ending with arr[N-1] return curmaxending; } // The wrapper function for _lis() int lis(int arr[], int N) { // The max variable holds the result int max = 1; // The function _lis() stores its result in max _lis(arr, N, &max); // returns max return max; } int main() { int arr[] = { 10, 15, 13, 9, 21, 22, 35, 29, 64 }; int N = sizeof(arr) / sizeof(arr[0]); cout <<"Length of lis is "<< lis(arr, N); return 0; } You have now discussed the recursive approach to find the Longest increasing subsequence with a code. This method has a time complexity of O(2n). If you look at the recursion tree of the above method, you will find some overlapping subproblems. That means you can still improve your time complexity. Now, see the dynamic programming-based solution to this problem. Dynamic Programming Based Solution to Find the Longest Increasing Subsequence Since the recursive approach uses a top-down approach, you will follow the bottom-up approach. - First, make a 1D array of size n. - Next, you must iterate it for each element from index 1 to n-1. - You will iterate the elements with indices smaller than the current element in a nested loop for each element. - In this nested loop, if you find the element’s value is lesser than the current element, then you will assign lis[i] with (lis[j]+1) and if (lis[j]+1) is greater than lis[i]. - Finally, you will traverse the entire lis[] array to find the maximum element, which will conclude your answer. And this is how you solve this problem using dynamic programming. Now implement this solution through a simple C++ code. Implement the Dynamic Programming Based Solution to Find the Longest Increasing Subsequence You will be provided with a set with elements {10, 15, 13, 9, 21, 22, 35, 29, 64}. You are to find the longest increasing subsequence in this set, which will come out to be the LIS{10, 15, 21, 22, 35, 64} and of length equal to six. Code: //A C++ program to implement LIS problem using Dynamic Programming #include <bits/stdc++.h> using namespace std; /* lis() returns the length of the longest increasing subsequence in arr[] of size N */ int lis(int arr[], int N) { int lis[N]; lis[0] = 1; /* Compute optimized LIS values in bottom up manner */ for (int i = 1; i < N; i++) { lis[i] = 1; for (int j = 0; j < i; j++) if (arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; } // Return maximum value in lis[] return *max_element(lis, lis + N); } /* Driver program to test above function */ int main() { int arr[] = { 10, 15, 13, 9, 21, 22, 35, 29, 64 }; int N = sizeof(arr) / sizeof(arr[0]); printf("Length of longest increasing sub-sequence is %d\n", lis(arr, N)); return 0; } With this, you have come to an end of this tutorial. You will now look at what could be your next steps to conquer dynamic programming problems. Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now! Next Steps Your next stop in mastering dynamic programming problems should be Knapsack Problem. The knapsack problem is used to explain both the problem and the solution. It derives its name from the limited number of things that may be carried in a fixed-size knapsack. You are given a selection of varying weights and values; your objective is to cram as much worth into the knapsack as possible while staying within the weight limit. If you're searching for a more in-depth understanding of software development that can help you carve out a successful career in the field, look no further. If that's the case, consider Simplilearn's Postgraduate Program in Full Stack Web Development, which is offered in collaboration with Caltech CTME, the world's largest technology education institution. This Post-Graduate Program will teach you how to grasp both front-end and back-end Java technologies, beginning with the basics and moving to more sophisticated Full Stack Web Development subjects. In this web development course, you'll study Angular, Spring Boot, Hibernate, JSPs, and MVC, which will help you get started as a full-stack developer. If you have any questions or require clarification on this "Longest Increasing Subsequence" tutorial, please leave them in the comments section below. Our expert team will review them and respond as soon as possible.
https://www.simplilearn.com/tutorials/data-structure-tutorial/longest-increasing-subsequence
CC-MAIN-2022-40
refinedweb
1,308
55.47
Background I could find lots of examples of mocking the AWS-SDK. But I have been finding it complex. I have been exploring some other approach that it will be easier to mocking AWS-SDK. Outlines - Eventually, AWS-SDK is a wrapper of WebAPI. All functions contain in a services object. - For keeping versatility, each service has versions of API - When a service instance created, the latest service is called from inside SDK. Thus backdoor approach, We can mock only specified aws-sdk functions. Example(Lambda Invoke) example.test.ts import * as AWS from 'aws-sdk' jest.spyOn(AWS.Lambda.services ["2015-03-31"].prototype, 'invoke').mockImplementation( (request) => { return {promise: () => 'debug'} }) - many cases, the promise method seem to be called. Return an object which includes the promise method. - spyOn is helpful. because it’s easy to restore the mock by calling jest.restoreAllMocks() Conclusion I think this is helpful. You don’t have to add another package, You don’t have to make a wrapper class of AWS-SDK for achieving testable. many cases, to keep testability, these wrapper class inserted as a parameter of constructer. (Dependency Injection)
https://hugtech.io/2019/07/05/simplify-mocking-aws-sdk-with-jest/
CC-MAIN-2021-21
refinedweb
188
52.46