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 |
|---|---|---|---|---|---|
- Silverlight
- .NET
- C# Elements
- C# Constructs
- C# Data Access
- C# Security/Debug
- C# Code
- C# Videos
- Windows Phone
- About
Data Streams
Backing Store Streams | Decorator Streams | Stream Adapters | Stream Class | File Stream | File, Directories, Paths | Memory Stream | Memory-Mapped Files | Pipe Stream | Buffered Stream | Text Adapters | Binary Adapters | FileSystemWatcher Class | Isolated Storage
"A stream is an abstraction for a sequence of bytes. Streams provide a more consistent way to interact with the various types of underlying data sources. Streams support reading, writing, and some streams support seeking. Async methods where created for the Stream class in .NET 4.5 which allow for resource-intensive I/O operations without blocking the main thread."
Data Streams
A stream is a data source abstraction which allows data from diverse sources to be processed in a similar fashion. All classes that represent streams are derived from the Stream base class. Components of the stream architecture can be broken down into three categories:
- Backing Store Streams - is the end point for the I/O operation. These streams are hard-wired to a specific type of backing store, such as a file or a network source of data.
- Decorator Streams - are based on the Decorator Design Pattern that "dynamically adds functionality to an object". These streams transform the data from an existing string. The data stream can cycle through multiple decorator streams, such a file which is encrypted and then compressed.
- Adapters - transform the bytes which used in Backing Store Streams and Decorator Streams into higher levels of data typically used by applications, such as text, XML, or the C# primitive data types.
Streams process data serially, either one byte at a time, or in a small block of bytes. So regardless of the size of the backing store, processing the associated stream requires little memory. Additional characteristics of streams include:
- Streams provide a consistent programming interface across a variety of data sources.
- Streams work exclusively at the byte level. Adapters are needed to work with the data at a higher level.
- Streams contain properties to indicate if the particular stream supports reading, writing, or seeking.
- Inherently streams are not thread-safe. However the Stream class offers a static Synchronized method which encapsulates the stream with concurrency protection.
- Network streams support time-out capability which can be specified in milliseconds. File and Memory streams do not support time-outs.
- Streams gained support for asynchronous reading and writing in .NET 4.5. The async stream methods allow for resource-intensive I/O operations without blocking the main thread.
- Stream buffers are automatically flushed when the stream is closed.
- Streams must be disposed after use to release the underlying resources. Disposal can be guaranteed by instantiating streams within a using statement. Alternatively the Dispose method can be called from inside the final clause of the try statement. See the Exception Handling
article for more details about disposing of resources in the finally clause.
Backing Store Streams
Backing store streams provide support for interfacing with particular types of data stores. It is also possible to have a null stream which contains no backing store and acts as a data sink. Support for additional backing store streams are included in the following namespaces:
- System.IO
- FileStream - exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.
- MemoryStream - creates a stream whose backing store is memory.
- System.IO.Pipes
- PipeStream - exposes a Stream object around a pipe, which supports both anonymous and named pipes.
- AnonymousPipeClientStream - exposes the client side of an anonymous pipe stream, which supports both synchronous and asynchronous read and write operations.
- AnonymousPipeServerStream - exposes a stream around an anonymous pipe, which supports both synchronous and asynchronous read and write operations.
- NamedPipeClientStream - exposes a Stream around a named pipe, which supports both synchronous and asynchronous read and write operations.
- NamedPipeServerStream - exposes a Stream around a named pipe, supporting both synchronous and asynchronous read and write operations.
- System.Net.Sockets
- NetworkStream - provides the underlying stream of data for network access.
Top
Decorator Streams
Decorator streams provide additional functionality to the stream at runtime. Decorator streams can be chained together to provide multiple transformations to the stream. Decorator streams free the backing store streams from having to provide compression, encryption, etc. Decorator streams are included in the following namespaces:
- System.IO
- BufferedStream - adds a buffering layer to read and write operations on another stream.
- System.IO.Compression
- DeflateStream - provides methods and properties for compressing and decompressing streams by using the Deflate algorithm.
- GZipStream- provides methods and properties used to compress and decompress streams.
- System.Security.Cryptography
- CryptoStream - defines a stream that links data streams to cryptographic transformations.
Top
Stream Adapters
The Adapter Pattern allows two incompatible interfaces to communicate. In C# all streams are defined as a series of bytes. Stream adapters provide a higher-level of data abstraction from bytes to characters, strings, primitive values, or XML. For example if you wish to work with a stream of bytes which represent character data, then you would use classes derived from the Text Adapter. For a stream of bytes which represent numeric data, you would use a Binary Adapter. The following adapters are provided by .NET:
- System.IO
- BinaryReader - reads primitive data types as binary values in a specific encoding.
- BinaryWriter - writes primitive types in binary to a stream and supports writing strings in a specific encoding.
- TextReader - the abstract base class for reading character only data.
- TextWriter - the abstract base class for writing character only data.
- StreamReader - implements a TextReader that reads characters from a byte stream in a particular encoding. The backing store is a stream. Translation is required between bytes and characters.
- StreamWriter - implements a TextWriter for writing characters to a stream in a particular encoding. The backing store is a stream. Translation is required between bytes and characters.
- StringReader - implements a TextReader that reads from a string. Backing store is String or StringBuilder. No translation required as backing store in already in character format.
- StringWriter - implements a TextWriter for writing information to a string. Backing store is String or StringBuilder. No translation required as backing store in already in character format.
- System.Xml
Top
Stream Class
All stream classes are derived from the abstract Stream class. A stream's I/O capabilities depend on the stream's underlying data store. A stream can be queried for its capabilities by using the CanRead, CanWrite, and CanSeek properties of the Stream class. Additional useful Stream properties include:
- CanTimeout - determines whether the current stream can time out.
- Length - gets the length in bytes of the stream.
- Position - gets or sets the position within the current stream.
- ReadTimeout - a value, in miliseconds, that determines how long the stream will attempt to read before timing out.
- WriteTimeout - a value, in miliseconds, that determines how long the stream will attempt to write before timing out.
The Stream class provides the following three read methods. There are also three corresponding write methods.
- Read - reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
- ReadByte - Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
- ReadAsync - asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
Additional useful Stream methods include:
- CopyTo - reads the bytes from the current stream and writes them to another stream.
- CopyToAsync - Asynchronously reads the bytes from the current stream and writes them to another stream.
- Dispose - releases all resources used by the Stream.
- Finalize - allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
- Flush - clears all buffers for this stream and causes any buffered data to be written to the underlying device.
- Seek - sets the position within the current stream.
- SetLength - sets the length of the current stream.
- Synchronized - creates a thread-safe (synchronized) wrapper around the specified Stream object.
The following example code shows how the different types of streams can be "upcast" to the base Stream class. This allows for reuse of code. Notice the Print method is passed a FileStream and then a MemoryStream and accepts them as the base Stream class. The Stream class property (length) and method (Read) are then used on both the FileStream and MemoryStream inside the Print method.
Upcast FileStream and MemoryStream to Stream class
using System;
using System.IO;
using System.Linq;
using System.Text;
class Program
{
const int BUFFER_SIZE = 250;
static int streamCounter = 0;
static void Main()
{
using (FileStream myFileStream = File.Open(@"C:\myFile.txt", FileMode.Open))
Print(myFileStream);
byte[] memoryBuffer = System.Text.Encoding.ASCII.GetBytes("Badfinger - Baby Blue (1972)\n");
using (MemoryStream stream2 = new MemoryStream(memoryBuffer))
Print(stream2);
}
static void Print(Stream stream)
{
// Print length of input stream
Console.WriteLine("{0}. Stream length is: {1}", ++streamCounter, stream.Length);
// Create read byte buffer
byte[] readBuffer = Enumerable.Repeat(Byte.MinValue, BUFFER_SIZE).ToArray();
// Read raw bytes from stream
int bytesRead = 0;
int byteSize = 1;
while (bytesRead < readBuffer.Length && byteSize > 0)
bytesRead += byteSize = stream.Read(readBuffer, bytesRead, readBuffer.Length - bytesRead);
// Convert raw bytes to default (UTF8) characters.
char[] myChars = Encoding.Default.GetChars(readBuffer);
// Print buffer contents
foreach (char myChar in myChars)
if (myChar != Byte.MinValue)
Console.Write(myChar);
Console.WriteLine("");
}
}
Top
File Stream
The FileStream class can be used to perform I/O operations on files or file-related handles (e.g. standard input, standard output, pipes). The FileStream class has asynchronous methods to perform resource-intensive file operations without blocking the main thread. A FileStream can be instantiated with the FileStream class, or (more easily) with the File class (see more details in the File class section).
A popular FileStream constructors is the one including the three parameters the FileMode ("Creation Mode"), FileAccess ("Read/Write Permissions"), and the FileShare ("Concurrent Sharing Permissions") as shown below. Another commonly used constructor just contains the FileMode and FileAccess parameters, with the FileShare parameter. In which case the FileShare.Read is the default for those FileStream constructors without a FileShare parameter.
FileStream myFileStream = new FileStream("myFile.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
The FileStream constructor contains three parameters which control access to the FileStream. The three access parameters and their enumerations are:
- FileMode - specifies creation mode.
- Append- opens the file if it exists and seeks to the end of the file, or creates a new file.
- Create - specifies a new file should be created. If the file already exists, it will be overwritten
- CreateNew - specifies a new file should be created. If the file already exists, an IOException exception is thrown.
- Open - specifies that the operating system should open an existing file. The ability to open the file is dependent on the value specified by the FileAccess enumeration. A System.IO.FileNotFoundException exception is thrown if the file does not exist.
-.
- Truncate - specifies that the operating system should open an existing file. When the file is opened, it should be truncated so that its size is zero bytes. This requires FileIOPermissionAccess.Write permission. Attempts to read from a file opened with FileMode.Truncate cause an ArgumentException exception.
- FileAccess - specifies read/write permission.
- Read - read access to the file.
- ReadWrite - read and write access to the file
- Write - write access to the file
- FileShare - specifies sharing permission. Used to define how much access to grant other processes wanting to use the same file before the current process is finished with it.
- Delete - allows subsequent deleting of a file.
- Inheritable - makes the file handle inheritable by child processes.
- None - declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.
- Read - (Default) allows subsequent opening of the file for reading.
- ReadWrite - allows subsequent opening of the file for reading or writing.
- Write - allows subsequent opening of the file for writing.
If the FileShare.ReadWrite is used in the FileStream constructor, the FileStream Lock and Unlock methods should be used by the processes concurrently accessing the FileStream. The Lock method will throw an exception if all or part of the file section has already been locked. The default for the FileShare parameter is FileShare.Read.
Some of the advanced FileStream characteristics are controlled through the use of the following additional parameters in the FileStream constructor:
- bufferSize- sets the size of the internal buffer (default is 4 KB).
- FileSystemRights - enumeration contains granular system rights which can be dynamically assigned.
-.
- FileOptions - enumeration which allows a bitwise combination of its member values.
- Asynchronous - Indicates that a file can be used for asynchronous reading and writing.
- DeleteOnClose - Indicates that a file is automatically deleted when it is no longer in use.
- Encrypted - Indicates that a file is encrypted and can be decrypted only by using the same user account used for encryption.
- None - Indicates that no additional options should be used when creating a FileStream object.
- RandomAccess - Indicates that the file is accessed randomly. The system can use this as a hint to optimize file caching.
- SequentialScan - Indicates that the file is to be accessed sequentially from beginning to end.
- WriteThrough - Indicates that the system should write through any intermediate cache and go directly to disk.
FileStreams can allow for real asynchronous I/O when the useAsync flag is set to true on the constructor. This is unlike the async methods in the File class which "fake" async I/O by using another thread from the pool to work with the file.
The following program shows how to use the CopyToAsync method to asynchronously copy the files, using async FileStreams, from one directory to another. The code contains EnumerateDirectories which can start enumerating the directories before the collection is completely retrieved. If GetDirectores were used instead, you would have to wait until all the directory names were in the collection before continuing the process. Notice the FileStream is constructed with the default 4096 buffer size followed by a Boolean flag set to "true" (useAsync flag) which allows for "real" asynchronous I/O.
Asynchronous FileStream Copy
using System.IO;
class Program
{
static void Main()
{
string fromDirectory = @"c:\kevin\from";
string toDirectory = @"c:\kevin\to";
foreach (string fileName in Directory.EnumerateFiles(fromDirectory))
CopyFiles(fileName, fromDirectory, toDirectory);
}
private static async void CopyFiles(string fileName, string fromDirectory, string toDirectory)
{
string filePathTo = toDirectory + fileName.Substring(fileName.LastIndexOf('\\'));
string filePathFrom = fromDirectory + fileName.Substring(fileName.LastIndexOf('\\'));
using (FileStream SourceStream = new FileStream(filePathFrom,
FileMode.Open, FileAccess.Read, FileShare.None, 4096, true))
using (FileStream DestinationStream = File.Create(filePathTo))
await SourceStream.CopyToAsync(DestinationStream);
}
}
Top
File, Directories, Paths
.NET contains various classes for supporting files and file systems. One of the most versatile classes for working with files is the File class. Other classes for I/O support include Directory, FileInfo, DirectoryInfo, Path, and DriveInfo. MSDN has examples of how to perform common I/O tasks in the article Common I/O Tasks.
File Class - Instantiating FileStreams
While a FileStream can be instantiated with FileStream constructors, they can also be instantiated in a simpler fashion using the following File class static methods:
- Create - (read/write access) creates or overwrites a file in the specified path.
using (FileStream fs = File.Create(path))
- File is created if it does not already exist. If file does exist and it is not read-only, the content is completely removed.
- FileStream has a default FileShare value of None.
- FileStream has the default 4K buffer size.
- FileStream has read/write access to all users.
- OpenWrite - (write-only access) opens an existing file or creates a new file for writing.
using (FileStream fs = File.OpenWrite(path))
- File is created if it does not already exist. If file does exist and it is not read-only, the content is left intact and the file pointer is positioned to the beginning of the file. If fewer bytes are subsequently written than exists in the file, then the file contains a mixture of the old and new content.
- This method is equivalent to the FileStream(String, FileMode, FileAccess, FileShare) constructor overload with file mode set to OpenOrCreate, the access set to Write, and the share mode set to None.
- FileStream has the default 4K buffer size.
- OpenRead - (read only access) opens an existing file for reading.
using (FileStream fs = File.OpenRead(path))
- This method is equivalent to the FileStream(String, FileMode, FileAccess, FileShare) constructor overload with a FileMode value of Open, a FileAccess value of Read and a FileShare value of Read.
- FileStream has the default 4K buffer size.
Additionally the File class has an Open method which allows the specification of FileMode, FileAccess, and FileShare, similar to a FileStream constructor.
- Open - (specify read/write access) opens a FileStream with the specified mode, access, and sharing.
FileStream myFileStream = File.Open(path, FileMode, FileAccess, FileShare);
File and FileInfo Classes
The File and FileInfo classes contain many of the same capabilities. An important difference between the two classes is that all the File class methods are static, while all the methods in the FileInfo class are instance methods. This makes a difference when accessing a file because each time a static File method is used, it performs a security check. When using an instance of FileInfo, the security check is only performed once. So as a general rule:
"Use the File class when performing a single operation on a file. Use the FileInfo class when performing multiple operations on the same file."
The following example program compares the coding of the File class with the FileInfo class for copying a file. If responding to the prompt to overwrite the existing file, then the File.Copy method is used with a Boolean flag set to true to allow the overwrite. If the file does not exist, then and instance of FileInfo is created and its CopyTo method is used to copy the file.
Coping a File - File Class vs FileInfo Class
using System;
using System.IO;
namespace FilevsFileInfo
{
class Program
{
static void Main()
{
String theInput;
string fromPath = @"c:\kevin\From\myfile.txt";
string toPath = @"c:\kevin\To\myfile.txt";
if (File.Exists(toPath))
{
Console.WriteLine("File already exists: {0}", fromPath);
Console.Write("Do you wish to overwrite? (Y/N): ");
theInput = Console.ReadLine();
if (theInput.ToUpper() == "Y")
{
// File Class Copy
File.Copy(fromPath, toPath, true);
}
}
else
{
// FileInfo Class Copy
FileInfo myFileInfo = new FileInfo(fromPath);
myFileInfo.CopyTo(toPath);
}
}
}
}
Below are additional static methods found in the File class and instance methods found in the FileInfo class. For the Getxxxx methods there are corresponding Setxxxx methods. Also for the Readxxxx methods there are corresponding Writexxxx methods.
- File - static methods for working with files.
- Static Methods
- AppendAllLines - appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.
- AppendText - creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist.
- CreateText - creates or opens a file for writing UTF-8 encoded text.
- Decrypt - decrypts a file that was encrypted by the current account using the Encrypt method.
- Encrypt - encrypts a file so that only the account used to encrypt the file can decrypt it.
- Exists - determines whether the specified file exists.
- GetAccessControl - gets a FileSecurity object that encapsulates the access control list (ACL) entries for a specified file.
- GetAttributes - gets the FileAttributes of the file on the path.
-.
- ReadLines - reads the lines of a file.
- Replace - replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file.
The "ReadAll" and "WriteAll" methods will handle the file opens and closes automatically (even if an exception occurs). The following three lines of code copies a file and displays the file contents using just three lines.
string fileContents = File.ReadAllText(@"c:\kevin\To\myFile.txt"); File.WriteAllText(@"c:\kevin\To\myFile.new", fileContents); Console.WriteLine(fileContents);
- FileInfo - instance methods and properties for working with files.
- Properties
- Attributes - gets or sets the attributes for the current file or directory.
- Directory - gets an instance of the parent directory.
- DirectoryName - gets a string representing the directory's full path.
- Exists - gets a value indicating whether a file exists.
- Extension - gets the string representing the extension part of the file.
- FullName - gets the full path of the directory or file.
- IsReadOnly - gets or sets a value that determines if the current file is read only.
- Length - gets the size, in bytes, of the current file.
- Instance Methods
- AppendText - creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
- CopyTo(String, Boolean) - copies an existing file to a new file, allowing the overwriting of an existing file.
- CreateText - creates a StreamWriter that writes a new text file.
- Decrypt - decrypts a file that was encrypted by the current account using the Encrypt method.
- Encrypt - encrypts a file so that only the account used to encrypt the file can decrypt it.
- GetAccessControl() - gets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileInfo object.
- MoveTo - moves a specified file to a new location, providing the option to specify a new file name.
- Refresh - refreshes the state of the object.
- Replace(String, String) - replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file.
Directory and Directory Info Classes
The Directory and DirectoryInfo classes contain many of the same capabilities. An important difference between the two classes is that all the Directory class methods are static, while all the methods in the DirectoryInfo class are instance methods. This makes a difference when accessing a directory because each time a static Directory method is used, it performs a security check. When using an instance of DirectoryInfo, the security check is only performed once. So as a general rule:
In .NET 4.0 the Enumeratexxxx methods where added. Unlike the corresponding Getxxxx methods, the Enumeratexxxx methods are lazily evaluated which make them work well with LINQ. MSDN describes the differences between theEnumeratexxxx methods and the Getxxxx methods:
."
Below are additional static methods found in the Directory class and instance methods found in the DirectoryInfo class. For the Getxxxx methods there are corresponding Setxxxx methods. Also for the Readxxxx methods there are corresponding Writexxxx methods.
- Directory - static methods for working with directories.
- Static Methods
- CreateDirectory(String) - creates all directories and subdirectories in the specified path unless they already exist.
- EnumerateDirectories(String) - returns an enumerable collection of directory names in a specified path.
- EnumerateFiles(String) - returns an enumerable collection of file names in a specified path.
- EnumerateFileSystemEntries(String) - returns an enumerable collection of file names and directory names that match a search pattern in a specified path.
- Exists - determines whether the given path refers to an existing directory on disk.
- GetAccessControl(String) - gets a DirectorySecurity object that encapsulates the specified type of access control list (ACL) entries for a specified directory.
- GetDirectories(String) - returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory.
- GetDirectoryRoot - returns the volume information, root information, or both for the specified path.
- GetFiles(String) - returns the names of files (including their paths) in the specified directory.
- GetFileSystemEntries(String) - returns the names of all files and subdirectories in a specified path.
- GetLogicalDrives - retrieves the names of the logical drives on this computer in the form "
:\".
- Move - moves a file or a directory and its contents to a new location.
- DirectoryInfo - instance methods and properties for working with directories.
- Properties
- Attributes - gets or sets the attributes for the current file or directory.
- Exists - gets a value indicating whether the directory exists.
- Extension - gets the string representing the extension part of the file.
- FullName - gets the full path of the directory or file.
- Name - gets the name of this DirectoryInfo instance.
- Parent - gets the parent directory of a specified subdirectory.
- Root - gets the root portion of the directory.
- Instance Methods
- Create() - creates a directory.
- CreateSubdirectory(String) - creates a subdirectory or subdirectories on the specified path.
- EnumerateDirectories() - returns an enumerable collection of directory information that matches a specified search pattern
- EnumerateFiles() - returns an enumerable collection of file information in the current directory.
- EnumerateFileSystemInfos() - returns an enumerable collection of file information that matches a specified search pattern and search subdirectory option.
- MoveTo - moves a DirectoryInfo instance and its contents to a new path.
- Refresh - refreshes the state of the object.
- SetAccessControl - applies access control list (ACL) entries described by a DirectorySecurity object to the directory described by the current DirectoryInfo object.
The following example code shows how to obtain directory and file information with DirectoryInfo.EnumerateFileSystemInfo. Notice how Environment.SpecialFolder.Desktop is used to set the directory to the "desktop" folder. More information on Special Folders enumeration is given in the following sections.
Obtain Directory and File Information with DirectoryInfo.EnumerateFileSystemInfo
using System;
using System.IO;
namespace EnumerateFileSystemInfoExample
{
class Program
{
static void Main()
{
var entries = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)).EnumerateFileSystemInfos();
foreach (var entry in entries)
{
Console.WriteLine("Name: {0}", entry.FullName);
Console.WriteLine(" Attrib : {0}", entry.Attributes);
Console.WriteLine(" Created : {0}", entry.CreationTime);
Console.WriteLine(" Accessed: {0}\n", entry.LastAccessTime);
}
}
}
}
Path Class
The Path class performs operations on String instances that contain file or directory path information. For example the ChangeExtension method does not change the extension on the file, but changes the extension on a filename inside a string that contains the file path. You could then use the original path name and the newly created path name to rename the file using the File.Move method (see example program below).
Below are some of the static methods found in the Path class
- Path - static methods for working with path strings.
- Static Methods
- ChangeExtension - changes the extension of a path string.
- Combine(String[]) - combines an array of strings into a path.
- GetDirectoryName - returns the directory information for the specified path string.
- GetFileNameWithoutExtension - returns the file name of the specified path string without the extension.
- GetInvalidFileNameChars - gets an array containing the characters that are not allowed in file names.
- GetInvalidPathChars - gets an array containing the characters that are not allowed in path names.
- GetRandomFileName - returns a random folder name or file name.
- HasExtension - determines whether a path includes a file name extension.
- IsPathRooted - gets a value indicating whether the specified path string contains a root.
The following example code shows how use Path.ChangeExtension to change the file extension inside a string which contains the full path name. The modified string is then used by the File.Move method to rename the file.
Change File Extension in Path String
using System;
using System.IO;
namespace PathExample
{
class Program
{
static void Main()
{
string newFileName;
// Get New File Name with Extension Changed
string myFileName = @"C:\kevin\To\myfile.txt";
newFileName = Path.ChangeExtension(myFileName, ".hold");
// Rename the File
try
{
File.Move(myFileName, newFileName);
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
}
}
}
Special Folders Enumeration
The Environment.SpecialFolder Enumeration contains constants used to retrieve directory paths to system special folders. A few of these special folder enumerations are listed below with the entire enumeration and corresponding paths displayed from the program.
- Desktop - the logical Desktop rather than the physical file system location.
- Favorites - the directory that serves as a common repository for the user's favorite items.
- MyComputer - the My Computer folder. The MyComputer constant always yields the empty string ("") because no path is defined for the My Computer folder.
- MyMusic - the My Music folder.
- MyDocuments - the My Documents folder. This member is equivalent to Personal.
The following example code shows how to obtain and use the information inside the Environment.SpecialFolder enumeration. The program lists the corresponding actual paths on my computer for the corresponding SpecialFolder constant.
Special Folder Enumeration and Paths
using System;
using System.Collections.Generic;
namespace SpecialFoldersExample
{
class Program
{
static void Main()
{
// Print out Enumeration Values and Constants and Corresponding Paths
foreach (var specialFolder in Enum.GetValues(typeof(Environment.SpecialFolder)))
Console.WriteLine("{0,2} {1,22} {2}", (int)specialFolder,
((Environment.SpecialFolder)specialFolder),
Environment.GetFolderPath(((Environment.SpecialFolder)specialFolder)));
}
}
}
DriveInfo Class
The DriveInfo class provides information about the accessible computer drives. DriveInfo contains methods and properties used to query for drive information. DriveInfo can be used to determine what drives are available, drive types, capacity and free space.
- DriveInfo - class contains methods and properties used to query for drive information.
- Properties
- AvailableFreeSpace - indicates the amount of available free space on a drive, in bytes
- DriveFormat - gets the name of the file system, such as NTFS or FAT32.
- DriveType - gets the drive type, such as CD-ROM, removable, network, or fixed.
- IsReady - gets a value that indicates whether a drive is ready.
- Name - gets the name of a drive, such as C:\.
- RootDirectory - gets the root directory of a drive.
- TotalFreeSpace - gets the total amount of free space available on a drive, in bytes.
- TotalSize - gets the total size of storage space on a drive, in bytes.
- VolumeLabel - gets or sets the volume label of a drive.
- Static Methods
- GetDrives - retrieves the drive names of all logical drives on a computer.
The following program show how to use the DriveInfo class to scan all the drives on a computer and report the drive information. If no media is in the removable drives, then only the drive name and type will be reported.
DriveInfo Class Reporting Drive Information
using System;
using System.IO;
class DriveInfoExample
{
public static void Main()
{
DriveInfo[] computerDrives = DriveInfo.GetDrives();
Console.WriteLine("Computer : {0}", System.Environment.MachineName);
Console.WriteLine("Run Date : {0}", DateTime.Now);
Console.WriteLine("----------------------------------\n");
foreach (DriveInfo drive in computerDrives)
{
Console.WriteLine("Drive {0} :", drive.Name);
Console.WriteLine(" File type: {0}", drive.DriveType);
if (drive.IsReady == true)
{
Console.WriteLine(" Volume label : {0}", drive.VolumeLabel);
Console.WriteLine(" File system : {0}", drive.DriveFormat);
Console.WriteLine(" Total Size : {0,15:N0} bytes ", drive.TotalSize);
Console.WriteLine(" Free Space : {0,15:N0} bytes", drive.AvailableFreeSpace);
Console.WriteLine(" Total Free Space: {0,15:N0} bytes", drive.TotalFreeSpace);
}
Console.WriteLine();
}
}
}
Top
Memory Stream
The entire backing store (an array) for a MemoryStream must reside entirely in memory. This can be useful when you need random access to a non-seekable stream. While a FileStream allows random access, it is slow as it is optimized for sequential access. MemoryStream, or introduced in .NET 4.0 Memory-Mapped files can be used to optimize random access.
A memory stream is easy to convert to a byte array by using the ToArray() method. Memory streams may also be useful when compressing or encrypting data. The .NET framework also contains an UnmanagedMemoryStream which provides access to unmanaged blocks of memory from managed code.
The following example program uses a memory stream to displays the middle twenty characters from a file. I first reads the bytes from a file into an array. It then writes the byte array to a memory stream. The middle twenty bytes from the memory stream is written to a second byte array, which is encoded and displayed as text. The entire array of bytes from the file is also displayed for comparison.
Memory Stream Used to Extract Bytes from File
using System;
using System.IO;
using System.Linq;
namespace MemoryStreamExample
{
class Program
{
static void Main()
{
const int NUM_BYTES_TO_WRITE = 20;
byte[] byteArray; // Bytes from File
byte[] middleBytes = Enumerable.Repeat((byte)0x20, NUM_BYTES_TO_WRITE).ToArray();
using (MemoryStream memoryStream = new MemoryStream())
{
try
{
Console.WriteLine("--------------------------------------");
Console.WriteLine("Display Middle Twenty Bytes from File.");
Console.WriteLine("--------------------------------------\n");
// Read Bytes from File into Byte Array
byteArray = File.ReadAllBytes(@"C:\kevin\From\myFile.txt");
// Write Bytes from File to Memory Stream
memoryStream.Write(byteArray, 0, byteArray.Length);
// Determine Point to Start Getting Bytes
long startPoint = memoryStream.Length / 2 - (NUM_BYTES_TO_WRITE / 2);
// Move to Point to Start Getting Bytes
memoryStream.Seek(startPoint, SeekOrigin.Begin);
// Read Bytes from Memory Stream to Byte Array
memoryStream.Read(middleBytes, 0, NUM_BYTES_TO_WRITE);
// Display Middle Bytes from Byte Array
Console.WriteLine("--------------------------------------");
Console.WriteLine("----------- Middle Bytes -------------");
Console.WriteLine("--------------------------------------");
Console.WriteLine(System.Text.Encoding.Default.GetString(middleBytes));
Console.WriteLine("\n");
// Display Entire Byte Array Read from File
Console.WriteLine("--------------------------------------");
Console.WriteLine("----------- Entire File --------------");
Console.WriteLine("--------------------------------------");
Console.WriteLine(System.Text.Encoding.Default.GetString(byteArray));
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
}
}
}
}
Top
Memory-Mapped Files
Memory-Mapped Files where introduced in .NET 4.0. A memory-mapped files use managed coded and contain the contents of files in virtual memory. Memory-mapped files are classified into two categories:
- Persisted - are memory-mapped files that are associated with a source file on a disk. When the last process has finished working with the file, the data is saved to the source file on the disk. These memory-mapped files are suitable for working with extremely large source files.
- Non-Persisited -).
Using Memory-Mapped Files for Random File Access
One reason to use memory-mapped files is for efficient random access of files. Memory-mapped files are several times faster than FileStreams for random access (However FileStreams are several times faster than memory-mapped files for sequential access). MemoryMappedViewAccessors are used with memory-mapped files to provide a randomly accessed view. Memory mapped view accessors provide methods for randomly reading and writing value types (primitives, structures, etc.), but does not support reference types (strings, classes, etc.). The public static members of MemoryMappedViewAccessors are thread safe, while any instance methods are not guaranteed to be thread safe.
Using Memory-Mapped Files to Share Memory Between Processes
Memory-Mapped files can be shared across multiple processes which are running on the same computer. The memory-mapped file is given a name by the process which creates it (using theMemoryMappedFile.CreateNew method) , then other processes can access it by name. The following programs show how a memory-mapped file can be shared between two different processes. The memory-mapped file is defined as 100 bytes in size with a name of "SharedMMF".
Memory-Mapped File Shared Between Processes
Process 1 - Create Shared Memory-Mapped File
using System;
using System.IO.MemoryMappedFiles;
namespace MemoryMappedFileIPC
{
class Program
{
static void Main()
{
Console.WriteLine("Process 1");
Console.WriteLine("----------\n");
// Create and Populate Shared MemoryMapped File
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("SharedMMF", 100))
using (MemoryMappedViewAccessor mmva = mmf.CreateViewAccessor())
{
mmva.Write(0, 747);
Console.WriteLine("SharedMMF is alive");
Console.ReadLine(); // Keep Shared Memory Alive
}
}
}
}
Process 2 - Read Shared Memory-Mapped File
using System;
using System.IO.MemoryMappedFiles;
namespace MemoryMappedFileIPC
{
class Program
{
static void Main()
{
Console.WriteLine("Process 2");
Console.WriteLine("----------\n");
// Read Data from Shared MemoryMapped File
using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("SharedMMF"))
using (MemoryMappedViewAccessor mmva = mmf.CreateViewAccessor())
{
Console.WriteLine("Read from SharedMMF: {0}\n",mmva.ReadInt32(0));
}
}
}
}
Top
Pipe Stream
"The PipeStream class was introduced in .NET 3.5 and provides the base class for support of Anonymous and Named pipes (Windows protocol)."
Pipes are a simple and efficient mechanism for allowing processes to communicate. Processes could open a TCP port to pass data, but this adds a lot of overhead from the network stack. Using pipes, the data is passed straight through the kernel between processes and avoids the network stack overhead. Pipes allow one process to write data to a pipe, then the other process(es) wait for the data and read it from the pipe. The concept of pipes is attributed to Douglas McIlroy. Ken Thompson added pipes to Unix in 1973. Pipes were adopted by other operating systems and became known as the Pipes and Filters design pattern. Pipe protocols and usage vary among operating systems.
Pipes provide one of the simplest means for Interprocess Communication (IPC). Other types of IPC include:
- Signals - software-generated interrupts sent to a process when an event occurs.
- Messaging - processes to exchange data by using a message queue.
- Semaphores - synchronizes processes competing for the same resource.
- Shared Memory - memory segments are shared among processes.
- Sockets - end-points for communication between processes.
The PipeStream class was introduced in .NET 3.5 and provides the base class for support of Anonymous and Named pipes (Windows protocol). The types for providing the support for pipes are located in the System.IO.Pipes Namespace. Two good references for the .NET usage of pipes are Pipes from Windows Dev Center and Pipe Operations in the .NET Framework from Microsoft Developer Network.
Anonymous Pipes vs Named Pipes
Anonymous pipes require less overhead than named pipes, but have limited functionality. Differences between anonymous and named pipes include:
- Anonymous Pipes - .a.k.a "Unnamed Pipes" in Unix terminology.
- Anonymous pipes are one-way pipes that typically transfer data between parent and child processes.
- Anonymous pipes are always local; they cannot be used over a network.
- Anonymous pipes do not support Message read modes.
- Named Pipes
- Named pipes provide communication between a pipe server process and one or more pipe client processes.
- Named pipes can be used for IPC communication locally or over a network.
- Named pipes support either one-way or two-way (full duplex) communications.
- Named pipes support message-based communication and allow multiple clients to connect simultaneously to the server process.
- Named pipes support impersonation, which enables connecting processes to use their own permissions on remote servers.
Anonymous Pipes
Anonymous pipes are implemented with the AnonymousPipeServerStream and AnonymousPipeClientStream classes. The client side of an anonymous pipe must be created from a pipe handle provided by the server side by calling the GetClientHandleAsString method. The string is then passed as a parameter when creating the client process. From the client process, it is passed to the AnonymousPipeClientStream constructor as the pipeHandleAsString> parameter.
Anonymous Pipe Classes:
- AnonymousPipeServerStream
- Exposes a stream around an anonymous pipe, which supports both synchronous and asynchronous read and write operations.
- The AnonymousPipeServerStream object must dispose the client handle using the DisposeLocalCopyOfClientHandle method in order to be notified when the client exits.
- AnonymousPipeClientStream
- Exposes the client side of an anonymous pipe stream, which supports both synchronous and asynchronous read and write operations.
- The client side of an anonymous pipe must be created from a pipe handle provided by the server side by calling the GetClientHandleAsString method.
Named Pipes
Named pipes are implemented with the NamedPipeServerStream and NamedPipeClientStream classes. Named pipes can be used for interprocess communication locally or over a network. A single pipe name can be shared by multiple NamedPipeClientStream objects. When the client and server processes are run on the same computer, the server name provided to the NamedPipeClientStream object can be ".". However if the client and server processes are on separate computers, the server name provided to the NamedPipeClientStream object would be the network name of the computer that runs the server process. Any process can act as either a named pipe server or client, or both.
Named Pipe Classes:
- NamedPipeServerStream
- Exposes a Stream around a named pipe server, supporting both synchronous and asynchronous read and write operations
- A single pipe name can be shared by multiple NamedPipeClientStream objects.
- NamedPipeClientStream
- Exposes a Stream around a named pipe client, which supports both synchronous and asynchronous read and write operations.
The following program uses named pipes to accept a value from the keyboard (by client) and write it to the pipe. The server reads the value from the pipe, adds angle brackets around it, then writes it back to the pipe. The client then reads the modified version of the value from the pipe. Both the client and the server continue to run until a null value is entered from the keyboard.
Named Pipes Example
using System;
using System.IO;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace NamedPipesExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("------------- Named Pipes Example -------------");
Console.WriteLine("-----------------------------------------------");
Console.WriteLine(" 1. CW - Client Writes keyboard entry to pipe ");
Console.WriteLine(" 2. SR - Server Reads from pipe ");
Console.WriteLine(" 3. Server adds brackets to value ");
Console.WriteLine(" 4. SW - Server Writes to pipe ");
Console.WriteLine(" 5. CR - Client Reads from pipe ");
Console.WriteLine("-----------------------------------------------\n");
StartServer();
// Client Stream
var client = new NamedPipeClientStream("PipeDreams");
client.Connect();
StreamReader reader = new StreamReader(client);
StreamWriter writer = new StreamWriter(client);
while (true)
{
string input = Console.ReadLine();
if (String.IsNullOrEmpty(input)) break;
// Write to Pipe
writer.WriteLine("CW: {0}", input);
writer.Flush();
// Read from Pipe
Console.WriteLine("CR: {0}\n", reader.ReadLine());
}
}
static void StartServer()
{
string line = null;
Task.Factory.StartNew(() =>
{
var server = new NamedPipeServerStream("PipeDreams");
server.WaitForConnection();
StreamReader reader = new StreamReader(server);
StreamWriter writer = new StreamWriter(server);
while (true)
{
// Read from Pipe
line = "SR: " + reader.ReadLine();";
// Write to Pipe
writer.WriteLine("SW: {0}", line);
writer.Flush();
}
});
}
}
}
Top
Buffered Stream
A BufferedStream is a buffer over an existing stream. Buffers can improve performance by reducing the number of I/O operations on expensive resources. A buffer is a block of bytes in memory used to cache data. BufferStreams are decorator streams which add functionality to an existing stream. This is not to be confused with a MemoryStream which is a backing store stream (the source of the entire stream data).
The BufferedStream class must be configured to either read or write, but the BufferedStream cannot be configured to perform both the tasks at the same time. If you always read and write for sizes greater than the internal buffer size, then BufferedStream might not even allocate the internal buffer. BufferedStream also buffers reads and writes in a shared buffer. Closing a BufferStream automatically closes the underlying backing store stream.
Note: Microsoft improved the performance of all streams in the .NET Framework by including a built-in buffer (around 2006). Applying a BufferedStream to an existing .NET Framework stream results in a double buffer. The BufferedStream is most commonly used in custom stream classes that do not include a built-in buffer.
Top
Text Adapters
"StreamReader/StreamWriter uses a byte stream for its backing data store and must translate bytes to characters. StringReader/StringWriter uses a string or StringBuilder for its backing data store so no character translation is needed. Both of these stream and string adapters can only read/write character based data."
Text adapters read/write only character-based data (i.e. string and char only, no other data types). The TextReader and TextWriter classes are the abstract base classes for text adapters. The Text base classes are used to derive concrete classes which are used as stream and string adapters:
- StreamReader and StreamWriter
- Uses a byte stream for its backing data store.
- Requires translation from bytes to characters.
- Will throw an exception if it encounters bytes which do not have a valid string translation.
- StringReader and StringWriter
- Uses a string or StringBuilder for its backing data store.
- Requires no byte/character translation.
StreamReader/StreamWriter Classes
The StreamReader/StreamWriter classes were designed for reading/writing character data such as a standard text file. They default to UTF-8 encoding which correctly handles Unicode characters. To be thread safe, the TextReader.Synchronized must be used. The Close() and Dipose() methods are synonymous for adapters, just as they are for streams. When you close an adapter, you also close the underlying stream.
- StreamReader - implements a TextReader that reads characters from a byte stream in a particular encoding .
- Properties
- BaseStream - returns the underlying stream.
- CurrentEncoding - gets the current character encoding that the current StreamReader object is using.
- EndOfStream - gets a value that indicates whether the current stream position is at the end of the stream.
- Methods
- DiscardBufferedData - Clears the internal buffer.
- Finalize - allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
- Peek - returns the next available character but does not consume it.
- Read() - reads the next character from the input stream and advances the character position by one character.
- ReadAsync - reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index.
- ReadBlock - reads a specified maximum number of characters from the current stream and writes the data to a buffer, beginning at the specified index.
- ReadLine - reads a line of characters from the current stream and returns the data as a string.
- ReadToEnd - reads all characters from the current position to the end of the stream.
- StreamWriter - implements a TextWriter for writing characters to a stream in a particular encoding .
- Properties
- AutoFlush - gets or sets a value indicating whether the StreamWriter will flush its buffer to the underlying stream after every call to StreamWriter.Write.
- BaseStream - gets the underlying stream that interfaces with a backing store.
- Encoding - gets the Encoding in which the output is written.
- FormatProvider - gets an object that controls formatting.
- NewLine - gets or sets the line terminator string used by the current TextWriter.
- Methods
- Finalize - allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
- Flush - clears all buffers for the current writer and causes any buffered data to be written to the underlying stream. .
- MemberwiseClone - creates a shallow copy of the current Object.
- Write(type) - writes the text representation of the type.
- WriteLine - writes a line terminator to the text string or stream.
- WriteAsync(type) - writes the text representation of the type to the stream asynchronously.
Translation for StreamReader/StreamWriter
A stream is an abstraction for a sequence of bytes. To use the bytes they usually need to be translated to a particular type of encoding, such as Unicode, ASCII, or UTF-8. The Encoding and Decoding classes are used to the translation between raw bytes and encoded values, or between different encoded values (e.g. ASCII to Unicode). For more information about character encoding, see the MSDN article Character Encoding in the .NET Framework.
StringReader/StringWriter Classes
The StringReader/StringWriter classes were designed for reading/writing string data which is already in character format. So no byte/character translation is needed. These classes are used when dealing with several string manipulations
- StringReader - implements a TextReader that reads from a string or StringBuilder.
- Methods
- Finalize - allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
- MemberwiseClone() - creates a shallow copy of the current MarshalByRefObject object.
- Peek - returns the next available character but does not consume it.
- Read - reads the next character from the input string and advances the character position by one character.
- ReadAsync - reads a specified maximum number of characters from the current string asynchronously and writes the data to a buffer, beginning at the specified index.
- ReadBlock - reads a specified maximum number of characters from the current text reader and writes the data to a buffer, beginning at the specified index.
- ReadToEnd - reads all characters from the current position to the end of the string and returns them as a single string.
- StringWriter - implements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder. .
- Methods
- Finalize - allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
- Flush - clears all buffers for the current writer and causes any buffered data to be written to the underlying device.
- Write(type) - write the data as the specified type to the string (or stream).
- WriteLine - writes a line terminator to the text string (or stream).
- ReadBlock - reads a specified maximum number of characters from the current text reader and writes the data to a buffer, beginning at the specified index.
- ReadToEnd - reads all characters from the current position to the end of the string and returns them as a single string.
StreamReader/StreamWriter Read and Writing of Text Files
The following program uses a StreamReader to read all the text files in the user's My Documents folder. It then uses a StreamWriter to write all the contents of all the individual text files into one large text file called "AllTxtFiles.txt".
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StringBuilder sb = new StringBuilder();
foreach (string txtName in Directory.EnumerateFiles(mydocpath, "*.txt"))
{
using (StreamReader sr = new StreamReader(txtName))
{
sb.AppendLine("----------------------------------------------");
sb.AppendLine(txtName.ToString()); // File Name
sb.AppendLine("----------------------------------------------");
sb.Append(sr.ReadToEnd()); // File Contents
sb.AppendLine();
sb.AppendLine();
}
}
using (StreamWriter outfile = new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
{
outfile.Write(sb.ToString());
}
}
}
Top
Binary Adapters
"Binary adapters can process all the primitive data types, where the Text adapters are restricting to processing only character data."
Binary adapters read/write all the primitive data types (e.g. char, int, float, byte, bool, etc.) plus strings and arrays of primitive data types. The BinaryReader and BinaryWriter classes contains several methods for reading and writing which specify the type of data, such as ReadInt32, ReadInt64, ReadDouble, ReadBoolean, ReadByte, etc.
The underlying data stream is specified when you create an instance of the BinaryReader. You can also optionally specify the type of encoding and whether to leave the stream open after disposing the BinaryReader object. If you do not specify an encoding type, UTF-8 is used.
The following example uses a BinaryWriter to create and write binary data to a file. It then uses the BinaryReader to open the file and display the binary data.
BinaryReader/Writer to Create and Read Binary File
using System;
using System.IO;
namespace BinaryFileExample
{
class Program
{
static void Main()
{
Console.WriteLine("-------------------------------------------");
Console.WriteLine("-------- Write Binary Data to File --------");
Console.WriteLine("-------------------------------------------");
// Data to Write to File
int i = 32;
double d = 3.14157;
bool b = true;
char c = 'A';
string s = "Is it Spring Yet!";
// Create and Write Values to Binary File
using (BinaryWriter writer = new BinaryWriter(new FileStream(@"c:\kevin\From\bindata", FileMode.Create)))
{
writer.Write(i);
writer.Write(d);
writer.Write(b);
writer.Write(c);
writer.Write(s);
}
// Open Binary File for Reading
using (BinaryReader reader = new BinaryReader(new FileStream(@"c:\kevin\From\bindata", FileMode.Open)))
{
i = reader.ReadInt32();
Console.WriteLine("Integer data: {0}", i);
d = reader.ReadDouble();
Console.WriteLine("Double data: {0}", d);
b = reader.ReadBoolean();
Console.WriteLine("Boolean data: {0}", b);
c = reader.ReadChar();
Console.WriteLine("Character data: {0}\n", c);
s = reader.ReadString();
Console.WriteLine("String data: {0}\n", s);
}
}
}
}
Top
FileSystemWatcher Class
The FileSystemWatcher watches for specific changes in a file system and allows actions to be performed when a change is detected. FileSystemWatcher can be used to watch for changes in files and subdirectories of the specified directory. It can be used to watch files on a local computer, a network drive, or a remote computer.
There are several types of changes you can watch for in a directory or file, such as changes in: attributes, file time stamps, file and directory sizes, renaming, deletion, or creation of files or directories. To watch for changes in all files, set the Filter property to an empty string ("") or use wildcards ("*.*"). To watch a specific file, set the Filter property to the file name. For example, to watch for changes in text files, set the Filter property to "*.txt"..
FileSystemWatcher notifies a process about changes to the file system by raising events. Several factors can affect which events are raised. Some common file system operations may raise more than one event as some complex operations consist of multiple simple operations. The following events can be raised:
- Changed - occurs when a file or directory in the specified Path is changed.
- Created - occurs when a file or directory in the specified Path is created.
- Deleted - occurs when a file or directory in the specified Path is deleted.
- Disposed - occurs when the component is disposed by a call to the Dispose method.
- Error - occurs when the instance of FileSystemWatcher is unable to continue monitoring changes or when the internal buffer overflows.
- Renamed - occurs when a file or directory in the specified Path is renamed.
Top. For additional details on Isolated Storage see my Silverlight page Local File Access.
Top
Reference Articles
- Stream Class - Microsoft Developer Network.
- File Class - Microsoft Developer Network.
- Asynchronous File I/O - Microsoft Developer Network.
- File and Stream I/O - Microsoft Developer Network.
- Encoding Class - Microsoft Developer Network.
- Common I/O Tasks - Microsoft Developer Network.
- Memory-Mapped Files - Microsoft Developer Network.
- Isolated Storage - Microsoft Developer Network.
- Pipe Operations in the .NET Framework - Microsoft Developer Network.
- FileSystemWatcher Class - Microsoft Developer Network.
- How to: Use Named Pipes for Network Interprocess Communication - Microsoft Developer Network.
- How to: Use Anonymous Pipes for Local Interprocess Communication - Microsoft Developer Network.
- Character Encoding in the .NET Framework - Microsoft Developer Network.
- File System and the Registry (C# Programming Guide) - Microsoft Developer Network.
- Isolated Storage - Microsoft Developer Network.
- Choosing Communication Options in .NET - Visual Studio.
- How to do basic file I/O in Visual C# - Microsoft Support.
- The Adapter Pattern in the .NET Framework - Visual Studio Magazine. | http://www.kcshadow.net/wpdeveloper/?q=iooperations | CC-MAIN-2018-22 | refinedweb | 8,736 | 50.33 |
mlock()
Lock a range of process address space in physical memory
Synopsis:
#include <sys/mman.h> int mlock(const void * addr, size_t len);
Since:
BlackBerry 10.0.0
Arguments:
- addr
- The starting address for the range of process address space.
- len
- The amount of the memory to lock, in bytes. There's no limit on the amount of memory that a process may lock, other than the amount of physical memory in the system..
In order to lock memory, your process must have the PROCMGR_AID_MEM_LOCK ability enabled. For more information, see procmgr_ability().
The successful call to mlock() function ensures that the pages are memory-resident (i.e. the addresses always reside in physical memory). For more information, see " Locking memory " in the Process Manager chapter of the System Architecture required permission; see procmgr_ability().
Classification:
Last modified: 2014-11-17
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/m/mlock.html | CC-MAIN-2017-17 | refinedweb | 155 | 51.75 |
Log loss metric explained
1/Nov 20181/Nov 2018
LogLoss is a classification metric based on probabilities. It measures the performance of a classification model where the prediction input is a probability value between 0 and 1. For any given problem, a smaller LogLoss value means better predictions.
Formula
In order to calculate LogLoss the classifier must assign a probability to each class rather than simply yielding the most likely class (class with the largest probability). LogLoss formula is as follows:
Let’s find out what every symbol in this formula means.
- N - is a number of samples (or instances)
- M - is a number of possible labels
- y_ij - takes value 1 if label j is the correct classification for instance i, and 0 otherwise
- p_ij - is the model probability of assigning label j to instance i
Example calculation
Let’s calculate LogLoss in 2 ways:
Data
Let’s assume that we predict car maker. We have only three possible labels:
audi,
bmw,
tesla. And we have 8 rows of data with known labels:
data = ['audi', 'tesla', 'tesla', 'bmw', 'audi', 'bmw', 'audi', 'tesla']
And we have a classifier that for given data gives following probabilities:] ]
Please notice that lengh of
probs array is equal to length of
data array, and each array in
probs array has size 3 (that is equal to the number of all possible labels). Internal arrays in
probs array are probabilities of labels: 1st item is for
audi, 2nd item is for
bmw, 3rd item is for
tesla.
E.g. consider first array:
[0.6, 0.3, 0.1]. Here
0.6 is probability of
audi,
0.3 - for
bmw and
0.1 for
tesla. Also notice, that labels are sorted alphabetically, and so are probabilities for them (I will rely on this fact when implementing our own function that calculates LogLoss).
Now let’s calculate LogLoss for this classifier.
LogLoss in sklearn
Here is how to use sklearn.metrics.log_loss for this:
from sklearn.metrics import log_loss data = ['audi', 'tesla', 'tesla', 'bmw', 'audi', 'bmw', 'audi', 'tesla']] ] ll = log_loss(data, probs) print(ll)
The result is
5.53374909081.
Handy LogLoss calculation
Now let’s calculate LogLoss with pure Python, not using any fancy library. Here is calculation for each data instance, summing all it up finally:
from math import log ll = [None]*8 EPS = 1e-15 ll[0] = 1*log(0.6)+0*log(0.3)+0*log(0.1) ll[1] = 0*log(0.45)+0*log(0.45)+1*log(0.1) ll[2] = 0*log(0.5)+0*log(EPS)+1*log(0.5) ll[3] = 0*log(1.0)+1*log(EPS)+0*log(EPS) ll[4] = 1*log(0.2)+0*log(0.6)+0*log(0.2) ll[5] = 0*log(0.1)+1*log(0.1)+0*log(0.8) ll[6] = 1*log(0.33)+0*log(0.33)+0*log(0.34) ll[7] = 0*log(0.3)+0*log(0.4)+1*log(0.3) logloss = -(1/8)*sum(ll) print(logloss)
The result will we the same as with
sklearn:
5.53374909081.
Let’s consider this calculation. You see that instead of zero I am using here a small value:
EPS, equal to
1e-15. This is because logarythm of
0.0 is minus infinity. To workaround this I am using reasonably small value:
1e-15.
Now let’s write our own function to calculate LogLoss. Let’s split it to 2 fundtions:
- one is validating input data:
logloss_validate
- another one is doing actual calculations, only if validation was successful:
logloss
def logloss_validate(a_true, a_probs, eps): # 1. Validate input variables if len(a_true) != len(a_probs): raise ValueError('Length of a_true does not match length of a_probs') unique_labels = set(a_true) # 2. Validate number of unique labels if len(unique_labels) < 2: raise ValueError('Should have at least 2 unique labels') # 3. Validate eps value if eps <= 0.0: raise ValueError('Eps should be very small (near zero) positive value') # 4. Validate probabilities for item in a_probs: # 4.1. Check that item in a_probs is iterable try: itemiter = iter(item) except TypeError as te: raise ValueError('Item in a_probs should be an iterable') # 4.2. Check that length of item in a_probs is equal to the number of unique labels if len(item) != len(unique_labels): raise ValueError('Size of item in a_probs does not match number of unique labels') for i in item: if i < 0.0: raise ValueError('Some items of a_probs have negative values') def logloss(a_true, a_probs, eps=1e-15): logloss_validate(a_true, a_probs, eps) from math import log result = 0.0 # uniqalize labels and sort them alphabetically unique_sorted_labels = sorted(set(a_true)) label_map = {} label_idx = 0 # put index of each unique sorted label into a map # I will use this map to get this label probability by label value itself for label in unique_sorted_labels: label_map[label] = label_idx label_idx = label_idx + 1 for true_label, probs in zip(a_true, a_probs): true_label_idx = label_map[true_label] # Here I rely on the fact that label probabilities are sorted alphabetically prob = probs[true_label_idx] if (prob < eps): prob = eps result = result + log(prob) return -1/len(a_true)*result;
Then, if we call
logloss(data, probs) we will get the same result for LogLoss metric:
5.53374909081.
Links
- Datawookie - Making Sense of Logarithmic Loss
- Kaggle - What is Log Loss
- Mark Needham - scikit-learn: First steps with log_loss
- FastAI Wiki - Log Loss
- Online LaTeX Equation Editor - create, integrate and download - I used it for creation of LogLoss formula image | http://iryndin.net/post/log-loss/ | CC-MAIN-2019-30 | refinedweb | 910 | 55.34 |
Mirroring with Matching or Different Axes
Hi,
I want to get the same results mirroring two objects with either matching or different axes. For my examples, I have two objects, L_Cone & R_Cone, on opposite sizes of the ZY plane. Both of their local transformations are being reset by a parent Null (positions & rotations are 0, scale is 1)
In the first example, I have two objects whose axes are oriented differently (e.g. +X & -X on Z). I'm going to manipulate the transformations of R_Cone. I want to transfer this rotation to L_Cone so that it's mirrored on the ZY plane.
How can I code this transfer so that it gets the same result, regardless of the axis offset? In the first example with the different orientations, the position values are negated and the scale/rotation values are the same so it'd be as simple as:
lCone[c4d.ID_BASEOBJECT_ABS_POSITION] = -rCone[c4d.ID_BASEOBJECT_ABS_POSITION] lCone[c4d.ID_BASEOBJECT_ABS_SCALE] = rCone[c4d.ID_BASEOBJECT_ABS_SCALE] lcone[c4d.ID_BASEOBJECT_ABS_ROTATION] = rCone[c4d.ID_BASEOBJECT_ABS_ROTATION]
In the second example, however, that code wouldn't work because pos.X, rot.H, & rot.B are negated.
I thought I could get the difference between the Cones' Parents' Matrices and add that to the new values but it didn't work.
lMat = coneL.GetUpMg() # L_Cone's Parent Matrix rMat = coneR.GetUpMg() # R_Cone's Parent Matrix offsetMat = lMat-rMat # the offset between the two parents coneL.SetMg(coneR.GetMg()+offsetMat) # the offset Matrix added to the R_Cone's Matrix
Could anyone please shed light on why this isn't working or how to do this another way?
Thank you!
Hi,
if I understand you correctly, you simply want to reflect a frame (i.e. a
c4d.Matrix) on an arbitrary plane of reflection. To do that you could:
- Interpret the frame to reflect as four points in the global frame. One point for the offset and three points for each axis, where each point is simply the respective frame axis vector plus the offset vector of the frame.
- Transform these points into a frame of the of the reflection plane.
- Invert the axis you want to invert on all four points expressed in the frame of the reflection plane.
- Transform the points back into the global frame.
- Construct your final reflected frame from these points (you have to go in reverse of what you did in the first step).
The problem with that approach is that Cinema has a fixed frame orientation (matrices are always left-handed in Cinema) and the operation described above will invert the frame orientation of the input frame (i.e. in the case of Cinema produce a right-handed matrix). When constructing a
c4d.Matrixin Cinema with axis components that form a right-handed frame, Cinema will silently rectify these inputs into a left-handed frame, changing the orientation of the frame on at least one axis. In some cases you might not mind, for example in the case of the y-axis in your picture, but in other cases this will result in an incorrect result, when the decision is left to Cinema.
The bigger insight here is that there is no solution for the reflection of a frame while preserving its frame orientation and scale. What you could do, is analyse your input matrix to find the axis that is "most parallel" to the plane of reflection to take control over which axis has to be inverted. This "most parallel" axis would be more likely less important and could therefor be inverted. You could also work with a negative scalings instead. But this is a hack in the broader sense of the term, because there is no guarantee that this assumption holds true.
The only way to faithfully reflect a point object, is to reflect each point individually.
Cheers,
zipit
Hi @zipit ,
Thank you very much for the reply. My apologies, but I could use some help with where to start on your advice. In the first approach you mentioned (the enumerated one), which picture did you mean when you said 'in the case of the y-axis in your picture'? You said the first approach is unreliable because of Cinema 4D's left-handed matrices. If this approach wouldn't work for both scenarios and will product incorrect results in some cases, I do not wish to pursue it.
For the second approach, you mentioned determining a most-parallel plane of reflection by the input matrix. Which matrix did you mean by the input matrix: the target's matrix (R_Cone in my example)? How would I go about analyzing the input matrix?
Finally, you mentioned the only faithful way to reflect a point object is to reflect each point individually. If that's the case, I'd be most interested in pursuing this approach. How would I go about this with the scenarios above (with R_Cone for L_Cone)? Not all of my objects will be point objects and, even if the points are flipped correctly, returning the offset to the axes would be necessary as well.
For a little more clarity, which of these approaches would you choose for this task?
Thanks!
Hi,
sorry, I was probably a bit too abstract.
- I was only describing one method (two if you count my last sentence as a "method"). What you refer to as method two, is just a way to deal with problems that come with general approach. While you can certainly construct the reflected frame in different ways, the general logic to achieve that construction is always the same.
- I might be wrong, but I think I haven't gotten my main point across (third paragraph about the general insight). The concept of left and right handed matrices is closely related to right-hand-rule of the cross product. Take your left or right hand and hold it in front of your body, with the thumb pointing up, the index finger pointing forward and your ring finger pointing along the plane parallel to your chest, forming a little axis gizmo. Now imagine a plane going through your nose, dividing your body into a left and right part and reflect that frame you are holding with the same hand along that plane. You will probably realise that this is impossible without breaking a few bones in your hand and that the only way to do this is using your other hand. This is what left and right handed matrices describe and the fundamental problem here.
- Since we cannot just use "the other hand" in Cinema, we will invert one axis in the frame result of our general approach in order to make the frame conform with the rules that Cinema does enforce on its frames (being left-handed). What you refer to as the second approach, was just a very broad assumption on how to find the axis that is probably the least "wrong looking" if being inverted. If you want to do something like this, you also have normally additional information on what you want to preserve and what not. If you are mirroring bones for example, you certainly do not want to flip the bone along its length so that you only have to choose in a more or less smart way from the remaining two axis.
- I was referring to the y-axis of the frame of your cone. Your pictures are a bit unfortunate, because the orientation of the frame in relation to your vertices changes (before the reflection the z-axis is pointing along the height of the cone and after the mirroring it is pointing along the direction which previously was the x-axis). But nevertheless the y-axis is pointing upwards in the "before" and downwards in the "after", but for a human this is all the same, since a cone is symmetrical to the plane the y-axis is a normal of.
- The analysing is not set in stone, you would have to define what you want to do. I was implying to evaluate the angle between each axis and a normal of the reflection plane to determine which axis would be the least painful to invert. But again, this is neither set in stone nor really helpful.
- Mirroring the vertices would be pretty much the same. Create a frame for your reflection plane, transform your vertices into that frame, reflect the vertices and transform back.
- I cannot really choose a way, since I do not know what you need. If you do not care about the frame of the reflected object, I probably would go for reflecting the vertices (you could also use
SendModellingCommandfor that). If you do care about the frames, this would be pure speculation on my side. You would have to explain what you want to do practically.
Cheers,
zipit
Hi @zipit ,
I'm sure it's more of a case that I don't know my linear algebra well enough
I've taken some online courses in it this weekend to get a better understanding of the dot & cross product. I do understand the difference between left & right-handed matrices after reading your description and looking more into them, thank you.
You were right about the result of my second example image being off: there was an error in my the animation I created. L_Cone was using the axis of the first example. I have fixed it and replaced it in the original post. Sorry about that and very perceptive of you to notice! I appreciate your attention to my issue.
Regarding your last message's #7, I do care about the axes because I am using this with animation controllers that drive joints.
I came up with some code based on what I think you're describing with 'evaluate the angle between each axis and a normal of the reflection plane'. Am I right in using the objects' position in relation to the mirror plane's normal value? I got the same result for both axis orientation scenarios, so I'm not sure this is correct. Perhaps I should be evaluating their Matrices' v1, v2, & v3 vectors this way as well?
import c4d, math from c4d import utils mirrorPlane = c4d.Vector(1,0,0) #ZY's normal rObj = doc.SearchObject("R_Cone").GetMg().off lObj = doc.SearchObject("L_Cone").GetMg().off mirNormMag = mirrorPlane.GetLength() #magnitude of the mirror plane's vector rDotProd = mirrorPlane.Dot(rObj) #dot product of the mirror plane & right object rMag = rObj.GetLength() #magnitude of the right object's position vector rTheta = math.acos( rDotProd / (mirNormMag * rMag) ) #angle between two the two vectors lDotProd = mirrorPlane.Dot(lObj) #dot product of the mirror plane & left object lMag = lObj.GetLength() #magnitude of the left object's position vector lTheta = math.acos( lDotProd / (mirNormMag * lMag) ) #angle between two the two vectors # This is the result for both examples. print "rTheta, rad: %s, deg: %s"%(rTheta,utils.RadToDeg(rTheta)) # rTheta, rad: 3.14159265359, deg: 180.0 print "lTheta, rad: %s, deg: %s"%(lTheta,utils.RadToDeg(lTheta)) # lTheta, rad: 0.0, deg: 0.0
Hi,
I probably should have not mentioned that stuff, because it obviously side tracked you, what was not my intention. I suppose you wrote this code just for fun, which is cool, Trigonometry and Linear Algebra can be fun, but it has little to do with your problem. So I wrote a little snippet which should bring you back on track. I also created a little file [1] which demonstrates said snippet, because the setup is a bit complicated. Below you will also find the code in case you run into problems with the file (which was created with an educational license).
And finally two cents about your code. You got the major gist of the dot product, but normally you simply compute the unit vectors before computing the dot product if you are interested in the angle these vectors span. Your solution of adjusting the dot product afterwards is not wrong, but a bit convoluted in my opinion. You usually also do not compute the inverse cosine of a dot product if you are only interested in their angular relation and not the specific angle they span (it just is an unnecessary and relatively expensive computation) . For unit vectors the dot product already has very nice properties. Parallel unit vectors will have a dot product of
1, anti-parallel (parallel, but pointing in different directions) unit vectors a dot product of
-1and orthogonal unit vectors a dot product of
0.
Cheers,
zipit
""" Example for reflecting a frame (matrix). This example will roughly do what you want (I am still not quite sure what you exactly want to do). For this example to work, you will need. 1. A reflection plane. Any object will do, we just need the matrix. 2. An object to reflect, referred to in this script as "source". 3. An "reflected object", i.e. something to write the result to, referred to in this script as "target". 4. A Python tag to put this script into. The Python tag will need four user data elements: ID 1 - A link to the reflection plane ID 2 - A link to the source object ID 3 - A link to the target object ID 4 - The reflection axis vector. This should be a vector clamped to the interval [-1, 1] with a step of 2 (i.e. it can only take on the values -1 and 1 on each component). I did not address any shenanigans regarding how Cinema interprets the computed frame when constructing a matrix. This would be another topic. """ import c4d def reflect_frame(source, plane, axis): """ Reflects a frame on a reflection plane. Reflects the frame "source" on the reflection plane defined by the frame "plane" on the axis defined by the vector "axis." Args: source (c4d.Matrix): The frame to reflect. plane (c4d.Matrix): The frame of the reflection plane. axis (c4d.Vector): The reflection axis. See the code for details. Returns: c4d.Matrix: The reflected frame. """ # We do not want the reflection plane to apply any translation # or scaling, i.e. we are only interested in its normalized # orientation. So we remove anything except the orientation information. # I took care in the Cinema file that this can not happen in the first # place, so this is kind of redundant here. plane.off = c4d.Vector() plane.v1 = plane.v1.GetNormalized() plane.v2 = plane.v2.GetNormalized() plane.v3 = plane.v3.GetNormalized() # Now we express the offset in the frame of the reflection plane. pl = source.off * ~plane # Now we express the three axis of our source as global points (e.g. # source.off + source.v1) and then express these global points in the # frame of our reflection plane. xl = (source.off + source.v1) * ~plane yl = (source.off + source.v2) * ~plane zl = (source.off + source.v3) * ~plane # Now we invert the component(s) we want to reflect by multiplying our # points expressed in the plane of reflection componentwise by the # reflection axis - which I did express as a signed vector # (e.g.: (10, 10, 10) ^ (-1, 1, 1) = (-10, 10, 10) - a reflection on # the x-axis). After that we express these points in the world frame # again. These four components are now almost our finished frame. # The offset, this is the final value. off = (pl ^ axis) * plane # The three axis, which are still points in world space. x = (xl ^ axis) * plane y = (yl ^ axis) * plane z = (zl ^ axis) * plane # Finally we localize our axis components again in respect to their # origin and normalize them and reinstate their original scaling. x = (x - off).GetNormalized() * source.v1.GetLength() y = (y - off).GetNormalized() * source.v2.GetLength() z = (z - off).GetNormalized() * source.v3.GetLength() # The final frame converted into a Cinema matrix. mg = c4d.Matrix(off, x, y, z) return mg def main(): """Entry point. """ # The input user data. plane = op[c4d.ID_USERDATA, 1] source = op[c4d.ID_USERDATA, 2] target = op[c4d.ID_USERDATA, 3] axis = op[c4d.ID_USERDATA, 4] # The user data are not fully populated. if None in (plane, source, target, axis): raise ValueError("User data input values are not fully populated.") # Compute the reflected frame. mg = reflect_frame(source.GetMg(), plane.GetMg(), axis) # Set the world matrix of the target object. target.SetMg(mg)
[1] The file: frame_reflection.c4d
Hi @zipit ,
I am so grateful for you taking the time to put this together, thank you! It is really cool that you can rotate the mirror plane. I never expected that, but it's a cool feature. The script I wrote wasn't for fun, but in response to when you wrote 'evaluate the angle between each axis and a normal of the reflection plane to determine which axis would be the least painful to invert.' I didn't fully understand the math, I was just trying to follow my understanding of your advice.
Your example works great with the second scenario from my original post where the axes are the same, but when I rotate the axis of the "source (transform me)" cone (mimicking the first scenario from my original post), it doesn't work anymore because, I believe, it's rotating the axis of the target. I do not wish to affect the axes in any way, but rather position & rotate the objects into the mirrored state. Being able to do this with different axes orientations is essentially what I am seeking.
In response to the comment in your code "(I am still not quite sure what you exactly want to do)", I am sorry if I have not made my intentions clear enough. I will try to explain once more in different terms, and please let me know if anything is unclear. Thank you for your patience and perseverance:
- This script will mirror two objects, identical to behavior that can be found with Cinema 4D's Mirror Tool (Character > Mirror Tool). In some cases, their axes will match. In others they might differ, so I want to account for this. Cinema 4D's Mirror Tool has an Axes dropdown. I'd be okay with an option like this, but would prefer to guess based on the difference of the objects' parents' axes. This is where I could really use help with the 3D Math behind this.
- I am not looking for a Python Tag that evaluates every frame, but rather something that can be run once to mirror a character rig pose.
- Both objects will have parent objects that reset their local transform values to zero. I mention this in case local or parent values would work better in repositioning & reorienting the objects correctly.
Here is the demo file you sent me with the other scenario for which I need to account (the objects are also parented under nulls):
frame_reflection_2.c4d
I need to create a programmatic solution for this as I cannot use the Mirror Tool for multiple objects. It only accepts one Source and Target object at a time and I will eventually use this for multiple control pairs. Right now, in the case of this forum example, I'd just like to get this behavior working with one pair of objects at a time (once with matching axes and once with different axes).
Please let me know if you need me to explain anything any more.
I am truly grateful for your help!
Hi,
I am not at home anymore, so I cannot look at your file right now, but your explanation was indeed a bit enlightening especially regarding "In some cases, their axes will match. In others they might differ, so I want to account for this." part. As I already stated in my first post, it confused the heck out of me that the axes were all over the place in your pictures in the first posting.
If you have two objects which are topologically identical, but have a different frame and you want to "reflect" one object in respect to the other and a reflection plane, you would first have to compute a transform which transforms the frame of the one object to the other in respect to their topology. Cannot say much more without having a better look at the problem and your file myself.
I will probably take a look at your file tomorrow and I will probably also have to take a look at the character mirror tool, because I am completely clueless when it comes to rigging. Maybe MAXON will chime in and tell you what the character tool does under the hood or someone else already knows this specific problem.
Cheers,
zipit
@zipit Thank you for the replies and I'm happy that has explained things a little better. Yes, hopefully the MAXON SDK team can speak to getting the mirroring working with different axes in Python similar to their Mirror Tool. Have a good rest of your weekend and thank you again.
Hi,
I just had a quick look at both the online documentation and your file. The online documentation for the mirror tool has this image (I hope it is okay that I hotlink it here) for the dropdown in question.
The option None would be what we discussed under reflecting the vertices, only that they here also shove the frame a bit around so that it sits where the reflected frame would sit, they do not touch the orientation at all and simply reflect the internal point data. The option Rotate is something that does not really matter here I think. And the options XY, XZ and YZ are exactly that what we did discuss regarding left-handed matrices. In the XY example you can see that for a truly mirrored frame, the z-axis should point downwards on the right side or upwards on the left side. But since Cinema only has left handed matrices, one axis has to be flipped and Cinema leaves the decision which axis to flip to the user via that option.
But in your file in the not working part of the hierarchy you have an target object with a different frame orientation than the source object. This is a different problem than addressed by the mirror tool, I think. We could differentiate two types here:
- The frame orientations are different, but each component appears in the other frame as another axis or the inverse of another axis (e.g. the x axis in one frame is the inverse of the y axis in the other) . The other frame would be here the result of rotating the primary frame by 90° around one of its axis or multiple of these operations. This could be relatively easily solved by swizzling the components of the reflected frame before assigning the result to the target object. The most straight forward option would be to leave the decision which planes/axis to swizzle to the user via the interface, because trying to detect the swizzle relation automatically would let you face the same problem as described in the next point under the hard way.
- The frame orientations are truly arbitrary and in no hidden predefined relation to each other. This seems to be the case in your file, at least the parent null-object of target object is in such orientation. This is either an annoying or a hard problem to solve and if I am not mistaken, Cinema offers no solution for the hard way in its toolset.
The annoying way would be reflecting the internal point data of the object. While this is trivial for a bunch of vertices, it can become tedious for more complex structures, because if you reflect vertices that have polygons, you will also have to flip the vertex index order in each polygon, i.e. flip the normals of the polygons, because reflecting the vertices flipped the point normals. And the list goes on: you might have to handle uvw and weight information, untangle hierarchical information like in your example, etc. pp.
The hard way would be analysing the topology of the object so that one can place the target object in a way that it looks like it is reflected, but its frame is no reflection relation to the source object and you also do not touch the internal (point) data. I will leave it at that for now.
So knowing the problem in all its nasty requirements: I would say there is no easy way, or at least I do not see one.
Cheers,
zipit
Hi @blastframe and @zipit, thanks for the thoughtful discussion on the topic.
With regard to the Mirror Tool's implementation it's not rocket science because the foundation of the tool have been properly explained by @zipit with regard to reflecting a transformation matrix on main axes, in case of XY, XZ, YZ mirroring and with the vertexes being actually displaced in the "mirrored" position in case None mirroring.
That said a very simplified version in Python could be based on the following matrix changes:
... ... if flip == "X == "Y == "Z) ... ...
Cheers
@r_gigante Hi Riccardo! I'm very happy to get your input into this matter and thank you for the mirroring code at its essence.
There is a major part of my issue that I'm still unsure how to resolve, however: even though it is useful to switch the mirroring plane to ZY, XY, XZ, I'm not able to mirror objects whose axes are inverted. This is common with character rigs so I need to account for it. I mention the Mirror Tool because it has Axes controls. I don't know how to do the matrix transformations for the differing axes along with the Mirror Plane and could really use your help.
While the original code works when the axes are the same, using the mirroring technique with the provided code flips the objects in Y and continually adds to their P rotation values. The rig is using X+ controls with XYZ rotation order. I've included these controls as Scenario 2 in the attached scene file, along with other axis orientations & rotation orders one might see in a rig:
Mirroring Different Axes.c4d
How can I account for the rotated axes? Thank you.
Hi @blastframe, sorry for getting back with a bit of a delay but summer time is usually pretty busy.
With regard on how to take in account the different axis, you can immediately see that for scenario 1 asking for Ml and Mg for both source and target object will return
---------------------------------------------------------------------------------------------------- L_Leg_con+ | L_Leg_zero | Scenario 1 - HPB Z- (works) (global): Matrix(v1: (1, 0, 0); v2: (0, 1, 0); v3: (0, 0, 1); off: (10, 15.171, 3.922)) R_leg_con+ | R_leg_zero | Scenario 1 - HPB Z- (works) (global): Matrix(v1: (1, 0, 0); v2: (0, 1, 0); v3: (0, 0, 1); off: (-10, 15.171, 3.922)) ----------------------------------------------------------------------------------------------------
Given this numbers you can immediately see that the frames are aligned and no changes in the mirroring code should be done
Repeating the same with scenario 2 will return:
---------------------------------------------------------------------------------------------------- L_Leg_con+ | L_Leg_zero | Scenario 2 - XYZ X+ (global): Matrix(v1: (0, 0, -1); v2: (0, -1, 0); v3: (-1, 0, 0); off: (10, 5.171, 3.922)) R_Leg_con+ | R_Leg_zero | Scenario 2 - XYZ X+ (global): Matrix(v1: (0, 0, 1); v2: (0, 1, 0); v3: (-1, 0, 0); off: (-10, 5.171, 3.922)) ----------------------------------------------------------------------------------------------------
and here you see, comparing the global matrices that Z and Y components are inverted. Thus inverting the Z and Y components of the mirroring matrices will provide you with the correct transformation.
Finally in scenario 3 checking again the frames will result in:
---------------------------------------------------------------------------------------------------- L_Leg_con+ | L_Leg_zero | Scenario 3 - XYZ Z+/Z- (global): Matrix(v1: (1, 0, 0); v2: (0, 1, 0); v3: (0, 0, 1); off: (10, -4.829, 3.922)) R_leg_con+ | R_leg_zero | Scenario 3 - XYZ Z+/Z- (global): Matrix(v1: (-1, 0, 0); v2: (0, 1, 0); v3: (0, 0, -1); off: (-10, -4.829, 3.922)) ----------------------------------------------------------------------------------------------------
where the X and Z component are inverted. Thus inverting the X and Z components of the mirroring matrices will provide you again with the correct transformation.
Again due to time constraint i can't come with full code, but once you got the logic won't be hard to implement it in the code.
Finally consider that in the test project you've shared in the previous post in the scenario 3 , L_Leg_con+ and R_Leg_con+ both had rotation mode set to HPB instead of XYZ
Best, R
mirroring-different-axes_correct.c4d
@r_gigante Hi Riccardo! Thank you for your reply and for taking a look at the file. I understand about this being a busy time of year. I appreciate the support you and your team gives year-round. It's a special and well-appreciated service that you all provide, thank you!
I think I have the problem narrowed down to one issue: can you offer any code help for determining & applying the axes' rotational differences to the mirrored values when they are at 0 values in position & rotation please?
Hi @r_gigante ,
I am still working on this problem every day and could really use some help before the weekend if it's possible.
I think I could just use help knowing how to get the difference between the axes in their default state. Could you please give me some advice on how to go about this? I am trying to apply the different axes' rotations to the mirrored matrices from @r_gigante 's code.
Can you help me to get the right axis rotation values to apply to the mirrored values? Any help would be huge so I don't spin my wheels on this problem for another weekend. Thank you!
Hi @blastframe , I understand the need of help but actually the SDK Team needs to balance the support efforts among different topics/services. In this case, the support you're looking for goes behind the scope of the APIs and it's mostly related to the math behind it.
When time has permitted we've always tried to be supportive even beyond the scope of the API providing snippets, scripts if not whole plugins. Unfortunately, this is not possible at this time but we'll try to keep this thread on our radars and hopefully to get back on it later.
Best, Riccardo
- blastframe last edited by
@r_gigante Okay, thank you for the reply.
Hi,
I have slightly updated my previous example for the case when the two frames are in a simple rotational relation around one of their standard basis vectors. As already stated, a general solution for this problem is much harder to accomplish and also not really a 'math' problem, but more a conceptual and algorithmic problem.
There are also other ways to calculate the delta between your two frames if you are in the non-general case, which will have different advantages and disadvantages to the solution provided by me, but will also require certain guarantees regarding the source and target object and their frames to work properly (like for example having their vertices occupy the same points in world space).
Cheers,
zipit
@zipit That is very kind of you to revisit this topic, thank you! Also, very cool gizmos
I have considered allowing the user to choose how the axes are different themselves as you have in your example, but I really want to see if calculating the delta is possible first. The reason is that there could be many left & right object pairs to be mirrored that have different axis orientations. Can you think of any way to do this?
For example, this is what I have tried:
- L_Cube's, local rotation is (45°, 0°, 0°). Save this matrix, reset the rotation to (0°,0°,0°) locally, and get the global rotation (-90°, 180°, 0°). We save this matrix and reset back to (45°, 0°, 0°).
- R_Cube's, local rotation is (0°, 45°, 0°). Save this matrix, reset the rotation to (0°,0°,0°) locally, and get the global rotation (90°, 0°, 0°). We save this matrix and reset back to (0°, 45°, 0°).
- Mirror the values using your code
- How can we then apply our global rotations that we got when the objects were reset: (-90°, 180°, 0°) and (90°, 0°, 0°) as corrections respectively?
- In other words, how do we determine the inverted_result_axis and target_adjustment_rotation from your code based on these values?
Here is what I have tried:
l_diff_x = utils.Rad((-90+90)) #difference between x-axes l_diff_y = utils.Rad((180-0)) #difference between y-axes l_diff_z = utils.Rad((0-0)) #difference between z-axes r_diff_x = utils.Rad((90-90)) #difference between x-axes r_diff_y = utils.Rad((0-180)) #difference between y-axes r_diff_z = utils.Rad((0-0)) #difference between z-axes l_correction = utils.MatrixRotX(l_diff_x) l_correction = utils.MatrixRotY(l_diff_y) l_correction = utils.MatrixRotZ(l_diff_z) r_correction = utils.MatrixRotX(r_diff_x) r_correction = utils.MatrixRotY(r_diff_y) r_correction = utils.MatrixRotZ(r_diff_z) l_cube.SetMg(l_reflection * l_correction) r_cube.SetMg(r_reflection * r_correction)
This makes sense to me but it doesn't work. There is something missing...putting the corrections into the objects' frames, or inverting them. I don't know; I have tried them to no avail.
Thank you!
Hi,
there are some fundamental problems with your code, but when I am trying to understand the intention of that code, you also seem to have overlooked the major prerequisite of your approach - It would require both objects to be topologically aligned. That was not the case in any of your example files.
Imagine an object "source" that you have just duplicated ("target"), so that target "sits in the same place" as source. If you now would rotate the frame of target with Cinema's axis-mode thingy, then its points would occupy the same coordinates in world space as before, but their local coordinates would be different. You could simply compute the transform between the two frames then by
correction = ~source.GetMg() * target.GetMg(). If however also target itself had been rotated (like it was the case in your files), then you cannot do this anymore, because there are now two sources of information that have been mixed: The orientation of the frame in respect to its vertices and the rotation of the frame in respect to the source. We do not have any clue how to untangle that (or more precisely - it is not so easy).
If you do not want to to dial in an angle, but also cannot guarantee that the objects are topologically aligned, you could also compute the correction transform by letting the user choose a from-to-axis pair. In pseudo code (i.e. I have written this on my iPad):
frm_source, frm_target = source.GetMg(), target.GetMg() # Rotate the source x-axis to the y-target axis. if user_choice is "x_source to y_target": # The two axis in question a, b = frm_source.v1, frm_target.v2 # The normal to both axis, which is the axis of rotation. We take # the cross product and normalize it (normalization is technically # not necessary, but better safe than sorry ;) nrm = ~(a % b) # The angle between both axis. theta = math.acos(~a * ~b) # We could construct the transform/matrix with that ourselves, but # why should we when Cinema has Quaternions for us. quat = c4d.Quaternion() quat.SetAxis(nrm, theta) # Get the rotation matrix for that Quaternion. transform = quat.GetMatrix()
Cheers,
zipit | https://plugincafe.maxon.net/topic/12745/mirroring-with-matching-or-different-axes | CC-MAIN-2021-17 | refinedweb | 5,876 | 61.97 |
{-# LANGUAGE ScopedTypeVariables #-} -- | The removeAncestors function in this module (actually an IO action) takes -- a graph G and a list of nodes N and computes N' = { n in N | -- there does not exist an m in N and a non-trivial path n -> m }. -- This is required for graph merging. module Graphs.RemoveAncestors( removeAncestors, removeAncestorsBy, removeAncestorsByPure, ) where import Control.Monad.Identity import qualified Data.Map as Map import Graphs.Graph -- | Takes a graph G and a list of nodes N and computes N' = { n in N | -- there does not exist an m in N and a non-trivial path n -> m }. removeAncestors :: Graph graph => graph nodeLabel nodeTypeLabel arcLabel arcTypeLabel -> [Node] -> IO [Node] removeAncestors graph nodes = do let getChildren node = do arcsOut <- getArcsOut graph node mapM (\ arc -> getTarget graph arc) arcsOut removeAncestorsBy getChildren nodes -- | General removeAncestors function, which takes as argument the action -- computing a Node\'s successors. removeAncestorsBy :: (Ord node,Monad m) => (node -> m [node]) -> [node] -> m [node] removeAncestorsBy (getChildren :: node -> m [node]) (nodes :: [node]) = do -- We maintain a state of type (Map.Map node NodeState) to express -- what is currently known about each node. We also maintain -- a set containing the target nodes. -- compute initial map let state0 = Map.fromList (map (\ node -> (node,Yes)) nodes) uniqueNodes = map fst (Map.toList state0) -- Return True if there is a, possibly trivial, path from this node -- to one of the target set, also transforming the state. -- EXCEPTION - we don't search down nodes which have Cycle set, -- and in that case return False. nodeIsAncestor :: node -> Map.Map node NodeState -> m (Bool,Map.Map node NodeState) nodeIsAncestor node state0 = case Map.lookup node state0 of Just Yes -> return (True,state0) Just No -> return (False,state0) Just Cycle -> return (False,state0) Nothing -> do let state1 = Map.insert node Cycle state0 children <- getChildren node (isAncestor,state2) <- anyNodeIsAncestor children state1 let state3 = Map.insert node (if isAncestor then Yes else No) state2 return (isAncestor,state3) -- Returns True if there is a, possibly trivial, path from any -- of the given nodes to one of the target nodes. anyNodeIsAncestor :: [node] -> Map.Map node NodeState -> m (Bool,Map.Map node NodeState) anyNodeIsAncestor [] state0 = return (False,state0) anyNodeIsAncestor (node : nodes) state0 = do (thisIsAncestor,state1) <- nodeIsAncestor node state0 if thisIsAncestor then return (True,state1) else anyNodeIsAncestor nodes state1 -- Returns True if there is a non-trivial path from the given node -- to one of the target nodes. nodeIsNonTrivialAncestor :: node -> Map.Map node NodeState -> m (Bool,Map.Map node NodeState) nodeIsNonTrivialAncestor node state0 = do children <- getChildren node anyNodeIsAncestor children state0 (list :: [node],finalState :: Map.Map node NodeState) <- foldM (\ (listSoFar,state0) node -> do (isAncestor,state1) <- nodeIsNonTrivialAncestor node state0 return (if isAncestor then (listSoFar,state1) else (node:listSoFar,state1)) ) ([],state0) uniqueNodes return list -- | Pure version of 'removeAncestorsBy'. removeAncestorsByPure :: Ord node => (node -> [node]) -> [node] -> [node] removeAncestorsByPure (toParents0 :: node -> [node]) nodes = let toParents1 :: node -> Identity [node] toParents1 = Identity . toParents0 in runIdentity (removeAncestorsBy toParents1 nodes) -- | This describes the information kept about a node during the course of -- removeAncestorsBy data NodeState = Yes -- ^ there is a, possibly trivial, path from here to an element -- of the target set. | No -- ^ the opposite of Yes. | Cycle -- ^ we are already searching from this element. {- SPECIALIZE removeAncestorsBy :: (Node -> IO [Node]) -> [Node] -> IO [Node] -} | http://hackage.haskell.org/package/uni-graphs-2.2.1.0/docs/src/Graphs-RemoveAncestors.html | CC-MAIN-2018-26 | refinedweb | 529 | 64.51 |
I have a problem connecting to my exist db running under JBoss-tomcat. I try
connecting using this url entered
in the client.properties file. but keep getting the error below. I succeeded
connection using the XMLdbGUI with the same url. I can't figure out where I
am wrong, so can anybody tell my how to solve this
Thanks in advance
Kasper
(In a browser i get "HTTP Status 405 - HTTP method GET is not supported by
this URL" with the url)
XMLDBException while retrieving collection contents: an io error occurred
java.io.IOException: Server returned HTTP response code: 401 for URL:
at org.apache.xmlrpc.XmlRpcClient$Worker.execute(Unknown Source)
at org.apache.xmlrpc.XmlRpcClient.execute(Unknown Source)
at
org.exist.xmldb.CollectionImpl.readCollection(CollectionImpl.java:256)
at
org.exist.xmldb.CollectionImpl.listChildCollections(CollectionImpl.java:229)
at
org.exist.InteractiveClient.getResources(InteractiveClient.java:352)
at org.exist.InteractiveClient.run(InteractiveClient.java:1604)
at org.exist.InteractiveClient.main(InteractiveClient.java:313).exist.start.Main.invokeMain(Main.java:94)
at org.exist.start.Main.run(Main.java:465)
at org.exist.start.Main.main(Main.java:44)
Hello !
Thanks for your helpful answers on how to order resultsets sent by eXist !
I'm now trying to use eXist in synergy with another software, SDX
(), hoping to get benefits from the complementary
features of these apps.
But... ;o)
I'm quite new at web applications under Tomcat, and I can't make my XSP test
page connect to eXist using xmldb protocol... (the xsp code is taken from
the an example of eXist's website).
The application I made under the /webapps/exist directory works very fine,
but when I try to put an xsp page under the /webapps/sdx directory, nothing
goes on.
I guess it's a matter of sitemap.xmap and / or cocoon.xconf : I tried to
declare the xmldb logicsheet in SDX, the xmldb protocol in the
source-handler, and the driver. I put a copy of required jars in the lib
directory of SDX.
But when I load the xsp page, nothing hapens. Any idea about where I'm wrong
?
I installed eXist as a webapp, with default settings.
Thanks in advance,
best regards, Marjorie
> The JAXB Marshaller offers a method
>
> void marshal(ContentHandler)
>
> and the JAXB Unmarshaller knows
>
> getUnmarshallerHandler()
>
Thank you a lot. Somehow I miss this method.
> Btw, if you combine JAXB and eXist, you may also be interested
> in. JaxMe 2 is aimed to become an open source
> JAXB implementation. JaxMe 1 includes a persistence layer, which
> allows to access xml:db with simple methods like
For sure I will also look also at this.
Once more thanks for quick answer, and showing me right track. ;)
Regards
Arek
Zitiere Arek Stryjski <developer@...>:
> To aces eXist which is embedded in Cocoon you suggest to use XML:DB
> API.
> This seams the most reasonable way but for JAXB the most effective way
> to
> marshal XML documents is to use InputStream.
Sorry, but I strongly disagree. The most effective way is SAX.
The JAXB Marshaller offers a method
void marshal(ContentHandler)
and the JAXB Unmarshaller knows
getUnmarshallerHandler()
(not sure about the name, written from memory!)
Btw, if you combine JAXB and eXist, you may also be interested
in. JaxMe 2 is aimed to become an open source
JAXB implementation. JaxMe 1 includes a persistence layer, which
allows to access xml:db with simple methods like
manager.store(jaxbObject)
or
jaxbObject[] result = manager.select(xpathQuery)
I hope that the persistency layer will soon be ported from JM 1
to JM 2.
Regards,
Jochen
Hello,
I would like to use eXist in my Cocoon application. To change (bind) some of
my XML's into Java Object representation I use JAXB. However I have
difficulty in combining these two technologies.
To aces eXist which is embedded in Cocoon you suggest to use XML:DB API.
This seams the most reasonable way but for JAXB the most effective way to
marshal XML documents is to use InputStream. In XMLResource I found only
methods that use DOM Node, SAX ContentHandler or simple String.
Using Node is completely ineffective for performance reasons, as XML
document stored in database first need to be parsed to DOM, and then
marshaled.
With String I could change it to StringReader and pass it to unmarshal()
method. But again I'm warred about performance as creation of String
representation of XML document can be resources consuming because it may
require using String concat() method, and creating many String instances on
the way.
SAX will be the best solution but XMLResource expects ContentHandler, and
unmarshal() method expect SAXSource, so combining this two seams to be
impossible for me at first glance.
Lack of access to XML document as simple byte array or InputStream is big
lack of XML:DB specification in my eyes. It was probably created then DOM
and SAX ware the only standard API's to work with XML in Java. However I
could still imagine that some programs would like to just get XML data as
quick as possible and pass it to other parts of programs (or clients) with
InputStream.
I was also thinking of using XML-RPC as it offers access to documents as
byte arrays. However I'm not sure if this is best solution either.
First if two parts of my program both embedded in Cocoon and run on same JDK
will use HTTP to communicate it seams a bit strange to me.
Secondly used in eXist XML-RPC implementation heavy use old fashion Java
collections (Vector and Hastable), which are less effective than new one.
This suggests that this implementation could be a little out of date, but
maybe I'm completely wrong at this point.
I'm wondering if anybody else came already across this difficulties and
dilemmas before, and found any solution. In my opinion it will be nice if
eXist could offer access to data as InputStream, Readeds or byte arrays. As
this is not present in XML:DB API it could be placed in some extra classes.
I could imagine that this is already present in some not public classes or
methods.
Another solution could be some connector between eXist and JAXB which will
use data format used internally by database to create JAXB objects. This
could be much nicer but probably will require a lot of work.
As funding (writing) good solution for this may take time, I would be also
glad if someone could help me to choose the best and most effective way to
unmarshal XML's stored in eXist using available methods.
Best regards,
Arek Stryjski
I've checked out the current version of exist from the cvs, built the
webapplication war and deployed it into tomcat 4.1.24
I'm currently having problems with Authentication/Authorization in the
Admin Interface and Server Status Servlet sections of the
webapplication. Before, I was able to disable this by commenting out the
security and login sections of the web.xml. But now this seems to not
have an effect. How can I disable the security of these sections so I
can access them temporarily for testing.
-Mark
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/exist/mailman/exist-open/?viewmonth=200305&viewday=5 | CC-MAIN-2017-34 | refinedweb | 1,237 | 56.55 |
I'm getting stack overflow errors when I'm trying to publish() a
NetStream after close()ing it. Pasted below is the error stack:
Error: Error #1023: Stack overflow occurred. at
com.luxideus.facebook.canvas.controllers::StreamsController/onNetStatus()[...] at flash.net::NetStream/invokeWithArgsArray() at
flash.net::NetStream/call() at flash.net::Ne
I'm planning to sync 2 folders from 2 dyfferent servers using a cronjob
scheduled to run every hour.The script that is to be scheduled will
check if a previous instance is already running, and if not, continue with
processing.
so, the first stage is to sync these folders. Daily
(or more often), the second server will have 1-2 thousands of new files
added, that need to be moved
I have now whittled this down to a minimal test case. Thus far I have
been able to determine that this is an issue related to pseudo-terminals
which come about with the pipe of ssh. Adding the '-t -t' to the ssh call
improved things, in that now, it takes a second call to fgets() to cause
the issue. I suspect that the stderr output of the ssh command somehow
works into the issue, for now I h
After calling setTimeout, is there memory leak issue
without calling clearTimeout?
setTimeout
clearTimeout
Thanks.
say suppose I have class as :
public class Age {
private int age; public int getAge() { return
this.age; }}
In my Main class I am
calling the getAge() method many times.
So I wanted to know is
it advisable to call so many times or call once and assign it to some
variable and use that variable.
I'm running a keys_only query, which fetches 20 results.
result_keys, cursor, more = ActivityIndex.query(cls.followers ==
key)
.order(-cls.date_created)
.fetch_page(num_results,
start_cursor = cursor,
I have an application written in Python.
The application
calls some functions in the dll (using ctypes) that calls some functions
from the python C API to load and run some functions in a (different)
python module. This causes WindowsError: exception: access violation
reading 0x00000004 Some cout debugging tells me that the access
violation happens on a call to the Pyth
WindowsError: exception: access violation
reading 0x00000004
Hi I am trying to call a webService in titanium using json.That
webService does not take any argument so i just have to call it.
here is my code:
var xhr =
Titanium.Network.createHTTPClient();xhr.setTimeout(10000);xhr.open("POST","");
xhr.setRequestHeader("Content-Type", "application/json; chars | http://bighow.org/tags/Calling/1 | CC-MAIN-2017-47 | refinedweb | 412 | 55.13 |
Hanoi 02/11/2008
CONTENTSI.Executive Summary1.Objectives 2.Missions 3.Keys to Success 4.Risks
VI.Management Summary1.Personnel Plan
VIII.Milestones
This business plan is prepared to obtain financing in the amount of 200,000,000VND. The financing is required to begin work on site preparation and modifications, equipment purchases, and to cover expenses in the first year of operation. DE will be joined by 5 investors.The investors will be treated as shareholders and therefore will contribute 40,000,000VND each This business plan provides a step-by-step plan for the business start-up, establishing favourable sales numbers, gross margin, and profitability. This plan includes chapters on the company, products and services, market focus and forecasts, management team, financial plan and action plans.
1.Objectives DE has established 4 objectives it wishes to achieve in the first three years of operation: + Gross margin approaching and surpassing 324,000,000 VND (= 36,000,000VND*9 months)by the end of the first fiscal year. +Targeting and maintaining a net profit margin of at least 15% by the second fiscal year. + Achieving a 30% net profit margin by the third fiscal year + Cultivating monthly sales to reach 23,000,000 VND by the end of the third month of operation( monthly break-even point), and 36,000,000VND monthly by the end of the first year of operation. 2.Missions: Educational Mission:+To creat an interesting learning environment for customers to attain better English communication skills Product Mission : + To provide customers good quality drinks . Economic Mission :+ To operate and grow at a profitable rate through sound economic decisions. 3.Keys to Success There are keys to success in this business,some of which are virtually the same as any foodservice business.
It is our 1ST three keys,the english-related factors,that will give us that extra measure of success as it differentiates DE from other local cafes +Native English shareholders +Presence of native English speaking people at DE every evening +Just English spoken with interesting activities (topics) to create unique attraction and originality for DE +Good location - accessible to a dynamic student population +Interior design style suitable for the business model +Reasonably priced products
4.Risks The risks involved with starting DE are: + Will the popularity of English speaking cafes continue to grow, or is an English speaking cafe a fad in HN? + Will individuals be willing to pay for the drinks and happy to come back again while the majority of our customers are budgetary students? + Will there be constant presence of native English speaking people at DE everyday to attract customers? + Will there be many competitors in the furure?
2.Company Ownership DE is a privately held cafe with the ownership shared by 5 investors:JOSH,JEFF,TUAN,KHIEM and DAI 3.Company Location and Facilities DE will be located in a renovated house in NGUYEN CHI THANH Street which can be seen as a crossroad of universities. It will be designed by??? Our design style features stained glass decorations,creating a nice and modern space suitable for an English speaking environment,especialy highlighting English culture but not loosing its foodservice function The facility will be divided equally between the caf function and the English learning function. The cafe will feature an indoor speaking room for approximately 30 patrons,a reading room for 20 and an outside space for 30 novice ones , designed for flexible seats and a small platform for presentaion, and shelves of books, magazines and newspapers available for reading and for sale Dcor:.( still waiting for a detailed sketch from a professional architect)
4.Start-up Summary The start-up costs for DE cafe can be found in the chart and table below. (just roughly) Start-up Expenses CONSTRUCTION & DCOR Cost 30.000.000VND(for more specifics,it will be sorted out later)
60.000.000VND
MARKETING&ADS
6.000.000VND 55.000.000VND (for more details,it will be sorted out later) 6.000.000vnd 10.000.000vnd
EQQUIPMENT PURCHASE: 1 Refrigerator 1 Computer,Wifi, 1 Printer,1 Telephone Stationery etc Tables, Chairs, Furnishings Cups /glasses 1 Microwave,1 gas cooker, 1 Blender Other.. Total Start-up Expenses
5.Expansion: Assuming this cafe is successful, it will be the first of a chain of English speaking cafes located in markets that have similar demographic profiles, a sizeable student population. we will use this as a "blueprint" for expansion. For example, daily sales are tracked and analyzed by item, time period and cost of goods. Labor requirements are matched to projected in-store sales based upon past performance for maximum efficiency
Socialisation : - Make new friends,especially native English speakers and people of different nationalities Educational products:
- Menu and pricing: DE offers its patrons the finest custom drinks. In addition, DE will offer bakery items and other confections.They are divided into 5 groups as follws: coffee, tea, juice & shake, fastfood and others Seasonally, DE will add beverages such as . Prices have been determined after a thorough analysis of all costs for every item in each drink. In some cases, an average price has been calculated and applied to all similar drinks in order to keep the menu from confusing customers.
HAMBURGER:
COFFEE:
SANDWICH:
BEER???:
GREEN TEA
TEA BAGS(LIPTON,DIMAH)
JUICES:
CAKES:
DrinksCoffee D1 D2 D3 Vietnamese (black)- C ph en Vietnamese (with milk) - C ph sa Western (Instant 3 in 1) - C ph ho tan 12,000vn d 12,000vn d 10,000vn d
Tea D4 D5 D6 Vietnamese Tea (by pot)- Tr Vit Nam Lipton - Tr Lipton Dilmah - Tr Dilmah 12,000vn d 10,000vn d 10,000vn d
Juice D7 D8 D9
(blended with ice) Orange - Nc Cam Passion fruit - Nc Chanh Leo Lemon - Nc Chanh 18,000vn d 15,000vn d 12,000vn d
(blended with ice & milk) Mango - Sinh t Xoi Pineapple - Sinh t Da Watermelon - Sinh t Da Hu Lemon - Sinh t Chanh ti Avocado - Sinh t B 18,000vn d 18,000vn d 18,000vn d 18,000vn d 20,000vn d
Other D15 D16 D17 Chocolate - Ca cao Milk - Sa Ti Yogurt - Sa Chua nh . (blended with ice & your choice of coffee, chocolate or orange) 15,000vn d 10,000vn d 15,000vn d
Salted lemon - Chanh Mui Salted apricot - M Mui Soft Drinks- Noc ngt (Coke, Fanta, Sprite, Mineral Water) Beer - Bia: Tiger & Halida (can)
D21
Food
sF1 F2 Toast - Bnh m B mt (served with butter & Jam) Pancakes - Bnh Kp (your choice of toppings: Chocolate/Banana, Lemon/Sugar, Honey/Banana) 12,000vnd 12,000vnd F3 Toast (Omelette) - Bnh m p la 12,000vnd
F4
American Hotdog (sausage in baguette, Fillings: cheese, onion, tomato) -Bnh m xc xch
20,000vnd
F5
F6
15,000vnd
F7
12,000vnd
F8
American PB&J Sandwich (peanut butter & jelly) -Bnh Sandwich kiu M
Snacks - Bim bim Melon Seeds- Ht Da Crackers/Biscuits - Bnh Quy Cakes- Bnh ngt
2.Sourcing DE will buy materials from 3.Future Products As the business is going well, DE will offer more products and improve services that will enhance sales and satisfy its customers' desires.
+ Growing interest in English but lack of such an environment + This type of business is new,so there is no competition in Hanoi up to present + Good location
2.Market Segmentation - In terms of familiarity with English, DE's customers can be divided into 2 groups: +The first group is familiar with ENG and desires a progressive and inviting atmosphere where they can enjoy a great drink in a friendly way +The second group is not familiar with ENG, yet, is just waiting for the right opportunity to enter this community. The majority of these individuals are students . See the Market Analysis chart below for more specific (there will be a chart later) - In terms of age, DE's customers are comprised of these target groups: + Universitiy and colledge Students + School children + People who are working but want to improve english for better jobs - Besides,foreigners who want to explore Vietnamese culture and make Vietnamese friends might be our potential custumers
-The second, and most important strategy focuses on pulling in power English speaking people. Power English speaking people are so familiar with English. This group of customers plays an important role at DE. Power ones have a good command of English and are willing to share,which will certainly impress and attract novice ones -The third strategy focuses on building a social hub for DE customers so that they see numerous benefits from frequenting DE To realize the above-mentioned strategies, we set forth a number of approaches as follows: + Specific Sales Programs:??? + Topic every evening???Anyone to conduct??? + Special performances on certain occassions ??? 2. Marketing and promotion Strategy - We will launch marketing to establish our brand image via several methods: + Using advertising as its main source of promotion. Ads placed in universities,schools, English clubs,and English centres will help build public awareness. + Handing out leaflets to students.Accompanying the leaflet will be a coupon for a discounted drink for the first time + Building relationships with teachers of universities,schools, other organizations as well as famous people + Taking advantage of word of mouth via our friends(both domestic and foreign) and our very patrons + Also conducting PR activities in media + Internet forums, DE blog, e-mails. + Inviting our pax (when on tour) to DE? - DE realizes that in the future, when competition enters the market, additional revenues must be allocated for promotion in order to maintain our market share, by: + Offering gifts on special occassions(Valentine,Chrismas,New year,Womens Day..), frequency cards, and discounts to key groups + Drink Coupons: At special events, we will be giving away drink coupons as door prizes or awards. This encourages the person to come in for their free beverage and bring their friends or buy a bakery item.DE will also hand out free drink coupons to those who have purchased a certain number of cups or something similar +Soliciting customer feedback to constantly improve our services and streamline our operation 3.Pricing Strategy Our food, drinks, and other options(books,CDs) are priced reasonably but still give us an attractive margin while at the same time offering value to the consumer. We want to repeat business . So, the beverages, food and the others will be relatively flexible. Pricing will be monitored accordingly 4. SWOT Analysis The SWOT analysis provides us with an opportunity to examine the internal Strengths and Weaknesses that DE must address. It also enables us to examine the Opportunities presented to DE as well as potential Threats. * Strengths DE has a valuable inventory of strengths that will help it succeed. These strengths include:
+ Native English shareholders and their native English-speaking friends can usually show up to attract custumers + All of DE founders are quite familiar with English,so we can easily manage English-related requests from our customers + Many of us work in the travel industry,so we have numerous opportunities to persuade our very pax touring with us to come to DE.Their presence contributes remarkably to appealing to our customers + Many of us have close connections with students who are eager to improve their english + There is a clear vision of the market need while we are currently enjoying a first-mover advantage in the local market + We can hire knowledgeable students with good English at cheap wages to work as friendly and skilled staff + By attracting students , we will generate excellent word-of-mouth Strengths are valuable, but it is also important to realize the weaknesses DE must face with. * Weaknesses These weaknesses include: +The majority of our customers are budgetary students and school children + The student population is not as strong during the summer as it is from May through August of each year , DE will do poorly during the non-school months.We must also market ourselves anew each year to the incoming students. DE cannot avoid these peaks and valleys in business * Opportunities DE's strengths will help it capitalize on emerging opportunities. These opportunities include: + An increasing need for English can be seen widely and becoming more and more popular.It gives us opportunities to multiply the model * Threats Threats that DE should be aware of include: + Currently high rental and will it be higher in the future? + Will the so-called budgetary custumers be willing to pay? + Will there be additional local competitors on the horizon? So,we need to be prepared for their entry into the market and will closely monitor pricing and our programs should be designed to build customer loyalty, and it is our hope that our quality service and up-scale ambiance won't be easily duplicated. 5. Sales Forecasts (there will be a chart later) In the firtst quarter of the first year of operation In the first year of operation. In the fiscal second year, In the third fiscal year.
VI.Management Summary1.Personnel Plan The staff will consist of HOW MANY? crucial part-time employees working HOW MANY hours a week at $? per month . Part-time personnel will be hired to handle bartending, serving, dishwashing function and..etc In addition, one full-time manager who will assist in maintaining and reviewing DEs operations will be employed to work HOW MANY hours? a week at $? per month *Requirements: + Good English(especially speaking skill) + Articulate,polite,friendly,honest,good sense of responsibility + With as much experience as possible and will be re-trained in line with DE style. The personnel plan is included in the following table: ESTIMATION: Personnel Plan Full-time Manager1 Part Time Manager2 7 pp 2.000.000vnd 1.500.000vnd
Part Time Bartender 1 800.000vnd Part Time Bartender 2 800.000vnd Part Time waitress 1 Part Time waitress 2 Part Time waitress 3 Total Payroll 800.000vnd 800.000vnd 800.000vnd 7.500.000vnd
Payroll Expense: Rent Expense Utilities Expense Bike keeping Tax Total
7.500.000vnd/1 month 10.000.000vnd/1 month 2.500.000vnd/1 month (water,electricity,gas,phone,ieternetetc.) 1.500.000/1 month 500.000vnd/1 month 23.000.000vnd/ 1 month
DE is leasing a 120 m2 location at 10.000.000vnd per month. The lease agreement specifies that we pay 60.000.000vnd for a total of every 6 months. At the end of the third year, the lease is open for negotiations and DE may or may not resign the lease depending on the demands of the lessor. Depreciation: In depreciating our capital equipment ,We depreciate our fixtures over a five-year time period 2.Estimated Monthly Revenue : Asumption: Average Number of custumers/1 day: 100pp Average Per-Unit Margin : Gross margin/1 day : 12,000vnd 1,200,000vnd 36,000,000vnd 23,000,000vnd 13,000,000vnd
3.Break-even Analysis +Monthly Break-even point: Monthly Margin Break-even Monthly Units Break-even Assumptions: Average Per-Unit Revenue Average Per-Unit Variable Cost Average Per-Unit Margin 15,000vnd 3,000 vnd 12,000vnd 23,000,000vnd 1,917drinks(64 drinks or 64 custumers/ day)
+ Duration of investment return (according to our assumptions): - Total fund: - Monthly Net Profit: 200,000,000vnd 13,000,000vnd
=> Duration = 200,000,000vnd/13,000,000vnd=15.4 months(+ the first 3 months without pfofit= 18.4 months) 4.Profit and loss Analysis (there will be a table later) 5.Projected Cash Flow Cash flow data is presented in the table below. Cash Flow Cash Received Expenditures Cash Balance FY1 200.000.000VND 151.000.000VND .. . FY2 FY3 . .
VIII.MilestonesThe accompanying table lists important program milestones, with dates and people in charge, and budgets for each. The milestone schedule indicates our emphasis on planning for implementation.
Start Date
End Date
Budget
Leasehold Buildout Marketing Plan Leaflet design Begin Construction Process Design Management
TUAN.B | https://ru.scribd.com/document/62953326/Drink-English | CC-MAIN-2019-39 | refinedweb | 2,634 | 50.36 |
In this tutorial, you use NetBeans IDE 6.0 or 6.1 to create an application that includes two JSF 1.2 (Woodstock) page fragment components. One fragment holds the application's logo. The second fragment holds links for navigating between the pages in the application.
Expected duration: 20:
A page fragment is a portion of a page, such as a header, footer, or navigation bar, that can be reused in other pages. For example, you might put a common element such as a graphic or a Search field in a page fragment and then include that fragment as a header in all pages in the application. You might also include your company name and copyright information in a page fragment and use that fragment as your application's footer. Like a main page, a page fragment is a JSP page with its own associated page bean; however, the file extension of a page fragment is jspf instead of jsp.
jspf
jsp
You begin this tutorial by creating the home page for the application. You then create a header fragment and a navigation fragment and include these fragments in the home page.
Create a new web application project and call it FragmentExample. Enable the Visual Web JavaServer Faces framework.
FragmentExample
The following figure shows the page that you will create in the steps that follow:
From the Layout section of the Components Palette, drag a Page Fragment Box component onto the upper left corner of the page.
Click Create New Page Fragment. Type CompanyLogo in the Name field and click OK.
CompanyLogo
<div>
Click Close to close the Select Page Fragment dialog box.
Navigation
Welcome to Sky Company
Title
Sky Company Home
Now you define the content of the CompanyLogo fragment, as shown in Figure 2. Any changes you make to a fragment must be made in the fragment itself, and not in the page.
Open the CompanyLogo fragment by double-clicking the component in the Visual Designer.
Width
720px
Height
120px
In the Properties window, click the ellipsis button for the Image's url property. Add the company logo to the page fragment as follows:
url
sky.jpg
Next you define the content of the navigation fragment.
150px
100px
id
homeLink
/faces/Page1.jsp
Company News
Set the Hyperlink's id property to newsLink and the url property to /faces/News.jsp.
newsLink
/faces/News.jsp
In this section, you create a second page that includes the header and navigation fragments. You set a background color for this page to demonstrate how the page's style settings are inherited by a page fragment.
In the Projects window, right-click the FragmentExample > Web Pages node and choose New > Visual Web JSF Page. Name the new page News and click Finish.
News
The News page opens in the Visual Designer. You will design the page shown in the following figure.
div
jsp:directive.include
form1
Page1.jsp
We have a new CEO
Sky Company News
Click the ellipsis button for the Background property and use the color chooser to set the color to light yellow. At runtime you will be able to see a clear distinction between the Sky Company News page and the Sky Company Home page.
Background
Note: NetBeans IDE 6.1 features on-demand attribute binding. You must manually add a binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.
In this section you add code to disable the Home link on the Page1 page and the Company News link on the News page.
Add the following code to the prerender method:
prerender
public void prerender() {
Navigation navigationFragmentBean = (Navigation)getBean("Navigation");
Hyperlink homeLink = navigationFragmentBean.getHomeLink();
homeLink.setDisabled(true);
}
Right-click in the Java Editor and choose Fix Imports. The IDE adds the following import statement:
import com.sun.webui.jsf.component.Hyperlink;
Add the following code to the prerender method.
public void prerender() {
Navigation navigationFragmentBean = (Navigation)getBean("Navigation");
Hyperlink newsLink = navigationFragmentBean.getNewsLink();
newsLink.setDisabled(true);
}
Click the Run Main Project button
to run the application.
This tutorial demonstrates how to use page fragments in a simple two-page application. A real application typically has more pages.
Try It. Add a third page to the FragmentExample application. Be sure to add another Hyperlink component in the Navigation page fragment and set the Hyperlink's url property.
Try It. Another common use for a page fragment is to include a company's copyright information. Add a page fragment at the bottom of each page with width of 720px and height of 100px. Include copyright information such as Copyright 1994-2008 Sky Company.
Here are some things to consider when using page fragments:
The example in this tutorial uses Hyperlink components with their url property set. This approach is recommended for its simplicity, because it does not require you to set the immediate property or set up page navigation. An alternative is to create a page fragment containing a Button or Hyperlink component with its action property set. In this case, you must set the immediate property and also set up the page navigation for each page that uses the fragment.
immediate
action
<from-view-id>
/Page1.jsp
/*
Bookmark this page | http://www.netbeans.org/kb/60/web/pagefragments.html | crawl-001 | refinedweb | 883 | 57.37 |
lua-l archive
[
Date Prev
][
Date Next
][
Thread Prev
][
Thread Next
] [
Date Index
] [
Thread Index
]
Subject
:
Re: ANN: luaSub 0.41 syntax front-end
From
: Fabien <fleutot+lua@
...
>
Date
: Tue, 22 Jan 2008 14:27:31 +0100
About luasub/metalua comparison:
First and foremost, both systems don't have the same purpose: metalua's core is about compile-time meta-programming, i.e. it tries to provide the best possible abstraction level and manipulation toolkit to analyze, modify and generate programs as data. One of the features required to do so is a dynamically extensible parser, which means that metalua has all the syntax tweaking features you might want, but that's just the gateway to metalua, not its core.
Your typical metalua extension will spend 80% of its code doing tree matching or code walking on AST, reading and generating trees, and maybe have a dozen lines or so of syntax extension glue at the end, to offer easy access to the features from source files. The focus is on code as data, not on syntax: syntax is boring, and is a very bad representation for automated manipulation, so you want to get rid of it in your extension's design ASAP. As a rule of thumb, if the core of your extension contains references to concrete syntax matters, you've screwed up somewhere.
As you noticed, metalua is a more complex framework to master than a "simple" preprocessor, and there certainly is a learning curve to follow before you can do interesting stuff. The thing is, most of these interesting stuff are not practically doable with a simple preprocessor. If you want to polish a syntax extension to the point where it's as reliable as a native Lua feature, you'll always have to fight some corner cases which require advanced code analysis. So metalua makes it possible to write robust macros, and the price to pay is, quick and dirty hacking without reading the manual is difficult.
Apart from robustness when provided with correct code, you want a compiler to provide helpful error messages when fed with syntactically incorrect sources; that's something most preprocessors fail miserably. This, together with macro robustness, is a strong requirement if you want to get distributable, reusable extensions. Trust in the extensions' robustness, not milliseconds saved on compilation time, make a meta-compiler usable or not.
A couple of examples of why writing usable macros is not so easy: if you're writing a "do...end as function" or "try...catch" extension, you want it to react correctly to embedded return statement, and ideally to coroutines. If you decide not to handle those, you want to emit a proper error message, at compile time for static stuff such as returns, at runtime for coroutine stuff.
If you're writing a runtime type checking extension, you want to give type to variables, and re-check their content every time they are re-assigned. You want to do that without being fooled by variable names capture. You want to check the values returned by each return statement in a function, without being fooled by local functions and their own return statements. You want your type assertions to live in a separate namespace, and still be expressive enough to support polymorphism, dependent types etc.
In most extensions, you want to avoid accidental variable capture. This includes internal capture (the kind you usually get with C macros), but also external captures, where it's the user's code that captures the macro's variable. For instance, if your macro uses the global function type() and I decide to use it within a block "do local type = 'foo'; $CALL_THE_MACRO() end", I want it to work, and without requiring me to know how your macro is implemented. This is just another instance of lexical scoping, and it is as important for macros as for regular code, if not more.
(End of examples)
A couple more words about compilation speed: either you're working on some embedded device with a CPU speed < 10MHz, and then you'd better precompile your Lua scripts on a development PC, or you have a PC less than 15 years old, and you can compile your source files on-the-fly without a significant overhead. With a lower-end notebook and the standard meta-libraries precompiled, I've never felt a significant compilation overhead. I really can't see the purpose of shaving more compilation time, especially at the expense of code maintainability. The same remark applies to memory consumption: there are cases where you care about the VM's consumption, but in such cases you precompile anyway so compiler consumption is not relevant.
About "Cons: non-Lua looking syntax": the very point of an extensible language is that you can make it map your problem space better (you've probably read Paul Graham's Lisp evangelism about this). Meta-programming is definitely a complex task that deserves significant syntactical support; I understand why some people want to stick to vanilla syntax whatever the task at hand, but those people don't want a static meta-programming system, period. If you want something that looks like Lua, stick to plain Lua, it's the global optimum by definition.
Finally, in your list of preprocessors, you have forgotten Luma, which is IMO the best simple approach (metalua being the best comprehensive one). It's essentially a term rewriting system, built on simple and quickly understood principles. It doesn't let your macros look like parts of the core language, which is consistent with the fact that it doesn't give you the tools to make them as robust as core features. So within its application domain, it has a consistent and usable design.
-- Fabien.
PS: if you're not bored with my logorrhea yet, you can read my PoV on metalua vs. luma at
.
Follow-Ups
:
Re: ANN: luaSub 0.41 syntax front-end
,
Fabien
References
:
ANN: luaSub 0.41 syntax front-end
,
Asko Kauppi
Prev by Date:
luagd small compile bug
Next by Date:
using Lua from Objective-C
Previous by thread:
ANN: luaSub 0.41 syntax front-end
Next by thread:
Re: ANN: luaSub 0.41 syntax front-end
Index(es):
Date
Thread | http://lua-users.org/lists/lua-l/2008-01/msg00474.html | CC-MAIN-2017-51 | refinedweb | 1,042 | 57.3 |
1. Introduction
Dot net remoting is client and server based distributed object technology. In this first article about dot net remoting, we will create two applications. One is a remote server application and another one is a client application. We will go ahead and start creating the applications and I will give the explanation when we are developing the example.
2. About this Example
The server we are going to create is a console application. This console application will host our remote objects on the server. The client will make a call to the public members (Usually function) exposed by that remote object(s).
The client is a windows form application, which will get access to the remotely hosted objects and start using it. Below is the screen shot of the client application., Customer Name, Last Deposit and Last Withdraw from the remote object LastTrans. I will explain other concepts when provides access to the dot net remoting API.
4) Next, add a class named LastTrans to the Project. Add one more class and name it as RemCustomer.
Explanation
We have created a console application project and then got access to the dot net remoting assemblies. Then we added classes to the project. RemoteObject is the one which will keep in the Server’s memory. And LastTrans object is created on the server but it will be sent to the client through serialisation using the RemoteObject.
"Serialisation" is a technique, which converts your class in the form of "bit streams" and these steam in the receiving end is collected to form the actual object. In our example, we are going to send the LastTrans to the client through serialisation .
All the skeleton code for our server is kept ready by the IDE. Now we will go ahead and add code.
4. The LastTrans Class
1) Locate the LastTrans class created by the IDE and Mark it as "Serializable" by adding the serializable attribute before the class. Below is the code for it:
//RemoteServer_018: Make the Class Serializable [Serializable()] public class LastTrans
2) Add a private variable to this class.
//RemoteServer_011: Private field for the Newly added class private int LastDeposit; private int LastWithdraw;
3) In the constructor initialize the above declared private variables. Note that here I hard-coded the values. In the real world, it will be queried from the database to get the latest result. Below is the code:
/; }
4) Next, provide a function to return the private variables. The client uses these functions to get the Last Deposit amount and as well as Last Withdrawal amount.
/.WriteLine does not print anything on our Remote Server. Because the object is serialised and sent to a client. The client creates this object and subsequent call on the object gets executed on the client machine.
5. The RemCustomer Class
1) Include the below-specified namespace.
//Remote_003: Include the Namespace using System.Runtime;
2) This class acts as the remote object. To make the IDE created object remote server compatible, (Refer Step 4) locate the class and derive it from the "MarshalByrefObject". OK. Why that derivation is required. It is required as we are planning to keep this object in server’s remote pool. Below is the Second step of the code:
//RemoteServer_004: Make the class Remotable by inheritance. public class RemCustomer : System.MarshalByRefObject
3) Next, declare the members of this class. Note our remote object is going to serve the client through standard as well as user-defined data types. User-defined type here in our case is.
/ also ready to serve the windows form based client. Note that the MarshalByrefObject states that this RemCustomer will reside on the server and a reference to it will be sent to the client. The client calls that reference as a "proxy". We will move to our last step, which is the program entry point of a console application.
6. Hosting the Remote Object on the Server
1) Locate the static void main, which is the program entry point for the console application. In the top of the file (Program.cs if you had not changed the file name) include the assemblies as shown. Below is the code:
//RemoteServer_001: Required Assemblies using System.Runtime; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp;
2) Next, a "TCP channel" with a "port number" 13340 is created and registered in the server machine. The client application will use this port to communicate with the remote object. The below code creates a TCP communication channel and registers that with the server machine in which the server application is going on the server machine. The first parameter to the function specifies the type of the object that is registered. The second one gives a unique name for the registered object. I do keep the registration name same as the class name. But, you can use a different name. The client should use the same name when they ask for the Proxy of the remote object. The third parameter says how the server your server. We will now move on creating the Client. Below is screen shot:
Note: The remote object is not created as the activation method is SingleCall. For each client call, a separate instance of the remCustomer will be created and kept in the remote object pool.
7. Prepare the Client Application
As you already know a client is a Windows form application. Follow the steps below to create the client application that uses the remote object hosted by our console server.
Make sure the Console server project is still in open state.
- Click on File|Add|New Project.
- Select Visual C# in the project Types and Select Windows Application from the available template.
- Name the project as RemClient and click ok.
- Design your form by referring the first screen shot. Download the attached project for your reference and set the properties by referring it. ConServer.sln will open both the project. In your case, this solution will be created now as you are adding one more project. A solution file is a combination two or more projects.
- Add reference for Remoting assembly as you did in the server step 3.
- Once your form is designed, double click the Button control to get the Click event handler for it.
- Right click the RemClient Project and select add reference. Go to the project tab and select ConServer Project.
Explanation
In the above steps, you created a windows application and designed the form. You added a reference to the Dot net’s Remoting assembly and added a reference to the ConServer application. If we use the interfaces we can avoid this project reference. We will see that in a separate article.
8. Start coding the client
1) First, include the below-specified Name Spaces on top of the file which has the click event handler for the button. The code is below:
//RemoteClient_001: Include the required namespace using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; the Local or Remote machine. Below is the code for doing that:
/ server object then the server developers usually provide the interface. By doing that the server piece of implementation not revealed to the client developers. In our case, let us assume the same party develops server and the client.
The Second string parameter has three parts on it. The first one is machine name. As the client and server applications are on the same machine, I kept localhost instead of specifying the machine name. If the Server application is running on the machine name say; C-AshCorner_01 then the localhost in the string should be replaced by the machine name; that is; C-AshCorner_01. Note one can also use the IP address of that machine.
Well. The client now knows which machine it need make a connection to get the RemCustomer proxy. But the server may an own dedicated port. Our application server registered the port 13340 saying “This port is in use like 80 for HTTP”.
Our client application by specifying this port number next to the machine name, sets-up the communication for a connection request. The last part specifies the registered name of the remote object. Look at Section 6 point 3.
Finally, we performed a type cast and stored the proxy in the remoteCust.
In summary to get the remote object,
1) First, a machine name in the network needs to be resolved
2) A port number that specifies which particular Server Application needs to be contacted.
3) The registered name specifies a single object type upon several registered remote objects (We registered only one)
3) Once the proxy is with us, make a call to the functions through a proxy. Note proxy just shows that the object is with you, but it is not. All the call is transmitted to the server to get the result. Below is the code, which makes use of the proxy object to make a call on the public functions, exposed by the remote object.
9. Testing the Application
Test it on Same Machine
1) Right click the solution and Click rebuild all.
2) Now navigate to both the exe using windows explore.
3) Run the Console Server
4) Run the Windows application
5) Click the button on the Windows application and Observe the result on the Client.
To Test it on different Machine, Place the Server project on the different machine. Keep the Client on your machine. Search for localhost in the client project and replace it with your machine name or IP Address. Run the Server first and then the client.
Below is the screen shot when Run both the application in the same machine. | http://www.mstecharticles.com/2010/12/ | CC-MAIN-2018-13 | refinedweb | 1,619 | 66.23 |
Having multiple App names while sharing AppResources
A solution is given how to share resources between multiple versions of an app but allowing for some differences like the app name or an icon.
Introduction
In order to keep multiple versions of an app it is desirable to share as much code and resources as possible. Resources present a special problem.
Problem details
Being a good WP citizen one creates multiple versions of the same app:
- a Windows Phone 7 free version,
- a Windows Phone 8 free version with extended features
and optionally
- a paid Windows Phone 8 version and maybe even
- a paid Windows Phone 7 version.
You localize it in half a dozen languages to reach as many customers as possible.
To reduce work and keep the app maintainable, it is desirable to share as much code and resources between the versions as possible. Sharing code and resources via the 'Add as Link' method in Visual Studio (Share code with Add as Link) is relatively easy. The problem starts when the differences between the versions have to be implemented.
Code differences can be made by defining a preprocessor directive on the project's property page's build tab:
In code this can then look as follows:
#if !PROVERSION
pivotcontrol.Items.RemoveAt(2);
#endif
This is easy. But how can you create slightly different resources? Unfortunately, preprocessor defines can't be used with resources. So there has another way to be found to differentiate resources for versions of the app.
An example
Say you have an app named 'TestApp' that you implement first for WP7. You then want to have a WP8 version and you share code and resources via 'Add as Link'. For additional features in the WP8 version you create some new strings in the AppResource. Those are simply not used in the old version. So far so good. No problems yet.
Then you get the idea to earn some money and build a paid Pro version with exciting additional features. You name it 'TestApp Pro'. Now you got a problem. You don't want to copy the resources as you have 6 localized resource files. And all this for one or two different strings, namely the app name and maybe the app icon source!
The solution
I imagine at least two different ways to solve this dilemma:
- Implement a datasource in code that gives different strings for the different versions (you can use preproc defines here) or
- implement a value converter (see Collection of Value converters for Windows Phone apps) that filters your strings and replaces the original app name with the Pro app name.
A sample for the first method is this implementation of the LocalizedStrings class that returns a different path dependent on a preproc define:
public class LocalizedStrings
{
private static AppResources localizedResources = new AppResources();
public AppResources LocalizedResources { get { return localizedResources; } }
public string AppIconSource
{
get
{
#if PROVERSION
return "images/testapppro99.png";
#else
return "images/testapp99.png";
#endif
}
}
}
To show the app icon you can use the following XAML:
<Image x:
Now we come to the second idea how to get different strings from the same resource file. The second solution employs an AppTitleConverter to replace occurencies of the simple app name with the Pro app name:
public class AppTitleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
#if PROVERSION
return value.ToString().Replace(AppResources.ApplicationName, AppResources.ApplicationNamePro);
#else
return value;
#endif
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
All you need are two strings for the app names, ApplicationName and ApplicationNamePro.
Then you can reference the app name in XAML as follows:
xmlns:local="clr-namespace:TestApp"
...
<phone:PhoneApplicationPage.Resources>
<local:AppTitleConverter x:
</phone:PhoneApplicationPage.Resources>
...
<TextBlock x:
Summary
Two ways are shown how to use slightly different strings while maintaining sharing of resources between multiple versions of an]]
Manikanthr - A great solution to create multiple apps
Hi, Thanks for this article as this helped me to achieve non-duplication. I will explain my problem, which is pretty much similar to your problem statement, I have referred all of my classes(Mainpage.xaml, Page01.xaml, Page02.xaml and their corresponding .cs files). My sub-project does not have any classes, which I have referred from base. Now I want to use the sub project's resource file to read data. Basically it is AppResources.resx file, how do I get string value from the sub-project's AppResources in my project.
Please do let me know, if I have to provide any extra explanation.Thanks and really humbled by the way I'm finding my problem solutions here :)
manikanthr (talk) 07:40, 22 January 2014 (EET)
Influencer - yes
Basically it's the same process with resx files as with xaml and cs. You add the resources as link. You'll need a link to the LocalizedStrings class, too. The problem is just that you can't do special handling in the resources depending on a proproc define. HTH,Thomas
influencer (talk) 09:54, 22 January 2014 (EET)
BuildNokia - Useful article
Hi Thomas and Manikanthr,
This article has the potential to be useful to a lot of people; especially as evidenced by the recent discussion about it, and by the fact that Manikanthr found the solution to his problem here.
I think that there is more we could add to this article to make it even more useful. First of all, I would broaden the scope; what you're really talking about here is sharing code and resources among different apps. So I would probably change the title to be something closer to what the discussion thread is called, maybe even the same thing "Performing code reuse in Windows Phone 8".
I might suggest structuring it as follows:
Introduction (and then merge "Problem Details" into this as well)
What type of data can be shared (code, resources, resx files) and what cannot (dataTemplates, styles)
For example it seems that you can't share code between WinRT and WP because they use different UIs.
Sharing code within the same namespace vs. sharing code between different namespaces
Referring to a child's resources vs. referring to a parent's resources - what are the differences?
Types of things that make code more reusable (using a pure MVVM implementation)
What might affect this (whether the apps share the same UI namespace)
Ways to reuse code
For each method give instructions for how to do it, what kind of data this is best suited for, any kinds of data this is not suited for, and anything specific the developer should know.
Next, a "Case Study" section that shows the examples that are already in the wiki.
Finally, a "Resources" section that references:
Would either/both of you be willing to incorporate that feedback into the article?Jen
BuildNokia (talk) 02:33, 29 January 2014 (EET)
Influencer - Will do...
I started researching articles and already found some very interesting links. Will write an overview when I'm ready.Thomas
influencer (talk) 19:40, 5 February 2014 (EET) | http://developer.nokia.com/community/wiki/Having_multiple_App_names_while_sharing_AppResources | CC-MAIN-2014-35 | refinedweb | 1,180 | 52.8 |
using functional tests for my API. Even with the nice Swagger frontend, it's almost faster to write a test than it is to try things manually... over and over again. To make writing tests even nicer, I have a few ideas.
Inside
src/, create a new directory called
Test/. Then, add a new class:
CustomApiTestCase. Make this extend the
ApiTestCase that our test classes have been using so far. If you're using API platform 2.5, the namespace will start with the
ApiPlatform\Core namespace.
We're creating a new base class that all our functional tests will extend. Why? Shortcut methods! There are a lot of tasks that we're going to do over and over again, like creating users in the database & logging in. To save time... and honestly, to make each test more readable, we can create reusable shortcut methods right here.
Start with
protected function createUser(). We'll need to pass this the
$password we want... and it will return the
User object after it saves it to the database.
Go steal the logic for all of this from our test class: grab everything from
$user = new User() to the flush call. Paste this and, at the bottom, return
$user. Oh, and we need to make a couple of things dynamic: use the
$password variable. This will temporarily still be the encoded password... but we're going to improve that in a minute. For the username, let's be clever! Grab the substring of the email from the zero position to wherever the
@ symbol is located. Basically, use everything before the
@ symbol.
We're also going to need to log in from... basically every test. Add a
protected function logIn(). To accomplish this, we'll need to make a request... which means we need the
Client object. Add that as the first argument followed by the same
string $email and
string $password, except that this time
$password will be the plain text password. We shouldn't need to return anything.
Let's sharpen our code-stealing skills once again by going back to our test, copying these last two lines, pasting them, and making
$password dynamic.
Woo! Time to shorten our code! Change the test class to extend our shiny new
CustomApiTestCase. Below, replace all the user stuff with
$this->createUser('cheeseplease@example.com') and... aw... dang! I should have copied that long password. Through the power of PhpStorm... undo.... copy... redo... and paste as the second argument.
Replace the login stuff too with
$this->login(), passing
$client that same
cheeseplease@example.com and the plain text password:
foo.
Let's check things! Go tests go!
php bin/phpunit
If we ignore those deprecation warnings... it passed!
Ok, this feels good. What else can we do? The weirdest thing now is probably that we're passing this long encoded password. It's not obvious that this is an encoded version of the password
foo and... it's annoying! Heck, I had to undo 2 minutes of work earlier so I could copy it!
Let's do this properly. Replace that huge, encoded password string with just
foo.
Now, inside the base test class, remove the
$password variable and replace it with
$encoded = and... hmm. We need to get the service out of the container that's responsible for encoding passwords. We can get that with
self::$container->get('security.password_encoder'). We also could have used
UserPasswordEncoderInterface::class as the service id - that's the type-hint we use normally for autowiring. Now say
->encodePassword() and pass the
$user object and then the plain text password:
$password. Finish this with
$user->setPassword($encoded).
Beautiful!
And this point... I'm happy! Heck, I'm thrilled! But... I do have one more shortcut idea. It'll be pretty common for us to want to create a user and then log in immediately. Let's make that easy! Add a
protected function createUserAndLogIn()... which needs the same three arguments as the function above:
$client,
$password... and we'll return the
User. Inside say
$user = $this->createUser() with
$password, then
$this->logIn() with
$client,
$password. At the bottom,
return $user.
Nice! Now we can shorten things a little bit more:
$this->createUserAndLogIn().
Let's try it! Run:
php bin/phpunit
All green!
Looking back at our test, the purpose of this test was really two things. First, to make sure that if an anonymous users tries to use this endpoint, they'll get a 401 status code. And second, that an authenticated user should have access. Let's add that second part!
Make the exact same request as before... except that this time we should have access. Assert that we get back a 400 status code. Wait, why 400 and not 200 or 201? Well
400 because we're not actually passing real data... and so this will fail validation: a 400 error. If you wanted to make this a bit more useful, you could pass real data here - like a
title,
description, etc - and test that we get back a 201 successful status code.
Let's try this!
php bin/phpunit
It works! Oh, but one last, tiny bit of cleanup. See this
headers key? We can remove that... and we have one more in
CustomApiTestCase that we can also remove.
But wait... didn't we need this so that API Platform knows we're sending data in the right format? Absolutely. But... when you pass the
json option, the Client automatically sets the
Content-Type header for us. To prove it, run the tests one last time:
php bin/phpunit
Everything works perfectly!
Hey! This is a great setup! So let's get back to API Platform security stuff! Right now, to edit a cheese listing, you simply need to be logged in. We need to make that smarter: you should only be able to edit a cheese listing if you are the owner of that cheese listing... and maybe also admin users can edit any cheese listing.
Let's do that next and prove it works via a } } | https://symfonycasts.com/screencast/api-platform-security/rock-solid-test-setup | CC-MAIN-2021-31 | refinedweb | 1,012 | 78.25 |
Pro PHP Security
samzenpus posted more than 7 years ago | from the keep-it-secure dept.105
Michael J. Ross writes "The global accessibility of Web sites is a double-edged sword: At the same time that your online e-commerce site is open for business to anyone with an Internet connection, it is also open to malicious attack. Web sites." Read the rest of Michael's review. Web site, Web site Web sites Web sites, as well as the countermeasures that should be adopted by the developer or maintainer of the site. First up is validation of user input, which — though being essential to basic security — is still neglected on far too many Web sites. Web site Web site.
Michael J. Ross is a freelance writer, computer consultant, and the editor of the free newsletter of PristinePlanet.com."
You can purchase Pro PHP Security from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.
Observation on Competitors (3, Informative)
SB_SamuraiSam (962776) | more than 7 years ago | (#15745663)
Here is an observation: With all the publicity Ruby on Rails [rubyonrails.org] and other frameworks like Zend Framework [zend.com] , Turbogears [turbogears.org] and the like are receiving these days--why are we not seeing an innumerable number of security trolls like Chris Shiflett on the *framework side of web development? My thoughts are that PHP users are told "you can too" when in many cases, with forums other resources like the ten gazillion books, they *can*, to an extent (but either with really bad help or books assuming the reader is not working on a *real* project).
Conversely, Rails, Turbogears and Symphony are, too, saying "you can too." Yet, where are the security trolls? It seems though that the *actual* users of the *frameworks, the ones using them for real-life projects are those who have struggled with PHP and (perl, python, etc...) CGI programming for so long and decided "fuck it." Things like database abstraction (and therefore quoting, etc), single-entry-point, and template-safety are, in the most part, taken care of for you.
P.S. XSS is not a PHP problem!
Re:Observation on Competitors (2, Interesting)
guruevi (827432) | more than 7 years ago | (#15745731)
A good programmer can also make mistakes, but if there is a decent thinking person and a small plan, then it will imho be just as good as those frameworks. The other thing is that you learn a lot and if you have a problem, you can take care of it yourself because you know how you think.
Re:Observation on Competitors (2, Insightful)
hey! (33014) | more than 7 years ago | (#15745862)
For example, Microsoft's infamous Foundation Classes (MFC) relies heavily on IDE wizardry and arcane preprocessor abuse to make things "simple".
On the other end of the spectrum, RoR just generates straightforward code using a sensibly chosen patterns. If somebody handed you the output of RoR, and you'd never heard of RoR, it would be perfectly readable and maintainable. RoR (or any framework for that matter) can't solve your problems for you; from what I've seen this is particularly true around security. But RoR is nice becauseit takes care of a some of the repetive work of your application in a way that doesn't create problems.
Thinking is the key concept (1)
suggsjc (726146) | more than 7 years ago | (#15746233)
Unfortunately, this is not a luxury that some website owners/creators have the luxury of...
On a more serious note. At lot of sites are "set it and forget it." Probably less that actually do e-commerce (or any volume of it). But I even do it every now and then...I just updated my libraries and packages, so its all good, nothing to worry about. Then a week goes by, a month...and the window is opened.
Maintaining a secure site and code base is a constant battle. And again unfortunately again one that most tend to either forget or ignore.
Re:Observation on Competitors (1)
SB_SamuraiSam (962776) | more than 7 years ago | (#15746344)
Re:Observation on Competitors (1)
Dzonatas (984964) | more than 7 years ago | (#15746492)
Forgot?!?!
Besides the SQL insertion hype, there are many web applications that serve inserted content into documents without any further validation. There was an article about RFID, "Virus Jumps to RFID [slashdot.org] ," and it is like RFID in this sense of validation. Someone scans, or http-gets, for data and it is served. The data actually might come from the expected object/webserver, but there may be other data inserted along with it. Did someone forget to check such inserted data?
Try to get a solid XHTML application to run on PHP. The problem is the PHP strings aren't easily validated when they are just kinda thrown into a document. If someone enters an ampersand and it echos to an XHTML page, it'll cause the client program to just display an error. With a nightmare of code, it is possible to get PHP to work well with XHTML. It is possible to test for the ampersand and properly handle it, but there are other environments without the code nightmare to do it.
Most of the HTML sent out over the web is not even validated before it is sent. The client app is left to validate it. However, how is the client app suppose to know where the source of the data came from a secure validation process or not? It just validates if the document is well-formed. Most HTML transitional processors don't even check if it is well-formed. They just display whatever it can figure out from what's given.
It appears that RFID is not the only application affected by such validation quirks. FUD or not, this RFID 'virus' example parallels a perfect picture of what happens with web pages. Both need more security.
Is it a problem with the webserver instead of PHP? The webserver is just designed to serve the content. A system like Apache could have a post processor to check every page before it actually is sent and detect security issues before it gets to the client. That still doesn't solve many issues. PHP or any other framework needs to validate the input. After you notice what needs to be done in PHP in order to get such validation secure, the competition does look greener.
Re:Observation on Competitors (0)
Anonymous Coward | more than 7 years ago | (#15748544)
Re:Observation on Competitors (0)
Anonymous Coward | more than 7 years ago | (#15746710)
Re:Observation on Competitors (2, Funny)
tbannist (230135) | more than 7 years ago | (#15752144)
No exception? (3, Funny)
ShaunC (203807) | more than 7 years ago | (#15745692)
PHP is broken... (-1, Flamebait)
Anonymous Coward | more than 7 years ago | (#15745753)
Re:PHP is broken... (1, Informative)
Anonymous Coward | more than 7 years ago | (#15745779)
Re:PHP is broken... (3, Informative)
John Nowak (872479) | more than 7 years ago | (#15745846)
Re:PHP is broken... (1)
KIFulgore (972701) | more than 7 years ago | (#15746186)
Re:PHP is broken... (1)
John Nowak (872479) | more than 7 years ago | (#15746258)
Re:PHP is broken... (0)
Anonymous Coward | more than 7 years ago | (#15746248)
Re:PHP is broken... (1)
xaraya (635792) | more than 7 years ago | (#15746506) [htdp.org]
Nice tip! (1)
-noefordeg- (697342) | more than 7 years ago | (#15746945)
Other books, albeit not free (to my knowledge):
-Design patterns : elements of reusable object-oriented software, Erich Gamma, ISBN: 0201633612
-Patterns of Enterprise Application Architecture, Martin Fowler, ISBN: 0321127420
Would really enjoy some more free information.
Re:Nice tip! (1)
Reverend528 (585549) | more than 7 years ago | (#15747300)
Re:Nice tip! (1)
John Nowak (872479) | more than 7 years ago | (#15747309)
Step 2: Structure and Interpretation of Computer Programs ()
Both are available online in full text from MIT Press. I personally feel everyone has something to gain from these books, even if you have twenty years experience. Not that I do yet -- It's a projection.
Re:PHP is broken... (0)
Anonymous Coward | more than 7 years ago | (#15745850)
Re:PHP is broken... (0)
Anonymous Coward | more than 7 years ago | (#15745913)
PHP: Get over it (1)
tehshen (794722) | more than 7 years ago | (#15749063)
I remember (ah, memories) when I discovered PHP. I thought it was brilliant. I could write dynamic web pages! Wow! I had variables, and for loops, and while loops, and all sorts. It was amazing! Then I got a database up and running, and could actually make a site, o frabjous day, calloo, callay! This was back when PHP was all I knew, apart from BASIC, which isn't saying much.
I was so impressed with what I could be doing with PHP that I overlooked all the things I didn't like. I didn't understand why the function naming was so inconsistent. Why sometimes my program couldn't see its variables. Heck, I was using hosting from Lycos Tripod, which was a complete pile of gibs, but it was worth it 'cause I could make dynamic web sites, and it was good.
We were happy, PHP and I. Why should I go and learn another language when PHP was accomplishing what I wanted just fine, thanks?
The answer is that I was lazy. Yes, I'm admitting that I was a big lazy fat-ass, to use a stupid term. I couldn't be bothered to learn another language, even though there were plenty out there. I thought that PHP was the best language there was. In the end, though, I gave in and dabbled in Python and Ruby, then gave up and went back to PHP again, then really gave in this time and went to Ruby for web development. (Then Rails came along... which was nice, though I'm not fond)
These days, I look at PHP and go "bleh". While it was alright to keep looking at the docs when I was learning the language, it's not right if I keep having to look at them several years later to find out what function to use. I look at some of the 'features' and wonder what the hell they were thinking. PHP is so inconsistent that I wonder if the coders talked to each other as much as the Slashdot editors do. (By the way, I don't see what's so special about the PHP docs. Sure, it's nice that they exist, but pydoc and perldoc and ri beat them any day)
Y'see, I'm done with PHP now. While it was nice of it to help me get started on web programming, I realised that it wasn't the only thing out there, and learning Ruby has improved my hacking ability by great amounts.
Even if you're 100% in love with PHP right now, please take the time to learn something else. Python and Ruby are popular for the right reasons these days. It doesn't matter what you learn: toss a coin, use what your favourite Slashdotter uses; they're both better than PHP and can both be used to make web sites with. Maybe you'll like one of them. They'll teach you new ways of doing things, and make you question the old ways, such as why you have to use for loops instead of iterating over a range. If not, learn one anyway. It'll do you good.
PHP is the right tool for the right task (0)
mangu (126918) | more than 7 years ago | (#15746882)
You are either not a professional programmer or a troll or both. PHP is the best available language if what you need is a simple way of creating dynamic web pages that handle database access. One sees so many people making so many claims about Ruby this or Ruby that, but have you ever tried to compare both languages? Forget closures and block parameters, you don't need that to create a dynamic web site. What you need is a simple syntax that works well with existing editors and code management tools, and PHP provides that. Using a database abstraction library such as Adodb and a good development framework, such as phpGroupWare, creating simple applications is faster in PHP than in any other language. And easier to maintain, too.
Of course, if what you want is to create a theoretical study on some esoteric programming task, by all means use your precious lambdas and closures or whatever resources you have in Ruby or Scheme, but if you need to keep a team of junior programmers chugging out simple enterprise applications you should choose PHP, the tool that gets the task done.
Re:PHP is the right tool for the right task (0)
Anonymous Coward | more than 7 years ago | (#15746958)
Re:PHP is the right tool for the right task (3, Insightful)
VGPowerlord (621254) | more than 7 years ago | (#15748205)
The original poster has a point. I can think of a number of language features that were just plain bad ideas.
1. Providing an inconsistant programming environment, based on INI settings. This exacerbates the next two problems.
2. Having register globals turned on by default. First "fixed" in php.ini-recommended for PHP 4. Later fixed in php.ini-dist for PHP 4.2. Scheduled for removal from the language in PHP 6.
3. Having magic quotes GPC turned on by default. First "fixed" in php.ini-recommended for PHP 4. Scheduled for removal from the language in PHP 6.
4. Lack of a good database abstraction layer shipped with PHP. Although dbx and Pear DB both ship with PHP, neither is that commonly used. dbx due to being disabled by default; Pear DB due to its slowness. This is fixed in PHP 5.1 with the addition of PDO. Unfortunately, this is a case of too little, too late, as anyone who writes things for multiple DBs already uses ADODB or hand-rolls their own abstraction layer (coughphpBBcough).
Rather than waiting for a perl programmer to come along and post this url, I will: PHP in contrast to Perl [tnx.nl] . I know very well that this is slanted against PHP, but that doesn't make a lot of the comments in it any less true. Particularly since PHP 1 was written in Perl 5.
Re:PHP is the right tool for the right task (0)
Anonymous Coward | more than 7 years ago | (#15748391)
How about a tool that gets the task done right, instead. You PHP fanboys are so funny. You simply have no clue about what real, enterprise software is. Did they teach you all about PHP at Devry?
Dueling Oxymorons (2, Funny)
kelzer (83087) | more than 7 years ago | (#15745754)
MOD PARENT FUNNY (0)
Anonymous Coward | more than 7 years ago | (#15745868)
YES!!! I NEARLY WET MYSELF (1)
Unski (821437) | more than 7 years ago | (#15746019)
Re:Dueling Oxymorons (0)
Anonymous Coward | more than 7 years ago | (#15745886)
We all know that slashcode, since it is written in perl is the pinnacle of perfection. Nevermind that I have never seen a php application that cannot paginate threads in a comments forum properly, unlike slashdot. Let alone losing posts altogether in some views. And its fixed oh so quickly, its been like this for ages now...
So come on everybody, lets shit on php, we know we'll never tire of it.
Re:Dueling Oxymorons (1)
jbarket (530468) | more than 7 years ago | (#15745998)
Re:Dueling Oxymorons (1)
1iar_parad0x (676662) | more than 7 years ago | (#15754260)
Re:Dueling Oxymorons (1)
ToxicBanjo (905105) | more than 7 years ago | (#15746254)
Obvious Question about PHP (-1, Troll)
heauxmeaux (869966) | more than 7 years ago | (#15745774)
Top Edge PHP Attack (4, Funny)
digitaldc (879047) | more than 7 years ago | (#15745781)
This is because someone tried to do a physical attack on the top edge of the PHP Security book.
However, the Page's Horizontal Periphery security kept it from getting through.
Book's available for cheaper through Amazon (-1, Offtopic)
Anonymous Coward | more than 7 years ago | (#15745819)
Re:Book's available for cheaper through Amazon (1)
CRiMSON (3495) | more than 7 years ago | (#15745870)
Re:Book's available for cheaper through Amazon (0, Troll)
Drantin (569921) | more than 7 years ago | (#15747740)
Re:Book's available for cheaper through Amazon (0)
Anonymous Coward | more than 7 years ago | (#15748077)
User/role management (1)
knipknap (769880) | more than 7 years ago | (#15745838)
Are there any secure user/role management solutions that you can recommend? What are the advantages and where are the drawbacks? How du you solve user/role management in a reusable way?
Re:User/role management (1)
Bogtha (906264) | more than 7 years ago | (#15746073)
I don't know of any general-purpose libraries, but the latest version of Wordpress has a system [wordpress.org] like that that you could rip out.
Re:User/role management (1)
beavis88 (25983) | more than 7 years ago | (#15746194)
Downside: it probably won't work with PHP
Re:User/role management (3, Informative)
gnud (934243) | more than 7 years ago | (#15746499) [php.net] supports users from multiple sources (at the same time), group permissions and per-user-permissions.
Re:User/role management (1)
knipknap (769880) | more than 7 years ago | (#15746626)
Re:User/role management (2, Informative)
Anonymous Coward | more than 7 years ago | (#15747004)
On top of your script, do
ini_set('include_path', ini_get('include_path'). ":pear/");
Done.
I can't remember if it is include_path or something similar, but after 14 hours at work, I am not gonna look it up
Re:User/role management (1)
Achromatic1978 (916097) | more than 7 years ago | (#15748200)
PHPGACL? (0)
Anonymous Coward | more than 7 years ago | (#15746928) [wiki.cc]
i haven't implemented it, but i have filed it for a future perusing.
Re:PHPGACL? (1)
knipknap (769880) | more than 7 years ago | (#15748623)
Re:User/role management (1)
tolan-b (230077) | more than 7 years ago | (#15747213)
PEAR::Auth & PEAR::LiveUser (1)
HighOrbit (631451) | more than 7 years ago | (#15747251)
Try this :
Re:User/role management (0)
Anonymous Coward | more than 7 years ago | (#15748797)
(User A belongs to Group 1 and Group 2. Group 1 has access to Function I and Function II. Group 2 has access to Function III and Function IV.
Therefore User A has access to Functions I, II, III and IV.)
Pro PHP (-1, Troll)
iluvcapra (782887) | more than 7 years ago | (#15745839)
The problem with the alternatives to PHP (4, Insightful)
baadger (764884) | more than 7 years ago | (#15745859)
Ignoring support by ISP's there is are two main reasons I think from the developers perspective,
1) PHP's online documentation of both the core language it's standard libraries is comprehensive. I'm not even aware of where I could find documentation on Python libraries to communicate with MySQL, with PHP it's all shipped in the package and all documented in one place - php.net. One place I might add where users/developers can and do comment and actually make the documentation better and clearer (although some bad ideas get into the mix too, they are usually corrected by following comments). All the Python and Ruby documentation seems to be humped into two ends of the spectrum, 101 and web framework. Atleast this is the impression I get as someone once interested in Python for web development, after being spoilt for documentation at PHP it's just frustrating.
2) PHP allows you to inline your code into your documents (as does ASP) providing a, nasty, dangerous yet incredibly easy route for people from a web design background to get into web development without any programming knowledge. As these users develop, some will become well seasoned and actually start to seperate code from design. The rate at which people are being introduced to server side scripting and indeed PHP is, in my opinion, probably increasing and there is always, for that reason, alot of unsavvy PHP users.
It's also worth mentioning that to a certain extent, Ruby on Rails gems (which I haven't used personally) and Perl's CPAN solve some of the shortfalls, but Python seens way behind.
Re:The problem with the alternatives to PHP (2, Insightful)
Timesprout (579035) | more than 7 years ago | (#15745958)
Re:The problem with the alternatives to PHP (1)
baadger (764884) | more than 7 years ago | (#15746066)
I am however implicitly responding to posts that always arise saying "Don't use PHP! It's a shit poorly designed language use (Python|Perl|Ruby)".
Oh and I also disagree with PHP for anything but web applications. I'm glad you mentioned it.
Re:The problem with the alternatives to PHP (1)
mattyrobinson69 (751521) | more than 7 years ago | (#15746128)
echo "update x set y=y+1 where z=a" | mysql -uuser -ppassword mydatabase
just seems like a nasty hack.
I'm not saying it should be used for desktop gui apps though
Re:The problem with the alternatives to PHP (1)
kv9 (697238) | more than 7 years ago | (#15748772)
Re:The problem with the alternatives to PHP (1)
kevin_conaway (585204) | more than 7 years ago | (#15745966)
Re:The problem with the alternatives to PHP (2, Informative)
macx666 (194150) | more than 7 years ago | (#15747195)
Re:The problem with the alternatives to PHP (1)
John Nowak (872479) | more than 7 years ago | (#15745995)
Re:The problem with the alternatives to PHP (1)
Anthony Boyd (242971) | more than 7 years ago | (#15747053)
I guess the decision for those language developers would be, do we want to use our existing documentation system at the risk of marginalizing our language, or do we want to jump on the "Web-based with comments" bandwagon to entice a larger audience?
Note that an important part of the PHP documentation is the ability to type php.net/function into the browser, and get back a page with guesses as to what function you need to use. So php.net/array returns info on arrays, php.net/string returns info on strings, php.net/array_push returns the documentation for that particular function, etc. That would be an important part to implement, for anyone considering copying the PHP model.
Re:The problem with the alternatives to PHP (1)
destiney (149922) | more than 7 years ago | (#15747352)
100% Troll..
Re:The problem with the alternatives to PHP (3, Insightful)
Bogtha (906264) | more than 7 years ago | (#15746030)
That's the #1 issue by far. Even if all the competition were ten times better than PHP, if the average person can only find cheap PHP hosting, that's what they are going to use.
Seriously? Go to python.org. Scroll down the page to where you see the "Using Python for... databases" link. Click it.
There's another point - Python modules come with help built into them, and Python comes with a help browser [incutio.com] . And if you don't want to use that, just load the Python interpreter and run help(module). I don't think PHP has anything similar to that yet.
So does mod_python [modpython.org] .
Re:The problem with the alternatives to PHP (1)
baadger (764884) | more than 7 years ago | (#15746096)
"Pydoc is awesome; I don't know how I missed it for so long".
I think this only puts emphasis one of my points. Thanks for the links, I will be investigating Python myself thoroughly at some point, but my post is based on initial impressions of web development in other languages, something I think is obviously vital for the uptake of a language in web dev.
Re:The problem with the alternatives to PHP (1)
linvir (970218) | more than 7 years ago | (#15746345)
Well, my host runs mod_perl, and my local server runs mod_perl. I'd gladly learn to use Perl, if only I could figure out how to run a Perl script. With PHP, I simply suffix a file with
.php, and any code between PHP tags will be executed. Apparently, it's not this simple with mod_perl.
With bash, all I have to do is put #!/usr/bin/perl at the start of the file. But no matter what I try, I can't get Apache to execute any Perl code. The result? I continue to use PHP.
So I'd say availability is pretty important, but ease of use matters too.
Re:The problem with the alternatives to PHP (1)
kv9 (697238) | more than 7 years ago | (#15748784)
Re:The problem with the alternatives to PHP (1)
linvir (970218) | more than 7 years ago | (#15748986)
What? My webserver? As in, the one owned by the company who provide my hosting? Are you suggesting that I root their datacentre and reconfigure my account on the sly? Are you suggesting that they advertise themselves as providing mod_perl while leaving it completely unconfigured?
PHP has worked out of the box on both hosts I've used, and on every version of the XAMPP [apachefriends.org] package I've installed. Even on the vanilla Slackware Apache setup, all I have to do is uncomment the PHP line in
/etc/apache/httpd.conf.
As far as I'm concerned, PHP does work automagically. Which was my point: ease of use is important.
Re:The problem with the alternatives to PHP (1)
kv9 (697238) | more than 7 years ago | (#15751012)
then perhaps you should ask them for support instead of whining on slashdot that "perl is teh hard omgplz!11one"?
Re:The problem with the alternatives to PHP (1)
KidSock (150684) | more than 7 years ago | (#15747338)
Funny, I just did this and couldn't find it. I ended looking at some sourceforge boilerplate. I think the OP was pointing out that PHP has comprehensive and *consistent* documentation.
Re:The problem with the alternatives to PHP (1)
sgtrock (191182) | more than 7 years ago | (#15749182)
I just did the same thing. There's a sidebar named "Using Python for..." on the right hand side. "Databases" is the second entry:
# Databases
# ODBC, MySQL, Others
How much easier does it have to be to find?
Oh, wait. You don't like the fact that it links directly to the site for the plug-in, I take it. Too bad. If you had bothered to check the "Docs" link on the Sourceforge page, you would have seen a link to "How to Use MySQLdb", which states:
"MySQLdb is compliant with the Python Database API Specification version 2.0. You should become familar with this document before trying to use MySQLdb.
Additional HTML documentation is located in the doc directory of the source tarball. If you obtained MySQLdb/MySQL-python through a third-party vendor, they should have installed these files where they install other documentation. Typically this is in
In addition, MySQLdb is documented using Python documentation standards. This documentation can be viewed using pydoc or the help function in recent versions of Python. Example:
>>> from pydoc import help # not needed for 2.2 or newer
>>> help("MySQLdb")"
The reason that the "import help" statement isn't needed in >=2.2 is because it's embedded.
Re:The problem with the alternatives to PHP (1)
jbarket (530468) | more than 7 years ago | (#15746058)
Re:The problem with the alternatives to PHP (0)
Anonymous Coward | more than 7 years ago | (#15746346)
PHP allows you to inline your code into your documents (as does ASP) providing a, nasty, dangerous yet incredibly easy route for people from a web design background to get into web development without any programming knowledge.
I think you're being a bit closed-minded with that comment. For many of us, this is what made PHP great. I've used PHP for nine years, and this feature is why I started using it and why I continue to use it. I have several good web designers, but I can afford only one good programmer. I can have my web designers layout web pages and get customer approval then my programmer will add the parts of the screen that make the system dynamic. Obviously this won't work when you're doing something like an online store, but for most web sites it works very well. You get to easily combine the strengths of two very different groups of people.
Things like XML with XSL promise this same sort of division of labor, but the simple fact is I can find web designers to do HTML (with or without a helper program like Adobe Premiere) much easier than I can find designers that can write XSL.
Re:The problem with the alternatives to PHP (2, Interesting)
prockcore (543967) | more than 7 years ago | (#15746533)
1. Ruby is a bitch to get working with apache. You've got to either run fastcgi (which is out of date), or proxypass to another webserver. They need to fix mod_ruby so that each instance doesn't share namespaces.
2. Python is stable, but the modules are too fragile. The API for libxml2-python has changed several times... breaking any scripts using it.
Re:The problem with the alternatives to PHP (1)
TheLink (130905) | more than 7 years ago | (#15748147)
It's a simple and fairly clean way to accelerate CGI style apps. It's so simple it doesn't usually need to be changed even if your webserver changes.
You can run your fastcgi apps on apache and zeus.
The apache mod_xxx stuff is more likely to give you problems.
Re:The problem with the alternatives to PHP (0)
Anonymous Coward | more than 7 years ago | (#15746571)
I know I'm going to be beat up for including Python in that list, but it is in many ways the VB of open source. It has it's uses, but rarely (just as VB or PHP) does it produce great and maintainable apps. They do exist, but there are far better tools if you don't buy the hype (from any of the three).
Great programmers can do wonders in any of them, but great programmers usually use something else because it is *even better*. Great programmers can do wonders in anything.
What all of the three really have is lots of users. That makes them popular. It does not by any means make them good.
PHP (1)
Vexorian (959249) | more than 7 years ago | (#15746826)
Re:The problem with the alternatives to PHP (1)
Ankur Dave (929048) | more than 7 years ago | (#15747773)
At least for me, PHP was easier to learn than Ruby or Python because it borrows a lot of concepts from C++ and C. The learning curve for a language is really important in its acceptance because it's great to be able to use knowledge you already have to enter a new field (for me, web applications).
Obvious Reason (0)
Anonymous Coward | more than 7 years ago | (#15745877)
Chris Snyder is a liar and a fraud. (1, Interesting)
Anonymous Coward | more than 7 years ago | (#15746053)
I've owned this book for a while (3, Informative)
Fozzyuw (950608) | more than 7 years ago | (#15746131)
It's a good book to get started with PHP Security ideas. It has a lot of theory and explains a lot of issues. However, I don't like the examples or how the book uses the examples.
Often times I would have like to see a larger scale project outline shown, instead of just the theory. But, it was worth the purchase.
PHP ...Security? (0)
Anonymous Coward | more than 7 years ago | (#15746193)
PHP Bashing (0, Redundant)
bryxal (933863) | more than 7 years ago | (#15746295)
zen certified engineer? (0)
Anonymous Coward | more than 7 years ago | (#15747709)
Save $15.30 by buying the book here! (1, Interesting)
Anonymous Coward | more than 7 years ago | (#15746307)
Do No tuse Global variables! (2, Informative)
shareme (897587) | more than 7 years ago | (#15746349)
RadEverything is awful. (0)
Anonymous Coward | more than 7 years ago | (#15746605)
Re:Do No tuse Global variables! (0)
Anonymous Coward | more than 7 years ago | (#15750020)
LAMP vs .Net (1)
jt2377 (933506) | more than 7 years ago | (#15747019)
Good Stuff (1)
cheese-cube (910830) | more than 7 years ago | (#15747224)
This is a rather well written review and the book sounds rather solid although I am turned off by the abundance of theory. When it comes to learning programming languages I really prefer a more hands-on approach. This is one of the reasons why I chose to study website design at TAFE (Technical and Further Education for all you non-Australians) instead of university. Of course you can just skip all the theory, but I am unsure whether the theory is a required prerequisite to the practical sections.
Also does this book deal with only PHP 5 or does it cover older versions of PHP? My host only has version 4.4.2 and I am aware that there are many differences between version 4 and 5, especially security wise.
PHP Security in 5 sentences, Not 500 Pages (2, Insightful)
KidSock (150684) | more than 7 years ago | (#15747318)
First, you trim() and strlen() to make sure you have something. Then you use ereg to validate the hell out of it. Then you use the following function:
function quote_smart($value)
{
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
to prep the input for inserting into the DB. Finally, you call that in conjuction with sprintf to build the SQL you're going to call like:
$sql = sprintf("SELECT * FROM acct WHERE name=%s", quote_smart($name));
This looks like a lot of work but in practice it's really not that bad. Also, every website must do this. It's not like there's something wrong with PHP. Some environments might abstract this stuff a little but frankly I'd rather do it explicitly so that I know exactly what's happening.
Lack of PHP Security in 5 sentences, Not 500 Pages (2, Informative)
jani (4530) | more than 7 years ago | (#15748388)
For one thing, you're not protecting yourself from URL-encoded strings.
And since PHP doesn't yet support bind-variables (prepared statements) natively, looking at PEAR::DB [php.net] is a good idea; it saves you the hassle of quoting and whatnot.
You're also not dealing with the problem of XSS, since you've failed to deal with output to screen.
You are, in fact, not dealing with anything that's not related to MySQL.
Re:Lack of PHP Security in 5 sentences, Not 500 Pa (1)
metarox (883747) | more than 7 years ago | (#15748788)
That was all so 2001 (0)
Anonymous Coward | more than 7 years ago | (#15748600)
Ten Bucks Cheaper at Amazon (1)
madstork2000 (143169) | more than 7 years ago | (#15747534)
-MS2k
PHP security: not what you think (2, Informative)
rhowardiv (856443) | more than 7 years ago | (#15747794)
Haste makes waste (1)
Bostik (92589) | more than 7 years ago | (#15748145)
Scary thought. If you are implementing encryption (or any security measure, for that matter), the last thing you should be in is hurry.
nice but SELECT * is evil (0)
Anonymous Coward | more than 7 years ago | (#15748189)*isevil.html [parseerror.com]
for those that don't what I'm talking about.
Re:nice but SELECT * is evil (1)
nyctopterus (717502) | more than 7 years ago | (#15748955)
Re:nice but SELECT * is evil (0)
Anonymous Coward | more than 7 years ago | (#15749803) | http://beta.slashdot.org/story/70131 | CC-MAIN-2014-23 | refinedweb | 5,920 | 70.02 |
Testing as you may know is the process of validating and verifying that a piece of software or hardware is working according to the way it’s expected to work. Testing is a very important part of the software development life cycle (SDLC) as it helps in improving the quality of the product developed. There are multiple types and levels of testing, for example, white-box, black-box, unit, integration, system, acceptance, performance, security, functional, non-functional, and so on. Each of these types of testing are done either manually or through automation, using automation tools.
Test automation, as the name suggests, refers to automating the testing process. Test automation gives an advantage of running tests in numerous ways such as at regular intervals or as part of the application build. This helps in identifying bugs at the initial phase of development itself, hence reducing the product timeline and improving the product quality. It also helps in reducing the repetitive manual testing effort and allows manual testing teams to focus on testing new features and complex scenarios.
Table of Contents Introduction of TestNG Advantages of TestNG Installing TestNG onto Eclipse Creating Java Project with TestNG Dependencies Creating your first TestNG class Running TestNG test
Introduction of TestNG
TestNG, where NG stands for “next generation” is a test automation framework inspired by JUnit (in Java) and NUnit (in C#). It can be used for unit, functional, integration, and end-to-end testing. TestNG has gained a lot of popularity within a short time and is one of the most widely used testing frameworks among Java developers. It mainly uses Java annotations to configure and write test methods.
A few of the features that TestNG has over JUnit 4 are:
- Extra Before and After annotations such as Before/After Suite and Before/After Group
- Dependency test
- Grouping of test methods
- Multithreaded execution
- In-built reporting framework
It is written in Java and can be used with Java as well as with Java-related languages such as Groovy. In TestNG, suites and tests are configured or described mainly through XML files. By default, the name of the file is
testng.xml, but we can give it any other name if we want to. TestNG allows users to do test configuration through XML files and allows them to include (or exclude) respective packages, classes, and methods in their test suite. It also allows users to group test methods into particular named groups and to include or exclude them as part of the test execution.
Advantages of TestNG
Now let’s discover more features/advantages offered by TestNG.
- Multiple Before and After annotation options
- XML-based test configuration and test suite definition
- Dependent methods
- Groups/group of groups
- Dependent groups
- Parameterization of test methods
- Data-driven testing
- Multithreaded execution
- Better reporting
We will discuss these features in more detail in coming tutorials.
Installing TestNG onto Eclipse
Before we can download and start using TestNG, make sure you have Java JDK5 or above is installed on your system. Also make sure that JDK is set in the system path.
In case you just want to download the TestNG JAR, you can get it from the following URL:
Now, let’s start with the installation process of TestNG onto Eclipse. I will try to capture all steps in the process.
1) Open your Eclipse application.
2) Go to Help | Install New Software.
3) Click on the Add… button next to the Work with text box.
4) Enter TestNG site into the Name box and enter URL into the Location box. Once done, click on the OK button.
5) On clicking OK, TestNG update site will get added to Eclipse. The available software window will show the tools available to download under the TestNG site.
6) Select TestNG and click on Next.
7) Eclipse will calculate the software requirements to download the selected TestNG plugin and will show the Install Details screen. Click on Next on the details screen.
8) Accept the License Information and click on Finish. This will start the download and installation of the TestNG plugin onto Eclipse.
9)In case you get the following warning window, click on the OK button.
10) Once the installation is complete, Eclipse will prompt you to restart it. Click on Yes on the window prompt.
11) Once Eclipse is restarted, verify the TestNG plugin installation by going to Window | Preferences. You will see a TestNG section under the preferences window.
We have successfully installed the TestNG plugin into our Eclipse installation. This will help us in executing our TestNG tests or suite using Eclipse.
Creating Java Project with TestNG Dependencies
Before we write our first TestNG test, we have to create a Java project in Eclipse and add our TestNG test dependencies.
1) Go to File | New | Other. A window with multiple options will be shown.
2) Select Java Project as shown in the following screenshot and click on Next.
3) On the next screen, enter a Project name for a Java project, let’s say
TestNGExamples, as shown in the following screenshot, and click on Finish:
This will create a new Java project in Eclipse.
4)Now go to Project | Properties. Select Java Build Path on the left-hand side on the Properties window as shown in the following screenshot. This will display the build path for the newly created project.
5) Click on the Libraries tab and click on the Add Library… option.
6) Select TestNG on the Add Library window as shown in the following screenshot and click on Next:
7) Click on Finish on your next window. This will add the TestNG library to your Eclipse project.
Great, We have successfully created a new Java project in Eclipse and added a TestNG library to the build path of the project.
Creating your first TestNG class
Perform the following steps to create your first TestNG class:
1) Go to File | New | Other. This will open a new Add wizard window in Eclipse.
2) Select TestNG class from the Add wizard window and click on Next.
3) On the next window click on the Browse button and select the Java project where you need to add your class.
4) Enter the package name and the test class name and click on Finish.
5) This window also gives you an option to select different annotations while creating a new TestNG class. If selected, the plugin will generate dummy methods for these annotations while generating the class. This will add a new TestNG class to your project.
package com.howtodoinjava.test; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class MyFirstTest { @Test public void f() { } @BeforeTest public void beforeTest() { } @AfterTest public void afterTest() { } }
We have successfully added a new TestNG test class to the newly created Java project in Eclipse. Feel free to modify the code as needed. Now let’s run the newly created test class through Eclipse.
Running TestNG test
Perform the following steps to run tests through Eclipse:
1) Select the Java project in the Eclipse and go to Run | Run Configuration.
2) Select TestNG in the given options and click on the New button to create a new configuration.
3) Please notice that TestNG plugin provides multiple options for running your test cases as follows:
- Class: Using this option you can provide the class name along with the package to run only the said specific test class.
- Method: Using this you can run only a specific method in a test class.
- Groups: In case you would like to run specific test methods belonging to a particular TestNG group, you can enter those here for executing them.
- Package: If you would like to execute all the tests inside a package, you can specify these in this box.
- Suite: In case you have suite files in the form of
testing.xmlfiles, you can select those here for execution.
Let’s enter the configuration name as
TestNGRunConfig and select the newly created class under the Class section and click on Apply.
4) Now if you would like to run the newly created configuration, just click on Run after clicking on Apply. This will compile and run the TestNG test class that we have written. The result of the test execution is displayed in the Console and Results windows of Eclipse as shown in the following screenshot.
[TestNG] Running: C:\Users\somelocalpath\testng-customsuite.xml PASSED: f =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== [TestNG] Time taken by org.testng.reporters.XMLReporter@177b3cd: 23 ms [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms [TestNG] Time taken by org.testng.reporters.jq.Main@b8deef: 46 ms [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@10ab323: 12 ms [TestNG] Time taken by org.testng.reporters.EmailableReporter2@5e176f: 13 ms [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@d1e89e: 142 ms
You can also run the test class by selecting it and then right-clicking on it, selecting Run as from the menu, and then choosing TestNG Test.
In this TestNG tutorial, we learned about TestNG, features offered by TestNG, installing the TestNG plugin into Eclipse and writing and executing a TestNG test class through Eclipse.
In coming tutorials, we will learn more advanced features of TestNG.
Happy Learning !!
Reference :
Feedback, Discussion and Comments
naseema
getting error “You need to specify at least one testng.xml, one class or one method”
Abu Yusuf
Very helpful and easy to understand
ali raza
my code is not working, @Test annnotation code is not working any more, there is no error shown in the class or anything but when i excute the code, beforeMethod annotation is working, while @test is not working, please help me out of this 🙁
John
Easy understandable steps for beginners, keep it up
Pushpa
Excellent!
Thanks a lot for clear steps.
Vipin
Can we test Spring based web application using this tool? Spring based web application used annotations and it has transactions and hibernate also.
Lokesh
Sure you can. Give me some time, I will post something on it soon.
Adarsh S
Thanks for this article ! | https://howtodoinjava.com/testng/testng-tutorial-with-eclipse/ | CC-MAIN-2019-43 | refinedweb | 1,701 | 62.98 |
3D VTK widget for a QWidget More...
#include <vtkQWidgetWidget.h>
3D VTK widget for a QWidget
This 3D widget handles events between VTK and Qt for a QWidget placed in a scene. It currently takes 6dof events as from VR controllers and if they intersect the widghet it converts them to Qt events and fires them off.
Definition at line 34 of file vtkQWidgetWidget.h.
Standard vtkObject methods.
Definition at line 48 of file vtkQWidgetWidget.h.
Definition at line 85 of file vtkQWidgetWidget.h.
Instantiate the object..
Specify an instance of vtkQWidgetRepresentation used to represent this widget in the scene.
Note that the representation is a subclass of vtkProp so it can be added to the renderer independent of the widget.
Methods for turning the interactor observer on and off, and determining its state.
All subclasses must provide the SetEnabled() method. Enabling a vtkInteractorObserver has the side effect of adding observers; disabling it removes the observers. Prior to enabling the vtkInteractorObserver you must set the render window interactor (via SetInteractor()). Initial value is 0.
Reimplemented from vtkInteractorObserver.
Return the representation as a vtkQWidgetRepresentation.
Create the default widget representation if one is not set.
Implements vtkAbstractWidget.
Set the QWidget that will receive the events.
Definition at line 36 of file vtkQWidgetWidget.h.
Definition at line 84 of file vtkQWidgetWidget.h.
Definition at line 87 of file vtkQWidgetWidget.h.
Definition at line 88 of file vtkQWidgetWidget.h. | https://vtk.org/doc/nightly/html/classvtkQWidgetWidget.html | CC-MAIN-2019-47 | refinedweb | 235 | 52.97 |
- (297)
- GNU General Public License version 2.0 (79)
- GNU Library or Lesser General Public License version 2.0 (27)
- BSD License (14)
- Apache License V2.0 (12)
- MIT License (12)
- Mozilla Public License 1.0 (4)
- Academic Free License (3)
- Common)
- Windows (241)
- Grouping and Descriptive Categories (223)
- Linux (210)
- Mac (132)
- Modern (123)
- BSD (95)
- Android (57)
- Other Operating Systems (35)
Top Magnumis
Os Magnumis started as a tabletop RPG. This is the C++, command line version of the game..4 weekly downloads
Hypercontext
Hypercontext is a software tool specifically designed to facilitate the creation of a contextual Tibetan-English dictionary. Hypercontext also aims to evolve into an application for browsing and searching this dictionary. Programs replacement
This project aims to provide appropriate alternatives from open-source programs to replace the programs closed.
VFP SQL Grammar Parser
SQL Parser for VFP developers. Replaces VFP functions with customizable expressions.
Verilog Perl
The Verilog-Perl distribution provides Perl preprocessing, parsing and utilities for the Verilog Language. It is also available from CPAN under the Verilog:: namespace.
gamescollection.it homebrew game
Old-looking game development initiative from development[k]s 4 Free; NO CONTRACTS/ PLAN!
Need a software [k]? You can get it here! Note: We specialize in mac[k]s
Flavor
Flavor is a language developed for describing (in a formal way) any coded audio-visual or general multimedia bitstream. It comes with a translator for automatic generation of C++/Java code, which can be used to read/write/trace the described bitstream.
Demosten's Perl distribution for Windows
This is a Perl distribution for Windows. It comes with a C/C++ compiler and EPIC IDE. Distribution features include installer, its own formatted help system and several additional modules already installed.
AgressoRTM
The Best htpd Server....
Talapatram
Indian Languages Editor with Keyboard Layouts. Type in 12 Indian Languages with onscreen keyboard layouts. Type as regular Unicode text. No proprietary fonts used. Works on any PC. Save text in simple text files with UTF8 encoding.
Eleonore Digital
Medieval open source game. The intention of this project is the collaborative invention of a 3D educational software on the life of Eleanor of Aquitain and the historical period of the 12 and 13 centuries in Europe. | https://sourceforge.net/directory/language%3Acpp/license%3Aartistic/?sort=update&page=8 | CC-MAIN-2017-13 | refinedweb | 373 | 51.04 |
markhunter45,564 Points
Explanation of what is going on with the HTML for builder.html
Hello!
I am a little confused on what is happening with the HTML. I am not too familiar with radio buttons with HTML and Kenneth really didn't explain what he was doing. For example, what does name and value do in the input and what does label for do?
'''
<div class="colors"> {% for color in options['colors'] %}<!-- basicly a python for loop --> <input type="radio" id="{{ color }}" name = "colors" value = "{{ color }}" {% if saves.get('colors') == color %} checked{% endif %}> <!-- if statement --> <label for="{{ color }}"> </label> {% endfor %} <button class="btn">Update</button> </div>
'''
dongli22,362 Points
dongli22,362 Points
You can refer to this link for more information about
forms. | https://teamtreehouse.com/community/explanation-of-what-is-going-on-with-the-html-for-builderhtml | CC-MAIN-2021-25 | refinedweb | 124 | 65.83 |
Seven Deadly SQL Sins Part II64
Introduction
.... continued from part one
This is the second in a series of four excerpts from the MySQL presentation I gave to my local Linux Group a while back. The presentation was inspired by Arjen Lentz's outline but I added a few of my own pet peeves. And I have to admit that the title is a bit deceptive. I am going to expose more than seven sins when all is said and done, but I just like the alliteration and the theological reference. I beg your indulgence for the technical inaccuracy.
They will haunt you
Sin #4 Galloping Inefficiency
Guilty, Guilty, Guilty, and even more guilty because I knew it was a sin and I did it anyway. "Only this once" has this tendency to become legacy code that grinds away inefficiently for years. When you order a table by RAND() you have to touch every row in the table to put an order on it. Then you throw all but one of them away? Look at that innocent-looking, but cycle-sucking query that can be found in almost any code you care to name:
SELECT ..... ORDER BY RAND() LIMIT 1;
The reason why everyone does this dumb thing above is that it's surprisingly hard to get a random row correctly and randomly. With the two argument form of LIMIT, the following works:
SELECT CAST(1+COUNT(*) * RAND() AS UNSIGNED) FROM country;
Put the result into an application variable. Let's say $foo
SELECT * FROM country LIMIT $foo,1
Sin #5 Dang! what's up here?
CREATE TABLE tbl (replace INT, count INT);
ERROR 1064: You have an error in your SQL syntax
near 'replace INT, count INT)' at line 1
Ummm.... MySQL has a lot of reserved words. If you must use them as fieldnames, you can enclose everything in backticks. I don't recommend it. For one thing the backticks are annoying, ugly, and easy to forget. For another thing it obfuscates things to use reserve words in a different namespace. Here is what it lookes like all backtickified.
CREATE TABLE `select` (`replace` INT, `update` INT);
I prefer something like
CREATE TABLE selector ( replacement INT, refresher INT);
Another gotcha with this sin is importing a table from an older version of mySQL. Things that weren't reserve words before suddenly are. My old version (4.0) had a table called "reads". MySQL 5 did not like it, and what fixed it was making up a new name for the table. I guess "reads" must somehow be a reserve word now. Thanks to encapsulation, the only place the reads table was called in the application was in one class. So I opted to change its name, and made the corresponding changes in the application, rather than backtick it and risk all the errors associated with that for the rest of my life. It would be a bigger problem if there were many applications accessing this data and the person maintaining the database did not know about them.
Sin # 6 I actually know someone who does this :P
$query = "SELECT * FROM ...";
...
$id = $row[0];
$name = $row[1];
This is soooo 1980. Early SQL's referred to data by their position, but being able to use field names as hashes has been available for quite some time. Not only is it bad from a human engineering point of view but if your friendly neighborhood DBA decides to reorder the fields for efficiency....oops your application is seriously broken and you will have a devil of a time fixing it. Use symbolic names in your application code!
PrintShare it! — Rate it: up down [flag this hub]
RSS for comments on this Hub
Ha ha Elena, spoken like a true programmer. All the elegant but never used features that one had so much fun writing pale in comparison with just ONE inefficient query that lives in the core (like fetching a user record or something.)
Conclusion
Well that's all the sins for today. Those weren't so bad were they? We like to keep them down to bite sized chunks that you can swallow easily. Almost everyone (including me) is guilty of "Galloping Inefficiency" at some time when they are in a hurry and don't want to bother to look up the CAST expression in their notes. I hope you are not in the habit of using reserved words as table or field names, and for heavens' sake use associative arrays when referring to database results! These are still pretty basic sins and they will bite you in pretty obvious ways if you do them, except for the inefficiency sin will quietly eat away your performance benchmarks for years. If your application is working, but slowly, look for RANDOM LIMIT 1 queries that are heavily used. If you are guilty, I'm a forgiving person so I'll forgive you, but don't do it any more, OK? I have a piping hot fresh batch of more diabolical sins at part III will be looking into ning and dojo. Ta Da! No promo links. Thank you for reading.
Elena. says:
6 months ago
Hi hot dorkage! I took to reading this series about the Seven SQL Deadly Sins --great, catchy title btw! :-) and can't help but commenting on this sentence here:
'"Only this once' has this tendency to become legacy code that grinds away inefficiently for years."
How I wish this was made into a bumper sticker and stuck in all programmers' errr desk! :-)
Now I'll continue with the deadly sins! :-) | http://hubpages.com/hub/Seven-Deadly-SQL-Sins-Part-II | crawl-002 | refinedweb | 932 | 71.65 |
only 1 line of code!
All you need to get started
1. Any Arduino board (here i used UNO)
3. Ultrasonic sensor (I used two for better navigation)
4. Male-female arduino jumbers or wires
5. Your belt
6. Any smart phone that runs Android V2.3 and above.
Download 1sheeld application to your android smart phone from here
Download 1sheeld library from here and put it in the libraries folder in your Arduino folder.
Teacher Notes
Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.
Step 1: Wiring and Electronics Setup
1. Connect your 1sheeld to your arduino board
2. Connect your ultrasonics as shown in figure
VCC ==> to the 5V in your 1sheeld
GND ==> to your GND in 1sheeld
ECHO ==> to any i/o pin here i used 11 and 13 for the two ultrasonics
Trigger ==> to any i/o pin here i used 10 and 12 for the two ultrasonics
If you have the 5 pin ultrasonic make the same wiring and put the out pin on SC.
(OUT ==> to your GND on 1sheeld)
Step 2: Belt Setup
Step 3: Software (Arduino Code)
#include <OneSheeld.h>
#define inputPin 11
#define outputPin 10
#define inputPin2 13 #define outputPin2 12
#define my_constant 20
unsigned int sensor_r_value; unsigned int sensor_l_value; unsigned int sensor_r_value_last; unsigned int sensor_l_value_last; int difference;
void setup(){ pinMode(inputPin,INPUT); pinMode(outputPin,OUTPUT); pinMode(inputPin2,INPUT); pinMode(outputPin2,OUTPUT); OneSheeld.begin(); }
void loop(){ read_sensors(); delay(1500); }
int measure_r(){ digitalWrite(outputPin, LOW); // send low pulse for 2μs delayMicroseconds(2); digitalWrite(outputPin, HIGH); // send high pulse for 10μs delayMicroseconds(10); digitalWrite(outputPin, LOW); // back to low pulse int distance = pulseIn(inputPin, HIGH); // read echo value int distance1= distance/29/2; // in cm return distance1; }
int measure_l(){ digitalWrite(outputPin2, LOW); // send low pulse for 2μs delayMicroseconds(2); digitalWrite(outputPin2, HIGH); // send high pulse for 10μs delayMicroseconds(10); digitalWrite(outputPin2, LOW); // back to low pulse int distance = pulseIn(inputPin2, HIGH); // read echo value int distance2= distance/29/2; // in cm return distance2; }
int read_sensors(){ sensor_r_value=measure_r(); sensor_l_value=measure_l(); if((sensor_r_value<30)||(sensor_l_value<30)){ TextToSpeech.say("stop now and rotate"); } else{} if(((sensor_r_value>30)&&(sensor_l_value>30))&&((sensor_r_value_last<30)||(sensor_l_value_last<30))){ TextToSpeech.say("Go Forward");} sensor_r_value_last=sensor_r_value; sensor_l_value_last=sensor_l_value; }
Step 4: Code Explanation
Basically, the ultrasonic sensors gets the distance in front of me, if it is higher than 30 cm then no problem, if not then it sends to my smart phone and it tells me through the speaker t turn till the distance is over 30 again, then the phone tells me to continue moving forward.
I used two sensors for better quality and wide range coverage, there is a function that compares between the 2 readings of the sensors and takes the decision based on that.
Let me know what do you think!
46 Discussions
Question 6 months ago
Bro can you give me Android code for this
5 years ago on Step 4
Why pay around 5-7k and use 1sheeld to make the arduino communicate with any android smartphone, when u can use a much cheaper bluetooth module (say HC-07) costing you abut 500-600 bucks, which accomplishes the same task.!
Would'nt it be cheaper and more convenient.? with all respect to ur work. Pl suggest.
Reply 4 years ago on Introduction
Brother , please help me with this project, i wana make use of cheaper bluetooth module instead of 1sheeld.. i am a beginner.
Reply 4 years ago on Introduction
@Deepak just use any bluetooth module, you can start off with by using HC-05 bluetooth module available on the internet for around $8-$9, to establish connection between your android phone and arduino. You however would need a custom android app which u would have to develop. I made an app and Added the functionality of voice aided Navigation to any destination i walking range. The app is deployed in such a way that, the user just has to plug in any earphone and the app automatically launches, scans and automatically connects to the Bluetooth module. Contact me for more information.
Reply 1 year ago
Please send me app on hseecco46@gmail.com
Reply 4 years ago on Introduction
The app basically uses built-in Text to Speech feature in the Android OS. Thus when an Obstacle is detected by your ultrasonic sensors, an appropriate Voice output is generated. (Something like "Please Stop Obstacle on your right")
Reply 4 years ago on Introduction
bro i have sent u a message, please check
Reply 4 years ago
bro u made a point
can u help me out as i am beginner
i will be grateful to you for this
ankitst2@gmail.com
5 years ago on Introduction
what a kind idea, i love it , can i share it in my blog?
Reply 5 years ago on Introduction
Thanks richardli, of course you can share it
Reply 2 years ago
Sir, I hav made this device. I made the conncections and programmed the UNO before it as you described. But I dont get ny output from my 1sheeld app which i was connected via BT. Here I used 1sheeld+ and is there any problem with it.
2 years ago
Sir, I hav made it as U said above. but i ddnt get ny output frm my phone. I purchased 1sheeld+ and 2 ultrasonic sensors and they were connented to arduino uno. I hav programmed it before making the connections.
2 years ago
What is the used of 1sheeld actually? And where did you put the ultrasonic sensor?
3 years ago
What is the replacement for 1Sheeld, I can't get one around
3 years ago
can you help me how to use Bluetooth module and to develop my own android application to make this possible?
3 years ago
One fixed the code repeating "stop now and rotate "
3 years ago
can you tell me what language this is
4 years ago on Introduction
cool,but not for me !
5 years ago on Step 4
And fyi, you could use androids very own built in tts (text to speech) API, for voice synthesis.!
Reply 4 years ago
bro can you please tell me more using Bluetooth how can we implement this project I'm beginner....please help me out | https://www.instructables.com/id/DIY-navigation-device-for-blind-people-using-Ardui/ | CC-MAIN-2019-43 | refinedweb | 1,054 | 60.65 |
table of contents
NAME¶
getttyent, getttynam, setttyent, endttyent - get ttys file entry
SYNOPSIS¶
#include <ttyent.h>
struct ttyent *getttyent(void);
struct ttyent *getttynam(const char *name);
int setttyent(void);
int endttyent(void);
DESCRIPTION¶¶
For an explanation of the terms used in this section, see attributes(7).
CONFORMING TO¶
Not in POSIX.1. Present on the BSDs, and perhaps other systems.
NOTES¶
Under Linux, the file /etc/ttys, and the functions described above, are not used.
SEE ALSO¶
COLOPHON¶
This page is part of release 5.10 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. | https://manpages.debian.org/bullseye/manpages-dev/endttyent.3.en.html | CC-MAIN-2021-49 | refinedweb | 112 | 66.94 |
Hi all,
ServiceStack: 5.0.2Webstorm: 2017.3.2ServiceStack IDEA: 1.0.12
Can anyone explain why, when I use the New > Typescript Reference tool in Webstorm, this c# dto:
public class Matter
{
public long Id { get; set; }
public long ClientId { get; set; }
public string Code { get; set; }
public string SearchCode { get; set; }
public string StdCode { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
public int? OwnerId { get; set; }
public int? ManagerId { get; set; }
public int? PartnerId { get; set; }
public bool? IsOpen { get; set; }
public string Stage { get; set; }
public DateTime? AtStage { get; set; }
public DateTime? LastActivity { get; set; }
public string Notes { get; set; }
public bool? IsConfidential { get; set; }
public bool? IsMinor { get; set; }
public DateTime? Created { get; set; }
public int? CreatedByUserId { get; set; }
public User CreatedByUser { get; set; }
public DateTime Closed { get; set; }
public int? ClosedByUserId { get; set; }
public User ClosedByUser { get; set; }
public int SystemId { get; set; }
public System System { get; set; }
public DateTime? Loaded { get; set; }
public DateTime? Archived { get; set; }
public List<int> MatterTypes { get; set; }
public List<MatterType> MatterTypeList { get; set; }
public List<MatterStage> MatterStages { get; set; }
public List<MatterKeyDate> MatterKeyDates { get; set; }
public List<string> MaskedProperties { get; set; }
}
is translated into this typescript class?
export class Matter
{
id: number;
clientId: number;
code: string;
searchCode: string;
stdCode: string;
name: string;
shortName: string;
ownerId: number;
managerId: number;
partnerId: number;
isOpen: boolean;
stage: string;
atStage: string;
lastActivity: string;
notes: string;
isConfidential: boolean;
isMinor: boolean;
created: string;
createdByUserId: number;
createdByUser: User;
closed: string;
closedByUserId: number;
closedByUser: User;
systemId: number;
system: System;
loaded: string;
archived: string;
matterTypes: number[];
matterTypeList: MatterType[];
matterStages: MatterStage[];
matterKeyDates: MatterKeyDate[];
maskedProperties: string[];
}
I was expecting the c# DateTimes to translate into Dates in typescript.
Any ideas?
On an aside: I've also found the Update ServiceStack Reference doesn't work. It seems to alter the BaseUrl in the comments and subsequent updates fail because a types/typescript suffix is ultimately appended to the base url more than once...
BaseUrl
types/typescript
The TypeScript classes represent the schema of the returned JSON which doesn’t have a Date Type, it’s defined as a string because that’s how it’s returned in JSON.
When you’re adding the reference are you using the BaseUrl?
Hey @mythz,
Yeah, makes sense and tbh I should have thought of that as I am always having to handle dates separately on my son responses.
It feels to me that SS does a lot of the heavy lifting for me in generating these types but stops just short of generating typescript references. It would be nice if, in the generated typescript, a method is created to convert to/from string to Date and some further classes that represent typescript versions of the c# classes rather than json versions.Thoughts?Or perhaps I'm missing something? (I'm no js or ts expert tbh)
On the second point:My workflow is: 1. Run the SS server and copy the api url (in my case:) 2. In Webstorm, go New > Typescript Reference 3. Paste the api url and enter the name of the file to be generated 4. The json types are created
My header now begins:
/* Options:Date: 2018-01-12 00:07:01Version: 5.02Tip: To override a DTO option, remove "//" prefix before updatingBaseUrl:
My header now begins (note the change to the BaseUrl value):
/* Options:Date: 2018-01-12 08:24:16Version: 5.02Tip: To override a DTO option, remove "//" prefix before updatingBaseUrl:
Error Updating Reference:
Seems a natural workflow to me. Am I doing something wrong?
The TypeScript only generates the Type representation of the JSON Schema, it can't do more than that because JavaScript doesn't have any Type Information of classes at runtime. Different ways to convert Dates are listed in this StackOverflow answer:
E.g. from TypeScript you can do:
import { todate } from "@servicestack/client";
var date = todate(wcfDateString);
Can you provide details of your Server, e.g. ASP.NET / .NET Core / HttpListner + the config mapping you're using for /api in both code and Web.config please.
/api
OK, understood. Cheers
We're using the HttpListener.Our config is split over several files and has quite a lot of content. Is there anything specific that will help?
The configuration you're using to specify /api path, i.e. are you setting both the Config.HandlerFactoryPath and calling Start("http://*:1234/api") ?
Config.HandlerFactoryPath
Start("http://*:1234/api")
Ah, good shout!
We are using Config.HandlerFactoryPath with:
stackHost.SetConfig(new HostConfig
{
//EnableFeatures = Feature.All.Remove(disableFeatures),
AppendUtf8CharsetOnContentTypes = new HashSet<string> { MimeTypes.Html },
HandlerFactoryPath = "api",
DebugMode = false
});
And we're also doing:
new AppHost(new InitialisationList(initialisers)).Init().Start("http://*:8088/");
"RESTful Web API listening at ".Print();
Process.Start("");
I assume we should just be doing one?
Can't repro this, can you post the BaseUrl returned in the comments from:
yeah, happy to share with you but its a large project and I'd rather not post all that IP on the web. Is there a way I can share it privately?
I would just need an empty project with the configuration causing the issue, can you please post the BaseUrl returned in the comments from:
The BaseUrl returned in the comments is:
The issue was due to the plugin sending an empty // double-slash in the URL. Both ASP.NET and .NET Core seem to automatically strip empty double slashes so I've updated HttpListener hosts to do the same which fixes this issue.
//
This change is available from v5.0.3 that's now available on MyGet.
I've also published a fix to the Intellij Plugin to prevent the // but it takes a couple of days for JetBrains to manually verify and approve the plugin.
Ah, great stuff!Thanks. | https://forums.servicestack.net/t/is-this-c-to-typescript-translation-correct/5166 | CC-MAIN-2018-43 | refinedweb | 962 | 56.66 |
Introduction
The
print() function in Python appends a newline to the output when displayed on the tty (teletypewriter A.K.A the terminal). When you don't want your message displayed with newlines or with spaces, how can you change the behavior of
print()?
This can easily be achieved by altering the default values of the
sep and
end parameters of the
print() function.
Printing Without a Newline
Until Python version 2.x,
This version of
print() is capable of taking the following arguments:
The values (
value1,
value2) mentioned above can be any string or any of the data types like list, float, string, etc. The other arguments include a separator (
sep) used to divide the values given as arguments whereas the argument
end is the
\n newline character by default. This is the reason why whenever the
print() function is called, the cursor slides to the next line.
In Python 3.x, the most straightforward way to print without a newline is to set the
end argument as an empty string i.e.
''. For example, try executing the following snippet in your Python interpreter:
print("I am a sentence", "I am also a sentence")
The interpreter would output the following:
I am a sentence I am also a sentence >>>
We are printing two strings, so Python will use the value of
sep, a blank space by default, to print them together. Python also adds a newline character at the end, so the interpreter prompt goes to the end line.
Now modify the previous statement to look like this:
print("I am a sentence", "I am also a sentence", sep="; ", end="")
Upon executing it in the interpreter, you will get an output resembling:
I am a sentence; I am also a sentence>>>
Two things happened here - the separator between the two strings now also includes a semicolon. The interpreter prompt also appears on the same line because we removed the automatically appended newline character.
Printing Without a Newline in Python 2.X
For earlier versions of Python - less than 3 but greater than 2.6 - you can import
print_function from the
__future__ module. This will override the existing
print() function as shown below:
from __future__ import print_function print("I am a sentence", "I am also a sentence", sep="; ", end="")
This will also yield:
I am a sentence; I am also a sentence>>>
This is how you can use Python version 3's
print() function in Python 2.x.
Using stdout.write()
The
sys module has built-in functions to write directly to the file or the tty. This function is available for Python 2.x and 3.x versions. We can use the
write() method of the
sys module's
stdout object to print on the console like this:
import sys sys.stdout.write("I am a line")
Let's execute this and take a look at the output:
I am a line>>>
Although this gives the output of what we are trying to achieve, there are quite a few differences between the
write() function and the
print() function. The
print() function can print multiple values at a time, can accept non-string values, and is friendlier to developers.
Conclusion
In this article, we have explored the different ways by which values can be printed without a newline character/carriage return. This strategy can come quite handy while printing the elements in the outputs of algorithms such as a binary tree or printing the contents of a list next to each other. | https://stackabuse.com/python-how-to-print-without-newline-or-space/ | CC-MAIN-2021-17 | refinedweb | 582 | 58.11 |
Let us consider one semicircle is given. Its radius is R. One rectangle of length l and breadth b is inscribed in that semi-circle. Now one circle with radius r is inscribed in the rectangle. We have to find the area of the inner circle.
As we know biggest rectangle that can be inscribed within the semi-circle has length l and breadth b, then the equation of l and b will be like following −
Now, the biggest circle that can be inscribed within the rectangle has radius r is like below −
#include <iostream> #include <cmath> using namespace std; float innerCircleArea(float R){ return 3.1415 * pow(R / (2 * sqrt(2)), 2); } int main() { float rad = 12.0f; cout << "Area: " << innerCircleArea(rad); }
Area: 56.547 | https://www.tutorialspoint.com/area-of-a-circle-inscribed-in-a-rectangle-which-is-inscribed-in-a-semicircle | CC-MAIN-2022-21 | refinedweb | 126 | 73.58 |
Tcsh, an enhancement of the original Berkeley UNIX C shell, is one of the most popular UNIX shells. This article looks at some of the power that tcsh brings to the table: it provides shell variables that make several regular tasks less time consuming, and it also brings in advanced security features like monitoring of users and their command histories. All commands and scripts described in this article have been tested with tcsh 6.15 (see the Resources section).
How to set shell variables
Tcsh comes with several built-in shell variables. Some of these, like
rmstar and
noclobber, are boolean in nature, so I recommend that you use
set <variablename> to turn them on. For other built-ins like prompt, you need to provide a value using
set <variablename>=<value>. To unset a variable, use
unset <variablename>. Listing 1 shows some basic examples.
Listing 1. How to set/unset shell built-in variables
tcsh# set prompt="arpan@tintin# " arpan@tintin# set autologout=1 arpan@tintin# unset prompt echo $autologout 1 <prompt has disappeared due to unset operation>
The next few sections describe some of the most useful features tcsh provides through shell built-ins.
Prevent disaster with rm
Perhaps the most common way of messing things up in UNIX is to inadvertently issue
rm *. Most users don't use the
-i option with
rm, thereby deleting the
files instantly. Tcsh defines a shell variable
rmstar; when
turned on, it provides the user with a prompt that requests confirmation of the user's action. However, it doesn't work if the user runs
rm –f * at the command prompt. Listing 2 shows the use of
rmstar.
Listing 2. Using the rmstar shell variable
arpan@tintin# pwd /home/arpan/scratchpad arpan@tintin# ls file1 file2 arpan@tintin# set rmstar arpan@tintin# rm * Do you really want to delete all files? [n/y] n arpan@tintin# ls file1 file2 arpan@tintin# unset rmstar arpan@tintin# rm * arpan@tintin# ls arpan@tintin#
Prevent accidental overwriting of existing files
Another typical doomsday scenario is the accidental overwriting of an existing file. To prevent this from happening, always keep the
noclobber shell variable turned on. (This variable is also available in the csh shell.)
arpan@tintin# ls file1 file2 arpan@tintin# set noclobber arpan@tintin# echo testing > file1 file1: File exists. arpan@tintin# unset noclobber arpan@tintin# echo testing > file1 arpan@tintin# cat file1 testing
Also note that the shell operators
>> and
>! override
noclobber. The former operator appends to the existing file (so data may still be recovered), and the latter overwrites existing content.
Automatic Tab completion
When you're typing commands at the shell prompt, it speeds things up considerably if
you can type in part of the command string, click Tab, and have the shell either complete the command string or provide options for completion. This functionality is particularly useful with long filenames -- you can key in the first few letters and let the shell complete the filename. To enable this feature, you need to set the
autolist shell variable. Listing 4 gives an example.
Listing 4. Using autolist for automatic command completion
arpan@tintin# ls this_is_a_big_file test.c threads.h arpan@tintin# set autolist arpan@tintin# vi t[TAB] this_is_a_big_file test.c term.h arpan@tintin# vi th[TAB] this_is_a_big_file threads.h
In this example,
[TAB] indicates clicking the Tab key. Type in
vi thi[TAB] at the shell prompt, and the shell expands
thi[TAB] to
this_is_a_big_file.
Use addsuffix to distinguish directories during Tab completion
If the
addsuffix shell variable is set along with automatic Tab completion, it's easier to distinguish folders because tcsh suffixes them with a / character when a match is found. It suffixes normal files with a space. Listing 5 shows a situation with a folder named documents and a file named deliverables in the same folder; the user types in
do[TAB], and in response the shell displays
documents/. If the addsuffix variable is unset, then tcsh displays only
documents, which is inconvenient because you need to determine whether documents is a normal file or a folder.
Listing 5. Using addsuffix for additional clarity while using autolist
arpan@tintin# ls documents deliverables arpan@tintin# set autolist arpan@tintin# ls do[TAB] arpan@tintin# ls documents arpan@tintin# set addsuffix arpan@tintin# ls do[TAB] arpan@tintin# ls documents/ arpan@tintin# unset autosuffix arpan@tintin# ls do[TAB] arpan@tintin# ls documents
Use the fignore shell variable to avoid accidental deletion
It makes sense to restrict the automatic Tab-completion feature under certain circumstances. For example, if vi is the most-used command in a session, then you can save time if only text files come up during Tab completion. Likewise, if .c and .cpp files aren't yet backed up and you want to avoid accidental deletion at all cost, then it's best to avoid files with .c/.cpp extensions during Tab completion so they aren't deleted when you use
rm followed by Tab completion. To prevent C/C++ file types from showing up during Tab completion, use
set fignore=(.c .cpp .h). See Listing 6.
Listing 6. Using fignore to prevent source files from showing up during Tab completion
arpan@tintin# set autolist arpan@tintin# ls memory.h memory.cpp kernel.c memory.o kernel.o arpan@tintin# rm m[TAB] memory.h memory.cpp memory.o arpan@tintin# set fignore=(.c .cpp .h) arpan@tintin# rm m[TAB] memory.o
Note that if you use
rm followed by Tab, as opposed to
m followed by Tab, then all C/C++ source files appear.
Automatically log out in case of no user activity
Data security is a prime concern in all organizations. Leaving a shell terminal open
inadvertently can potentially provide access to secure files, but this happens all the time. You can solve this problem using the tcsh
autologout variable. When there is no user activity for a specific time (measured in minutes), the user is logged off the system to tcsh (if it's the login shell). If tcsh isn't the login shell, the user exits to the previous shell, which isn't much help. Thus, it makes sense to have tcsh as the login shell of choice in a secure environment. Listing 7 shows a case of automatic logout due to inactivity.
Listing 7. Automatic logout in case of inactivity
arpan@tintin# rsh herge arpan@herge# set autologout=1 arpan@herge# date Sat Jun 28 18:13:07 IST 2008 <After 1 min of inactivity> arpan@herge# auto-logout Connection to herge closed. arpan@tintin# date Sat Jun 28 18:14:10 IST 2008
Enhanced security in tcsh: Monitor everyone who's using the system
Access to a restricted system must be continuously monitored. Tcsh provides the
built-in shell variable
watch, which makes it easy to view
who is logging in and out of the system. The syntax is
set watch=(username1 ttyname1 username2 ttyname2 …). This monitors whether the user with username1 is logged on to terminal ttyname1. The special syntax
set watch=(any any) lets you monitor all users across all system terminals.
By default, watch checks the system for login/logout activity every 10 minutes. You can override this behavior by specifying the time between activity checks as the first variable of the watch syntax: for example,
set watch=(5 any any). See Listing 8.
Listing 8. Using watch to check for login/logout activity
arpan@tintin# set watch=(5 any any) <checks for login/logout activity across system every 5 minutes) arpan@tintin# set watch=(b* any) <check the login/logout activities of all users whose name starts with b across any terminal in the network>
Tcsh provides the built-in command
log, which lists the terminals affected by watch variables and who's using them (see Listing 9). Note that using
log without
watch being set causes an error.
Listing 9. Using log to check for terminal usage under watch
arpan@tintin# log arpan has logged on pts/0 from 132.132.6.73 root has logged on console zanies has logged pts/5 from 132.132.2.1
Use the prompt variable to keep track of the current working directory
Tcsh defines the
prompt built-in shell variable, which you can use to customize shell prompts. One of the most common UNIX tasks is keeping track of which folder and machine you're currently in. Instead of continuously using
pwd and
hostname, you can achieve the same effect by manipulating the
prompt variable to reflect the current working directory and hostname. See Listing 10.
Listing 10. Change the prompt variable to reflect the current working directory and host
tcsh-6.15$ pwd /home/arpan/ibm1 tcsh-6.15$ hostname tintin tcsh-6.15$ echo $user arpan tcsh-6.15$ set prompt="$user@`hostname`[$cwd] " arpan@tintin[/home/arpan/ibm1]
But an issue remains with this approach: if you change to a different folder, the prompt doesn't reflect the change. To make this change continual as you switch folders, you use the special alias
cmdcwd. If this alias is set, then tcsh executes the command that
cmdcwd was aliased to after switching to a new folder. To reflect the changed folder in the prompt,
cmdcwd must be aliased to the
set prompt command (see Listing 11).
Listing 11. Use the cmdcwd alias to reflect changed folders in the prompt
tcsh-6.15$ alias cmdcwd 'set prompt="$user@`hostname`[$cwd] " ' tcsh-6.15$ cd arpan@tintin[/home/arpan/ibm1] cd net arpan@tintin[/home/arpan/ibm1/net]
Note that this scheme works seamlessly with the
pushd and
popd commands as well, not just with
cd while changing folders. If you're using X-Windows, yet another smart way to keep track of the current folder is to display the folder name on the title bar of the xterm as you work your way across multiple folders.
For example, you can print some basic information on the xterm title bar using the
echo command. Type
echo
"[Ctrl-v][Esc]]2; Hello [Ctrl-v][Ctrl-g]" at the shell prompt. Note that
[Ctrl-v] means to click the key combination Ctrl-V. Keying in this sequence displays the following at the shell prompt:
echo "^[]2; Hello ^G". On execution of this command, the xterm title bar displays
Hello. Listing 12 shows how to display the current folder name in the xterm title bar along with the prompt.
Listing 12. Use cmdcwd to change the prompt and set xterm title bar
arpan@tintin[/home/arpan1/ibm1]# alias cwdcmd 'set prompt="$user@`hostname`[$cwd]# "; echo "^[]2;$cwd^G" '
Automatically correct invalid command usage
Tcsh provides the built-in variable
correct, which helps you correct invalid command usage. For example, if you want to invoke
perl and have typed in
prl, tcsh lets you correct it. Listing 13 gives an example.
Listing 13. Automatically correct typos with tcsh
arpan@tintin# set correct=cmd arpan@tintin# prl CORRECT>perl (y|n|e|a)? y .. arpan@tintin# figner CORRECT>finger (y|n|e|a)? y ..
Periodic execution of specific commands
One of the most common tasks system administrators need to do is monitor disk usage and
take action if it nears 100%. Tcsh has a great feature that lets you perform such periodic execution of events with ease. Alias
periodic to the task you want to be executed on a periodic basis, and set the shell built-in
tperiod equal to the number of minutes between executions of the task. Listing 14 shows how to use
tperiod and
periodic. Note that
periodic is aliased to the script
checkdiskusage, which checks for disk usage and is run by tcsh every 10 minutes.
Listing 14. Use tcsh built-ins for periodic execution of commands
arpan@tintin# set tperiod=10 arpan@tintin# alias periodic checkdiskusage arpan@tintin# cat checkdiskusage df -k | awk -F" " '{print $5}' | grep "9[0-9]*" if ($status <> 0) then mail –s "disk quota exceeded 90%" root@officemail.com endif exit $status
Set a history file on a per-terminal basis
It's fairly common to have the same user of a UNIX system logged on from multiple terminals. To maintain the command execution history on a per-terminal basis, you can use the
histfile and
savehist environment variables. The
histfile variable lets the user specify the name of the file where the command execution history should be stored; the default is $HOME/.history. The
savehist variable asks tcsh to store the user's last N commands on the shell prompt. The
histfile variable definition in Listing 15 allows for multiple history files so you can monitor multiple terminals.
Listing 15. Use the histfile and savehist variables to store the user's command history
arpan@tintin# tty /dev/pts/0 arpan@tintin# set savehist=25 arpan@tintin# set histfile=~/.history_`tty | sed –e 's/\//_/g' ` arpan@tintin# echo $histfile ~/.history_dev_pts_0
Monitor the time it takes to run a command
To monitor the time it takes for a UNIX process to execute, you can set the
time variable. The output displays the user time, kernel time, and
real elapsed time. Listing 16 shows an example.
Note that you can achieve the same output using tcsh's built-in
time command, but the script change isn't minor -- every command must be prefixed with
time (for example,
time du –sm /opt). If you use the
time variable, the single line set time at the start of the script is good enough to display the time it takes to run individual commands.
Listing 16. Use time to display individual commands' execution time
arpan@tintin# cat script set time du –sm /opt df –k /lib arpan@tintin# tcsh –f ./script 198 /opt 0.628u 0.008s 0:02.00 0.0% 0+0k 0+0io 0pf+0w Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 15773312 1125772 13846300 8% / 0.000u 0.004s 0:00.02 0.0% 0+0k 0+0io 0pf+0w
Debug shell scripts: Automatically print the exit value on error
The shell variable
printexitvalue is a useful feature of
tcsh that immensely aids script debugging. Typically, shell scripts and UNIX programs
return 0 on successful completion. If you set this variable, tcsh displays the exit
status whenever a script or program returns a non-zero value, thereby indicating a potential error. See Listing 17.
Listing 17. Use printexitvalue for debugging
arpan@tintin# set printexitvalue arpan@tintin# ls /tmp/opt ls: /tmp/opt: No such file or directory Exit 2 arpan@tintin# cat error_script ls –l; return 2 arpan@tintin# ./error_script ./error_script: line 1: return: can only `return' from a function or sourced script Exit 1 arpan@tintin# unset printexitvalue; ls /tmp/opt ls: /tmp/opt: No such file or directory
Note that when you use this variable in conjunction with a shell script, the non-zero return value of the script is displayed, not the individual return values of commands or user programs that the script may use internally.
Conclusion
Tcsh provides a gamut of shell variables and aliases, in addition to supporting those that csh supplies. This article has focused mainly on the variables that are unique to tcsh. The discussion covers only a cross section of the variables; for a detailed discussion, see the Resources section.
Resources
Learn
- Get the latest tcsh updates, downloads and FAQ.
- Visit the Tcsh man pages.
- Read a brief introduction to many tcsh shell variables .
- Browse the technology bookstore for books on these and other technical topics.
-. | http://www.ibm.com/developerworks/aix/library/au-tcsh/ | CC-MAIN-2013-48 | refinedweb | 2,586 | 61.26 |
I'm getting close to a workable version of a Ruby Wiki - currently titled RuWiki. There a couple of others that exist already, mostly they're difficult or impossible to install on a site host when all you have access to is the standard web services.
RuWiki is designed for multiple backends - currently the only one is a flatfile. MySQL or PostgreSQL will probably be next. The twist for RuWiki is that you can define different "Projects" which essentially create separate namespaces for Wiki topics. I need to decide on a notation for cross-project notations still...
I decided to start looking for full-time work. I've been working small projects, but that was never the intent of Digikata. I'd like to see something in the Open Source area, but it's more likely that I'd return to my roots in Aerospace Engineering (or Engineering related simulation and modeling).
I'm going to try to keep up at least a once-a-month posting to Advo. | http://www.advogato.org/person/aero6dof/diary.html?start=10 | CC-MAIN-2015-40 | refinedweb | 169 | 63.9 |
I have this code
Instant now = Instant.now(); if (amountDays >= 0) { now = now.plus(amountDays, ChronoUnit.DAYS); } else { now = now.minus(Math.abs(amountDays), ChronoUnit.DAYS); }
And I was thinking to simplify it like this
Instant now = Instant.now(); now = now.plus(amountDays, ChronoUnit.DAYS);
However, I am unsure if
plus works correctly with negative values or if that messes up the result.
Can I use
plus like that, with possibly negative values?
Answer
plus with negative values
The
plus method supports adding negative times to go back in time, from its documentation:
amountToAdd – the amount of the unit to add to the result, may be negative
So all good, you can use it like that and it will work as expected.
Implementation
Little trivia, the current implementation of
minus even delegates to
plus with
-amountToSubtract as value:
return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
Notes
In general, if you just want to go back in time, prefer using
minus for readability.
In your particular case I would stick with just
plus though to not bloat the code and logic unecessarily. Instead, prefer adding a comment
// amountDays may be negative
or ensure that your javadoc is clear about that.
Minor improvement, you can simplify your code from two statements to just one:
Instant now = Instant.now().plus(amountDays, ChronoUnit.DAYS); | https://www.tutorialguruji.com/java/instant-plus-with-negative-values/ | CC-MAIN-2021-21 | refinedweb | 227 | 55.54 |
The release of version 9 of the Firebase Web SDK has introduced breaking changes in methods for managing users and querying databases. Code written in Firebase v8.x will throw errors when used in v9.x, which calls for refactoring.
In this article, we’ll learn how to refactor a React app that uses the Firebase Web SDK v8.x to v9.x., which is also called the modular Web SDK. For our example, we’ll use an Amazon clone built with v8.x and refactor it to v9.x. Let’s get started!
Prerequisites
To follow along with this tutorial, you should be familiar with React and Firebase v8.x. You should also have Node.js installed on your machine.
Introducing Firebase v9.x Web SDK
The new web SDK moves away from the namespace approach that was used in version 8. Instead, it adopts a modular format optimized for eliminating unused code, for example, tree shaking, resulting in a significant reduction in the JavaScript bundle size.
The transition to a modular approach has introduced breaking changes, making the new library backward incompatible and causing the code used in v8.x to throw errors in the new Firebase v9.x SDK.
The following code shows some of the breaking changes introduced in the new library:
// VERSION 8 import firebase from 'firebase/app'; import 'firebase/auth'; firebase.initializeApp(); const auth = firebase.auth(); auth.onAuthStateChanged(user => { // Check for user status }); // VERSION 9 EQUIVALENT import { initializeApp } from 'firebase/app'; import { getAuth, onAuthStateChanged } from 'firebase/auth'; const firebaseApp = initializeApp(); const auth = getAuth(firebaseApp); onAuthStateChanged(auth, user => { // Check for user status });
Both code samples above monitor a user state. Although both are similar in the number of lines of code used, in v9.x, instead of importing the
firebase namespace or the
firebase/auth side effect, which augments authentication service to the
firebase namespace, we are importing and using individual functions.
These changes take advantage of the code elimination features of modern JavaScript tools like Webpack and Rollup.
For example, the v8.x code above includes the following code snippet:
auth.onAuthStateChanged(user => { // Check for user status });
auth is a namespace and a service that contains the
onAuthStateChanged method. The namespace also contains methods like
createUserWithEmailAndPassword, and
signOut, which are not being used by the code. When we bundle our entire code, these unused methods will also be included in the bundle, resulting in a relative size increase.
Though bundlers like Webpack and Rollup can be used to eliminate unused code, due to the namespace approach, they will have no effect. Solving this issue is one of the primary goals of remodeling the API surface to take a modular shape. To learn more about the reasons behind the changes in the new library, check out the official Firebase blog.
Firebase compatibility library
The new SDK also includes a compatibility library with a familiar API surface, which is fully compatible with v8.x. The compatibility library allows us to use both old and new APIs in the same codebase, enabling us to progressively refactor our app without breaking it. We can use the compatibility library by making a few tweaks to the import paths as follows:
import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; import 'firebase/compat/firestore';
We’ll take advantage of the library when we refactor our Amazon clone app.
Firebase Web SDK v9.x benefits
In short, the Firebase Web SDK v9.x offers reduced size and increased performance overall. By taking advantage of code elimination features through JavaScript tools like Webpack and Rollup, the new web SDK offers a faster web experience. With the new modular shape, the new SDK is said to be about 80 percent smaller than its predecessors, according to the official Firebase Twitter account.
Setting up our React app for refactoring
Now that we’re familiar with the new SDK, let’s learn how to refactor our v8.x app. The Amazon clone app that we’ll use in this section is an ecommerce app built using Firebase and Strapi.
In our app, we used Firebase to add features like managing user identity with Firebase authentication and storing products purchased by authenticated users with Cloud Firestore. We used Strapi to handle payments for products bought on the app. Finally, we created an API with Express.js that responds with the Strapi client secret of a customer who is about to purchase a product with Firebase Cloud Functions.
You can access a deployed version of the site, which looks like the image below:
Feel free to play around with the app to better understand what we’re working on in this article.
Setting up the Amazon clone app
Before we begin coding, first, let’s clone the repo from GitHub and install the necessary npm packages. Open your terminal and navigate to the folder you would like to store the React app in. Add the following commands:
$ git clone $ cd Amazon-clone-FirebaseV8
Now that we’ve successfully cloned the repo, we need to change the Firebase version in the
package.json file to v9.x before we install the packages. the root directory, open the
package.json file and replace
"firebase": "8.10.0" in the dependencies object with
"firebase": "9.2.0". Now, let’s install our app’s dependencies by running the following command in the terminal:
$ npm install $ cd functions $ npm install
Although we’ve set up and installed all of our app’s dependencies, if we try running the app with
npm start, it will throw errors. To avoid this, we need to fix our app’s breaking changes, which we’ll do shortly.
React app structure
The structure for the
src directory of our app is as follows, but we’ve removed all the style files to make it look shorter:
src ┣ Checkout ┃ ┣ Checkout.js ┃ ┣ CheckoutProduct.js ┃ ┗ Subtotal.js ┣ Header ┃ ┗ Header.js ┣ Home ┃ ┣ Home.js ┃ ┗ Product.js ┣ Login ┃ ┗ Login.js ┣ Orders ┃ ┣ Order.js ┃ ┗ Orders.js ┣ Payment ┃ ┣ axios.js ┃ ┗ Payment.js ┣ App.js ┣ firebase.js ┣ index.js ┣ reducer.js ┣ reportWebVitals.js ┗ StateProvider.js
We’ll only be working with the files that use Firebase services,
firebase,
App.js,
Header.js,
Login.js,
Payment.js, and
Orders.js,
Refactoring the Amazon clone to a modular approach
Let’s update to the v9.x compat library, helping us to progressively migrate to a modular approach until we no longer have any need for the compat library.
The upgrade process follows a repeating pattern; first, it refactors code for a single service like authentication to the modular style, then removes the compat library for that service.
Update imports to the v9.x compat library
Head to the
firebase.js file in the
src directory and modify the v8.x import to look like the following code:
import firebase from 'firebase/app'; import 'firebase/auth'; import 'firebase/firestore';
With just a few alterations, we’ve updated the app to the v9.x compat. Now, we can start our app with
npm start, and it won’t throw any errors. We should also start the Firebase function locally to expose the API that gets the client secret from Strapi.
In your terminal, change to the
functions directory and run the following command to start the function:
$ firebase emulators:start
Refactoring authentication codes
In the
Login.js,
App.js, and
Header.js, we used the Firebase authentication service. First, let’s refactor the code in the
Login.js file, where we created the functionality to create a user and sign them in with the Firebase
createUserWithEmailAndPassword and
Login.js file, we’ll see the following v8.x code:
// src/Login/Login.js const signIn = e => { ... // signIn an existing user with email and password auth .signInWithEmailAndPassword(email, password) .... } const regiter = e => { ... // Create a new user with email and password using firebase auth .createUserWithEmailAndPassword(email, password) .... }
To follow the modular approach, we’ll import the
createUserWithEmailAndPassword methods from the
auth module, then update the code. The refactored version will look like the code below:
// src/Login/Login.js import {signInWithEmailAndPassword, createUserWithEmailAndPassword} from 'firebase/auth' ... const signIn = e => { ... // signIn an existing user with email and password signInWithEmailAndPassword(auth, email, password) ... } const regiter = e => { ... // Create a new user with email and password using firebase createUserWithEmailAndPassword(auth, email, password) ... }
Now, let’s refactor the
App.js and
Header.js files. In the
App.js file, we used the
onAuthStateChanged method to monitor changes in the user’s sign in state:
// src/App.js useEffect(() => { auth.onAuthStateChanged(authUser => { ... }) }, [])
The modular v9.x of the code above looks like the following segment:
// src/App.js import {onAuthStateChanged} from 'firebase/auth' ... useEffect(() => { onAuthStateChanged(auth, authUser => { ... }) }, [])
In the
Header.js file, we used the
signOut method to sign out authenticated users:
// src/Header/Header.js const handleAuthentication = () => { ... auth.signOut() ... }
Update the code above to look like the code snippet below:
// src/Header/Header.js import {signOut} from 'firebase/auth' ... const handleAuthentication = () => { ... signOut(auth) ... }
Now that we’re done refactoring all the authentication codes, it’s time to remove the compat library to gain our size benefit. In the
firebase.js file, replace
import 'firebase/compat/auth' and
const auth = firebaseApp.auth() with the following code:
import {getAuth} from 'firebase/auth' ... const auth = getAuth(firebaseApp)
Refactoring Cloud Firestore codes
The process for refactoring Cloud Firestore code is similar to what we just did with the authentication codes. We’ll be working with the
Payment.js and
Orders.js files. In
Payment.js, we use Firestore to store the data of users that paid for products on the site. Inside
Payment.js, we’ll find the following v8.x code:
// src/Payment/Payment.js ... db .collection('users') .doc(user?.uid) .collection('orders') .doc(paymentIntent.id) .set({ basket: basket, amount: paymentIntent.amount, created: paymentIntent.created }) ...
To refactor the code, we first have to import the necessary functions, then update the rest of the code. The v9.x of the code above looks like the following:
// src/Payment/Payment.js import {doc, setDoc} from 'firebase/firestore' ... const ref = doc(db, 'users', user?.uid, 'orders', paymentIntent.id) setDoc(ref, { basket: basket, amount: paymentIntent.amount, created: paymentIntent.created }) ...
In the
Orders.js file, we used the
onSnapshot method to get real-time updates of the data in Firestore. the v9.x code looks like the following:
// src/Orders/Orders.js .... db .collection('users') .doc(user?.uid) .collection('orders') .orderBy('created', 'desc') .onSnapshot(snapshot => { setOrders(snapshot.docs.map(doc => ({ id: doc.id, data: doc.data() }))) }) ...
The v9.x equivalent is as follows:
import {query, collection, onSnapshot, orderBy} from 'firebase/firestore' ... const orderedOrders = query(ref, orderBy('created', 'desc')) onSnapshot(orderedOrders, snapshot => { setOrders(snapshot.docs.map(doc => ({ id: doc.id, data: doc.data() }))) }) ...
Now that we’re done refactoring all the Cloud Firestore codes, let’s remove the compat library. In the
firebase.js file, replace
import 'firebase/compat/firestore' and
const db = firebaseApp.firestore() with the following code:
import { getFirestore } from "firebase/firestore"; ... const db = getFirestore(firebaseApp) ...
Update initialization code
The final step in upgrading our Amazon clone app to the new modular v9.x syntax is to update the initialization code. In the
firebase.js file, replace
import firebase from 'firebase/compat/app'; and const
firebaseApp = firebase.initializeApp(firebaseConfig) with the following functions:
import { initializeApp } from "firebase/app" ... const firebaseApp = initializeApp(firebaseConfig) ...
Now, we’ve successfully upgraded our app to follow the new v9.x modular format.
Conclusion
The new Firebase v9.x SDK provides a faster web experience than its v8.x predecessor, thanks to its modular format. This tutorial introduced the new SDK and explained how to use its compact library to reflector a React app. You should be able to follow the methods and steps outlined in this article to upgrade your own apps to the newest version.
If you’re still having trouble refactoring your React app, be sure to check out the following Firebase support communities:. | https://blog.logrocket.com/refactor-react-app-firebase-v9-web-sdk/ | CC-MAIN-2022-40 | refinedweb | 1,978 | 51.44 |
make generate-pl: 128 (showing only 100 on this page)
1 | 2 »
www/hiawatha: Make it work with Mbed TLS 2.28
Tested by: Karsten Brand <unknown@u53r.space>.
www/hiawatha: Reset MAINTAINER
www/hiawatha: Add missing patches to fix build
www/hiawatha: Update to 11.2
www/hiawatha: adopt port
www/hiawatha: Reset maintainer
PR: 265848
Reported by: Christopher.petrik@usm.edu(previous maintainer)>
devel/cmake: Update to 3.23.0
Update to 3.23.0.
Fix pkg-plist: using the default share/man location
Release Notes:
PR: 262886
Exp-run by: anto
security/mbedtls: Update to 2.28.0 and fix make test
Also bump dependent ports for library version change.
PR: 255084
www/hiawatha: Add CPE information
Approved by: portmgr (blanket)
www/hiawatha: give maintainership to Chris Petrik <christopher.petrik@usm.edu>
PR: 258113
www/hiawatha : Fix run errors on 13
Change regular expressions to POSIX-style.
References:
PR: 255182
Reported by: ascilia@free.fr
all: Remove all other $FreeBSD keywords.
Remove # $FreeBSD$ from Makefiles.
Update to 10.12
Reset MAINTAINER
www/hiawatha: Update to 10.11
Changes:
www/hiawatha: Update to 10.10
- Remove no longer supported and now always on options
www/hiawatha: remove useless pkg-message
- Pet portclippy while here
www/hiawatha: Update to 10.9
Changes:
www/hiawatha: Update to 10.8.4
Changes:
MFH: 2019Q1 (bug fix)
www/hiawatha: Add WebServerLoad support and cleanup port
- Sort options helpers and add pkg-help to describe options better
- Add CGIWRAPPER option which when turned off will turn off packaging
of the setuid cgi-wrapper(1) binary
- Cleanup post-patch; use LOCALBASE where appropriate
- Drop incidental variables
- Do not install useless documentation; README.md is a copy of
pkg-descr; ChangeLog does not contain any juicy information either
- Trim pkg-message further
www/hiawatha: Unbreak build with XSLT=off
${LOCALBASE}/include is implicitly added to the search path when
Hiawatha is built with XSLT=on. Without it the system mbed TLS
headers cannot be found anymore. Add USES=localbase:ldflags to the
MBDEDTLS option to work around this.
src/filehashes.c:27:10: fatal error: 'mbedtls/sha256.h' file not found
#include "mbedtls/sha256.h"
^~~~~~~~~~~~~~~~~~
- While here reset maintainer and take maintainership after the
third consecutive timeout
PR: 224156
Reported by: Ross McKelvie <ross@exitzero.uk>
Approved by: portmaster@BSDforge.com (maintainer timeout, 2 weeks)
www/hiawatha: Update to 10.8.3
- Tweak pkg-message a bit
PR: 232980
Submitted by: Chris Petrik <christopherpetrik335@student.athenstech.edu>
Approved by: portmaster@BSDforge.com (maintainer timeout, 2 weeks)::
www/hiawatha: Update to 10.7
Changes:
While here, update WWW.
PR: 223112
Submitted by: Chris Petrik <christopherpetrik335@student.athenstech.edu>
Approved by: Chris Hutchinson <portmaster@bsdforge www>
Servers and bandwidth provided by New York Internet, iXsystems, and RootBSD
8 vulnerabilities affecting 101 ports have been reported in the past 14 days
* - modified, not new
All vulnerabilities
Last updated:2022-09-22 07:37:08 | https://aws-1.freshports.org/www/hiawatha/ | CC-MAIN-2022-40 | refinedweb | 486 | 50.94 |
Sets the width at which child elements will break into columns. Pass a number for pixel values or a string for any other valid CSS length. Sets the gutter (grid-gap) between columns. Pass a number for pixel values or a string for any other valid CSS length.
A tiny (~2kb) CSS grid layout for React, built with styled-components 💅. See the website.react grid css styled-components
The
react-flexbox-grid is a set of React components that implement flexboxgrid.css. It even has an optional support for CSS Modules with some extra configuration.react-flexbox-grid imports the styles from flexboxgrid, that's why we're configuring the loader for it.css-modules flexbox-grid react-components flexbox grid react react-component
Primitive for controlling width, margin, padding and more. Both <Flex /> and <Box /> share the same props.react flexbox grid react-component css-in-js grid-component layout
Pinterest like layout components for React.js. You can install the react-stack-grid from npm.react pinterest animation react-component grid-layout layout grid masonry
Example of a two column, responsive, centered grid. All grid layout classes and responsive width classes are modifiers. $av-namespace Global prefix for layout and cell class names. Default: grid.css sass scss bem grid-layout grid oocss
Inspired by Flexbugs this list aims to be a community curated list of CSS Grid Layout bugs, incomplete implementations and interop issues. Grid shipped into browsers in a highly interoperable state, however there are a few issues - let's document any we find here. While I'd like to focus on issues relating to the Grid Specification here, it is likely that related specs such as Box Alignment will need to be referenced. If you think you have spotted an issue and it seems to relate to Grid, post it. We can work out the details together and make sure browser or spec issues get logged in the right place.css css-grid-layout
Auto responsive grid layout library for React.See our CONTRIBUTING.md for information on how to contribute.react layout react-components data-grid table data-table
"Bricks"
Bootstrap's responsive grid and responsive utility classes only, without any extras. Lightweight yet still powerful. Style to taste. Include one of the precompiled grids (grid12.css, grid24.css, grid30.css, grid100.css) in your site, or customize and compile grid.css.less with command line lessc or LessPHP (no extends are used).bootstrap grid layout css less
What you ASCII is what you get. Build layout through ASCII art in Sass (and more).sass grid grid-layout grid-system ascii-art
Less Framework is a CSS grid system for designing adaptive web sites. It contains 4 layouts and 3 sets of typography presets, all based on a single grid. Solid knowledge of HTML and CSS is recommended. You'll find the dimensions for each layout noted down in comments within the CSS files.
A CSS grid framework using Flexbox. Flexible Box Layout Module and calc() as CSS unit value used in Grd are available on modern browsers (Chrome, Firefox, Safari, Opera, Edge and IE11).css grid framework flexbox
We have large collection of open source products. Follow the tags from
Tag Cloud >>
Open source products are scattered around the web. Please provide information
about the open source projects you own / you use.
Add Projects. | https://www.findbestopensource.com/product/jxnblk-react-css-grid | CC-MAIN-2020-10 | refinedweb | 561 | 58.99 |
In Office 365, there's no direct way to send an email programmatically because the SPUtility.SendEmail Method isn't available in sandboxed solutions. The workaround is to use the Send an Email action in a list workflow. First, you need to create a custom list:
The list should contain at least three text columns: one to store each of the email's address, subject and body. Then, create a list workflow bound to the list:
Add a step to the workflow that performs theSend an Email action. When setting up this action, define the email message so that it looks up the values from the columns of the current item. You can also consider adding a second step to the workflow to delete the item just processed.
At this point, you have a list and a workflow tied to it. Now, adding an item to the list will cause your workflow to send an email. You may choose to just let your user trigger sending an email by adding items to that list through the SharePoint user interface. However, you can also add an item to the list from code to trigger sending an email. Assuming your list is called SendMail and has columns called Subject, To, and Message, that's what this code fragment shows:
using Microsoft.SharePoint;
...
SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists["SendMail"].Items;
SPListItem item = listItems.Add();
item["Subject"] = "subject";
item["To"] = "user@server.com";
item["Message"] = "message";
item.Update();
Posted by Peter Vogel on 04/12/2012 at 1:16 PM
Printable Format
> More TechLibrary
I agree to this site's Privacy Policy.
> More Webcasts | https://visualstudiomagazine.com/Blogs/Tool-Tracker/2012/04/Send-an-Email-in-Office-365.aspx | CC-MAIN-2017-09 | refinedweb | 274 | 74.19 |
[Marc] > [Disclaimer: I'm not really keen on having the possibility of > letting code execute in arbitrary namespace objects... it would > make code optimizations even less manageable.] Good point - although surely that would simply mean (certain) optimisations can't be performed for code executing in that environment? How to detect this at "optimization time" may be a little difficult :-) However, this is the primary purpose of this thread - to workout _if_ it is a good idea, as much as working out _how_ to do it :-) > The proposal allows one to use such a proxy to simulate any > kind of mapping -- it works much like the __getattr__ hook > provided for instances. My only problem with Marc's proposal is that there already _is_ an established mapping protocol, and this doesnt use it; instead it invents a new one with the benefit being potentially less code breakage. And without attempting to sound flippant, I wonder how many extension modules will be affected? Module init code certainly assumes the module __dict__ is a dictionary, but none of my code assumes anything about other namespaces. Marc's extensions may be a special case, as AFAIK they inject objects into other dictionaries (ie, new builtins?). Again, not trying to downplay this too much, but if it is only a problem for Marc's more esoteric extensions, I dont feel that should hold up an otherwise solid proposal. [Chris, I think?] > > Case-independant namespaces seem to be a minor point, > > nice to have for interfacing to other products, but then, > > in a function, I see no benefit in changing the semantics > > of function locals? The lookup of foreign symbols would I disagree here. Consider Alice, and similar projects, where a (arguably misplaced, but nonetheless) requirement is that the embedded language be case-insensitive. Period. The Alice people are somewhat special in that they had the resources to change the interpreters guts. Most people wont, and will look for a different language to embedd. Of course, I agree with you for the specific cases you are talking - COM, Active Scripting etc. Indeed, everything I would use this for would prefer to keep the local function semantics identical. > > Does btw. anybody really want to see case-insensitivity > > in Python programs? I'm quite happy with it as it is, > > and I would even force the use to always use the same > > case style after he has touched an external property > > once. Example for Excel: You may write "xl.workbooks" > > in lowercase, but then you have to stay with it. > > This would keep Python source clean for, say, PyLint. > > "No" and "me too" ;-) I think we are missing the point a little. If we focus on COM, we may come up with a different answer. Indeed, if we are to focus on COM integration with Python, there are other areas I would prefer to start with :-) IMO, we should attempt to come up with a more flexible namespace mechanism that is in the style of Python, and will not noticeably slowdown Python. Then COM etc can take advantage of it - much in the same way that Python's existing namespace model existed pre-COM, and COM had to take advantage of what it could! Of course, a key indicator of the likely success is how well COM _can_ take advantage of it, and how much Alice could have taken advantage of it - I cant think of any other yardsticks? Mark. | https://mail.python.org/pipermail/python-dev/1999-May/095165.html | CC-MAIN-2014-10 | refinedweb | 571 | 58.92 |
by having these labels centralized is that it makes translating easier. Just switch the properties file and you can have your application translated in no time. If you’re working with the Spring framework already, this is very easy to do, and is part of Spring MVC (internationalization or i18n).
Project setup
I’m going to start with a simple Spring boot project, so open start.spring.io. Enter the project metadata, and as dependencies you choose Web and Thymeleaf. Once done, press the big Generate project button, unzip the archive and import it in your IDE. Well done, your project is set up!
Creating a simple webpage
Now, let’s create a simple webpage using Spring MVC. First we have to create a controller:
@Controller @RequestMapping public class MainController { @Autowired private AwesomeWebsiteServiceImpl service; @RequestMapping public ModelAndView getAwesomeWebsite() { return new ModelAndView("awesomeWebsite", "website", "The most awesome website is " + service.getAwesomeWebsite()); } }
This controller is going to use a service called
AwesomeWebsiteServiceImpl to retrieve the most awesome website. The view used withing the
getAwesomeWebsite() method is
"awesomeWebsite" and the model name is
"website".
So, let’s create the
AwesomeWebsiteServiceImpl first:
@Service public class AwesomeWebsiteServiceImpl { private String[] awesomeWebsites = new String[] { "", "" }; @Autowired private Random random; public String getAwesomeWebsite() { return awesomeWebsites[random.nextInt(awesomeWebsites.length)]; } }
So, what happens here isn’t that hard. We have an array of strings containing the most awesome websites (a bit opinionated though 😀). Then we use the
getAwesomeWebsite() method to obtain a random website from that list.
We do have to inject the
Random instance though, to do that you open the
Application class (the class with the
@SpringBootApplication annotation), and you add the following bean:
@Bean public Random randomGenerator() { return new Random(); }
Finally, we have to add the HTML template itself inside the src/main/resoruces/templates folder. We called the view “awesomeWebsite”, so that means we have to create an HTML file called awesomeWebsite.html:
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="" /> </head> <body> <div class="container"> <h1 class="text-center">Most awesome website<br /><small th:</small></h1> </div> </body> </html>
As you can see here, we’re using the Thymeleaf
th:text attribute, containing an expression that will be rendered when we view that page. In this case it contains
${website} which is a placeholder for the website model we defined earlier in our controller (as part of the
ModelAndView).
Now, if we run the application, we should see something like this:
Internationalization
Now, is this application available in multiple languages? No. So let’s do that now. Even if you won’t have an application available in multiple languages, you can still profit from using Spring i18n, because now you have a centralized spot to change any label.
To do that, you first have to open application.yml or application.properties and then you have to add the following properties:
spring: messages: basename: messages/messages cache-seconds: -1 encoding: UTF-8
Or in properties:
spring.messages.basename=messages/messages spring.messages.cache-seconds=-1 spring.messages.encoding=UTF-8
Back in the early days you had to define your message resolver bean yourself, but now all you need is some properties, if you use Spring boot. So, what happens now is that we told Spring that inside messages/ folder we have several properties files starting with messages_{code}.properties. The code in this case is the locale code (for example nl, nl_be, en, en_us, …) but make sure that you always use underscores.
First of all, let’s create a default file called messages.properties inside the src/main/resources/messages folder:
label.mostAwesomeWebsite=Most awesome website
So, I just created a property called
label.mostAwesomeWebsite, and it contains the text “Most awesome website”, great!
Now, open the awesomeWebsite.html again, and remove the “Most awesome website” text and replace it by the following:
<span th:</span>
We do have to replace it by a separate HTML element, because otherwise the placeholder would replace the
<small> tag as well. Anyways, if you run the application again, you’ll see that it still looks the same, obviously.
So, let’s create another file in your own language, for me it is Dutch, so I’m going to create a file called messages_nl.properties.
If I provide the same labels now, but using a different value, I now have a translated version:
label.mostAwesomeWebsite=De beste website
If you now run the application again, and you make sure that you’re using the correct language settings in your browser to see the different language, you’ll see that it is now translated.
Using internationalization in your code
There is one issue though, the programmatically defined message is still not translated.
Obviously, the most easy way to fix that is to move the message (except the website) to the HTML template as well. However, sometimes you need to provide translated messages programmatically as well, for example when showing error messages. So, let’s see how you could fix that as well.
First of all, we’re going to add another property to messages.properties and the translated messages_nl.properties:
message.mostAwesomeWebsite=The most awesome website is {0}
message.mostAwesomeWebsite=De beste website is {0}
Now, open the
MainController. First of all you have to autowire the
MessageSource itself:
@Autowired private MessageSource messageSource;
Then, inside the
getAwesomeWebsite() method we have to change a few things:
@RequestMapping public ModelAndView getAwesomeWebsite() { final String[] params = {service.getAwesomeWebsite()}; final String msg = messageSource.getMessage("message.mostAwesomeWebsite", params, LocaleContextHolder.getLocale()); return new ModelAndView("awesomeWebsite", "website", msg); }
First of all, we have to create a new String array, containing the parameters we want to use. You may have noticed that we added the
{0} thing to our message properties. This will be replaced by the first element in the given array, in this case, the website coming from the service.
Now, the next part is that we use the
messageSource to obtain the message with the message.mostAwesomeWebsite key, provide the given parameters, and to provide the locale, you can use the
LocaleContextHolder which contains the locale of the request.
Now all you have to do is to replace original model with the new
msg.
If you run the example again, you’ll see that it is now properly translated.
Using parameters in Thymeleaf
We kinda did two things here, we programmatically used the
MessageSource and we provided parameters. Using parameters is also possible if you use Thymeleaf. So, if we undo all our changes and replace
getAwesomeWebsite() in our controller by this:
return new ModelAndView("awesomeWebsite", "website", service.getAwesomeWebsite());
And then we go to awesomeWebsite.html and we replace the following:
<small th:</small>
With this:
<small th:</small>
Then you’ll see that it yields exactly the same result. | http://g00glen00b.be/spring-internationalization-i18n/ | CC-MAIN-2017-26 | refinedweb | 1,127 | 54.22 |
I'm trying to run a couple of spark SQL statements and want to calculate their running time.
One of the solution is to resort to log. I’m wondering is there any other simpler methods to do it. Something like the following:
import time startTimeQuery = time.clock() df = sqlContext.sql(query) df.show() endTimeQuery = time.clock() runTimeQuery = endTimeQuery - startTimeQuery
If you're using spark-shell (scala) you could try defining a timing function like this:
def show_timing[T](proc: => T): T = { val start=System.nanoTime() val res = proc // call the code val end = System.nanoTime() println("Time elapsed: " + (end-start)/1000 + " microsecs") res }
Then you can try:
val df = show_timing{sqlContext.sql(query)} | http://www.devsplanet.com/question/35280581 | CC-MAIN-2017-04 | refinedweb | 114 | 60.92 |
Back in March 2014 Stephan Schluchter blogged about the new features of SAP Process Orchestration 7.31 SP10 & 11 / 7.4 SP05&06, which you can read all about here
One of the new features, is the XSLT 2.0 support for XSLT mappings, which provides new functions that could save a lot of XSLT 1.0 code or minimize the need for java mapping to achieve same functionality. Unfortunately I couldn’t find much documentation about how to actually start using this new feature. Therefore I decided to write this step by step blog about how I implemented my first XSLT 2.0 mapping.
There are essential 3 things you need to do:
- Create and import an XSLT 2.0 mapping
- Download an external XSLT parser
- Tell PI/PO to look for the external parser and use it.
1. Create and import an XSLT 2.0 mapping
In my example I have a requirement of replacing the pound sign with the ISO code on all elements in an XML document, so I created the following XSL:
<xsl:stylesheet <xsl:output <xsl:strip-space <xsl:param <xsl:param <xsl:template <xsl:copy> >
Please note that I have set the stylesheet version=“2.0” which indicates that I want to utilize XSLT 2.0 functions.
I then saved the XSL and compressed it as a .zip file. Hereafter I imported the archive in ES Builder.
2. Download an external XSLT parser.
In my test I used the Saxon 9 parser, which can be downloaded as a home edition from Sourceforge.
If you need further extensibility, the Professional and Enterprise edition can be optained directly from Saxonica homepage (Please note that these editions have license cost).
All other parsers should also work as long as they follow the JAXP specification.
In order for the mapping to use the parser, it needs to be imported to the software component that needs to utilize it. The procedure is the same as with importing the XSL document. In my case, I just imported the saxon9he.jar file.
Note:
When importing an external transformer, the following resources must be available in the archive(s), according to the JAXP specification:
- /META-INF/services/javax.xml.transform.TransformerFactory
- /META-INF/services/javax.xml.xpath.XPathFactory
The content of these resources defines the implementation of the transformer or XPATH evaluator.
3. Tell PI/PO to look for the external parser and use it.
(*Note: If you have a Dual Stack System, then please refer to Evgeniy Kolmakov‘s excellent extension of this blog here: How to use external XSLT processor for PI Dual stack installations.)
To do this we must set the new global parameter: “com.sap.aii.ibrun.server.mapping.externalTransfomer” to true
(Note that the missing “r” in Transfomer is not a misspelling)
If this property is set to true, the mapping runtime will search for imported transformers, and will use one if found.
To maintain the parameters, perform the following steps:
- Access SAP NetWeaver Administrator at: http://<host:port>/nwa
The variables host and port are the hostname and connection port of your AEX.
- Choose -> Configuration -> Infrastructure -> Java System Properties and select the “Services” tab and search for Service XPI: AII Config Service
- Ensure the custom calculated value for property com.sap.aii.ibrun.server.mapping.externalTransfomer is set to “true”
That’s it, now the PO should be good and ready to utilize your next fantastic XSLT 2.0 Mapping 😉
Hi Chris,
Very Nice Blog….. Highly informative. But I am having some doubts like whether following the same procedure can we use XSLT 2.0 in PI 7.11.
Hi Nav,
Thanks, glad you like it 🙂
According to Stephans blog mentioned in the beginning, the features is available for Process Orchestration 7.31 SP10&11 / 7.4 SP05&06, so I don’t think you will be able to make it work on PI 7.11.
If you try it out, then please share the results.
Best regards,
Chris
Hello Chris,
Thanks for a very useful blog.
We have implemented some map using XSLT 2.0. The mapping uses few of the functions
like for-each-group and replace. Saxon9he.jar has also been imported by making sure the
required XSLT and XPath factory configuration files are available.
In order to enable the use of the external processor imported, the “AII Config service
property “com.sap.aii.ibrun.server.mapping.externalTransfomer” is also been set to “true”.
But still the runtime throwing error the used functions are not supported by the processor.
Upon deploying and checking the XPI traces, we encountered that the imported processor
is not being referred by JDK. It is still referring to the internal Xalan processor.
Can you please provide us any inputs to identify the root cause of the issue.
By the way, PI version is: PI 7.4 dual stack SP9.
Thanks in advance..
Regards,
Manasa.
Hi Chris,
We are having requirement of Saxon Enterprise Edition in SAP Netweaver PI 7.4 system for which I need to import it JAR file but I am not aware how to import these jar files into SAP Netweaver PI 7.4 system and where to place it. Couldyou please help me with it asap..
Hi Sumit!
You should import your jar as Imported Archive in SCW where your xslt 2.0 mapping would be used.
Regards, Evgeniy.
You beat me to it Evgeniy 😉
Thanks for helping out
Cheers,
Chris
Hi Chris!
Did you evaluate if it works for both PI/PO installations or for PI AEX/PO only?
Regards, Evgeniy.
Hi Evgeniy
I have actually only tried ot on PO single stack. But as long as it is at least 7.31 SP10 & 11 or 7.4 SP05&06 then I imagine that it should work.
If you test it out, then please let us know your findings
Cheers,
Chris
Hi Chris!
I couldn’t make it work for now. I’ve tried with Saxon 9 HE and Saxon-B. In both cases I have error on XSLT 2.0 syntax and in error trace I can see that it raised by java’s xalan processor, not Saxon.
Regards, Evgeniy.
Hi Evgeniy
Did you set the new global parameter: “com.sap.aii.ibrun.server.mapping.externalTransfomer”
to true?
Chris
Hi Chris!
Of course, I’ve set it.
Actually, I have one guess. Gonna try it on Monday.
Regards, Evgeniy.
Hi Chris!
Finally, I’ve got it working 🙂
I described the solution for dual stack system in blog record:
Regards, Evgeniy.
Hi Evgeniy
Perfect.. I just added a link to your blog post in step 3.
Thanks for helping out 😎
Cheers,
Chris
Hi Kolmakov,
Thanks for your reply.
Could you please provide me with step by step screenshots..
Where can I find Imported Archive option in ESR?
SCW?
Regards,
Sumit
Hi Sumit
In ESR goto the SWCV that you need the XSLT 2.0 mapping for. Here you will have a namespace where your actual mapping objects are. In this namespace, you should have “Imported Archives”. Find the Archive where your XSLT 2.0 mapping is located. Change object and click “Import Archive” Now add the saxon9he.jar file (or whatever XSLT parser you have downloaded)
Hope this explains it. Otherwise please feel free to ask again
Cheers,
Chris
Hi Chris,
Thanks for your quick reply.
In ESR SWCV means Software Component version right?
I am unable to find Imported Archive option
COuld you please provide me your email id so that I can share more details .
Regards,
Sumit
Hi Sumit
How did you upload your XSLT then? Or didnt you upload it yet?
The import archive is located here (The SAP BASIS Software Component Version is just an example):
Cheers,
Chris
And by the way, if you dont see any “Imported Archives” then right click on the namespace and choose -> new -> Mapping objects -> Imported Archive and create a new one.
/Chris
Hi Chris,
Thanks for the above screenshot .
I haven’t uploaded any XSLT till yet . I found the Imported archive option as per above screenshot.
I am not sure whether xslt mapping creation has been done or not .
As Saxon EE is an alternative for XSLT 2.0 mapping tool hence I want to download Saxon EE SaxonEE9-6-0-9J JAR file and deploy it to SAP Netweaver PI 7.4 system
Please let me know what next I need to do to import Saxon EE jar file SaxonEE9-6-0-9J from below screenshot.
Hi Summit
Please be aware that the SWCV that I used was just an example (SAP BASIS 7.40) You probably want to use your own instead.
When you have the “imported archive” you want to import your XSLT (Zipped) which contains the mapping, and then the saxon9ee.jar file.
(Refer to Imported Archives (XSLT/Java) – SAP XI: Design and Configuration Time – SAP Library for procedure if you are in doubt)
When done, you should change the parameter as described in section 3 of the blog.
Chris
Hi Chris,
Nice blog.. 🙂 🙂
Hi Rahul
Thanks! I am glad you like it.
Have a great day 🙂
Cheers,
Chris
Hi Chris,
Even after importing saxon9ee.jar file into imported archive of xslt mapping and set the parameter com.sap.aii.ibrun.server.mapping.externalTransfomer value to True in exchange profile , it is still throwing error..Pls find below screenshots..
Please suggest how to proceed further
Hi Sumit!
Blog comments is not the right place to post questions about your technical problems.
Please start new discussion, thus much more experienced forum members will be able to help you with decision for your problem.
Regards, Evgeniy.
Hi Chris,
Thanks a lot for the Great blog.
It works just like that for me.
Regards,
Antony.
Hi Antony
Thanks and great to hear it worked out for you 🙂
Cheers,
Chris
Hello Chris and guys/girls.
First of all – thanks for great blog. Everything explained nicely and without many words.
I’ve configured parameters as described and tried with several versions of Saxon parser (latest version 9.7 and also older 9.2 – just imported saxon9he.jar in each case), but still no success for me. 🙁
During mapping test (operation mapping) ES builder throws such error:
Transformer Configuration Exception occurred when loading XSLT <my xslt name goes here>; details: com.sap.aii.ib.server.mapping.execution.MappingClassNotFoundException: com/sap/aii/mapping/xslt/saxon/JavaExtensions$JavaFunctionLibrary.class
Any ideas what can be causing that?
I’m afraid this problem can be related to some issue in latest patch we applied on DEV system (we are on NW PI 7.4 single-stack with latest components SP13).
BR, Artem.
Hi Artem!
It’s worth mention that Saxon HE processor doesn’t support java extensions:
Not included in the Home Edition are: schema processing and schema aware XSLT and XQuery; support for higher-order functions; numerous Saxon extensions; calling out to Java methods;
If you use java extensions in your XSL transformations try Saxon-B, which also supports XSLT 2.0.
Regards, Evgeniy.
Hello Evgeniy.
That’s what is most confusing – I don’t have any calls to Java methods in my mapping.
I’ve tried with simplest XSLT-mapping which is based on XSLT 1.0 (without any additional namespaces prefix except for xmlns:xsl)and executed successfully as such. After copying this mapping into SWCV where Saxon parser is imported – it starts to throw error shown above. Thank you for suggestion – I’ll try with Saxon-B as well, but I’m afraid this is just another issue among others which we got along with newest SP. 🙁
BR, Artem.
Hi Artem,
According to the instruction i got it done recently. It is really simple. I am using pi 7.5.
Download the JAR saxon9he.jar extract it and upload to the PI external archives.
After the export make sure that you see
javax.sml.transform.transformerFactory with path META-INF/Services/
If you do not see this means you have to search the correct jar file where you can find this line and download it.
Go to NWA java system property, then service tab and search
Service XPI: AII Config Service
and change the
com.sap.aii.ibrun.server.mapping.externalTransfomer is set to “true”.
That is it. It should work.
Regards,
Antony.
Hello Antony.
I did everything exactly like you described, but unfortunately with no success.
At the moment I have just two suggestions:
1. Latest SP broken external transformer functionality.
2. Maybe I need much older version of parser which was built using Java version corresponding to the one used in NW 7.4 (version 1.6). So far I have tried only with Saxon 9.2 (built on Java 1.7) and latest 9.7 (built on Java 1.8).
BR, Artem.
Hi Artem,
Can you post the recent error description or still it is the same as before?
It is not a bad idea to restart your java stack if you can.
First of all which NWDS you are using?
Did you install the XSLT2.0 processer in your NWDS?.
Is the xslt2.0 transfomation working on your NWDS?
You can find the instruction on the youtube (4.55 min time).
Regards,
Antony.
Hi Antony.
Thanks for your interest, but as I mentioned in my comment below – this is a problem of latest patch. I was able to run the same parser and XSLTs successfully on another system with lower patch level.
Also patched system was restarted – it didn’t help.
Thanks for your link above – I hadn’t used XSLT in eclipse before. Now gonna use it on such occasion.
BR, Artem.
Update: the error I mentioned above is really related to newest SP applied on our system (NW 7.4 SP13 with latest PLs which indeed is part of SPS15).
I have checked on another system (based on SP12 components) and it worked fine with latest Saxon version (even though XSLT mapping is running slowly when testing it in ES Builder).
So be extremely careful with patches !
BR, Artem.
Another update:
it seems that following note should fix the problem I’ve mentioned above:
2221350 – Support for Java Extensions in the SaxonHE XSLT Transformer
it refers to exactly the same class/package which is reported in the above exception and must be created according to the note as Function Library.
Unfortunately proposed solution doesn’t work out of the box with latest version of Saxon HE parser (9.7) because of changed class hierarchy there (so attached code is not consistent anymore).
Still this is a valid solution for previous version(s) of Saxon parser. I was able to run XSLT 2.0 mappings using it with Saxon parser 9.5 (some older versions like 9.1/9.2 do not compile with it same way as it does not work with version 9.7).
Going to ask SAP for updating above note to make it searchable by exception text and also adding more code versions for different parser version (at least for the latest version 9.7, if possible – or otherwise it should be possible to disable use of Java extensions with external parsers which don’t support them).
BR, Artem.
Hello Artem,
did you get any response about the update of the note for Saxon HE parser 9.6 or higher?
We had the same problem and had installed Saxon 9.6 which was working fine, then patched the system to latest SP and it was not working anymore.
So I downgraded the saxon to 9.5 and applied 2221350 – Support for Java Extensions in the SaxonHE XSLT Transformer and then it was working.
But would be interesting if SAP will deliver a solution for Saxon 9.6 or higher.
Best Regards
Sebastian
Hi Artem,
did you find any solution or did you get any response from SAP related this issue?
We face the same problem and are wondering if this issue has been solved in the meantime.
Thanks and Regards,
Helmut
After changing the properties, run time was behaving weird. my understanding was if we enable 2.0, then runtime will look if any external processors are there or not. if not, then execute using jdk xalan 2.6.0 processor. if it finds the external processor, it will proceed with it.
my observation,
1. if we use external processor archive imported in one namespace, it is used in all namespaces under one swcv.
2. If we dont import any external processor(archive in imported archive) then it complains with error transformer is not found.
3. after changing the java system properties “com.sap.aii.ibrun.server.mapping.externalTransfomer” to false(turning off 2.0),mapping execution works in ESR but fails in runtime(while testing). after server restart it started working in runtime.
4. execution takes longer in ESR. for xalan latest version, it is taking 18s, saxon is taking 4m to output the results.
HI!
which version of Saxon did you use ? WE always get an error saying:
om.sap.aii.ib.server.mapping.execution.MappingClassNotFoundException: com/sap/aii/mapping/xslt/saxon/JavaExtensions$JavaFunctionLibrary.class
and in xpi_inspector:
Hi Martin
In my test I used the Saxon 9 parser, which can be downloaded as a home edition fromSourceforge.
Cheers
Chris | https://blogs.sap.com/2014/10/14/how-to-import-and-use-xslt-20-mappings-in-sap-pipo/ | CC-MAIN-2019-13 | refinedweb | 2,878 | 66.94 |
Hello
I'm trying to create a calculator that takes a keyboard-entered variable, followed by a choice of variable, a value for that variable, then a calculation, using one of two expressions. The expression used depends on the chosen variable.
It should read something like this:
Please enter a mass
5
Will you enter [S]peed or [M]omentum?
s
Please enter the speed
10
A mas of 5kg with speed of 10m/s has kinetic energy of 250J.
The program I have so far works until the calculation, where I get a runtime error. If I chose to enter a speed, it says the variable representing momentum is being used without being initialised. If I chose momentum, the speed variable gets the same error. I've tried multiple variations, but it keeps happening.
I don't understand what is wrong with it, and I'm not sure if I'm linking the expressions to the statements correctly..I don't understand what is wrong with it, and I'm not sure if I'm linking the expressions to the statements correctly..Code:
#include <iostream>
using namespace std;
int main () {
//variable declarations and initialisation
double en_k1;
double en_k2;
double mass;
double vel;
double mom;
//prompt and read mass
cout << "Please enter the mass (kg):" << endl;
cin >> mass;
//prompt for choice of speed or momentum
cout << "Are you going to enter a [S]peed or a [M]omentum?" << endl;
char choice;
cin >> choice;
switch (choice){
case 's':
case 'S':
cout << "Please enter the speed (m/s)." << endl;
cin >> vel;
break;
case 'm':
case 'M':
cout << "Please enter the momentum (kgm/s)" << endl;
cin >> mom;
break;
default:
cout << "You entered a mass of " << mass << "kg, but your choice of speed or momentum was not a valid choice." << endl;
}
//conditional read and calculate energy
if (vel){
en_k1 = 0.5 * mass * (vel * vel);
}
else if (mom){
en_k2 = mom / (2 * mass);
}
//print result
cout << "A mass of " << mass << "kg with a speed of " << vel << "m/s has a kinetic energy of " << en_k1 << "J." << endl;
cout << "A mass of " << mass << "kg with a momentum of " << mom << "kgm/s has a kinetic energy of " << en_k2 << "J." << endl;
//spit if invalid input
//sign off politely
cout << "Thank you for using the kinetic energy calculator." << endl;
} //end of main()
Could anyone offer any help?
Thanks. | http://cboard.cprogramming.com/cplusplus-programming/142146-multiple-choice-conditional-printable-thread.html | CC-MAIN-2014-15 | refinedweb | 387 | 67.79 |
C# is one of the most popular programming languages in the world. In this article, I'll explain top C# interview questions and answers. What is C#? What is the difference between classes and objects? What is an enum type? What is the difference between a class and a struct?.
If you want to learn more about C# application types, read,.
C# is versatile, modern and supports modern programming needs. Since its inception, C# language has gone through various upgrades. C# 8.0 is the latest build of C# language that is expected to release this year. Read the following article for some of the newest features of C#:
While classes are concepts, objects are real. Objects are created using class instances. A class defines the type of an object. Objects store real values in computer memory.
Any real-world entity, which can have some characteristics, or which can perform some work is called as Object. This object is also called as an instance i.e. a copy of an entity class Car. The Model, Type, Color, and Size properties of Honda Civic are Civic, Honda, Red, 4 respectively. BMW 330, Toyota Carolla, Ford 350, Honda CR4, Honda Accord, and Honda Pilot are some examples of objects of Car.
To learn more about real world example of objects and instance, please read
“The code is the code that is developed using the .NET framework and its supported programming languages such as C# or VB.NET. The manage code is directly executed by the Common Language Runtime (CLR or Runtime) and its lifecycle including object creation, memory allocation, and object disposal is managed by the Runtime. Any language that is written in .NET Framework is managed code”. Unmanaged Code
The code, which is developed outside of the .NET framework is known as unmanaged code.
“Applications that do not run under the control of the CLR are said to be unmanaged. The languages such as C or C++ or Visual Basic are unmanaged. The object creation, execution, and disposal on unmanaged code is directly managed by the programmers. If programmers write bad code, it may lead to the memory leaks and unwanted resource allocations.”
The .NET Framework provides a mechanism for unmanaged code to be used in managed code and vice versa. The process is done with the help of wrapper classes.
Here is a detailed article on managed and unmanaged code.
The process of converting from a value type to a reference type is called boxing. Boxing is an implicit conversion. Here is an example of boxing in C#.
The process of converting from a reference type to a value type is called unboxing. Here is an example of unboxing in C#.
Check out these two articles to learn more about boxing and unboxing.
Class and struct both are the user defined data type but have some major differences:
Struct
Class
Read the following articles to learn more on structs vs classes.
Here are some of the common differences between an interface and an abstract class in C#.
To learn more about the difference between an abstract class and an interface, visit the following articles.
An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
An enum type can be an integer (float, int, byte, double etc.). But if you use it.
Some points about enum
For more details follow the link,
Using break statement, you can 'jump out of a loop' whereas by using continue statement, you can 'jump over one iteration' and then resume your loop execution. Eg. Break Statement
Output The number is 0;
The number is 1;
The number is 2;
The number is 3;
Eg. Continue Statement
Output
The number is 1;
The number is 2;
The number is 3;
The number is 5;
For more details follow link,
Const is nothing but "constant", a variable of which the value is constant but at compile time. And.
See the example
We have a Test Class in which we have two variables, one is readonly and other is a constant.
Here I was trying to change the value of both the variables in constructor but when I am trying to change the constant it gives an error to change their value in that block which I have to call at run time.
Learn more about const and readonly here:
The ref keyword passes arguments by reference. It means any changes made to this argument in the method will be reflected in that variable when control returns to the calling method.
The out keyword passes arguments by reference. This is very similar to the ref keyword., but in the case of Extension Methods we can use it the functions parameters.
Let’s have a look at the “this” keyword.
The "this" keyword in C# is a special type of reference variable that is implicitly defined within each constructor and non-static method as a first parameter of the type class in which it is defined.
Learn more here on The this Keyword In C#.. Now the three types of properties: Read/Write, ReadOnly and WriteOnly. Let's see each one by one.
Learn more here: Property in C#.
For more details on extension methods, you can read these articles,
Finalize
Dispose
For more details follow this link,
StringBuilder and string both use to string value but both have many differences on the bases of instance creation and also for performance: String
String is an immutable object. Immutable like when we create string object in code so we cannot modify or change that object in any operations like insert new value, replace or append any value with existing value in string object, when we have to do some operations to change string simply it will dispose the old value of string object and it will create new instance in memory for hold the new value in string object like,
StringBuilder
System.Text.Stringbuilder is mutable object which also hold the string value, mutable means. Let’s have an example to understand System.Text.Stringbuilder like,
Note
For More details read this article by following link: the device to overcome such complications.
Learn more about Delegates and Events in C# .NET sealed. If a class is derived from a sealed class then the compiler throws an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
The following class definition defines a sealed class in C#,
Learn more about sealed classes here: Sealed Class in C#
A partial class is only use to splits the definition of a class in two or more classes in a same source code file or more than one source files. You can create a class definition in multiple files but it will be compiled as one class at run time and also when you’ll create an instance of this class so you can access all the methods from all source file with a same object.
Partial Classes can be create in the same namespace it’s doesn’t allowed to create a partial class in different namespace. So use “partial” keyword with all the class name which you want to bind together with the same name of class in same namespace, let’s have an example,
Boxing and Unboxing both using for type converting but have some difference: application domain. Example
To learn more about boxing and unboding, visit Boxing and Unboxing in. doesn’t have this interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query.
Early Binding and late Binding concepts belong to polymorphism in C#. Polymorphism is the feature of object oriented programming that allows a language to use same name in different forms. For example, a method name Add that can add integers, doubles, and decimals.
Polymorphism we have 2 different types to achieve that:
Compile Time Polymorphism or Early Binding In Compile time polymorphism or Early Binding we will use multiple methods with same name but different type of parameter or may be the number or parameter because of this we can perform different-different tasks with same method name in the same class which is also known as Method overloading.
See how we can do that by the following example,
Run Time Polymorphism or Late Binding
Run time polymorphism also known as late binding, in Run Time polymorphism or Late Binding we can do use same method names with same signatures means same type or same number of parameters but not in same class because compiler doesn’t allowed that at compile time so we can use in derived class that bind at run time when a child class or derived class object will instantiated that’s way we says that Late Binding. For that we have to create my parent class functions as partial and in driver or child class as override functions with override keyword. Like as following example,
Before we go into the differences, lets learn what the IEnumerable and IQueryable. IQueryable
As per MSDN.
If we implement multiple interfaces in the same class with conflict method names,
Now see how to use those in a class, do.
The following code snippet declares an array that can store 100 items starting from index 0 to 99.
Learn more about Arrays in C#: Working with Arrays In C#
The Array.Clone() method creates a shallow copy of an array..
The CopyTo() static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types.
Learn more about arrays here,
We can use multiple catch blocks with a try statement. Each catch block can catch a different exception. The following code example shows how to implement multiple catch statements with a single try statement.
To learn more about Exception Handling in C#, please visit:
What isSingleton Design Pattern?
This is the example how to write the code with Singleton,
To read more about Singleton in depth so follow the link:
The basic difference is that the Throw exception overwrites the stack trace and this makes it hard to find the original code line number that has thrown the exception.
Throw basically retains the stack information and adds to the stack information in the exception that it is thrown.
Let us see what it means rather speaking so many words to better understand the differences. I am using a console application to easily test and see how the usage of the two differ in their functionality.
Now run the code by pressing the F5 key of the keyboard and see what happens. It returns an exception and look at the stack trace:
To learn more about throw exceptions, please visit:
C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C#. They are not essential part of object-oriented programming.
Defining an indexer allows you to create classes that act like virtual arrays. Instances of that class can be accessed using the [] array access operator. Creating an Indexer
In the above code, <modifier>
can be private, public, protected or internal. <return type>
can be any valid C# types.
To learn more about indexers in C#, visit Indexers in C#.
Answer
Delegate is one of the base types in .NET. Delegate is a class, which is used to create and invoke delegates at runtime.
A delegate in C# allows developers to treat methods as objects and invoke them from their code.
Implement Multicast Delegates Example,
Learn more about delegates in C# here,
Answer
Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents. Let’s see with some examples.
In this.
For more details go with this following Links,
Answer "is" operator
In C# language, we use the "is" operator to check the object type. If two objects are of the same type, it returns true, else it returns false.
Let's understand this in our C# code. We declare two classes, Speaker and Author.
Now, let's create an object of type Speaker,
Now, let’s check if the object is Speaker type,
In the preceding, we are checking the matching type. Yes, our speaker is an object of Speaker type.
So, the results as true.
But, here we get false,
Because our speaker is not an object of Author type. "as" operator
The "as" operator behaves in similar way as the "is" operator. The only difference is it returns the object if both are compatible to that type. Else it returns a null.
Let's understand this in our C# code.
We have a method that accepts a dynamic object and returns the object name property if the object is of the Author type. Here, we’ve declared two objects,
The following returns the "Name" property,
It returns an empty string,
Learn more about is vs as operators here,
Answer
A nullable type is a data type is that contains the defined data type or the null value.
This nullable type concept is not compatible with "var".
Any data type can be declared nullable type with the help of operator "?".
For example, the following code declares int i as a null.
As discussed in previous section "var" is not compatible with nullable types.
So, if you declare the following, you will get an error.
To learn more about nullable types in C#, read the following:
Answer
Method overloading is a way to achieve compile time polymorphism where we can use a method with the same name but different signatures. For example, the following code example has a method volume with three different signatures base don the number and type of parameters and return values.
Example
Note
If we have a method that have two parameter object type and have a same name method with two integer parameter so when we call that method with int value so it’ll call that method have integer parameter instead of object type parameters method.
Read the following article to learn more about method overloading in C#.
Answer
Object Pooling in .NET allows objects to keep in the memory pool so the objects can be reused without recreating them. This article explains what object pooling is in .NET and how to implement object pooling in C#.
What does it mean?
Object Pool is a container of objects that are ready for use. Whenever there is a request for a new object, the pool manager will take the request and it will be served by allocating an object from the pool. How it works?
We are going to use the Factory pattern for this purpose. We will have a factory method, which will take care about the creation of objects. Whenever there is a request for a new object, the factory method will look into the object pool (we use Queue object). If there is any object available within the allowed limit, it will return the object (value object), otherwise a new object will be created and give you back.
To learn more about object pooling in C# and .NET, read the following,
Answer.
Learn more here about generic classes in C# here,
Answer
Access modifiers are keywords used to specify the declared accessibility of a member or a type.
Access modifiers are keywords used to specify the scope of accessibility of a member of a type or the type itself. For example, a public class is accessible to the entiere world, while an internal class may be accessible to the assembly only.
Why to use access modifiers?
Access modifiers are an integral part of object-oriented programming. Access modifiers are used to implement encapsulation of OOP. Access modifiers allow you to define who does or who doesn't have access to certain features.
In C# there are 6 different types of Access Modifiers.
To learn more about access modifiers in C#, learn here,
Answer
A overridden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overridden
Learn more about virtual methods in C#,
Answer
Here is a list of difference between the two.
Answer.
In C#, basic data types such as int, char, bool, and long are value types. Classes and collections are reference types.
Answer
Serialization in C# is the process of converting an object into a stream of bytes to store the object to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
There are three types of serialization,
Learn more about serialization in C# here,
Answer
There are two ways to use the using keyword in C#. One is as a directive and the other is as a statement. Let's explain!
Learn more here,
Answer
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays."
A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ. Example
In the above declaration the rows are fixed in size. But columns are not specified as they can vary. Declaring and initializing jagged array.
Answer
Multithreading allows a program to run multiple threads concurrently. This article explains how multithreading works in .NET. This article covers the entire range of threading areas from thread creation, race conditions, deadlocks, monitors, mutexes, synchronization and semaphores and so on..
To learn more about threading in .NET, visit,
Answer.
Learn more about anonymous types here,
Answer
A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage location and is immutable and cannot have duplicate entries in, a hash code is generated automatically. This code is hidden from the developer. All access to the table's values is achieved using the key object for identification. As the items in the collection are sorted according to the hidden hash code, the items should be considered to be randomly ordered.,
Learn more about HashTable, visit the following,
Answer<T> interface. Advantages of LINQ
Answer type and they are typically, employed for obtaining the full details of a file or directory because their members tend to return strongly typed objects. They implement roughly the same public methods as a Directory and a File but they are stateful and the members of these classes are not static.
Answer
Reflection is the process of runtime type discovery to inspect metadata, CIL code, late binding and self-generating code. At run time by using reflection, we can access the same "type" information as displayed by the ildasm utility at design time. The reflection is analogous to reverse engineering in which we can break an existing *.exe or *.dll assembly to explore defined significant contents information, including methods, fields, events and properties.
You can dynamically discover the set of interfaces supported by a given type using the System.Reflection namespace.
Reflection typically is used to dump out the loaded assemblies list, their reference to inspect methods, properties etcetera. Reflection is also used in the external disassembling tools such Reflector, Fxcop and NUnit because .NET tools don't need to parse the source code similar to C++. Metadata Investigation
The following program depicts the process of reflection by creating a console based application. This program will display the details of the fields, methods, properties and interfaces for any type within the mscorlib.dll assembly. Before proceeeding, it is mandatory to import "System.Reflection".
Here, we are defining a number of static methods in the program class to enumerate fields, methods and interfaces in the specified type. The static method takes a single "System.Type" parameter and returns void.
To learn more about reflection, read these articles,
View All | https://www.c-sharpcorner.com/UploadFile/puranindia/C-Sharp-interview-questions/ | CC-MAIN-2019-26 | refinedweb | 3,433 | 63.29 |
I have a simple Nifi flow where it picks up the files from landing directory (Get file processor) and place them on HDFS. To place files on HDFS I am using webhdfs over knox. As Nifi does not have webhdfs processor, I am using python executeScript processor to run the Curl command for webhdfs post. But I am getting an error while running the below code.
Here is my python script code
import sys import os import traceback from org.apache.commons.io import IOUtils from java.nio.charset import StandardCharsets from org.apache.nifi.processor.io import InputStreamCallback from org.python.core.util import StringUtil
class readFirstLineCallback(InputStreamCallback): def __init__(self): pass
def process(self, inputStream): try: input_text = IOUtils.toString(inputStream, StandardCharsets.UTF_8) os.system('touch /u/itlaked/process_outputs/' + input_text) print 'AD_TEST' os.system('echo '+input_text+' | curl -iku user:password -L --data-binary @- -x PUT') except: traceback.print_exc(file=sys.stdout) raise
flowFile = session.get() if flowFile != None: readCallback = readFirstLineCallback() session.read(flowFile, readCallback) session.remove(flowFile) session.commit() ERROR Message: 2016-10-20 09:36:15,106 ERROR [NiFi logging handler] org.apache.nifi.StdErr /bin/sh: -c: line 1: syntax error near unexpected token `|' 3262 2016-10-20 09:36:15,106 ERROR [NiFi logging handler] org.apache.nifi.StdErr /bin/sh: -c: line 1: ` | curl -iku user:password -L --data-binary @- -x PUT'
Please let me know if anybody has any thoughts ...I am very new to the Nifi and I just chose ExecuteScript because this curl command runs fine on the command line. Not sure if there is any other ways to achieve this...
If your Python script is just calling out to the operating system, consider using ExecuteStreamCommand or ExecuteProcess instead. Otherwise there are (hopefully!) some pure Python module(s) for doing HTTP requests, rather than using curl via os.system().
@Matt Burgess
I did try those two processors. But it didn't work for me. I need to run the curl command on incoming filefile. Executeprocess - I don't see an option to specify the incoming flowfile. ExecuteStreamCommand - I did try running this by specifying the curl command and specifying static target filename for now and @- to get the stdin to the curl.
curl -iku user:password -L --data-binary @- -x PUT
But it doesn't work for me with the below error. seems it doesn't understand the @-
org.apache.nifi.processor.exception.ProcessException: java.io.IOException: Cannot run program " curl -iku user:password -L --data-binary @- -x PUT": error=2, No such file or directory...
Created 10-20-2016 03:21 PM
Here's example python code that you can run from within NiFi's ExecuteProcess processor:
import json import java.io from org.apache.commons.io import IOUtils # Get flowFile Session flowFile = session.get() # Open data.json file and parse json values filename = flowFile.getAttribute('filename') filepath = flowFile.getAttribute('absolute.path') data = json.loads(open(filepath + filename, "r").read()) data_value1 = data["record"]["value1"] # Calculate arbitrary new value within python new_value = data_value1 * 100 # Add/Put values to flowFile as new attributes if (flowFile != None): flowFile = session.putAttribute(flowFile, "from_python_string", "python string example") flowFile = session.putAttribute(flowFile, "from_python_number", str(new_value)) session.transfer(flowFile, REL_SUCCESS) session.commit()
Hi Dan, Thank you for your sample code. I am able to get this working by using Flowfile attributes and by specifying local file system file. I ended up using os.system call as I am facing issues with python libraries(requests,urllib,..etc) for webhdfs op command options.
Issues with this is approach ,
I have to keep my source files exist in my Getfile processor. If I keep the source files exist then the subsequent iterations it complains the file already exists.
If I don't keep the source file , once the Getfile processor completes it removes the source file and it will not be available for the execute script processor to refer for the curl command.
Here is my new code..
import sys import os import java.io from org.apache.commons.io import IOUtils flowFile = session.get() filename = flowFile.getAttribute('filename') filepath = flowFile.getAttribute('absolute.path') file= filepath + filename if (flowFile != None): print 'filename is ::'+file os.system('curl -ku user:password -L -T '+file+' -X PUT "'+filename+'?op=CREATE"') session.remove(flowFile) session.commit()
Created 10-22-2016 08:02 PM
Hi @Dan Zaratsian, out of curiosity how do you debug this stuff? I tried starting a jython interpret and loading some of the nifi bits into the classpath, but it's still not really convienent. You surely aren't just debugging in that little box that is the nifi form right?
I would suggest using build in Jython http functionality if possible:
Here's an example POST request.
If you still need to shell out, os.system should be replaced with subprocess.Popen where possible.
os.system is pretty much the same as subprocess.Popen with shell = True. This is bad because it opens the door for shell injection. If there are unexpected characters in your input_text variable, bad things could happen either on accident or via crafted input by a malicious user.
It is much safer to use multiple Popen invocations connected together with Python's piping functionality. | https://community.cloudera.com/t5/Support-Questions/How-to-pass-flowfile-to-a-Python-curl-command/td-p/141549 | CC-MAIN-2022-33 | refinedweb | 868 | 52.87 |
I am reading a csv file with German date format.
Seems like it worked ok in this post:
Picking dates from an imported CSV with pandas/python
However, it seems like in my case the date is not recognized as such.
I could not find any wrong string in the test file.
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib import style
from pandas import DataFrame
style.use('ggplot')
df = pd.read_csv('testdata.csv', dayfirst=True, parse_dates=True)
df[:5]
If you use
parse_dates=True then
read_csv tries to parse the index as a date.
Therefore, you would also need to declare the first column as the index with
index_col=[0]:
In [216]: pd.read_csv('testdata.csv', dayfirst=True, parse_dates=True, index_col=[0]) Out[216]: morgens mittags abends Datum 2015-03-16 382 452 202 2015-03-17 288 467 192
Alternatively, if you don't want the
Datum column to be an index, you could use
parse_dates=[0] to explicitly tell
read_csv to parse the first column as dates:
In [217]: pd.read_csv('testdata.csv', dayfirst=True, parse_dates=[0]) Out[217]: Datum morgens mittags abends 0 2015-03-16 382 452 202 1 2015-03-17 288 467 192
Under the hood
read_csv uses
dateutil.parser.parse to parse date strings:
In [218]: import dateutil.parser as DP In [221]: DP.parse('16.03.2015', dayfirst=True) Out[221]: datetime.datetime(2015, 3, 16, 0, 0)
Since
dateutil.parser has no trouble parsing date strings in
DD.MM.YYYY format, you don't have to declare a custom date parser here. | https://codedump.io/share/ej1aWbKstl1D/1/read-csv-with-ddmmyyyy-in-python-and-pandas | CC-MAIN-2017-13 | refinedweb | 271 | 65.93 |
I think this one important reason that many people can't wait until DTDs are
dead. They really make it hard to embed one XML document into another. If
DTDs are dead, it's trivial to embed one document into another.
If you need to do this, the best options I can think of are:
1. Bin64 the embedded document. This makes it hard to read, but does give
you the best fidelity with the original document.
2. Stick the Prolog of the document in a CDATA section. Stick the rest of
the document in a container element. An Internal Subset prolog _might_
contain "]]>", but it's pretty unlikely. If you car about namespaces, you
should also put a xmlns="" on the container element.
-Wayne Steele
>From: Michael Brennan <Michael_Brennan@...>
>To: "'michael.h.kay@...'" <michael.h.kay@...>,
>xml-dev@...
>Subject: RE: [xml-dev] Documents within documents
>Date: Thu, 7 Feb 2002 12:15:26 -0800
>
> > From: Michael Kay [mailto:michael.h.kay@...]
>
><snip/>
>
> > The usual excuse for doing it seems to be that the inner
> > document has a
> > <!DOCTYPE..> declaration that people want to preserve while
> > carrying an XML
> > document over some protocol like SOAP.
> >
> > Is there a better solution that we can point them to?
>
>Are they using internal DTD subsets or just referencing external DTD
>entities? If the latter, perhaps some sort of XLink based annotation that
>would let the recipient fetch the DTD separately (and add the DOCTYPE back
>into the document, if needed). If using SOAP With Attachments, the DTD
>could
>even be included as an attachment and referenced via a "cid:" href.
>
>-----------------------------------------------------------------
>The xml-dev list is sponsored by XML.org <>, an
>initiative of OASIS <>
>
>The list archives are at
>
>To subscribe or unsubscribe from this list use the subscription
>manager: <>
>
_________________________________________________________________
Chat with friends online, try MSN Messenger: | http://www.oxygenxml.com/archives/xml-dev/200202/msg00382.html | crawl-002 | refinedweb | 304 | 65.32 |
This article explains about why Silverlight is needed, why we should move to Silverlight and it also explains about the relationship between Web Server, Web Browser and Silverlight.
What made me really invest time in learning Silverlight? Hope this will be helpful for beginners who want to know about "Why Silverlight?"
I will try to write a post daily but my first post will concentrate on “What made me move to Silverlight?”. The second post will include more on the technical side of Silverlight. After a few posts, I will be writing one application which will help us to understand Silverlight starting from Login, WCF, Data Binding, Prism, ADO.NET Entity framework, which will give us a complete flow and help us to understand Silverlight. Please feel free to write to me at dhaneel.shanthpure@gmail.com for any suggestions or questions. Please do leave comments on the post.
So let’s start.
Before beginning to know more on Silverlight, first we should know:
Before I begin with any new language, I always want to know what language it is? How to use it? And what is the architecture behind it?
I will answer these questions with a case study. In that way, you all will understand it very clearly.
I got one project last year. The client need was to develop a website for some product which will have tree control, menu item, UI elements and business logic involved in it, etc. Then I took the project and started working on it.
I wrote JavaScript to do few things. When we had a small demo with the client, he was very upset and said “Is this a way to write JavaScript code? What code have you written?? Where are the namespaces?” They started shouting at me. They very well knew JavaScript and I never knew that there was anything called namespace in JavaScript! I started searching on the internet but couldn’t find any related information on JavaScript. From before, I always thought that JavaScript is a very simple language but I was 100% wrong. I always thought that very few people use JavaScript and never wanted to learn it because one of my college seniors said JavaScript is very simple language and he showed me the following program in JavaScript.
<html>
<head>
<script type=”text/javascript”>
function load()
{
alert(’Hello World..’);
}
</script>
</head>
<body onload=”load()”>
</body>
</html>
This used to show me Hello World when I used to open it in the browser. After that, I never bothered to learn more on JavaScript. But you can’t believe JavaScript is the most widely deployed application on the Internet!!! Can’t believe me?? I will tell you how…
Before that, please understand that JavaScript is nowhere related to Java language. The person who was developing JavaScript at netscape got inspired by Java so he used few tags from Java and then named it LiveScript but when they wanted to collaborate with Sun Microsystems, then they named it as JavaScript. I don’t want to discuss more on this. But just remember one thing that Javascript and Java are totally different. If you want to know more, here are the links… They say Javascript is the World’s Most Misunderstood Programming Language.. J ..
Every machine Windows, Mac, Linux has a web browser in it?? And every web browser has JavaScript in it. So JavaScript is the most widely deployed application in the internet. You can just code using HTML and JavaScript and there is no need to worry about deploying on client’s machine.
I will come back to my problem.. .. After getting yelled at from my client, I started looking for more information on the internet. I asked the client to give me some time so that I can learn about JavaScript. I didn't find any good article on the internet about JavaScript which told anything about namespaces. I took complete 30 days to learn about JavaScript. I really got shocked when I got to know that we have inheritance, classes, etc. in JavaScript. At that time, I found that on Yahoo developers site, Douglas Crockford was doing a hell lot of things on JavaScript and I think he is a real genius. If anyone is interested in knowing more about JavaScipt, here is the link:
There are some 4 videos by Douglas Crockford — “The JavaScript Programming Language”.
Here you won’t find simple Hello World Stuff.
Again back to my problem. I learned JavaScript and started coding for my client. Each UI control used to take hell lot of time for me as I was a beginner. As they were paying well enough, I thought I will buy controls from another company. There are some companies like infragistics[] where you can buy controls. But on Yahoo developers, you can find loads of free JavaScript stuff. So make sure you first look at it and then write your own or buy from others.
Somehow I managed to complete the project and delivered it. The same client again came to me and started asking me that he will be giving the demo of this application to his client and needs a good UI and said he will pay me for that. Then I said ok, I will look into it then I got to know that in Adobe Flash, we can do a lot of good UI stuff, animation, etc. I had very little time to deliver this, therefore started searching for a Flash designer. Then I found one who did his job well. He created a very nice UI with Menu Dropping from top and very good jazzy user interface. Then the biggest problem was waiting for me. How will I call events from Flash??? Damn…. There is something called action script in Java which will do that work. I failed to find an action script programmer. People who know Flash just know UI and animation they don’t know about action script. I struggled a lot to find one developer and get it done. Finally I ended up learning:
All need different expertise and I got really very frustrated learning them. I know everything but I am not a master in any one of those. Take any of the above mentioned languages. They need more time and effort to get expertise in them. All I was doing was wasting time and money in outsourcing each and everything to another company and not giving the client a very good product.
Then I found out that Microsoft is coming with a product called Silverlight. They were very well aware about the problem developers were facing. They bundled everything into Silverlight. To make it simple to explain, Silverlight is nothing but a replacement for JavaScript, Flash (or any other UI dev kit), HTML. When I say replacement, I should also mention corresponding things which are replacing them so here is what I have listed:
Silverlight
I am a good ASP.NET programmer and I know C# well. So I can do client side coding in C# instead of JavaScript. Coooooool… That’s good.. Then Flash is replaced by WPF which is nothing but Windows Presentation Foundation which gives Drag and Drop like control in Visual Studio with Rich UI. And the code behind them is again C#. That’s awesome. And HTML is replaced by XAML silverlight which is nothing but a markup language like XML, but the only difference is TAGs are pre-defined unlike XML where we can have anything as TAG name. So I need to just concentrate on C# and XAML. I already know C# now I am left with XAML which is exactly like XML. Let me show you one sample XAML syntax.
<TextBox Name=”txtBox” Text=”Hello Silverlight!”>
</TextBox>
The above XAML code will create a TextBox with “Hello Silverlight!” written in its textbox. It’s so simple. Now I have a technology which is worth learning.
TextBox
Hello Silverlight
textbox
And that’s Silverlight. Now you might have got enough idea on Why Silverlight?
Now we can move to the relationship between WebBrowser, Webserver and Silverlight.
We will try to understand the relationship between web browser, web server and Silverlight.
This post is dedicated to these.
Web browser is nothing but an application residing on the Operating system which will render the HTML.Rendering means that it will know how to present the HTML Tags. It’s very important to know about working of web browser and most of the content here will talk about web browser and web server.
I will explain with one example.When you type, you see my blog, but what is happening behind is what I am going to explain.
What web browser does the same thing we are going to do to it with telnet command.
Now open command prompt. You can do that by going to Start -> Run and type the following:
telnet 80
[ Note : Telnet Comes along with Windows. It’s a program which can be used to connect to any machine on any port. Like you want to connect to SMTP server of Google. Then use this command.telnet smtp.gmail.com 25]
command.telnet smtp.gmail.com 25
Figure 1.0 shows usage of telnet to connect to webserver [ Port 80 – Default ].
Once you are connected to the webserver, then you need to talk to the webserver in a language which it can understand and those are called protocols. Webserver supports mainly two protocols:
GET
GET protocol is generally used to request for a page and POST protocol is used to post the data to the webserver. We will discuss the GET protocol.
GET
What webserver expects is a string named GET followed by the page it want to fetch.
string
GET “page url”
So after connecting to webserver, you need to enter the following thing:
GET
And mainly press Enter twice. That’s how the protocol is designed. That’s it. Now you will have the HTML code coming back from the server.
If you save all this data in a file with .html extension and open it in browser, you will see the same content which you will see when you visit.
The entire HTML comes up to the client side as a DOM document needs to be replaced each time a new request goes to the server. Let me give one example. Suppose you want to delete one mail in your inbox. Then one new request will be sending it to the server and then the entire response HTML without that deleted mail should come back. Then we need to refresh the entire screen.
Then the new concept was added and that was AJAX (Asynchronous JavaScript + XML). You can read more on it here. This gave us the feature for modifying the DOM which was available at the Browser. So each time you delete a mail, an asynchronous request goes to the server and returns back with a flag and based on that, we change the DOM. This new feature which was implemented in the DOM was called Inner HTML property. This allowed us to make use of AJAX kind of calls.
Hope now we are clear with Web Browser and Web Server. Let’s move ahead and find out how Silverlight is working. use this to program in C#. You can make use of almost all basic data types which are present in .NET CLR.
Microsoft is trying to put some lightweight CLR on the client side. I think it's kind of desktop application, but we are making use of web browser to put the necessary components. | http://www.codeproject.com/Articles/36685/Silverlight-for-Dummies-Why-Silverlight | CC-MAIN-2014-35 | refinedweb | 1,940 | 82.95 |
Compile Error with QT Creator 5.9
- William.Tran
Hi All,
I have a problem with my project when i use QT creator 5.9. The problem error is:
C:\Program Files (x86)\Windows Kits\8.1\include\um\sapi.h:12407: error: C2440: 'default argument': cannot convert from 'const wchar_t [1]' to 'BSTR'
I had investigated on this issue however, i could not find out any solution to resolve it. I have tried to use :
win32: QMAKE_CXXFLAGS_RELEASE -= -Zc:strictStrings
win32: QMAKE_CFLAGS_RELEASE -= -Zc:strictStrings
win32: QMAKE_CFLAGS -= -Zc:strictStrings
win32: QMAKE_CXXFLAGS -= -Zc:strictStrings
From this link:
But it does not help.
Can somebody help me on this?
Thanks.
- SGaist Lifetime Qt Champion
Hi,
Qt Creator is innocent in that matter, that's the compiler you are using that is problematic.
Which version of Visual Studio are you using 2015 or 2017 ?
Did you re-run qmake after adding these flags ?
- William.Tran
I am using Visual Studio 2015. I just tried to run QMake again. I don't get error message any more. However, i could not run my application. The build status is in RED.
I got this complier error message:
The kit Desktop Qt 5.9.0 MSVC2015 64bit has configuration issues which might be the root cause for this problem.
When executing step "Make"
Should i use Visual Studio 2017?
- William.Tran
i am still having this error. Are there any way to update my compiler or we should use new one (2017)?
- jsulm Moderators
@William.Tran Maybe you should use a newer Windows SDK: ?
- William.Tran
It looks like the error from my code. I have a class which support speech text.
void speechcontext::startSpeaking(){
qDebug("start speaking thread"); pVoice = NULL; isSpeaking = true; HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice); if( SUCCEEDED( hr ) ) { LPCWSTR text = (const wchar_t*) currentTextToSpeak.utf16(); if(currentVoiceToken != NULL){ pVoice->SetVoice(currentVoiceToken); } hr = pVoice->Speak(text, 0, NULL); HANDLE hWait = pVoice->SpeakCompleteEvent(); HRESULT rs = WaitAndPumpMessagesWithTimeout(hWait, INFINITE); if(rs == S_OK){ qDebug("speaking completed"); } pVoice->Release(); pVoice = NULL; }
}
Something like that, and i have used:
#include <sapi.h>
#include <sphelper.h>
#include <conio.h>
#include <iostream>
#include <string>
If i remove <sphelper.h> and its components. (some objects used in handle class). I can build my app success. So i think the speech text class is not compatible anymore. I should you QtSpeech in 5.9?
- SGaist Lifetime Qt Champion
That would be a good idea yes. | https://forum.qt.io/topic/80259/compile-error-with-qt-creator-5-9 | CC-MAIN-2017-43 | refinedweb | 404 | 69.18 |
Symptoms
Consider the following scenario:
In this scenario, CPU usage of the server seems to spike close to 100 percent, and you may experience performance issues such as delays.
- You have a computer that is running Windows 8.1, Windows RT 8.1, Windows Server 2012 R2, Windows 7 Service Pack 1 (SP1), or Windows Server 2008 R2 SP1.
- You have access-based enumeration enabled on a shared folder. Or you enable access-based enumeration on a DFS namespace on a folder.
- You use the Server Message Block 2.0 file-sharing protocol. By default, this protocol is used on Windows-based computers.
- You try to browse the contents of the shared folder. Or you try to do any other standard work that involves shared files.
In this scenario, CPU usage of the server seems to spike close to 100 percent, and you may experience performance issues such as delays., install update 2919355 in Windows 8.1 or Windows Server 2012 R2. Or, install Service Pack 1 in Windows 7 or Windows Server 2008: 2920591 - Last Review: 10 Dec 2015 - Revision: 1
Windows Server 2012 R2 Datacenter, Windows Server 2012 R2 Standard, Windows Server 2012 R2 Essentials, Windows Server 2012 R2 Foundation, Windows 8.1 Enterprise, Windows 8.1 Pro, Windows 8.1, Windows RT 8.1, Windows Server 2008 R2 Service Pack 1, Windows Server 2008 R2 Datacenter, Windows Server 2008 R2 Standard, Windows Server 2008 R2 Enterprise, Windows Server 2008 R2 Foundation, Windows Server 2008 R2 for Itanium-Based Systems, Windows 7 Service Pack 1, Windows 7 Ultimate, Windows 7 Enterprise, Windows 7 Professional, Windows 7 Home Premium, Windows 7 Home Basic, Windows 7 Starter | https://support.microsoft.com/en-gb/help/2920591/high-cpu-usage-and-performance-issues-occur-when-access-based-enumerat | CC-MAIN-2017-34 | refinedweb | 277 | 57.37 |
With my exploration into mass concurrency and big data problems, I’m always finding challenges to give myself on how I might solve a given issue. Such examples that have intrigued me along the way as PLINQ, MPI/.NET, Data Parallel Haskell, but one in particular has intrigued me more – MapReduce. A challenge I gave myself is to fully understand this paradigm and implement a version using F#.
What Is MapReduce?
MapReduce is a Google programming model and implementation for processing and generating large data sets. Programs written using this more functional style can be parallelized over a large cluster of machines without needing the knowledge of concurrent programming. The actual runtime can then partition the data, schedule and handle any potential failure. The Google implementation of it runs on a large cluster of machines and can process terabytes of data at a time.
The programming model is based upon five simple concepts:
- Iteration over input
- Computation of key/value pairs from each input
- Grouping of all intermediate values by key
- Iteration over the resulting groups
- Reduction of each group
So, where does this Map/Reduce wording come in? Well, let’s explore each:
- Map
Function written by the user to take an input pair and produce a result of intermediate key/value pairs. The intermediate values are then grouped with the same intermediate key and passed to the Reduce function.
- Reduce
Function also written by the user to take the intermediate key and sequence of values for that key. The sequence of values are then merged to produce a possibly smaller set of values. Zero or one output value is produced per our Reduce function invocation. In order to manage memory, an iterator is used for potentially large data sets.
How useful is this programming model? Using this model, we’re able to express some interesting problems such as the following:
- Word counts in large documents
- Distributed Grep – Find patterns in a document
- Count of URL Access Frequency
- Reverse Web-Link Graph – Find all source URLs for a given destination
- Term-Vector per Host – Summarize most important words in a document
- Inverted Index
- Distributed Sort
That’s only a start to what we can do. After the paper which explained the technology was published in 2004, there have been several implementations including the open-source Hadoop project and the Microsoft Research Project Dryad. Of course, it doesn’t come without some criticism about the resource usage such as this post called “eBay doesn’t love MapReduce”.
Dryad is more interesting in that its functionality subsumes MapReduce and can do in regards to job creation, resource management, job monitoring, visualization and more. What’s even more interesting is the associated project DryadLINQ, which allows us to compile LINQ expressions to have sent across the cluster so that I could perform intense data analysis using LINQ operators that we’re used for our other data tasks. What does the future hold for Dryad remains to be seen, but the possibilities seem plenty.
F# Implementation
The challenge I gave myself was to understand the basics of the programming model. Ralf Lämmel, formerly of the Microsoft Programmability Team, published a paper entitled Google’s MapReduce Programming Model – Revisited which I used as a source for how my F# implementation works. If you want to understand not only the deep internal details, but also how an implementation in Haskell would look, I highly recommend this paper.
In our example, we’re going to use a MapReduce implementation to look for the most frequent IP addresses from our IIS logs. Let’s first start by defining the outer skeleton needed. Let’s define what the map_reduce function and associated steps will look like:
namespace CodeBetter.MapReduceExample
module MapReduceModule =
let map_reduce
// Map function take pair and create sequence of key/value pairs
(m:‘k1 -> ‘v1 -> seq<’k2 * ‘v2>)
// Reduce function takes key and sequence to produce optional value
(r:‘k2 -> seq<’v2> -> ‘v3 option)
// Takes an input of key/value pairs to produce an output key/value pairs
: Map<’k1, ‘v1> -> Map<’k2, ‘v3> =
map_per_key >> // 1. Apply map function to each key/value pair
group_by_key >> // 2. Group intermediate data per key
reduce_per_key // 3. Apply reduce to each group
I’m using the standard sequences instead of lists for this because the data may be large and the List<T> in F# by default is eagerly evaluated. The case could be made to use the LazyList<T> to model the data, but as I might want to use the Parallel Extensions and the PSeq module I used before, I’ll stick with the IEnumerable<T>.
The comments here in the code say a lot about what’s going on. Our map_reduce function takes two functions, the map and the reduce which are explained in the code comments. It’s important to understand what happens last is our series of three functions, our map_per_key, group_by_key and reduce_per_key. Each of those steps fall into line with the explanation from above. At this point, we haven’t actually yet implemented the functions, but let’s go ahead and do that now to flush out our map_per_key, group_by_key and reduce_per_key. The following code comes before the last statement which ties our three functions together:
Map.to_seq >> // 1. Map into a sequence
Seq.map (Tuple.uncurry m) >> // 2. Map m over a list of pairs
Seq.concat // 3. Concat per-key lists
let group_by_key (l:seq<(‘k2 * ‘v2)>) : Map<’k2,seq<’v2>> =
let insert d (k2, v2) = Map.insert_with Seq.append k2 (seq [v2]) d
let func (f:Map<’a, seq<’b>> -> Map<’a, seq<’b>>) (c:‘a * ‘b)
: (Map<’a, seq<’b>> -> Map<’a, seq<’b>>) =
fun x -> f(insert x c)
(Seq.fold func (fun x -> x) l) Map.empty
let reduce_per_key : Map<’k2, seq<’v2>> -> Map<’k2,’v3> =
let un_some k (Some v) = v // Remove optional type
let is_some k = function
| Some _ -> true // Keep entires
| None -> false // Remove entries
Map.mapi r >> // 1. Apply reduce per key
Map.filter is_some >> // 2. Remove None entries
Map.mapi un_some // 3. Transform to remove option
The first function is the map_per_key which first turns a map into a sequence. Then we map the m function over our list of pairs, and then finally concat the per-key lists. Next our group by key might look a little interesting, but it’s simply a right fold over our insert function and our sequence of key/value pairs. As I had in a previous post about how you can do right-folds in the terms of a left-fold. Finally, our reduce per key applies the reduce function, then filters the removable entries, and finally transforms to remove the optional type.
There you have it, our implementation of a MapReduce. Now let’s step ahead with our implementation to step through our IIS logs. Let’s first retrieve the data for our logs from a given directory. We can use the async workflows in F# to retrieve this data in parallel given a base directory. Next, we need a way to harvest the data from the given logs so that we can get the IP address from it.
open System.IO
let processed_logs : (string * string) array =
Async.Run (
Async.Parallel
[for file in Directory.GetFiles @"C:\Logs\" ->
async { return file, File.ReadAllText file }])
let harvest_data (data:string) : seq<string> =
seq { for line in String.lines data do
if not (line.StartsWith "#") then
yield line.Split([|' '|]).[2]
}
Finally, we can count get the IP occurrence count by implementing our map and reduce functions and calling our map_reduce implementation.
let m = const’ (harvest_data >> Seq.map(flip Tuple.curry 1))
let r = const’ (Seq.sum >> Some)
MapReduce.map_reduce m r
module MainModule =
[<EntryPoint>]
let main(args:string array) =
printfn "%A"
(LogCount.ip_occurrence_count
(Map.of_seq LogCount.processed_logs))
0
The m function above harvests the data from the string value and then mark each IP address with an occurrence of 1. Then our reduce function will sum the sequence of 1s for each given key to produce our result. There is some boilerplate code that has been omitted due to space constraints but will be available at the end of this post. Once we run this against a known set of data, we might get the following results:
[[192.168.1.2, 46]; [192.168.1.8, 339];
[192.168.1.10, 11]; [192.168.1.15, 43]]
Press any key to continue . . .
With this simple example, we can see some of the power and possibilities such a programming model can bring. This exercise is more of an idea of how one might be written using the programming model, as I didn’t write any system to handle concurrency, scheduling and so on.
Conclusion
In many of my adventures in big data analysis and data parallel concurrency, MapReduce is one of the more interesting solutions. By utilizing functional programming constructs, we are able to write rich code to analyze our data that may not as structured as we wish. But, does our adventure stop here with this implementation? Not necessarily, but either way it was a lot of fun.
You can find the source code for this example here. | http://codebetter.com/matthewpodwysocki/2009/03/03/exploring-mapreduce-with-f/ | crawl-003 | refinedweb | 1,531 | 63.59 |
"
Mozilla Firebird becomes Firefox
Posted Feb 9, 2004 9:06 UTC (Mon) by rknop (guest, #66)
[Link]
When it takes this much effort for a free software organization to find a safe *name* for their project, it's clear that we've got some global issues with proprietization of words. These impact freedom of speech issues too, even if a bit obliquely.
I can imagine an alien civilization coming to Earth and looking at our civilization, and coming away scratching their heads. In line with years of science fiction cliches, they will be horrified with the violence and war that they see, of course, but they will say, well, any species that developed through the tooth-and-claw process of evolution will have to overcome those issues, so we can understand why you're struggling with it. But all this tremendous amount of time, effort, and resources that go to determining who owns which idea and which thought and which word, and who should be punished for thinking or saying something that somebody else owns-- what's THAT all about? War is something that any species has to be overcome, but since you Earthlings devloped this and spend so much effort on this notion of owning thoughts and ideas, you must be REALLY backward.
-Rob
Posted Feb 9, 2004 9:22 UTC (Mon) by alspnost (subscriber, #2763)
[Link]
Posted Feb 9, 2004 9:31 UTC (Mon) by pglennon (guest, #649)
[Link]
Posted Feb 9, 2004 9:36 UTC (Mon) by rknop (guest, #66)
[Link]
We're well on our way in that direction.
Posted Feb 9, 2004 10:20 UTC (Mon) by JoeBuck (subscriber, #2330)
[Link]
Even in the absence of trademark law, it would still be advisable to give different programs different names. As it was, there were two significant free software programs named Firebird. Changing the name of the newer one in a case like this is good manners.
Posted Feb 9, 2004 17:48 UTC (Mon) by jamesh (subscriber, #1159)
[Link]
You do realise that there were many more than just two programs going by the name "Firebird"? And that the database wasn't even the first program to use the name? (let alone the first free software program)
What would the Firebird Database people do if the Firebird BBS people complained about them stealing the name? My guess is that they would claim that there is no confusion due to one being a BBS and the other being a database.
There is a reason that trademarks are limited to cover particular subjects rather than being global ...
Posted Feb 10, 2004 2:29 UTC (Tue) by james (subscriber, #1325)
[Link]
Unfortunately, that particular piece of "IP" law isn't universal.
It's true, as far as I can tell, for the US and the UK. It's not true in France or Germany.
Humans are not perfect
Posted Feb 9, 2004 12:49 UTC (Mon) by proski (subscriber, #104)
[Link]
Posted Feb 9, 2004 13:10 UTC (Mon) by elanthis (subscriber, #6227)
[Link]
The only problem in this situation at all is that Mozilla has gone with 'Firebird' for a while now, vs switching earlier before the world got accustomed to the name.
Posted Feb 9, 2004 15:24 UTC (Mon) by tjc (guest, #137)
[Link]
What we really have is a global namespace issue. But I think it may work out for the best in this case. I would rather call my web browser "Firefox" (not to be confused with entertainment.movies.firefox) than "software dot webclients dot Firebird."
Posted Feb 9, 2004 16:42 UTC (Mon) by rknop (guest, #66)
[Link]
But the fact that you can't choose a name without hiring lawyers and searching proprietary databases, and that you are in danger of civil penalties if you choose wrong, is what really gets me all annoyed.
-Rob
...speaking of which. My name is Rob. So are lots of other people's. Yet we seem to cope.
Posted Feb 10, 2004 8:37 UTC (Tue) by tjc (guest, #137)
[Link]
Posted Feb 9, 2004 9:28 UTC (Mon) by sphealey (guest, #1028)
[Link]
sPh
Posted Feb 9, 2004 9:38 UTC (Mon) by rknop (guest, #66)
[Link]
Which Hollywood studio put it out? (And I wouldn't be surprised if there was a computer game tie-in, although the movie may have come out too early.)
I can't wait for the movie company to sue the project over trademark infringement. After all, parts of the movie industry (the parts that do the suing, in contrast to the parts that do the special effects) *hate* free software.
Posted Feb 9, 2004 10:02 UTC (Mon) by KaiRo (subscriber, #1987)
[Link]
Robert Kaiser
German Firefox/Thunderbird ?
Posted Feb 9, 2004 12:58 UTC (Mon) by gadeiros (subscriber, #3929)
[Link]
Are you planning to translate also Firefox and Thunderbird ? Or do you stick with Seamonkey ?If not, is there any planning by others you know of (mozilla.org ?) to do this ?
Couldn't find a hint on your homepage.
Regards,Harald Henkel
Posted Feb 10, 2004 6:04 UTC (Tue) by KaiRo (subscriber, #1987)
[Link]
Posted Feb 14, 2004 5:42 UTC (Sat) by crankysysadmin (guest, #19449)
[Link]
Exactly, so why did they have to jump through hoops shying away from both Phoenix and Firebird? Neither was a web browser.
I agree with the "community" argument to a certain extent, but working out disputes can be taken to extremes, and I wish that the law was laxer on forcing you to defend your trademark. Of course, I also wish brand names and marketing weren't so important to so many consumers in the first place, since they have exactly nothing to do with the quality of a product, so clearly I expect too much.
Posted Feb 9, 2004 10:06 UTC (Mon) by southey (subscriber, #9466)
[Link]
Posted Feb 10, 2004 5:53 UTC (Tue) by the_JinX (guest, #3953)
[Link]
Posted Feb 9, 2004 9:57 UTC (Mon) by KaiRo (subscriber, #1987)
[Link]
I'm not fond of any of those names, not even of the product itself. As many people who lived in the Mozilla community quite some time, I love to stick with the Mozilla Application Suite (code-named "Seamonkey").AOL/Netscape/mozilla.org went a long way to find a new name after they found out that Phoenix had issues (there already had been a browser called "Phoenix" somewhere), and they secured that "Firebird" had no legal issues..It again took the (now already founded) Mozilla Foundation months and legal chacking to find a name they could use (see Ben's blog). And still, the name has smaller issues with registered trademarks in Europe (Germany and Switzerland). From Ben's speaking, it seems they solves those issues in some way, though.
It really seems damn difficult to find good names today - to quote the Firefox name FAQ: "We've learned a lot about choosing names in the past year (more than we would have liked to)."I hope this still will not make progress in good projects stagnate or stop, just because they have to consider one name after the other. And I don't think we want to end up with "The browser created by Ben Googer, Dave Hyatt and a few others" or something like that as a project name because shorter names are too hot. [Mozilla] Firefox, the browser formerly known as Mozilla Firebird, the browser formerly known as Phoenix, has shown us a good example of how hard it is to find a suitable name for a big project these days.
The more important thing is something completely different though:A new release of Mozilla Firefox, and that 0.8 release can be considered the currently best cross-platform stand-alone browser available, and one of the best browsers available for Linux and even Windows. Spread the word and make some of your friends enter open-source with a more secure browser than the default on their OS might be.(And if they want/should migrate Mail as well, consider newly released Mozilla Thunderbird, or the Mozilla 1.6 "Seamonkey" Application suite that includes browser and mail)
Posted Feb 9, 2004 11:32 UTC (Mon) by sphealey (guest, #1028)
[Link].
Posted Feb 9, 2004 11:41 UTC (Mon) by KaiRo (subscriber, #1987)
[Link]
Robert Kaiser(being no official of mozilla.org in any way, only a small contributor and leading the German l10n project of the Mozilla)
Firefox????
Posted Feb 9, 2004 10:04 UTC (Mon) by jensend (guest, #1385)
[Link]
Posted Feb 9, 2004 10:07 UTC (Mon) by xorbe (guest, #3165)
[Link]
Posted Feb 9, 2004 10:10 UTC (Mon) by KaiRo (subscriber, #1987)
[Link]
And you can always stick with plain Mozilla 1.6 (or call it "Seamonkey", like we've been doing for years now).
BTW, Firefox is a cute littel animal, also called the Red or Lesser Panda, belonging the the Panda family...
Posted Feb 9, 2004 10:28 UTC (Mon) by proski (subscriber, #104)
[Link]
Pictures of lesser panda, courtesy of Google.
Posted Feb 9, 2004 10:37 UTC (Mon) by KaiRo (subscriber, #1987)
[Link]
Posted Feb 9, 2004 10:49 UTC (Mon) by ballombe (subscriber, #9523)
[Link]
> BTW, Firefox is a cute littel animal also called the Red or Lesser
> Panda, belonging the the Panda family...
It is certainly a cute little animal, but it is not clear
whether it belongs to the same family as the Giant Panda.
See the wikipedia
entry which include a nice photograph.
Posted Feb 9, 2004 11:10 UTC (Mon) by jensend (guest, #1385)
[Link]
Posted Feb 9, 2004 13:57 UTC (Mon) by jsebrech (guest, #11709)
[Link]
Posted Feb 10, 2004 9:10 UTC (Tue) by tjc (guest, #137)
[Link]
(The) Red Panda sounds like a Chinese restaurant to me. ;-)
Worst name...
Posted Feb 9, 2004 11:34 UTC (Mon) by sphealey (guest, #1028)
[Link]
Worst. Project name. Ever.
Posted Feb 9, 2004 11:55 UTC (Mon) by KaiRo (subscriber, #1987)
[Link]
And to quote the Firefox name.
-- Steve Garrity, Gervase Markham, Ben Goodger, Bart Decrem et al. "
Posted Feb 9, 2004 16:37 UTC (Mon) by fLameDogg (guest, #11305)
[Link]
Posted Feb 9, 2004 10:44 UTC (Mon) by ncm (subscriber, #165)
[Link]
Moas are more impressive than emus, but are (recently) extinct. Both birds' bipedal locomotion, useless forelimbs, and fierce nature seemed more or less appropriate to the project.
What is worst about the whole fiasco is not the repeated renaming, but the contempt displayed by the principals in the project who insisted on Firebird, in the first place, despite knowing about the other project already. I would never hire people like them. Actually, it's generally foolish to use any dictionary word as a trademark, when it's so easy to invent a word that certainly does not collide with any existing product/project.
Posted Feb 9, 2004 10:59 UTC (Mon) by KaiRo (subscriber, #1987)
[Link]
Anyways, mozilla.org agreed with the copyright holders of Godzilla not to name any new products ending in -zilla, so what you proposed wouldn't work.
Posted Feb 9, 2004 11:17 UTC (Mon) by smoogen (subscriber, #97)
[Link]
other Firebird's
Posted Feb 9, 2004 10:57 UTC (Mon) by ccyoung (subscriber, #16340)
[Link]
Posted Feb 9, 2004 11:14 UTC (Mon) by ncm (subscriber, #165)
[Link]
Posted Feb 9, 2004 11:16 UTC (Mon) by TimCunningham (guest, #10316)
[Link]
Posted Feb 9, 2004 14:59 UTC (Mon) by hensema (guest, #980)
[Link]
is this a Biblical name?
Posted Feb 9, 2004 14:40 UTC (Mon) by error27 (subscriber, #8346)
[Link]
The thing is that Samson tied the foxes into pairs so that they would run more randomly and the Firefox logo only shows one fox instead of two. Perhaps somone can correct this detail?
Posted Feb 9, 2004 16:39 UTC (Mon) by fLameDogg (guest, #11305)
[Link]
Posted Feb 9, 2004 19:22 UTC (Mon) by dlang (subscriber, #313)
[Link]
It does seem noticably faster (but some of that could just be expectations, no benchmarks have been done)
Posted Feb 10, 2004 9:07 UTC (Tue) by tjc (guest, #137)
[Link]
I'm hoping that by the time Firefox gets to version 1.0 it will have full support for the W3C DOM level 2 recommendation, but version 0.8 is still failing UIEvents, MutationEvents, and Traversal in my informal test. It's not a big deal, since it's already light years ahead of IE 6 (which fails EVERYTHING except level 1 core), but it would be nice.
Posted Feb 10, 2004 4:51 UTC (Tue) by sitaram (subscriber, #5959)
[Link]
I wonder if anyone thought of using the name (as in "given name") of a specific phoenix in mythology. Not knowing any mythology that involves a phoenix, the only one I could think of is Fawkes -- Professor Dumbledore's pet bird in the Harry Potter series.
And guess what - fox rhymes with Fawkes ;-) So I'm happy!
Sitaram
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/70206/ | crawl-002 | refinedweb | 2,185 | 72.9 |
reader sub
Expand Messages
- Hi,
would it be possible to return from a handler, a reader sub instead of a list of values.
For example:
sub enumerate {
my ($start,$end) = @_;
return ($end-$start, sub { $start < $end ? $start++ : undef });
}
That way, when SOAP::Lite looks at the result from the handler, it replaces the array with the return value of the closure, until that closure returns undef.
Why do I want this? I tend to deal with large amount of elements, and passing the array back to SOAP::Lite, and then SOAP::Lite encoding it, and so on, tends to result in a heavy use of memory. This would mean that my code never has to keep more than 1 element at a time in memory.
Another possible improvement would be for the XML serializer to be able to spit out it's XML to STDOUT (or wherever it's supposed to go) right away, instead of encoding the whole thing in memory and then sending it.
-Mathieu
Your message has been successfully submitted and would be delivered to recipients shortly. | https://groups.yahoo.com/neo/groups/soaplite/conversations/topics/1194?var=1 | CC-MAIN-2018-05 | refinedweb | 181 | 66.27 |
OSX:Changing the “Web Receipts” FolderApril 14, 2008 | 8 Comments
One of my favorite features in Leopard is the “Save to Web Receipts”. Judging by the posts on the web I’m not sure whether this is a new feature or not. Either way, I really like it… except… Saving important web pages (receipts, confirmations, reservations, etc) is something I’ve been doing for a long time now without this feature, it was just a pain. In fact I did it on Windows for years before even switching to Mac, except all by hand. The function in OSX saves me the trouble of naming the file and choosing the directory which is great, except I don’t like the way it does either.
The first problem is that in general the date of the receipt is the most importat sorting factor, and having it in the “date modified” column is mildly dangerous, like if I make changes or notes on it for example. The second problem is at work when I’m saving receipts it doesn’t help me get them to the unified receipts folder at home.
I decided to solve both problems today and luck you, I’ll share. Reading the web the way this was implemented changed at some point. It used to be an Automator script but apparently that was rather limiting (which is pretty bad if you’re Apple and your own Automator doesn’t cut it). So they re-implemented in Python. This is a shame because having opened up Automator for the first time it looks really cool and relatively user friendly, unlike what you’re about to repeat below.
- In Finder, go to /Library/PDF Services/
- Duplicate the “Save PDF to Web Receipts Folder” and rename it to something else but keep the .pdfworkflow extension, in my case, “Save to DropBox Receipts.pdfworkflow”
- Right-click and select “Show Package Contents”
- Naviage into the “Contents” folder
- Delete the “Resources” folder
- Open “Info.plist” in a text editor and rename the “CFBundleName” string to something helpful, probably something that strongly resembles the filename you created in Step 2, then save and close that file
- Open the “tool” file in a text editor
- If you want to change the target folder:
- around line 24 you’ll see something the line that sets the value of destDirectory to “~/Documents/Web Receipts/”, change that.
- If you want to add a date at the beginning of the filename
- at the top of the file (around like 9) insert a new line with:
from datetime import date
- around the previously mentioned line 24 add:
title = "%s - %s" % (date.today(), title)
- Save and exit
That will end up giving you filed names like “2008-04-13 – American Express Online.pdf” saved in the directory of you’re choosing. To test just go to any app, bring up the print dialog and confirm that your new entry shows up. Also, if you have any problems, just trash the duplicate you created and edited.
EDIT (2008/08/26) – Fixed the missing close parenthesis at the end of item 9.2 pointed out by James. Thanks!
Making RSS feeds for TruveoMarch 31, 2008 | Comments Off
You’ve probably seen or heard of the unconventional “You Suck at Photoshop” tutorials. Maybe you weren’t offended, maybe you even like them. Maybe you want to track new releases via RSS. I was just like you a few minutes ago. I checked the MyDamnChannel.com website and couldn’t within my attention span find a feed that was just for YSaP videos. I’d seen them on YouTube so my first instinct was to go to YouTube and build an RSS feed from a search. Oops you can’t (at least not a very specific one).
Then I remember: Wait, I work with a search engine that does this EVERY DAY. Truveo makes this trivial. I went to Truveo.com and searched for:
“You Suck at Photoshop” channel:youtube
This returned the right set plus other spoofs and knock-offs. It needs to be restricted to the official user that posts them:
“You Suck at Photoshop” channel:youtube author:mydamnchannel
Perfect! Now click the “most recent” button to get the newest episodes first, and towards the bottom left hand corner you’ll see the traditional RSS icon. Copy and paste that link into your RSS reader and you’re done! (Click the thumbnail for a larger view of the page I’m referring to.)
Alexis Victoria AverbujFebruary 20, 2008 | 23 Comments
Alexis Victoria born 2/20 around 3:15pm at 7 lb 5 oz and 19.5 inches long. Pictures later tonight. Mom and baby are healthy, happy, and hungry!
Update (2/21, 9:30am): Pictures of Alexis are now available.
Dilbert Widget leaks dataJanuary 22, 2008 | Comments Off
Scott Adams blogged about the new Dilbert comic widget which is great and I’m pleased with. The problem is (assuming United Media cares about not pre-releasing comics) that the comics are named predictably in sequence and are available on the server ahead of time. For example here is the comic for Sunday February 3. Oops! Now I don’t have to wait. I imagine they’ll solve this problem pretty quickly when they find out. While I’m on the subject of people who have solved this differently, Penny Arcade has an interesting system where always points to the latest comic and there are absolute paths to get to a specific date. They have a particularly odd problem where the absolte URL doesn’t work, but /comic/ does. I get bitten by that problem fairly frequently since their RSS points to the absolute location. Another comic strip solves this problem in a decidedly low-tech way. Something Positive names each comic strip (image) with a descriptive title of the strip. Also, he releases comics unpredictably, and near as I can tell, maintains no buffer unlike Dilbert.
Back on the Dilbert side, interestingly at 400 it loops back to 2005, althought comic 1 is Jan 1 2007. It makes me curious about how the numbering sequence progresses, but invariably it will be deterministic. The easy way to solve this problem is to put something on the server side that prevents images from being served before their publish date. The wrong way to try to fix this is to try authenticating the widget (which, by the way, is now possible with FMSv3, but that’s for another day).
Update (Jan 23, 12pm): Just checked this today and the hole has been fixed. Now the actual gif seems to be an hash of some data, although apparently not the comic strip itself. Good turn around time!
Encoding.
BootCamp on Tiger (Post Lepoard)December 18, 2007 | Comments Off
So Apple did a fairly crass thing by terminating Boot Camp for Tiger when Lepoard launched. I was replacing my Dell at work with a Mac and wanted to have a native install of XP for troubleshooting. I couldn’t find Boot Camp 1.4 which was presumably able to work until Dec 31 because Apple had pulled it, but I did find an old copy of 1.2 on my laptop but it wouldn’t run because it was past expiration. How do you solve this impossible problem? Uh, set the clock back. I circumvented annoying beta policy by the same technology with which I avoided nag screens in shareware in 1996. Lame.
Bugs.
Web.
Mac:.
On ShameNovember 16, 2007 | Comments Off
From an IM conversation:
Friend: I want the syntax to find all files in /home older than 30 days so I can nuke them
Pablo:
find /home -mtime +30 -type f
Friend: so
find /home -mtime +30 -type f | rm -rf
Friend: thats all I need?
Pablo:
find /home -mtime +30 -type f -print0 | xargs --null -- rm -f --
Friend: ok
Friend: I’m doing it with PHP right now….
Pablo: the print0/null parts are in case you have filenames with spaces
Friend: which is… fun… :(
Pablo: i hate you
Pablo: why do you need to make me feel so dirty | http://pablo.averbuj.com/page/2 | CC-MAIN-2017-51 | refinedweb | 1,353 | 70.43 |
With the oop way, i get a 0 value with echo (in controller), while the test app still shows the correct value:
require_once $_SERVER ['DOCUMENT_ROOT'] . "/testing/IPTest.php"; echo \IPv4\checkIPAddressIsInRange();
No way is working: Neither session or include/require_once nor the oop one. WTF is going on, something must be completely fu***d up..
The crazy thing is that the test app works without any problems:
<.", "; echo var_dump($test); $test = $ipAddressIsInRange; echo ", without session: ".$test.", "; echo var_dump($test); ?>
...with that IPTest:
<?php namespace IPv4; if(true) { error_reporting(E_ALL & ~E_NOTICE); ini_set ( 'display_startup_errors', 1 ); ini_set ( 'display_errors', 1 ); } if(!session_id() || session_id() == null || session_id() == '') { session_start(); } require_once $_SERVER ['DOCUMENT_ROOT'] . "/testing/ipv4-subnet-calculator/src/SubnetCalculator.php"; //] = "77.239.32.0/19"; $range [1] = "46.255.168.0/21"; $range [2] = "37.35.112.0/21"; $range [3] = "185.74.112.0/22";; } $ipAddressIsInRange = checkIPAddressIsInRange(); // Use caching or not... if(false) { if(!isset($_SESSION['ipAddressIsInRange2'])) { $_SESSION['ipAddressIsInRange2'] = $ipAddressIsInRange; } } else { $_SESSION['ipAddressIsInRange2'] = $ipAddressIsInRange; } ?>
Regards, Jan
I don't think you even understand much about object oriented concepts... I have never needed to use the global keyword inside of a class and I have definitely never put code like you are outside of the class when it could be used in a class method instead. You seem to be stuck in a procedural mindset. Perhaps you should watch one of these video series to catch up...
Yes, at least not a lot about the syntax in PHP... with PHP, for me it's an advantage when i don't need to use OOP... and, as far as possible, i also try to avoid functions in that language...;)
a "global" (with the include/procedural way) does also not help here so it seems:
public function index() { require_once $_SERVER ['DOCUMENT_ROOT'] . "/testing/IPTest.php"; global $ipAddressIsInRange; ... ... ...
Regards, Jan
Now i will try to use PHP "scriptlets" in Smarty template... escaped out of OO context!!
The other "solution" is to place the google analytics/statcounter.com tracking code in a site in an iframe...
The most idiotic and not elegant solutions are mostly working in IT, that's well-known to me! ;)
Regards, Jan
In WordPress "functions.php" i use that code, zero problems:
require_once ABSPATH.'/testing/IPTest.php'; $_SESSION['ipAddressIsInRange'] = IPv4\checkIPAddressIsInRange();
..but it's not in an OO context. Same as my test application. So the problem must be OO.
In WordPress "functions.php" i use that code, zero problems:
Of course you're not going to have problems; WordPress is mostly procedural. Are you unwilling to adapt to newer programming practices or something? OOP makes for much easier to maintain code, as well as reusable code.
It's ok. You're only about 20 years behind the times. Blame the modern framework for your lack of oop understanding... you might as well skip a modern framework and stick to your outdated procedural code and think you're smarter. WordPress is anything but modern/current as far as php goes. It's a relic.
OOP != OOP, i don't hope that is too complicated to unterstand.
Java and, for example, C# is REAL OOP... C++ and Java are not, it's just wannabe... that just my humble my opinion, maybe i'm completely wrong.
In Java, there is almost no other way than to use OOP. You can't programm ALL in a static way, completely impossible..
In Java i have a lot of experience in OOD & OOP. But the syntax and the concept of PHP or C++ OOP is all very different. In Java, i have a good OO knowledge, including the "advanced" things like design patterns, null interfaces, weak and strong references, serialization, reflection, etc. pp.
"...and think you're smarter."
No, but maybe my apps and websites are faster...;)
"WordPress is anything but modern/current as far as php goes."
Now i use WordPress only as a backend, that's the reason for my Laravel-frontend-Problems... but i don't have the time to read book for hundreds of hours about PHP OOP and Laravel...
Because of that: "learning by doing"...
P.S.: Now i've solved the problem with a laravel-independent PHP script, that will be called by SJAX GET request, and it returns 0 or 1. content-type ist text/plan, really simple.
If 1 then -> ip address is in range -> do nothing... If 0 then -> ip address is not in range -> javascript block x will be executed
Thanks to everyone and best regards, Jan
Please sign in or create an account to participate in this conversation. | https://laracasts.com/discuss/channels/laravel/cant-use-sessions-in-laravel-controller?page=2 | CC-MAIN-2018-43 | refinedweb | 755 | 68.67 |
what's the best way to return a List from a list of Lists of a base class based on string passed in. I've got:
public List<myBaseData> FindFromListofLists(string aClass, List<List<myBaseData>> data)
{
foreach (var item in data)
{
foreach(myBaseData baseData in item)
{
if (baseData.ToString().CompareTo(aClass) == 0) //not sure if this is the best way as if the class overides the toString method...
return item;
}
}
return null;
}
I'm sure there's a better way to do this. Any help would be appreciated.
Try -
public List<myBaseData> FindFromListofLists( string aClass, List<List<myBaseData>> data) { return data.Find( item => item .Where(d => d.ToString().CompareTo(aClass) == 0) .Count() > 0); }
You can also try to write it as -
return data.Find(item => item.Select(x => x.ToString()).Contains(aClass));
Please note that the code is untested :P
Is this what you need?
How to Union List<List<String>> in C#
And then you can use the
.Where() method to narrow down the results to those matching
aClass.
you can use:
if (((List<myBaseData>)item).Contains(aClass)) ; { return (item); }
instead of your second "foreach". and that's the great thing about dynamic lists.
I would use a
Dictionary<string, List<myBaseData>> or
Dictionary<Type, List<myBaseData>> insted of
List<List<myBaseData>>
The Dictionary-s
TryGet method does exactly what you need in
FindFromListofLists
I think what you are trying to achieve is this.
public class MyBaseClass{} public class MyChildClass : MyBaseClass{}
then somewhere else you want to return only the MyChildClass objects. this is what you need to do:
public IEnumerable<MyBaseClass> GetFilteredObjects(Type type, List<List<MyBaseClass>> lists) { foreach(var list in lists) { foreach(var item in list) { if(item.GetType() == type) yield return item; } } }
then you call this method like this:
var myChildClasses = GetFilteredObjects(typeof(MyChildClass), listOfLists);
Hope this is what you are looking for. | http://m.dlxedu.com/m/askdetail/3/32ce55a4a139ce5c7cceba5223697952.html | CC-MAIN-2018-22 | refinedweb | 308 | 56.96 |
Brendon Towle wrote: > ? (cons <item> <list>) > > returns a single level list, with <item> as its new first item, and > the original contents of <list> as the remainder of the list. The > OP's code doesn't do that; it returns a list of two items, with > <list> as the second item. That is equivalent, as <list> is the remainder of the list. By list I mean the resulting chained data structure, not the Python list as it is an array. > To put it another way, the following code is always true in Lisp: > > ? (= (length (cons <item> <list>)) (1+ (length <list>))) > > But the OP's code only allows that to be true when <list> is of > length 1. That is indeed a discrepancy. > I suppose, of course, that you could claim that the following Lisp list: > > (1 2 3 4) > > should translate into the following Python list: > > [1, [2, [3, [4]]]] > > But, I think that's a bit silly. It is not at all silly. Let us look at how these lists are stored in memory. (Use a fixed size font like courier.) First the Lisp list (1 2 3 4): (car,cdr) | | 1 (car,cdr) | | 2 (car,cdr) | | 3 (car,cdr) | | 4 nil Here, car is a reference to the number, cdr is a reference to the remainder of the list. Now look at the Python "list" [1, [2, [3, [4,null]]]]. Again, car is a reference to the value, cons is a reference to the remainder of the list. [car,cdr] | | 1 [car,cdr] | | 2 [car,cdr] | | 3 [car,cdr] | | 4 null You can see that they are indeed equivalent. In Lisp you have a pair of references, lets call them car and cdr, one pointing to the value the other to the remainder of the list. In Python you have the exactly same thing. The original poster was asking about using Python for teaching data structures and algorithms. Chaining together elements in e.g. a linked list or a binary tree is elementary concepts. This shows how it can be done in Python without having to define "classes" for the data stuctures as one would in Java or (Heaven forbid) C++. Thus I stand by my original claim. Essentlially: def cons(car,cdr): return (car,cdr) # or [car,cdr] def car(cons): return cons[0] def cdr(cons): return cons[1] | http://mail.python.org/pipermail/python-list/2006-September/365653.html | CC-MAIN-2013-20 | refinedweb | 393 | 72.66 |
Tassilo Horn <address@hidden> writes: > Oh, checking the backtrace I've posted at the beginning of this thread, > I've found this code in gtkutil.c: > > #if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 10 > /* GTK 2.2-2.8 has a bug that makes gdk_display_close crash (bug >). This way we > can continue running, but there will be memory leaks. */ > g_object_run_dispose (G_OBJECT (gdpy)); > #else > /* This seems to be fixed in GTK 2.10. */ > gdk_display_close (gdpy); > #endif > } > > That's already the right workaround, isn't it? The only thing is that > this bug is *not* fixed in GTK 2.10 but instead still exists (or > exists again) in GTK 3.2.0. I've just commented the line in the #else and recompiled emacs and reproduced the issue, i.e., started emacs using the application menu (resulting in a frame on display :0) and then opened another frame using emacsclient -c in a gnome terminal, so that in the end (x-display-list) returned (":0" ":0.0"). Then I deleted the frame created by emacsclient -c using C-x 5 0. The result is that the frame is still there but not functional. I can't even see the mouse pointer when hovering over it. From my perspective, that's an improvement. :-) (x-display-list) returns (":0") again. Bye, Tassilo | https://lists.gnu.org/archive/html/emacs-devel/2011-10/msg00403.html | CC-MAIN-2014-15 | refinedweb | 215 | 75.4 |
Subject: Re: [boost] [local] Simplifying the parenthesized syntax
From: John Bytheway (jbytheway+boost_at_[hidden])
Date: 2011-02-10 16:13:12
On 10/02/11 15:59, Lorenzo Caminiti wrote:
>?
Amazing!
(I might argue that the parentheses around "f" are extra, but that would
be churlish ;))
<snip>
>).
You shouldn't need to use Typeof if you extract the return type in the
manner Steven Watanabe suggested:
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/function_traits.hpp>
#include <boost/type_traits/is_same.hpp>
#define EXTRACT_TYPE_BEFORE \
deduce_result(); \
typedef boost::function_traits< \
typeof(deduce_result)>::result_type result_type;
int main()
{
void EXTRACT_TYPE_BEFORE
BOOST_MPL_ASSERT((boost::is_same<result_type, void>));
}
It even gives a (relatively) nice error when the user forgets the return
type (on gcc 4.4):
deduce_result was not declared in this scope
I share your hope that this syntax is enough to satisfy most of the
objectors! Do check how they respond when misused, though; a little
effort to improve error messages might go a long way.
John
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/2011/02/177026.php | CC-MAIN-2020-16 | refinedweb | 183 | 50.23 |
SD_EVENT_NEW(3) sd_event_new SD_EVENT_NEW(3)
sd_event_new, sd_event_default, sd_event_ref, sd_event_unref, sd_event_unrefp, sd_event_get_tid, sd_event - Acquire and release an event loop object
#include <systemd/sd-event.h> typedef struct sd_event sd_event; int sd_event_new(sd_event **event); int sd_event_default(sd_event **event); sd_event *sd_event_ref(sd_event *event); sd_event *sd_event_unref(sd_event *event); void sd_event_unrefp(sd_event **event); int sd_event_get_tid(sd_event *event, pid_t *tid);
sd_event_new() allocates a new event loop object. The event loop object is returned in the event parameter. After use, drop the returned reference with sd_event_unref(). When the last reference is dropped, the object is freed. sd_event_default() acquires a reference to the default event loop object of the calling thread, possibly allocating a new object if no default event loop object has been allocated yet for the thread. After use, drop the returned reference with sd_event_unref(). When the last reference is dropped, the event loop is freed. If this function is called while the object returned from a previous call from the same thread is still referenced, the same object is returned again, but the reference is increased by one. It is recommended to use this call instead of sd_event_new() in order to share event loop objects between various components that are dispatched in the same thread. All threads have exactly either zero or one default event loop objects associated, but never more. After allocating an event loop object, add event sources to it with sd_event_add_io(3), sd_event_add_time(3), sd_event_add_signal(3), sd_event_add_child(3) or sd_event_add_defer(3), and then execute the event loop using sd_event_run(3). sd_event_ref() increases the reference count of the specified event loop object by one. sd_event_unref() decreases the reference count of the specified event loop object by one. If the count hits zero, the object is freed. Note that it is freed regardless of whether it is the default event loop object for a thread or not. This means that allocating an event loop with sd_event_default(), then releasing it, and then acquiring a new one with sd_event_default() will result in two distinct objects. Note that, in order to free an event loop object, all remaining event sources of the event loop also need to be freed as each keeps a reference to it. sd_event_unrefp() is similar to sd_event_unref() but takes a pointer to a pointer to an sd_event object. This call is useful in conjunction with GCC's and LLVM's Clean-up Variable Attribute[1]. Note that this function is defined as inline function. Use a declaration like the following, in order to allocate an event loop object that is freed automatically as the code block is left: { __attribute__((cleanup(sd_event_unrefp)) sd_event *event = NULL; int r; ... r = sd_event_default(&event); if (r < 0) fprintf(stderr, "Failed to allocate event loop: %s\n", strerror(-r)); ... } sd_event_ref(), sd_event_unref() and sd_event_unrefp() execute no operation if the passed in event loop object is NULL. sd_event_get_tid() retrieves the thread identifier ("TID") of the thread the specified event loop object is associated with. This call is only supported for event loops allocated with sd_event_default(), and returns the identifier for the thread the event loop is the default event loop of. See gettid(2) for more information on thread identifiers.
On success, sd_event_new(), sd_event_default() and sd_event_get_tid() return 0 or a positive integer. On failure, they return a negative errno-style error code. sd_event_ref() always returns a pointer to the event loop object passed in. sd_event_unref() always returns NULL.
Returned errors may indicate the following problems: -ENOMEM Not enough memory to allocate the object. -EMFILE The maximum number of event loops has been allocated. -ENXIO sd_event_get_tid() was invoked on an event loop object that was not allocated with sd_event_default().
These APIs are implemented as a shared library, which can be compiled and linked to with the libsystemd pkg-config(1) file.
systemd(1), sd-event(3), sd_event_add_io(3), sd_event_add_time(3), sd_event_add_signal(3), sd_event_add_child(3), sd_event_add_defer(3), sd_event_add_post(3), sd_event_add_exit(3), sd_event_run(3), gettid(2)
1. Clean-up Variable Attribute_EVENT_NEW(3) | http://man7.org/linux/man-pages/man3/sd_event.3.html | CC-MAIN-2017-17 | refinedweb | 648 | 54.93 |
.
But in C, array always starts from 0 and end with size-1 and be written as
rollnumb[0], rollnumb[1]……….rollnumb[49]
and be declared as
int rollnumb[50];
means declaration syntax is
datatype arrayname [size];
Types of array
- One-Dimensional
- Multi-Dimensional
One Dimensional Arrays
Array having only one subscript variable is called one-dimensional array and also called as single dimensional array or linear array.
Example of one dimensional array definition
int marks[5] = {50, 85, 60, 55, 90};
And represented as
marks[0] =50
marks[1] = 85
marks[2] = 60
marks[3] = 55
marks[4] = 90
A specific element in an array is accessed by an index.
Program 1 : Input and output of an Array
#include <stdio.h>
void main()
{ int marks[5],i;
printf(“Input of Array marks”);
for (i=0; i<5; i++)
scanf(“%d”, &marks[i]);
printf(“Output of Array marks”);
for (i=0; i<5; i++)
printf(“marks[%d] = %d ”, i, marks[i]);
}
Input of Array marks
(if you entered )
50
85
60
55
90
(you will get)
Output of Array marks
marks[0] =50
marks[1] = 85
marks[2] = 60
marks[3] = 55
marks[4] = 90
Multi Dimensional Arrays
Multidimensional arrays are defined in much the same manner as one dimensional arrays, except that a separate square brackets required in each subscript.
Thus, a two dimensional array will require two pairs of square bracket,
aij -> a[i][j] -> a[rows][coulmn]
a three dimensional array will require three pairs of square brackets, and so on
aijk -> a[i][j][k] -> a[page][rows][coulmn]
Operations like
Traversing in arrays
Insertion in Arrays
Deletion in Arrays
Sorting and Searching in Array
Programming With C : Lecture 1
Programming With C : Lecture 2
Programming With C : Lecture 3
Programming With C : Lecture 4
19 thoughts on “Programming with C – Arrays- Lecture5”
hello sir i’m yours student inder josan from cheeka.
i learn more about c language from here.
sir,
i request you if you will discuss with us file handing( read file).,
Thanks Inder, We are uploading all the lectures, It will take time.
Hi Gagan,
My name is Anuj Agarwal. I’m Founder of Feedspot.
I would like to personally congratulate you as your blog Rozy Computech Services
I got what you intend, regards for posting. Woh I am glad to find this website through google.
I think the admin of this page is actually working hard in support of his website, for the reason that here every material is quality based material..
You’ve made some good points there. I looked on the internet issue is something which too few men and women are speaking intelligently about.
I am very happy that I came across this in my search for something regarding this.
Having read this I believed it was really informative. I appreciate you spending some time
and effort to put this short article together. I once again find myself spending way
too much time both reading and commenting.
But so what, it was still worthwhile!
Marvelous, what a website it is! This web site gives valuable data to us, keep it up.
Hi there! I could have sworn I’ve been to this site before but after
browsing through some of the post I realized it’s new to me.
Anyhow, I’m definitely glad I found it and I’ll be bookmarking and checking back often!
Hi, I check your blogs regularly. Your story-telling style is awesome,
Howdy! I could have sworn I’ve visited this web site before
but after going through some of the posts I realized it’s new to me.
Anyhow, I’m certainly happy I stumbled upon it and
I’ll be book-marking it and checking back often!
Article writing is also a fun, if you be familiar with afterward
you can write or else it is complicated to write..
Many thanks
I have read so many posts regarding the blogger lovers
however this post is genuinely a good piece of writing, keep it up.
If some one needs expert view regarding blogging and
site-building afterward i propose him/her to go to see this
webpage, Keep up the pleasant job. 0mniartist asmr | http://www.rozyph.com/arrays/ | CC-MAIN-2021-25 | refinedweb | 703 | 59.53 |
Bug Description
I installed anoise on a freshly installed xubuntu core installation and nothing seemed to happen. It did not get added to the sound menu as it did on my previous xubuntu installation.
I tried running it from the cli to see if there were any messages and this is what I got:
user@linux:~$ anoise
Traceback (most recent call last):
File "/usr/share/
from preferences import Preferences
File "/usr/share/
from gi.repository import Gtk, WebKit
ImportError: cannot import name WebKit
The problem seems to be in the preferences files. And without that it doesn't work.
Great!! You were absolutely right.
That solve the problem straight away.
Thank you so much.
You are welcome :)
--
---
Costales
Hi Dan!
I think Xubuntu Core is just the basic libraries and in your case, you
need this library at least:
sudo apt-get install gir1.2-webkit-3.0
Could you confirm me if that worked?
Thanks in advance! | https://bugs.launchpad.net/anoise/+bug/1458686 | CC-MAIN-2017-39 | refinedweb | 158 | 75.91 |
useEffect Hook - Fetching Data With useEffect
In this video you will learn useEffect hook. This is the most complicated but versatile hook in react hooks and I will share a lot of advanced stuff so make sure that you stay until the end of the video. do we need useEffect for? As you can understand from title it is to make side effects in components. What are side effects? Fetch data from API, working directly with DOM, communicating via web sockets, writing to localStorage. This are all side effects.
So we already learned what is useState hook. If you didn't watch that video go watch it first. Now let's create a counter example and every time when we change our counter we change the title of the page.
import React, { useState, useEffect } from "react"; function App() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); } export default App;
So as you can see we just call useEffect directly inside our component. Inside we are passing a callback what will be done. In this case we are setting a title of the page.
If we are comparing classes to react hooks useEffect is the combination of componentDidMount, componentDidUpdate, componentWillUnmount.
Now as you can see in browser, our title is updated every time when we click. So how exactly is it working? When we change a state with setter (in our case setCount) our component is rerendered. Let's write the console inside component at the beginning and inside useEffect.
function App() { console.log("component is rerendered"); ... useEffect(() => { console.log("use effect is triggered"); ... }); ... }
As you can see every time when we change the state we get 2 logs. And order is extremely important to understand the concept of useEffect. First of all we get the console that component is rerendered and only after that useEffect was triggered. So useEffect happens always after component was rerendered.
Now the first question why do we have such strange notation that we write useEffect inside component directly? This is the easiest way to give useEffect direct access to all local variables without any additional code. And this is the only correct place to write useEffect. Only directly inside component, without any nesting or if conditions. No useEffect in closures or inner functions. Just directly in component. In all other cases you will get only problems.
You next question is why do we need use effect if it just runs after every rerender? Why not just write some code inside a component. There are 2 reasons for this. First of all only with useEffect you are sure that React finished rerendering of the component. Second reason is that it's possible to run useEffect not on every rerender but when we need. For example when some property changed
We can do that by providing the list of dependencies as a second argument. Then our effect will only trigger when our dependency was changed.
useEffect(() => { console.log("use effect is triggered"); document.title = `You clicked ${count} times`; }, [count]);
So here we provided our count state as a dependency. So we are saying that we need to call this effect only when count property changes.
In our case this code will work exactly like before because the only state that changes in our application is count. Let's create 1 more counter to see the difference.
function App() { console.log("component is rerendered"); const [count, setCount] = useState(0); const [count2, setCount2] = useState(0); useEffect(() => { console.log("use effect is triggered"); document.title = `You clicked ${count} times`; }, [count]); return ( <div> <p>You clicked {count} times</p> <p>You clicked {count2} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> <button onClick={() => setCount2(count2 + 1)}>Click me 2</button> </div> ); }
So we just duplicated counter logic. As you can see in browser every change of count or count2 triggers the component rerender but our effect is only called when count changes.
At this point you might ask why it is triggered at the first rerender? Obviously because our count was changed to it's default value zero.
So when we need to do something when a variable changes we can easily achieve this with useEffect and dependencies array.
The next question which is the most popular question about hooks i think is "How to fetch some data on component initialize". And normally the answer that you will find "Just provide an empty array as a dependency to effect".
Let's try this out. As you can see it is working correctly but it's the completely incorrect mentality to work with hooks and all people who wrote classes in React have this mentality.
We are trying to apply classes knowledge and patters to hooks. Like we had componentDidMount where we fetched data and we want something similar.
The way that we need to thing while working with hooks is defining the dependencies on properties and stop thinking about just triggering something on initialize or on change. Our components should be build in the way that simply reacts somehow on data changes. And we define how. It's one of the main problems that stops people on mastering hooks.
So empty array doesn't mean that it's the same like componentDidMount. It just means that you don't have any dependencies that we retrigger your effect.
One more important point to mention is that if you don't provide the dependencies inside your useEffect it will be called after each rerender and it's the default behaviour.
Now let's make an example with fetching data inside useEffect hooks because it's actually the most popular user of useEffect. We don't have any API to fetch data and I prefer to use json-server to build fake API
The problem here is that json-server as create-react-app starts the server on 3000 port so we need to specify other port to make it working. As you can see now we have access to our local API that we created.
As React doesn't have a library to fetch data we need to install it. I recommend axios library because it's the most popular and easy way to make API requests.
npm install axios
And now we can fetch data inside our useEffect
import axios from "axios"; function App() { const [apiData, setApiData] = useState(null); useEffect(() => { console.log("use effect is triggered"); axios.get("").then((res) => { console.log("res", res); setApiData(res.data); }); }, [count]); return ( <div> <p>You clicked {count} times</p> <p>You clicked {count2} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> <button onClick={() => setCount2(count2 + 1)}>Click me 2</button> </div> ); }
As you can see we just called our setter from useState after getting the data. This is how our data from API are getting inside the component. No we can simply render this data as a normal array.
{apiData && apiData.map((item) => <div key={item.id}>{item.title}</div>)}
And the last thing that I want to mention is that it's super easy to get and infinite loop with useEffect. If we just simply remove dependencies array which means that we trigger this fetch after each rerender it will be infinite loop. Why? Because we trigger useEffect after each rendering and then inside we set state which will trigger rerender again. So you should really know what you are doing.
Call to action
So this were the most important parts of using useEffect. | https://monsterlessons-academy.com/p/use-effect-hook-fetching-data-with-use-effect | CC-MAIN-2021-31 | refinedweb | 1,265 | 65.42 |
There are several reasons why you should test your Rake tasks:
- Rake tasks are code and as such deserve testing.
- When untested Rake tasks have a tendency to become overly long and convoluted. Tests will help keep them in bay.
- As Rake tasks typically depend on your models, you (should) loose confidence in them if you don’t have tests and are attempting refactorings.
A problematic Rake task test
Here is a Rake file…
File: lib/tasks/bar_problematic.rake namespace :foo do desc "bake some bars" task bake_a_problematic_bar: :environment do puts '*' * 60 puts ' Step back: baking in action!' puts '*' * 60 puts Bar.new.bake puts '*' * 60 puts ' All done. Thank you for your patience.' puts '*' * 60 end end
…and its too simplistic spec:
File: spec/tasks/bar_rake_problematic_spec.rb require 'spec_helper' require 'rake' describe 'foo namespace rake task' do describe 'foo:bake_a_problematic_bar' do before do load File.expand_path("../../../lib/tasks/bar_problematic.rake", __FILE__) Rake::Task.define_task(:environment) end it "should bake a bar" do Bar.any_instance.should_receive :bake Rake::Task["foo:bake_a_problematic_bar"].invoke end it "should bake a bar again" do Bar.any_instance.should_receive :bake Rake::Task["foo:bake_a_problematic_bar"].invoke end end end
Some notable aspects of testing Rake tasks:
- Rake has to be required.
- The Rake file under test has to be manually loaded.
- In this example, the Rake task depends on the
environmenttask, which is not automatically available in a spec. Since we are in rspec, the environment is already loaded and we can just define
environmentas an empty Rake task to make the bake task run in the test.
When run, this spec fails on the second it block… and that is not the only problem with this spec and the Rake task:
- The Rake task duplicates code to output information to the user.
- The spec “should bake a bar” will output that information when run, which clobbers the spec runners output.
- The spec “should bake a bar” again will fail, because Rake tasks are built to only execute once per process. See rake.rb. This makes sense for the normal use of Rake tasks where a task may be named as the prerequisite of another task multiple times through multiple dependencies it might have – the task only needs to run once. In our tests we have to reenable the task.
A better Rake task test
A new version of the above Rake file…
File: lib/tasks/bar.rake class BarOutput def self.banner text puts '*' * 60 puts " #{text}" puts '*' * 60 end def self.puts string puts string end end namespace :foo do desc "bake some bars" task bake_a_bar: :environment do BarOutput.banner " Step back: baking in action!" BarOutput.puts Bar.new.bake BarOutput.banner " All done. Thank you for your patience." end end
… and its spec:
File: spec/tasks/bar_rake_spec.rb require 'spec_helper' require 'rake' describe 'foo namespace rake task' do before :all do Rake.application.rake_require "tasks/bar" Rake::Task.define_task(:environment) end describe 'foo:bar' do before do BarOutput.stub(:banner) BarOutput.stub(:puts) end let :run_rake_task do Rake::Task["foo:bake_a_bar"].reenable Rake.application.invoke_task "foo:bake_a_bar" end it "should bake a bar" do Bar.any_instance.should_receive :bake run_rake_task end it "should bake a bar again" do Bar.any_instance.should_receive :bake run_rake_task end it "should output two banners" do BarOutput.should_receive(:banner).twice run_rake_task end end end
This spec passes just fine and does not clobber the spec output. Again, let’s look at noteworthy things:
- The output of the Rake task now goes through the
BarOutputclass. This reduces code duplication and allows for easy stubbing. There are other ways to achieve a similar effect and not clobber test output: Stub puts and print, stub on $stdout.
Rake.applicationhas a nicer way of requiring Rake files than a simple
load, because
rake_requireknows where Rake files live.
Rake::Task["TASK"].reenablereenables the task with name “TASK” so that it will be run again and can be called multiple times in a spec.
Here is the gist:
Thanks | http://pivotallabs.com/how-i-test-rake-tasks/?tag=gems | CC-MAIN-2014-10 | refinedweb | 662 | 67.25 |
Chapter 3. ADTs unsorted List and Sorted List. List Definitions. Linear relationship Each element except the first has a unique predecessor, and each element except the last has a unique successor. Length The number of items in a list; the length can vary over time. List
ADTs unsorted List and Sorted List
Linear relationship Each element except the first has a unique predecessor, and each element except the last has a unique successor.
Length The number of items in a list; the length can vary over time.
Unsorted list A list in which data items are placed in no particular order; the only relationship between data elements is the list predecessor and successor relationships.
Sorted list A list that is sorted by the value in the key; there is a semantic relationship among the keys of the items in the list.
Key The attributes that are used to determine the logical order of the list.
Development of an Unsorted List ADT: UnsortedStringList
public boolean isFull ( )
// Returns whether this lis is full
{
return (list.length == numItems);
}
Ways we could reuse the code of the Unsorted List ADT to create the code for the Sorted List ADT:
Abstract Data Type Sorted List
Big-O Notation A notation that expresses computing time (complexity) as the term in a function that increases most rapidly relative to the size of a problem
If
f(N) = N4 + 100N2 + 10N + 50
then f(N) is 0(N4).
N represents the size of the problem.
So far…
Generic Data Type A type for which the operations are defined but the types of the items being manipulated are not
To Create a sorted list of strings use either of its constructors:
SortedList list1 = new SortedList();
SortedList list2 = new SortedList (size);
Declare at least one object of class ListString
ListString aString;
Instantiate ListString objects and place them on the list.
aString = new ListString(“Amy”);
list.insert(astring) | http://www.slideserve.com/kaden-hood/chapter-3 | CC-MAIN-2017-04 | refinedweb | 317 | 55.78 |
Please bare with me. I am still a newb at programming and this may seem a bit confusing, but I have many comments and debug lines. This is an extremely long code, but could the advanced programmers out there please help me out? The goal of my program is to simply read an expected number of values, read the values (on one line) themselves, and print their averages. The expected number of values is used as a counter in a while loop. I am trying to make my program robust so that it will print an error when something other than an integer is entered. Therefore, I declare a char string, determine whether each value of string is a digit or letter, and convert the character of that string into an int. My problem with this program is my first while loop. The first loop seems to be fine, but second time around, it is unable to read user input. It instead uses the last output printed to the screen as the input. Any suggestions/help will be greatly appreciated. Here's my program:
* Read in a number of values to read and then print the average * of those values. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "tfdef.h" #define DEBUG #define FLUSH while(getchar() != '\n'); int IS_DIGIT(char c); /* Given : character * Returns: TRUE if digit, FALSE otherwise */ int main(void) { /* Declare variables */ int expected; /* Expected number of inputs for desired avg */ int count; /* Count of expected number of inputs for calculating avg */ float sum; /* Sum of all inputs for desired avg */ int value; /* Value of input for desired avg */ char input[10] = " "; /* Input string of expected number of inputs for avg */ int i = 0; /* Counter for string */ int digit; /* Variable to call function for determining digit */ /* Prompt user for expected number of inputs for desired avg */ #ifdef DEBUG printf("debug: Enter expected number value of inputs: "); #endif #ifdef FLUSH while (scanf("%s", &input) != EOF) { #endif #ifdef DEBUG printf("debug: The expected number value is %s\n", input); #endif /* For i is initially 0, increase i by one for every character in input string */ for(i; input[i]; i++) { /* Call function to determine if character is a digit */ digit = IS_DIGIT(input[i]); /* Convert string input to integer (binary) */ expected = atoi (input); #ifdef DEBUG printf("debug: The integer form of the input: %d\n", expected); #endif /* If the input is not a digit, it is a letter */ if (digit == FALSE) { #ifdef DEBUG printf("debug: %d is not a digit\n", expected); #endif } /* If the input is a digit */ else { #ifdef DEBUG printf("debug: %d is a digit\n", expected); #endif } } /* Check for last value of string */ /* If the input is not a digit, it is a letter */ if (digit == FALSE) { #ifdef DEBUG printf("debug: Final value on line: not a digit\n"); #endif } /* If the input is a digit */ else { #ifdef DEBUG printf("debug: Final value on line: is a digit\n"); #endif } /* Initializee sum at 0 */ sum = 0; #ifdef DEBUG printf("debug: Enter values for average: "); #endif /* Read input of values for the average */ scanf("%d", &value); /* Initialize count at 0 While the count is less than the expected count (first input), increase count by one */ for (count = 0; count < expected; count++) { /* Sum is equal to previous sum increased by value */ sum += value; #ifdef DEBUG printf("debug: Sum = %f\n", sum); #endif } /* Print average result of all values */ printf("Average of %d values is %.2f\n", count, count != 0 ? sum / count : 0.0); /* If the last character is not a digit, print an error */ if (digit == FALSE) { printf("Error! Can't read number of expected values.\n"); } /* Update loop */ #ifdef DEBUG printf("debug: Enter expected number value of inputs: "); #endif } } /* Functions */ int IS_DIGIT(char c) /* Given : character * Returns: TRUE if digit, FALSE otherwise */` { if ((c) >= '0' && (c) <= '9') { return TRUE; } else { return FALSE; } }
With the following input, I hope to get the following output:
5
10 20 30 40 50
Average of 5 values is 30.00
6
50 70 whatever 40 60
Error! Can't read expected value #2.
Average of 2 values is 60.00 | https://www.daniweb.com/programming/software-development/threads/275105/while-loop-problem-with-reading-a-character-string | CC-MAIN-2017-34 | refinedweb | 690 | 54.66 |
PoseAggregator is a multiplexer for heterogeneous sources of poses and the velocities of those poses. More...
#include <drake/systems/rendering/pose_aggregator.h>
PoseAggregator is a multiplexer for heterogeneous sources of poses and the velocities of those poses.
Supported sources are:
PoseAggregator is stateless.
The output is a flat PoseBundle that contains all the poses and velocities from all the inputs. Unspecified velocities are zero. By convention, each aggregated pose or velocity is in the same world frame of reference.
The output poses are named in the form
<source> or
<source>::<pose>.
The output poses are also each assigned a model instance ID, which must be an integer that is greater than or equal to zero. All poses with the same model instance ID must have unique names. This enables PoseAggregator to aggregate multiple instances of the same model.
In typical usage, Diagrams should contain just one PoseAggregator, and every pose in the Diagram should appear as an input to it. Then, Systems that need to ingest every pose in the universe, such as renderers or sensor models, can simply depend on the output.
This class is explicitly instantiated for the following scalar types. No other scalar types are supported.
Scalar-converting copy constructor. See System Scalar Conversion.
Adds an input for a PoseBundle containing
num_poses poses.
Adds an input for a PoseVector.
name must be unique for all inputs with the same
model_instance_id.
Adds an input for a PoseVector, and a corresponding input for a FrameVelocity.
name must be unique for all inputs with the same
model_instance_id. | http://drake.mit.edu/doxygen_cxx/classdrake_1_1systems_1_1rendering_1_1_pose_aggregator.html | CC-MAIN-2018-43 | refinedweb | 257 | 50.84 |
K
C
M
Y
CM
MY
CY
CMY
K
EDITORIAL
Welcome aboard this Air Uganda flight and thank you for choosing to fly with us.
E
very morning I make it a point to thank God for the gift of life and the opportunities life brings. I believe that Air Uganda has enabled you to explore some of these opportunities. Our aim is to give you a memorable experience and try not to make your travel with Air Uganda a mere chore. We are committed to ensuring that a booking on Air Uganda means a smooth and painless journey, from selecting your flights at our call centre or website, to check in, and on board our flights. That aside, I am excited to introduce our new sports and entertainment features as well as book reviews in this issue. In our entertainment section, we shine the spotlight on the Ugandan award-winning musician, Maurice Kirya, who is well known for his masterly guitar skills, both nationally and internationally. In sports, we feature and celebrate the one thing that unites Ugandans - the Uganda Cranes. We are elated to have reached one of our milestones at Air Uganda by moving to what is called a Self Handling Airport Operation. On 22 May 2012, we became the proud handlers of our own Airport operations and customers at Entebbe International Airport. This long awaited self handling project means that all airport related functions at Entebbe, from check in to flight dispatch are handled by our very own staff and not a third party handler. This also means that an Air Uganda staff member gets to handle you at every step of our flight process. Finally this time round, our main feature story is focusing on Uganda which will celebrate its 50th Anniversary on 9 October 2012. In remembrance of the same date in 1962, when the Union Jack was lowered in favour of the black, yellow, red national flag, I would like to invite you to join me and the rest of Uganda as we celebrate our 50th Golden Jubilee Independence in October 2012. On behalf of the entire Air Uganda team, I would like to thank you for your business and value you as our customer. We are committed to getting you to your destination on time and look forward to welcoming you back soon. Asante!
Jenifer B. Musiime Head of Sales & Marketing
1 asante aug – oct 2012
8
Celebrating 50
The Pearl of Africa is shinning again.
26
Celebrating 50 Years of Sport in Uganda
14
Every September, Kampala comes alive as a vibrant and eventful city – a veritable hub for innovation and creativity.
30
What was a spontaneous act of celebration four decades ago is now known as the ‘lap of honour’ or ‘victory lap’.
Semliki: Land of Plenty
Discover the rainforests of Semliki Wildlife Reserve, a slice of paradise on earth, wondrously blessed with topography, flora and fauna.
The views expressed in this magazine should only be ascribed to the authors concerned, and do not necessarily reflect the views either of the publishers or of Air Uganda. The printing of an advertisement in Asante does not necessarily mean that the publishers or Air Uganda endorse the company, product or service advertised.
Bayimba: International Festival of Music and Arts
18
Maurice has taken Ugandan music, fused it with R&B and jazz, and developed a unique style that will soon be recognisable worldwide.
40
City of the Sultans, Dar es Salaam
Explore Dar, the largest and richest city in Tanzania with a picturesque seaport and fascinating blend of African, Arabic and Indian influences.
Publishers:
Camerapix Magazines Ltd
Editorial Director: Editor: Editorial Assistant:
Rukhsana Haq Roger Barnard Cecilia W. Gaitho
Senior Designer: Creative Designer:
Sam Kimani Charles Kamau
Production Manager: Production Assistant: Editorial Board:
2 asante aug – oct 2012
Maurice Kirya: Really Sings from the Soul
Azra Chaudhry, U.K Rose Judha Rukhsana Haq Jenifer B. Musiime
44
50
The Art of Giving
What makes the perfect gift, graciously given?
Feathered Creatures for the Table
With an innate desire for variety and change, white meat is a welcome treat.
6
Regulars Whats Up Uganda
Your most up to date events calender.
20
Meet the Staff
Francis Asiimwe.
46
The Thames Diamond Jubilee Pageant
Marking 60 years of The Queen’s reign, the Pageant was the highlight of a number of Diamond Jubilee celebrations.
22
A Nation’s Spirit
At the heart of every Olympic sports event, is the glorious medal ceremonies.
36
Cover picture: Watoto Childrens Choir, Uganda.
The Cave Elephants of Mount Elgon
Here are a true wonder of the natural world and a ‘must see’ species for any visitor to Uganda.
1
Editorial by Head of Sales & Marketing
4
Air Uganda News
24 Bookshelf 52 Air Uganda Flight Schedule 53
Asante News
54
Healthy Travelling
55
Tips for the Traveller
56 Air Uganda Offices 57 Route Map 58 Abato Corner 60 Crossword Puzzle & Sudoku
ASANTE meaning ‘Thank you’ in Kiswahili is published quarterly for Air Uganda by Camerapix Magazines Limited P.O. Box 45048, 00100 GPO Nairobi, Kenya | Tel: +254 (20) 4448923/4/5 | Fax: +254 (20) 4448818 E-mail: creative@camerapix.co.ke Editorial and Advertising Offices: Camerapix Magazines (UK) Limited | 32 Friars Walk, Southgate, London, N14 5LP | Tel: +44 (20) 8361 2942 Mobile: +44 79411 21458 | E-mail: camerapixuk@btinternet.com Air Uganda, Marketing Office | Tel: +256 (0) 414 258 262/4 or +256 (0) 417 717 401 Fax: +256 414 500 932 | E-mail: info@air-uganda.com or jbmusiime@air-uganda.com Investment House, Plot 4, Wampewo Avenue, Kololo Correspondence on editorial and advertising matters may be sent to either of the above addresses. ©2012 CAMERAPIX MAGAZINES LTD All rights reserved. No part of this magazine may be reproduced by any means without permission in writing from the publisher. All photographs by Camerapix unless otherwise indicated.
3 asante aug – oct 2012
AIR UGANDA NEWS
Special Golden Jubilee Fare * Fly Daily to Kigali USD50 * return * Taxes and surcharges exclusive. Flying between Entebbe and Kigali just got better as Air Uganda has introduced a return special Golden Jubilee fare of $50 (exclusive of taxes and surcharges). With a choice of convenient daily flights, this promotional fare is available through travel agents or the website at.
Fly Direct to Mombasa 5 times a week for only USD60 *One way, taxes exclusive. With the recently introduced direct flights to Mombasa, Air Uganda has launched a promotional one way fare for car dealers heading to the Port of Mombasa. From as low as $60 (one way exclusive of taxes), customers can book their flights from any of the Air Uganda offices or travel agents. Book now while seats last.
Nairobi Same Day Return From USD282* return *taxes inclusive For those travelling for business to Nairobi, Air Uganda offers same-day return journeys between the two cities. Our value-for-money fares from as low as $282 return (inclusive of taxes) enabling you to wrap up your business in a day.
Self Handling On 22 May 2012, we became the proud handlers of our own Airport operations and customers at Entebbe International Airport. This long-awaited self-handling project means that all Airport related functions at Entebbe, from check-in to flight dispatch are now handled by our own staff and not a third party handler.
Personalised Customer Service
MAHOGANY DOORS
MODERN STYLE KITCHEN
QUALITY ON-TIME DELIVERY AFFORDABLE
ALUMINIUM PRODUCTS
SANDWICH PANEL
HWAN SUNG INDUSTRIES LTD. TEL.: +256 41/4286019 / 4286604 EMAIL : hsind@hwansungbiz.com PLOT M/243, NTINDA INDUSTRIAL AREA, P.O. BOX - 7628, KAMPALA (UGANDA)
Latin Flavour Night Source of the Nile Festival The Festival on the Nile will celebrate cultural identity and unity through diverse cultural art practices of people along the Nile and traditional arts and cultural practices from other parts of the world.
Experience a mix of various Latin dances at the National Theatre, Kampala. Enjoy the thrills of New York Salsa, Cuban Salsa, cha cha cha, merengue, samba, bachata, jive and rumba.
WEAVER BIRD fiest ART This event aims at celebrating and promoting community arts. It features local Ugandan, regional and international artists. The festival is hosted three times a year by the Weaver Bird Community for the Arts in Masaka, Uganda.
weaver bird COMMUNITY FOR THE ARTS
5th Annual Nile Gold Jazz Safari This will feature Regina Belle, Gerald Albright and Marion Meadows in a Jazz &Soul tribute to Michael Jackson / The Jacksons and Whitney Houston.
6 asante aug – oct 2012
The Young Professionals Technology Symposium An annual event that seeks to recognise, reward and promote technology among young professionals plus create opportunities for commercialising their technologies by introducing them to mentors and financial institution. 700 participants from the region are expected.
Commonwealth Games Federation General Assembly International Trade Fair Uganda Manufacturers Association will hold the 20th Uganda International Trade Fair at Lugogo. The intention is to provide a wide platform for displaying products or services all over the world. This will help to extend industrial investment and economic growth in Uganda.
Delegates from 71 countries are expected to attend the CGF. This will boost Uganda’s economy through flights and accommodation at the Munyonyo Commonwealth Resort. The CGF is the organisation responsible for the direction and control of the Commonwealth Games.
Watoto Childrens Choir, Uganda.
50th Jubilee Celebrations Uganda got independence in October 1962 and will celebrate 50 years of Independence. Uganda invites everyone to come and participate in the celebrations.
The Nile Kayaking Festival New kayaking events and rafting races on the warm waters of the Nile.
7 asante aug – oct 2012
jubilee celebrations Photo: Watoto Childrens Choir, Uganda.
celebrating
O
n 9 October 2012, Uganda celebrates 50 years of independence since the day it gained its freedom from Colonial rule in 1962. The country had been ruled by Great Britain as a Protectorate since 1894 but that era came to an end when the Duke of Kent formally handed over the instruments of freedom to Milton Obote, Uganda’s Prime Minister. With Independence came great expectations for the people of Uganda: the hopes for improved infrastructure; better health facilities, greater respect for local citizens and unity among the diverse groups in Uganda.
8 asante aug – oct 2012
In truth, Uganda did not exist as a single country when, in the 19th century, the first western explorers arrived, since at that time the area was divided into kingdoms. Shortly afterwards, the first missionaries came to Uganda and in their wake came trade. In 1888, the British government gave the Imperial British East Africa Company control of a territory consisting mainly of Buganda Kingdom. After the Treaty of Berlin in 1890, when Europeans carved up Africa without consulting any Africans, Uganda, Kenya and Zanzibar were declared British Protectorates in 1894. When the Uganda Protectorate was established the territory was extended beyond the borders of Buganda to an
area that roughly corresponds to that of present-day Uganda, except for a portion that is now in Western Kenya. The British ruled indirectly, giving the traditional kingdoms a considerable degree of autonomy, but favoured the recruitment of Buganda people for their civil service. Other tribal groups, unable to make inroads into the Buganda-dominated colonial administration or commercial sector, were forced to seek other avenues for advancement. The Acholi and Lango soon became dominant in the military. Thus were planted the seeds for the intertribal conflicts that were to tear Uganda apart following independence. By the 1950s the ‘winds of change’ were blowing through Africa and many colonial rulers made preparations to grant independence to their colonies. In Uganda the first elections were held on 1 March 1961. Benedicto Kiwanuka of the Democratic Party became the first Chief Minister. In the period leading up to independence there was considerable jockeying for position between rival parties and after April 1962 Uganda’s National Assembly consisted of 43 UPC (Uganda Peoples’
9 asante aug – oct 2012
uganda at 50 Army (NRA) and pledged to improve respect for human rights, end tribal rivalry, and conduct free and fair elections. In the meantime, human rights violations continued as the Okello government carried out a counterinsurgency in an attempt to destroy the NRA’s support.
a’s orates Ugand
ument in the
Striking mon
la commem art of Kampa
ce.
independen
he
Congress) members, 24 KY (Kabaka Yekka) members, and 24 DP (Democratic Party) members. The new UPC-KY coalition led Uganda into independence in October 1962, with Milton Obote as Prime Minister and the Mutesa, King of Buganda becoming President a year later. In succeeding years, supporters of a centralised state vied with those in favour of a loose federation and a strong role for tribally-based local kingdoms. Matters came to a head armed forces commander Idi Amin Dada. Amin declared himself ‘President,’ dissolved the parliament, and amended the constitution to give himself absolute power. and for a few months Uganda was ruled by a military commission. The December 1980 elections returned the UPC to power under the leadership of President Milton Obote. He ruled until 27 July 1985, when an army brigade, composed mostly of ethnic Acholi troops took Kampala and proclaimed a military government. Obote fled to exile in Zambia. The new regime, headed by former defence force commander Gen. Tito Okello opened negotiations with Yoweri Museveni’s National Resistance
The NRA seized Kampala and the country in late January 1986, forcing Okello’s forces to flee north into Sudan. Museveni’s forces organised a government with Yoweri Museveni as President. Just as in the Independence celebrations of 1962, the post 1986 epoch ushered in a great sense of hope in Uganda’s chequered history. Twenty-six years later, the regime remains in place and much has been achieved, but there is still work to be done to meet the aspirations of the people. One area which has seen great strides is women’s rights. Since independence, women have been given a platform to air their views on a wide range of issues that contribute to Uganda’s development. Today, women make up 35 per cent of the Ugandan Parliament, occupy some key positions in government and the private sector, as ministers, ambassadors and academicians. In his swearing in on the steps of the Parliament Building on 26 January 1986, Museveni referred to the National Resistance Movement’s victory not as ‘a mere change of guards, but a fundamental change’. A great deal has been introduced that has changed the Uganda political scene: peace exists in most parts of the country;
Idi Amin’s six-year rule ended when. After Amin’s removal, the Uganda National Liberation Front formed an interim government with Yusuf Lule as President and Jeremiah Lucas Opira The late Jayant
10 asante aug – oct 2012
Muljibhai Madhv ani, leading entre
preneur, was bo rn
in Jinja.
One area which has seen great strides is women’s rights. Since independence, women have been given a platform to air their views on a wide range of issues that contribute to Uganda’s development. participatory democracy – based on the system of Resistance Committees and Councils – has been introduced and taken root; and, perhaps most important of all, a new national constitution, based on the views of the people of Uganda, has been debated, enacted, and promulgated. In the realm of economics, the National Resistance Movement (NRM) administration has embraced the economic medicine prescribed by the International Monetary Fund and the World Bank, based on the total liberalisation of the economy and the full reorientation of that economy toward free-market forces – a strategy which, the NRM leadership assures Ugandans, will transform Uganda from a
peasant to an entrepreneurial society. The economic policies now in place are another example of fundamental changes that have been introduced. Uganda is still an overwhelmingly agricultural country, employing 7 out of 10 Ugandans, and its main export is coffee. Overall, the Ugandan economy has grown strongly and there is every reason to be optimistic about its future, although the country currently faces some harsh economic difficulties, in keeping with the rest of the world. Among measures planned to stimulate growth is a programme of road improvements. The impending commissioning of Bujagali Hydropower Dam and the reliable power it
is expected to provide, is another positive for the economy. Today, as the population of Uganda approaches 35 million, the prayer of many Ugandans is that peace and stability continue to prevail, as the road trodden by the country’s people since independence in 1962 has been difficult (as indeed has been the case with many African countries). Many feel that there is now light at the end of the tunnel; Ugandans hope that whatever lies ahead will enable them to enjoy peace, tranquillity, and more prosperity. All this will benefit not only Ugandans, but also their friends abroad, to whom the country has opened its doors, for them to visit as tourists or conduct business as investors. In this way the Pearl of Africa is shining again•
uganda cities
FORT PORTAL Set on the moist, verdant northern foot slopes of the Rwenzori, Fort Portal is one of the most attractive towns in Uganda. It is surrounded by Crater Lakes of Kabarole district, caves and tea estates. It is well placed for visits to the primaterich Kibale National Park and scenic Semliki National Park and Semliki Game Reserve hence a good starting point for a rich adventurous tour. Additionally, Fort Portal is the capital of the Toro Kingdom, hence the presence of the Royal Palace that overlooks the town.
ENTEBBE Entebbe is located on the shores of Lake Victoria, only 34 kilometres south of Kampala. It is home to Entebbe International Airport, the only one of its kind in Uganda. Three kilometres away is the well known Entebbe Botanical Gardens, a paradise for bird-watchers and botanists. Another popular tourist site is the Entebbe Wildlife Education Centre, a showplace of Africa’s vast wildlife species. In addition, a boat excursion on Lake Victoria to Ngamba Island Chimpanzee Sanctuary provides a great chance to see and interact with chimpanzees.
12 asante aug – oct 2012
KAMPALA The vibrant capital of Kampala, like legendary, Rome was built on seven hills. Head for the hills and take in the older cultural, historic and religious sites including the imposing Gaddafi Mosque – the largest in sub-Saharan Africa, the Bahai Temple, the only one of its kind in Africa and the Namugongo Martyrs Shrines – now a world heritage site of UNESCO (United Nations Educational, Scientific and Cultural Organization) – where the Ugandan Martyrs died. Other popular drop-offs include the Uganda Museum, the Uganda National Theatre with its big crafts centre and Nakasero Market among others.
JINJA This is Uganda’s second largest town, located at the banks of Lake Victoria. It is here that the source of the Nile is marked by a plaque. The Nile River near Jinja has several grade five rapids which offer exhilarating white-water rafting and is ranked as one of the most thrilling and safest in the world. Presently, the eastern bank of the Nile between Jinja and Bujagali is the mecca for water sports; quad biking, kayaking, bungy-jumping, jet boat riding, river surfing and sportfishing. Nearby is Mabira Forest Reserve, home to an astonishing variety of bird and monkey species.
feSTIVAL Photos Š Meltem Yassar
Left: A visit to the Bayimba International Festival of the Arts is like going to another, seemingly mythical country, a hip and thrilling Brigadoon that appears every year.
14 asante aug – oct 2012
Above: The Bayimba Festival has become a highlight on Uganda’s exciting cultural calendar and a template for all the festivals that have since followed its example. Below: Now celebrating its fifth year, the 2012 Bayimba Festival will feature an extensive line-up of Ugandan artists, and is already shaping up to be one of the greatest yet.
L
adies and Gentlemen the ‘Season’ has begun! Time to slip the bonds of the office, get out those new summery outfits, picnic baskets, old school blazers, gorgeous strappy sandals, and head for Uganda’s vibrant capital – home to the Bayimba International Festival of the Arts, says Peter Holthusen.
Even if you’re not a fan of music and the arts, you’ll be perfectly aware that the quintessentially African setting of the Uganda National Cultural Centre in the heart of Kampala, with its spectacular Auditorium, Dance Studio, Restaurant, Resource Centre and worldrenowned Nommo Gallery, is steeped in entertainment history and that for one three-day period every September it becomes the focus of the world.
The brainchild of the Bayimba Cultural Foundation, the Festival was first organised in 2008, and is the main and most visible activity of the Kampala-based company, whose vision from the very outset of its inception was to form a vibrant arts and cultural sector that was professional, creative, viable and contributed to the social and economic development of Uganda and East Africa, while increasing awareness of the important role that arts and culture play in the societal community. At its launch in June 2008, only 1,000 people attended the Festival which was held at the famous Kyadondo Rugby Club in Kampala, home to the MTN Heathens, Toyota Buffaloes, Stallions, Thunderbirds and ENGSOL Tigers rugby teams, but it was nevertheless the first of its kind in Uganda and attracted the interest of the media. Small wonder the next venue chosen for the Festival was the Uganda National Cultural Centre, more often known by its official acronym the UNCC. A semiautonomous body, the Centre was officially inaugurated on 2 December 1959, and is now a vibrant institution guided by
unity in diversity, integrity and relevance to national development, nourishing, celebrating and promoting arts and culture. Today, the Bayimba International Festival of the Arts has grown into a multi-cultural event that attracts more than 50,000 people to the city of Kampala, drawing a diverse mix of locals, expats and tourists to a three-day celebration of the finest visual and performing arts, with a budget of approximately 110 million UGX. The Bayimba team, under the guidance of Artistic Director Faisal Kiwewa, has built tremendous capacity in Festival programming, technical and logistical planning, artist handling and promotion. Bayimba has also joined numerous other Festival and event networks within the region, such as the celebrated African Music Festival Network (AFRIFESTNET), and established links with a considerable number of famous festivals throughout the world, enabling mutual learning and artistic exchanges. With a varied and qualitative programming policy, presenting exciting, innovative and creative ideas to large audiences, each Bayimba Festival brings an unparalleled feast of music, dance, theatre, film, and visual arts from renowned and upcoming Ugandan, East African and international artists to Kampala.
15 asante aug – oct 2012
BAYIMBA FESTIVAL Ugandan and East African music and arts by building audiences and an appreciation for the arts and culture of the region. Most importantly, to highlight the Jubilee celebrations of both Uganda and Bayimba, the unique ‘Visionary Africa - Art at Work’ travelling platform, a joint initiative of the African Union and European Union, will be coming to Kampala at the time of the Festival with an itinerant urban exhi bition of contemporary African artistic practices, providing through the eye of African artists, a snapshot of the many transformations that have occurred on the African continent over the last 50 years.
The Bayimba Festival has become a highlight on Uganda’s exciting cultural calendar and a template for all the festivals that have since followed its example. Every September, Kampala comes alive as a vibrant and eventful city – a veritable hub for innovation and creativity. The Bayimba Festival is eagerly awaited by local artists and local people alike, while artists from abroad and visitors from as far afield as the United Kingdom, the United States of America, Australia and Latin America pour into Kampala to take full advantage of the exciting artistic experience. It is rapidly developing into an important East African destination Festival, enhancing both national and international cultural tourism in the process. Now celebrating its fifth year, the 2012 Bayimba Festival will take place from 21-23 September in the Auditorium at the Uganda National Cultural Centre, and is shaping up to be one of the greatest yet – and so it should be in the year that Uganda commemorates its 50 years of Independence. Much as it has in the past, there will be an excellent and extensive line-up of Ugandan artists, with established names such as Afrigo Band, one of the longest surviving popular bands in Uganda, and
16 asante aug – oct 2012
Baxmba Waves, the multi-cultural fusion band, presenting their latest artistic ventures, together with popular acts like the comedians from Fun Factory, and new and upcoming artists that will perform for the very first time at the Festival, such as the Beautiful Feet Dance Company and Mbale-based Titan. Other Ugandan participants include world-class acts such as Yoyo, Kabuye Semboga and, of course, Bakayimbira Dramactors, who have developed into a formidable troupe. As usual, local Kampalan artists will be joined by others from the region while Festival revellers can reckon on a considerable number of surprise acts from other parts of the world as well. The Festival will also include an interesting programme of art films and fascinating documentaries while the venue will also open its space to fashion shows and artistic installations. In common with world-renowned Festivals such as Cambridge and Glastonbury in the United Kingdom and the celebrated Edinburgh Festival in Scotland, a wide range of fringe events will also be organised in conjunction with the Bayimba International Festival of the Arts. Training sessions for new artists, exchanges and collaborations with visiting artists and various networking meetings, are all aimed at developing and promoting
And if that isn’t enough to tempt you to come to Bayimba, the National Theatre Restaurant at the Uganda National Cultural Centre is unrivalled, at least in Kampala. On Friday, the first day of the Festival, you can try culinary delicacies such as the famous finger-licking luwombo, the celebratory meal from Buganda that often comprises chicken, beef or goat meat and ground nuts mixed with dried fish or mushrooms – each individual portion steamed in banana leaves. I cannot begin to talk about the mouth-watering malewa, (their popular smoked bamboo shoots, a delicacy from Eastern Uganda), and eshabwe (ghee sauce) from Western Uganda, with crowned vegetables and all very often served with matooke or rice. A visit to the Bayimba International Festival of the Arts is like going to another, seemingly mythical country, a hip and thrilling Brigadoon that appears every year. Coming to Bayimba involves a fair amount of travel, and probably a queue to get in but, when you get past these minor impediments, you will be well rewarded for charting a course to her doors. This is the yardstick by which other Festivals must be judged. • [The Bayimba International Festival of the Arts:]
Left: The celebrated Bayimba International Festival of the Arts has grown into a multicultural arts Festival that attracts over 50,000 people to the city of Kampala.
)RUHQUROPHQWVSOHDVHYLVLWZZZJFLVQDLURELFRP RUHPDLOUHJLVWUDUBFLQ#JHPVHGXFRP
STAR profile
Really Sings from the Soul, by Kalungi Kabuye.
I
t was just an exhibition by a local telecoms company. Entry was free, as was the music interlude that was to follow. It was to be in a small room that quickly filled to capacity with hordes of young people, the ones who will show up any time there are free things to be had. A couple of artists took the stage and did one or two songs, actually mimed them, and were on their way. The crowds didn’t seem to mind; after all, they were up and close to the singers. Then a break was announced, after which a band set up on the small stage. You could almost touch the thick air of anticipation in the audience. This was unexpected: a live band at a free concert. Who could it be? A few minutes later they found out as Maurice Kirya bounded onto stage, dressed in a T-shirt with the words ‘Kirya for President’ on the front. He then proceeded to turn the planned 20 minutes’ ‘free performance’ into a fullblown concert. He sang most of his songs, cracked jokes with the very appreciative crowd, gave away copies of his CD, and really, really sang. At the end everyone in the audience could have sworn that Maurice Kirya was the best musician in the land, and none would have disagreed. “They are all my fans,” he said at that time, “and I will give them all I have, wherever they are, whatever they paid, and whatever the occasion is.” It did not seem to matter to him that he was just coming off a Central African tour to almost a dozen countries; he gave it his all, just as he had been doing a day earlier in Addis Ababa. Kirya is a new breed among musicians in Uganda, and probably the whole region. Although he did grow up in what could be called a ghetto, the Ndeeba suburb of Kampala, he does not wear it on his sleeve. He does not wear dreadlocks, although he recently shaved his shaggy hair (that is another
story) and has never been known to abuse any substance.
to win Radio France International’s Discovery Award for ‘Best New African Artist’.
His clean-cut image is what is making waves, together of course with his music. In an industry where street creed is currency, he distances himself from the street and the dancehall beats that are preferred. Not to say that he has not paid his dues along the way.
That award came with a cash prize and an amount that goes into his various tours and promotions. He has never really looked back since then.
Growing up in a family of five siblings, Maurice at times had to look for his own school fees by doing odd jobs, errands, farm-work, working on building sites and working with local restaurants. He paid all of sh2,000 (less than a dollar) for his first guitar, which had been rescued from a garbage skip. “I got the wood fixed at a local carpenter’s,” he said, “and then I had to find wires to use as strings which I did, using clutch pedal wire from a garage!” His first guitar lesson was from a village drunk who showed him how to tune it and taught him his first chords. Meanwhile his elder brothers were dabbling in dancehall and hip hop, and two of them, Alex (now known as Sabasaba) and Elvis (Vampos) are star musicians in their own right. Maurice was inevitably in awe of them, but was to break away, ‘busking’ as he put it. “Basically, it’s what musicians often do in New York, Detroit, the streets of Paris… offering free performances to passers-by, breaking out into acapellas or running through a saxophone solo on a street corner.” He formed a group called The Outkamaz, and they would raid birthday parties, gate crash graduation parties and insist on performing, free. At this time he was also singing regularly in church, at his mother’s insistence, in addition to attending piano lessons. His formative years came to a head when he started the Maurice Kirya Experience, a once-a-week gig at a disco in Kampala. It was one of only two live band acts in town, the other being the Jam Session at the National Theatre. All that seems a long time ago, and it really changed with his album Misubbaawa, one of the best to come out of Uganda in years. It was released in 2010 in what was to become a watershed year for the rising singer. That year he became the first ‘Anglophone’ singer
Kirya was also nominated in three categories of the 2011 eWorld Music Awards held annually in Hollywood, in the United States. He won the Best World music artist and best Indie Group/Progressive. And when he held his first concert at the Serena Victoria Hall every single seat was taken, and the tickets were the highest-priced that Ugandans had ever paid for a concert by a local singer. After that he embarked on an African tour that took him to more than a dozen African countries, making him a bona fide continental star. And in the process it might just help save Ugandan music. ‘Most Ugandan artists prefer dancehall, and many of them just copy stuff from the Caribbean,” said a Kampala music critic. “But Maurice has taken Ugandan music, fused it with R&B and jazz, and developed a unique style that will soon be recognisable worldwide. Our other musicians should take a page from his book.” The Book of Kirya is what his second album, soon to be released, will be called. It will continue his unique blend of music which he calls Mwooyo, a Luganda word for soul. Soul is what Maurice brings to the table every time he performs, as those young folks at the free expo found out. And at the Big Brother Star game eviction show, Africa’s largest TV reality show, he had the audience singing along with him the chorus of the song Misubbaawa. No artist has ever done that, then or since. “Maurice Kirya is easily becoming the biggest music star in the country today, which is a good thing,” said music critic and musician Dennis Asiimwe. “As a musician has his strength in an area that a lot of other musicians seem to take for granted or simply lack: songwriting or composition. This is his strength, more than his voice, even way more than his ability as a performer. It is his strength as a songwriter/composer that helps him stand out, and because song writing and composition are so innate, Maurice himself probably doesn’t know just how ingrained this trait is in him.” •
19 asante aug – oct 2012
AIR UGANDA
MEET THE STAFF… Francis Asiimwe
H
aving lost both my parents in the 1986 war in Fort Portal in western Uganda, I was taken to an orphanage at a very tender age of three years by an organization called Ambassadors of Hope. My hope was renewed. I had a chance to live again as any child with parents. I was introduced to music and I joined the African Children’s Choir. A most exciting part of my life followed, having the opportunity to travel around the world to the United Kingdom, Canada and the United States of America, singing with international personalities like Sandi Patty, Ron Kenoly, Michael W Smith and many others. I went through school majoring in the American Standard of Education and the Ambassadors of Hope/African Children’s Choir catered for my needs for school, right from primary level through to University. Through travelling and meeting different people I was inspired to work in an industry that catered for people’s needs. I decided to pursue my dream by studying Hospitality Management and Tourism with the hope that after I graduated I would be able to join either a cruise liner or an airline. I graduated from Makerere University in 2006, and I did my internship at Kabira Country Club and Emin Pasha, in Uganda. Finally my dream came true when I applied for, and was accepted for, a job with Air Uganda as a flight attendant in 2008. I wake up every day and I am living my dream. I still do charity work with the Ambassadors of Hope and also hope that, one day, I will be able to help children orphaned at such an early age to find a home like I did, and also achieve their dreams. I am thankful because that light could have gone out many years ago had I not found caring people to take me in. I meet new people every day when I get to fly and I am dedicated to making their experiences worthwhile for the time that they are with us on board the aircraft, because they are the reason I am living my dream.•
20 asante aug – oct 2012
;SVOWXEXMSRW·7IEXMRK· *MPMRK·'SRJIVIRGI·'SRWYPXEXMSR
'VIEXMRK3JJMGIW8LEX;SVO
asante_feb-apr√.indd 21
4)6*361%2') *962-7,-2+7 9 08( P.O. BOX 14016, Plot 8 Hannington Rd, Kampala Uganda (Opposite Serena Hotel)
+256-312-261774 +256-792-261774 +256-772-261775 JE\ +256-312-261775 IQEMP performanceafrica@gmail.com XIP
2/4/11 4:31:26 PM
feature
A Nation’s Spirit The Olympics may have come and gone but the National Anthems endure. Frankly, there have been occasions where I just wished they’d only show some shortened highlight, because the sports only distract me from the main event: the medal ceremonies, says Brian Johnston.
T
he coveted gold is bestowed, bunches of flowers handed over. And then the supreme moment that tugs at the hearts of every citizen of the winning country: the national anthem crackles over the loudspeakers. If only they’d put the words of each anthem up on the screen, we could all join in, and then we really would have a great time. The oldest national anthem in the world is Wilhelmus van Nassouwe. The Dutch national anthem was written for Prince William of Nassau in 1568 and set to the music of a French soldiering song. Not a word of its 20 verses has been changed since, although the Dutch make do with singing just the first and eighth verses. One of the newest national anthems, on the other hand, is that of the United Arab Emirates, for which a competition for best lyrics was held in 1996; the winner scooped a US$120,000 prize. Which is the world’s most famous national anthem? Hard to say, but La Marseillaise must be among the contenders, a stirring and blood-thirsty song first heard during the French Revolution. Not all Frenchmen are happy with their song’s violent lyrics. It was suggested that the line March! March! That their impure blood may drench our furrows be changed to the more genteel March! March! That an azure sky may shine upon the horizon, but the French National Assembly turned it down.
Many national anthems are surprisingly bloodthirsty, since they were usually created at a time of great political change, revolution or war. The Marseillaise was written in one night in 1792 when the French army was encamped outside Strasbourg, defending the city against invading Prussians, with a swaggering tune intended to stir French soldiers to battle. Another much-recognised anthem, God Save the Queen, was written when the British were worrying about an invasion from Napoleonic France. Scatter her enemies, make them fall, trumpet the verses. Some voices, including that of Andrew Lloyd-Webber, have called for changes to these words too, particularly the desire in the fifth verse the rebellious Scots to crush. The Chinese national anthem is also far from benign. Arise! Arise! Arise! it goes, before exhorting the Chinese to March on! Brave the enemy’s gunfire! Perhaps the most casual in its attitude to warfare is the anthem of the Congo, which comments, And if we have to die, what does it really matter? Other anthems celebrate great victories. The American Star-Spangled Banner is the most famous example, but who couldn’t fail to be moved by the Cambodian song, which runs: Hurrah for the 17th of April, That wonderful victory had more significance than the Angkor Period! And I’m sure it did. But let us all hope beyond hope that some athlete from Burkina-Faso wins
a gold medal, so we can all sing Against the humiliating bondage of a thousand years / Against the cynical malice / Of neo-colonialism and its petty local servants / Many gave in, but some resisted. Neutral Switzerland avoids any bloodthirsty lyrics, and with great diplomacy offers one verse in each of their four national languages. The Czechoslovakians, when the country was split in two, politely opted to split their anthem down the middle as well. And there’s nothing violent about The Call of South Africa, which is a gentle song that includes the suggestion that South Africans should Bless agriculture and stock raising and well as Banish all famine and diseases and then Fill the land with good health. Countries take their anthems very seriously. Until recently there was a law in the USA prohibiting alteration to the tune, harmonies or words of The Star-Spangled Banner. In the 1960s Jimi Hendrix caused uproar with his electric guitar version at Woodstock. Classical composer Benjamin Britten’s version of God Save the Queen also caused quite a stir long before the days when the Sex Pistols dealt it a final blow. But the Brits aren’t the only people with an interest in their tune, which was written by noted composer
Henry Purcell in a reworking of a popular French court air. Many of the newly created European states (such as Germany and Norway) used it for their own anthems throughout the 19th century, and it’s still used by Liechtenstein. God Save the Queen tends towards the slow, hymn-like Victorian mood that is now echoed in the anthems of many Anglo-Saxon countries.(New Zealand’s is a good example). Monarchs are saluted in the national anthems of a variety of countries from Japan and Monaco to Bhutan and Morocco. Denmark’s national anthem is based on a national hero and former king. Curiously enough, there are no official words to the Spanish national anthem, the Royal March, although different words have been penned by two lyricists. South American anthems, on the other hand, are neither martial nor hymnal but sound like arias from an Italian opera, and tend to be just as long. The music for at least three of them was actually composed by Italians and they tend to be ambitious and complicated affairs. Brazil takes the crown, with over 100 bars to its anthem (O beloved, idolized homeland, hail, hail!). But beware of Greeks, since that country probably has the world’s longest national anthem, with 158 stanzas of four lines each. It was written in 1823 about the heroic deeds of Greek freedom fighters: ‘Twas the Greeks of old whose dying / Brought to birth our spirit free / Now, with ancient valour rising / Let us hail you, oh Liberty! If you haven’t got the stamina, stick with the anthems of Middle Eastern countries; many of these are short and sweet, little more than a fanfare flourish, and some without any text. Qatar’s takes just 32 seconds, which some might see as a great improvement on Uruguay’s full five minutes. A final category of national anthems is the slightly folkloric style, largely taken up in Asian countries, who
arrived relatively late with their national anthems. The songs of Myanmar, Sri Lanka and Japan are based on folk music and some Asian anthems actually call for indigenous instruments to be played. Perhaps the most gentle of all anthems belongs to Bangladesh, which runs: In spring, O mother mine / The fragrance of your mango groves / Makes me wild with joy. The words were penned by Nobel Prize-winning poet, Rabindranath Tagore, who also wrote the lyric to the Indian national anthem. If a representative of some unexpected country does win an Olympic medal, prepare for confusion. In the Tokyo Olympics of 1964, Abebe Bikila of Ethiopia became the first person to win two consecutive marathons. At the medal ceremony the band realised to their alarm that it had no idea what the national anthem of Ethiopia was. They settled instead on playing the far more familiar Japanese national anthem, much to the confusion of the spectators. Fortunately these days all the national anthems are stored electronically, ready to play at a moment’s notice. Let us all wait with bated breath – if only those preliminary sporting events would be over quicker! The ‘wind of change’ which blew through African colonies in the 1950s and 60s spawned a host of new national anthems for those nations which became independent. Uganda was no exception. Fifty entries were submitted and considered by a committee headed by Prof. Senteza Kajubi. Words for the winning entry were produced by Prof. George William Kakoma in collaboration with Mr P. Wyngard, an English master at the then Makerere College, and set to music by Mr E. A. Moon, director of music with the Uganda Police Force. The new anthem was played on Radio Uganda for the first time on 9th August 1962. There was subsequently a small alteration to the wording, before it settled on the now familiar version:
Uganda National Anthem.
For Uganda’s neighbours, the national anthem of Kenya became official in 1963, on the date of the country’s independence. The words were written by a commission appointed by the government. The task given to them, which begin: O God of all creation, Bless this our land and nation were meant to establish a common identity for Kenyans from all tribes and to express convictions held deeply by all of them. The words of the Tanzanian national anthem, Mungu Ibariki Africa (God Bless Africa), were written by a committee and set to the music of a hymn composed in 1897 by Enoch Sontonga, a South African Methodist school teacher. Parts of the same anthem were used to form South Africa’s new anthem in 1997. •
23 asante aug – oct 2012
bookshelf
Speak Swahili Dammit
By James Penhaligon.
This is an extraordinary, hilarious and heartbreaking book – an inspiring biographical account of a young white boy’s chaotic life in a remote, wild, corner of East Africa. Born in try.
of understanding of this necessity however, varies from person to person. Even those who do not pray or go to church would often be heard muttering especially in difficult situations, the words such as ‘let’s hope and pray’. Some people only pray when times are hard, others make an effort to pray but their prayer time is something they would rather see the end of as quickly as possible. Zion, in her book, Prayer, has expounded on many things that could make our praying enjoyable experiences. Prayer will inspire those who are keen to take their prayer lives to another level.
Lifeblood
How to Change the World, One Dead Mosquito at a Time By Alex Perry.
Prayer
By Zion Mukisa. Prayer is an absolute necessity in our lives, says the author. The level
24 asante aug – oct 2012
One day in 2006, the rich, well-connected but very private philanthropist Ray Chambers flicked through the holiday snaps of his friend, the development economist Jeffrey Sachs, and remarked on the
placid beauty of a group of sleeping Malawian children. ‘They’re not sleeping,’ Sachs tells a shocked Chambers. ‘They. Alex Perry is the Africa bureau chief for Time magazine.Publication date: September 2011
sports
of Sport in Uganda By Joseph Kabuleta.
L
ater this year, as the spectacle of the London Olympics draws to a close and Uganda clears its deck in preparation for a gargantuan 50th Independence celebration that will undoubtedly touch all walks of life, the world of athletics will be commemorating an equally significant anniversary of its own.
What was a spontaneous act of celebration four decades ago is now known as the ‘lap of honour’ or ‘victory lap’.
Forty years ago, at the Olympics in Munich, an athlete, hardly known until then, ran the race of his life to cross the finish line 10 metres ahead of the field. He then picked up his national flag from a spectator, unrolled it, held it high, and encircled the stadium absorbing the adulation of an audience that had been bewildered by his world record performance. The flag was a Ugandan one, and the athlete was 23 yearold John Akii-Bua. “I just carried on running and running,” he said later. A legend was born, and so was a tradition. What was a spontaneous act of celebration four decades ago is now known as the ‘lap of honour’ or ‘victory lap’ and has become an ingrained Olympic tradition performed by virtually all triumphant track athletes. The man who started it in 1972 is Uganda’s legendary 400 metre hurdler who, on that evening, obliterated a field of distinguished athletes that included Britain’s David Hemery, the previous record holder and a red hot favourite for the gold medal. Running in the inside Lane, the lanky Akii-Bua looked to be trailing irretrievably
26 asante aug – oct 2012
at the halfway stage and only emerged as a contender on the final bend. But by the time he crossed finish line he was well clear of his closest challenger. What made his triumph all the more remarkable is that there was nothing from the hurdler’s previous performances that suggested that such a feat was within the realm of possibility. Akii-Bua had finished a distant fourth at the 1970 Commonwealth games in Edinburgh, Scotland and hadn’t accumulated any competitive experience in the consequent years. But his ascent to greatness was in many respects birthed at London when a 27 year-old PE teacher in a Bristol secondary school and part-time athletics coach answered an advert in Athletics Weekly. Malcolm Arnold then went for an interview in London’s Trafalgar Square and returned home to tell his wife and two young children that they were headed for Uganda. “His name was difficult for us, so we simply called him ‘Mzungu’, a Kiswahili word for ‘white man’,” Akii-Bua said in his pencilwritten memoirs left with the coach. Arnold encountered a rudimentary competition structure, patchy grass tracks – and talent. He introduced a little modernity to the training regime that included scientific ‘periodisation’ of an athlete’s year into different phases of preparation, the first to build endurance and stamina, then, in the weeks before the season, honing speed, sharpness and technique.
Above: Commonwealth Games - AustraliaMelbourne, Inzikuru celebrates gold 22.03.06. Middle: Cranes striker Brian Umony leaves the Namboole pitch in tears after Uganda could only draw 0-0 with Kenya and failed yet again to qualify for the African Nations Cup. Right: Uganda’s John Akii Bua races ahead of Britain’s David Hemery to win gold in Munich 1972.
Perhaps Arnold’s biggest success was in convincing Akii-Bua to abandon the 110m hurdles for which he wasn’t suited and concentrate on the 400 metre hurdles. Even if he didn’t compete much in the two years between Edinburgh 1970 and Munich, Akii-Bua engaged himself in the most gruelling training regimes imaginable. He did hill-running in a weighted vest, repeated 600m runs with just a minute’s interval, morning and afternoon. The athlete acknowledged in his notes that such a programme was “not natural”. But it was effective. “The Ugandan national anthem played (at the medal ceremony) as I stood to attention with the whole stadium in respect to this small nation, which was on its way to disaster in the years to follow,” wrote Akii-Bua. After his success in Uganda, Arnold moved back to Britain in the early 1970s and worked with such luminaries as sprinter Linford Christie and the Welsh 110 metre hurdles legend Colin Jackson. He went on to head the Great Britain track and field team to the 1996 Olympics in Atlanta, Georgia. Yet in an interview with the Guardian newspaper in 2008, the soonretiring coach admitted that the first cut was in many respects the deepest. “Of all the athletes I have worked with, I put John (Akii-Bua) number one,” he said,
own career has made me realise quite how remarkable he was,” concluded Arnold.
as he looked nostalgically back to his days in Uganda and the triumph in Bavaria. “He came from very poor circumstances, living in a hovel while working as a policeman. We worry today about the technology of drugs; he struggled for one square meal a day. From there, his achievement was incredible. “He had everything: enormous talent, a huge commitment and capacity for work, a very astute mind, and from nowhere reached dizzy heights. Yet the sadness is, he only really had two years. Reviewing my
The story of a policeman who rose from obscurity and blew the Munich field away to set a new world record has been told and retold, but it still has not been equalled. As Uganda marks 50 years since the British Union Jack was lowered and the blackyellow-red flag of the Colony was hoisted amidst ululations, Akii-Bua’s 1972 feat still stands unchallenged at the pinnacle of the country’s sporting success. Whether that points to a nation’s underachievement or
27 asante aug – oct 2012
sports old Kipsiro was seen as a prospective new king. But he missed the event for unclear reasons. He could still make amends at London 2012, but anybody who has followed the careers of previous Ugandan athletes will not be quick to put a wager on him. The Uganda Cranes, the national soccer team, played all the way to the final of the African Nations Cup in 1978, where they lost to hosts Ghana, and a period of dominance thereafter was expected. Instead, Uganda went into an unmitigated decline and has not qualified for the biennial tournament since. Consequent qualifying campaigns have been about hopes raised before being cruelly dashed.
accentuates the greatness of its forerunner is open to debate. It’s probably a bit of both. The athlete spoke of how he lost three of his brothers in that period. Amidst such disquiet, his training for the 1976 Olympics in Montreal was far from sufficient, which was just as well because he never got the chance to defend his medal. He had arrived with the Ugandan team in Canada, ready to compete, when the 25 African countries withdrew from the Games because New Zealand, which had a team at the Olympics, were also playing rugby against South Africa. Akii-Bua was on a plane back home when the 400 metre race was being run in Montreal. When he landed, a journalist broke the news to him. “Your record is gone.” Davis Kamoga, another gifted athlete, came out of nowhere and shook the world briefly before returning straight back to oblivion. The 400 metre runner spent much of his formative years attempting to forge a football career that he never had the talent to sustain, then out of frustration tried his hand in athletics. Within less than two years he had won a bronze medal at the Olympics in Atlanta 1996. The following year he snatched silver at the World Athletics Championships in Athens.
28 asante aug – oct 2012
But just when Ugandans were looking forward to the prospect of a rivalry between one of their own and the dominant Michael Johnson, Kamoga, without any warning, clocked out before his time and has not been seen competitively since. Next on the catwalk of Ugandan one-hit wonders was Dorcus Inzikuru. The country girl from the northwest of the country surprised the world and herself when she won the 3,000 metre steeplechase gold medal at the World Championships in Helsinki 2007. She was only 24 at the time and an era of dominance was similarly predicted. Instead, like others before her, she vanished in the mists and hasn’t competed, much less won, at an international event of that magnitude since. Then along came Moses Kipsiro. After threatening to burst on to the world scene for a number of years, he won the 5000 metre and 10,000 metre gold medals at the Commonwealth Games in New Delhi two years ago, becoming the first athlete in the 70-year history of the Games to win both distance events. With Ethiopian legend Kenenisa Bekele battling injury, the 5,000 m stage was vacant at the 2011 World Championships in Daegu and the 26 year-
Above: Dai Greene presents athletics coach Malcolm Arnold with the J.L.Manning Award for an Outstanding Contribution to Sport – the SJA 2011 Sports Awards on December 7, 2011 in London. Arnold’s first success was with John Akii Bua in Uganda.
Yet in spite of all the heartbreak suffered in more than three decades of exclusion from the big stage, football is unrivaled as the abiding passion of the country and Cranes are the single most unifying force in Uganda. Every campaign is treated with the same excitement and expectation that this could be the year when all the pentup pain gives way to euphoria. Draws for the next Nations Cup have dealt Uganda a cruel blow, it would seem, as the Cranes will take on reigning champions Zambia for a place in South Africa 2013. But Ugandans are bubbling with expectation nonetheless and the symmetry of their arguments is difficult to ignore. The final leg of the qualifying campaign will be played in Kampala in October, the very month Uganda celebrates 50 years as an independent nation. The first 50 years of sport have been about random success and unfulfilled potential. Will the invisible scriptwriter of the next era be a little kinder to Ugandan sport and inscribe some happier endings? Could it all start in the festive month of October with a victory over African champions Zambia and that longawaited trip to the African showpiece? What a script that would be; one to rival Cinderella and the fitting shoe for fairytale romance. Ugandans wait. • Joseph Kabuleta is a freelance journalist who writes on sport and culture: jkabuleta@gmail.com
Driver Training for harsh environments
tech @ OnCourse4wd.com +256 772 22 11 07
Photos courtesy of Camerapix/David Pluth
feature
Semliki Land of Plenty
“I have enjoyed the privilege of visiting Uganda on a number of expeditions in the past and Semliki has always held a very special place in my heart. If your idea of peace and tranquility is a green and golden landscape studded with trees and scattered with herds of pretty Uganda kob,then this is the place to come, writes Peter Holthusen.
S
unlight filters down through the dense tree canopy above, sparkling off dewdampened leaves and mosscovered boulders. The humid air wraps itself around monumental tree trunks and ferns, while in the distance a waterfall tumbles into a crystal-clear pool. Insects hum, birds call across the almost infinite horizon. Welcome to the rainforests of the Semliki Wildlife Reserve, a slice of paradise on earth
30 asante aug – oct 2012
and only five hours drive from Kampala. Previously known as the Toro Game Reserve, Semliki is the oldest protected area in Uganda and home to a staggering array of flora and fauna. It is unique, beautiful and blessed with a tortured topography of natural barriers that have formed a veritable haven for wildlife. The Semliki Wildlife Reserve, located within the boundaries of the new Semliki National Park, is situated 375 kilometres west of
Kampala in the lush and verdant basin of the Western Rift Valley. It is one of the most diverse habitats in Africa with wonderful examples of riparian forest, gallery rainforest, Borassus palm forest, and short and high grass savannah. The habitat diversity within the 558 square-kilometre area of the Reserve supports an array of fauna including lion, leopard, elephant (both savannah and forest species), Uganda kob, buffalo, impala, and chimpanzees as well as a staggering number of birds, with
the richest areas of floral and faunal diversity in Africa, bird species being especially diverse.
over 400 species having been recorded in the area. To reach the Reserve, you leave Fort Portal (the closest town to Semliki) by the road towards the Democratic Republic of the Congo (DRC) and a bumpy three hours drive. Once a winding gravel or ‘murram’ road, this is now rapidly being transformed into a broad four-lane tarmac highway and no doubt shortly to be the main route out of the DRC for all their precious minerals and metals. Once at Karagutu, at the bottom of the escarpment, the traveller makes a decision to go either to Bundibugyo, on the border with
the DRC, via the Semliki National Park and Sempaya Hot Springs or to do what we did, turn right across the savannah and aim for the Semliki Wildlife Reserve. The Semliki National Park is located in Bwamba County, a remote part of the Bundibugyo District on western Uganda’s border with the DRC. It was elevated to the status of a National Park in October 1993, and is one of Uganda’s newest National Parks, with no less than 194 square kilometres of East Africa’s only lowland tropical rainforest being found in the park. It is managed by the Uganda Wildlife Authority and is one of
From 1932 to 1993, the area covered by the Semliki National Park was managed as a forest reserve, initially by the colonial government and then by the Ugandan Government’s Department of Forestry. It was made a National Park in order to protect the forests as an integral part of the protected areas of the Western Rift Valley. Above: Uganda Kob. Above left: From 1932 to 1993, the area covered by the Semliki National Park was managed as a forest reserve, initially by the colonial government and then by the Ugandan Government’s Department of Forestry. Today it is managed by the Uganda Wildlife Authority and is one of the richest areas of floral and faunal diversity in Africa. Opposite page: The spectacular Semliki Wildlife Reserve, 375 kilometres west of Kampala, is one of the most diverse habitats in Africa with wonderful examples of riparian forest, gallery rainforest, Borassus palm forest, and short and high grass savannah.
The Park is part of a network of protected areas in the Ugandan sector of the Albertine Rift Valley. Other protected areas in this network include the Rwenzori Mountains, the Bwindi Impenetrable Forest National Park, the Mgahinga Gorilla National Park, the Kibale National Park, and the lush savannah of the Queen Elizabeth National Park, with its elusive giant forest hog and legendary tree-climbing lions. This largely forested Park represents the eastern-most limit of the great Ituri forest of the Congo Basin and contains numerous species of flora and fauna associated with
31 asante aug – oct 2012
semliki Central rather than Eastern Africa. Semliki is the only Park in Uganda composed primarily of tropical lowland forest. The land is quite flat, creating a startling contrast to the rugged Rwenzori Mountains nearby. The Park borders the Semuliki and Lamia rivers which are watering places for many animals. There are also two hot springs located in a hot mineral encrusted swamp. This amazing field of boiling water at the Sempaya Hot Springs ejects a conspicuous cloud of steam seen as far away as two kilometres. According to the records at the Uganda Wildlife Authority, Sempaya’s water temperature at over 1,000˚C is well above the maximum temperature of most hot springs worldwide. The average temperature for most hot springs is about 500˚C. Tourists have been seen to boil eggs, cassava and green bananas in the two geothermal heating springs. The first hot spring is a pool – 12 metres in diameter – and the second is a field of geysers. Both ooze steamy sulphur-scented waters reputed to have healing powers. One of the springs – Mumbuga – regularly forms a 50 centimetres high fountain. These spectacular natural wonders attract a large number of shorebirds and they are a valuable source of salt and other minerals for many animals. To the north of Semliki is Lake Albert whilst to the east dense woodland climbs the steep valley wall. On the western horizon are the Congolese Blue Mountains and in the south a spur of rugged hills climbs up to the ice-capped peaks of the legendary Rwenzori ‘Mountains of the Moon’. The majority of the Reserve is open
acacia woodland and grassland whilst patches of gallery forest border the rivers. The area that Semliki covers is a distinct ecosystem within the larger Albertine Rift system. The Park is located at the junction of several climatic and ecological zones and, as a result, has a high diversity of plant and animal species and many microhabitats. Most of the plant and animal species in the Reserve are also found in the Congo Basin forests, many of which reach the eastern limit of their range in the Semliki National Park. Of the 400 bird species found in Semliki, 216 of these (66 per cent of the country’s total bird species) are true forest birds, including the rare forest ground thrush, Congo serpent eagle, long-tailed hawk, forest francolin, the lyretailed honeyguide and Sassi’s olive-green bulbul. Nine species of hornbill have been recorded in the Park, while the shore of Lake Albert and the swamps that surround it are home to a variety of common and rare waterbirds including the enigmatic shoebill stork and vast colonies of redthroated bee-eaters.
32 asante aug – oct 2012
The game populations in the Semliki Wildlife Reserve were at one time enormous but the poaching and hunting that occurred during the civil war and throughout the 1980s saw the numbers plummet. However, since the early ‘90s the Reserve has been protected by the Ugandan Government and, although the numbers do not yet equal those of the reserve’s heyday, they are increasing rapidly. In addition to the resident population of lion, leopard and
Above: The Semliki (also known as Semuliki) is a major river in Central Africa. It flows northwards from Lake Edward in the Democratic Republic of the Congo, across the Ugandan border and through the west of the country in Bundibugyo District, near the Semliki National Park. Below: The amazing field of boiling water at the Sempaya Hot Springs are one of Semliki’s most spectacular natural wonders. One of the springs – Mumbuga – regularly forms a 50 centimetres high fountain.
ENJOY RESPONSIBLY. EXCESSIVE CONSUMPTION OF ALCOHOL IS HARMFUL TO YOUR HEALTH. STRICTLY NOT FOR SALE TO PERSONS UNDER 18 YEARS.
semliki
Uganda kob are now commonly seen along with reedbuck, waterbuck, bushbuck and buffalo. The breeding population of elephants and lion appear to be re-colonising the Reserve from over the Congolese border, including the largemaned lions for which the reserve was once famous. The gallery forest is home to a variety of primates in addition to the chimpanzees, including black-and-white colobus and red-tailed monkeys.
Photo courtesy of Peter Holthusen
Above: Semliki is the oldest protected area in Uganda and home to a staggering array of flora and fauna, with over 400 bird species having been recorded in the area including the striking red-throated bee-eater. . Below: The forests of Semliki are also the home of the Bantuspeaking Batwa, or ‘Twa’ people, an indigenous community of short-statured people also known as ‘Pygmies’ who still largely live as hunter-gatherers.
34 asante aug – oct 2012
Photo courtesy of Peter Holthusen
elephant, Semliki has over 60 mammal species, including forest buffalo, pygmy hippos, mona monkeys, water chevrotains, bush babies, civets, and the endangered pygmy flying squirrel. Nine species of duiker are found in the Reserve, including the rare bay duiker. The forest has eight primate species and almost 300 butterfly species.
The forests in Semliki are of great socioeconomic importance to the human communities that live near the Reserve. The local people practice subsistence agriculture and use the park’s forests to supplement their livelihoods. Some of the products they obtain from the forests include fruits and vegetables, bushmeat, herbal medicines, and construction materials. The forest also plays an important cultural and spiritual role in local people’s lives. The forests are also the home of approximately 100 Bantu-speaking Batwa, or ‘Twa’ people, an indigenous community
of short-statured people also referred to as ‘Pygmies’ who still largely live as hunter-gatherers. The Bantu term ‘Twa’ is generally translated as ‘Pygmy’. However, in the Western conception ‘Pygmies’ are short forest-dwelling people, whereas southern Twa populations do not live in the forest and may not be shorter than the farming/village population, generally not reaching the anthropological definition of ‘Pygmy’ as males averaging less than 150 centimetres in height. The Batwa and Bambuti Pygmies are the country’s most ancient inhabitants, confined mainly to the hilly southwest, and they are anthropological relics of the hunter-gatherer cultures that once occupied much of East Africa. They left behind a rich legacy of rock paintings, such as those at the Nyero Rock Shelter near Kumi. Past practices of the managing authorities that excluded the local people created resentment among them. This reduced the effectiveness of conservation policies and contributed to the occurrence of illegal activities such as poaching and logging. However, since the 1990s, the Uganda Wildlife Authority has actively involved the local communities in Park planning and Semliki is rapidly becoming one of Africa’s leading wildlife conservation areas. With its relatively easy access from Kampala and Fort Portal, Semliki is Uganda’s prime ecotourism destination and offers employment opportunities for local villagers, giving them a financial alternative to clearing the forests for subsistence farming. For conservationists, Semliki’s discovery is timely. It brings hope that these ancient trees and the rare endemic species that live among them may be preserved for future generations. For scientists, the new creatures that almost certainly await discovery in the shelter of the massive trees, caves and streams that dot this spectacular landscape are an irresistible lure. I, for one, can’t wait to go back •
wild zone
sen
nd via Peter Holthu
Photo © Ian Redmo
LGON E T N U O M F O S T N A H P E L THE CAVE E ts tching the mysterious elephan
t of wa inerally relived his excitemsen ount Elgon to excavate the m M Peter Holthusen receent on ve ca of h int yr lab rk disappearing into th da Photo © Ian Redmond via rich rock for salt. Peter Holth
I
36 asante aug – oct 2012
usen
The elephants enter these ca ves as whole fa very often with milies, youngsters in tow, and walk as 160 metres as far into the pitch da rkness to find stream in the a salt rock.
Photo © Ian
the first European to visit Mt. Elgon’s caldera and to climb any of the major peaks. Ironically, Jackson climbed from the south and probably never even saw the summit of Masaba peak which was later named ‘Jackson’s Summit’ after him. Elgon’s slopes support a rich variety of vegetation ranging from montane forest to high open moorland studded with giant lobelia and groundsel plants, which varies with altitude. The mountain slopes are covered with East African Olive (Olea hochstetteri) and Aniegre (Aningueria adolfi-friedericii) wet montane forest. At higher altitudes, this changes to olive and Fern Pine (Podocarpus gracilior) forest, and then a Podocarpus and the African mountain bamboo (Arundinaria) alpine zone. Higher still is a African redwood (Hagenia abyssinica) zone with moorland heaths, Tree heaths (Erica arborea/white-renowned cave elephants that are the main draw to visitors to this spectacular mountain. The species of elephant who live on the mountain are savannah
elephants (Loxodonta africana africana), not the forest elephants of West and Central Africa. The ancient volcano of Mt. Elgon is penetrated by a suite of highlyunusual caves. The larger caves of Kitum, Ngwarisha, Chepnyalil, and Makingeny are neither limestone solution caves, nor lava tubes. Their origin lies in the interplay of unique geology with the fauna – particularly the elephants and other mammals who ‘mine’ the salt-bearing rock from the walls of the caves. Numbering only about 100 individuals, this unique population of elephants was hit hard by ivory poaching in the 1980s and ‘90s..
ter Holthusen Redmond via Pe
near the ve paintings on the ancient ca e s in the regi ud nt cl ha in ep rk el ons in the Pa ence of cave ti es ac pr tr e at th r ct he Ot h depi Budadiri, whic trailhead at e. Ag c hi it ol Ne even in the
The elephants enter these caves as whole families, very often with youngsters in tow, and walk as far as 160 metres into the pitch darkness to find a salt seam in the rock. They then excavate the mineral-rich rock with their
37 asante aug – oct 2012
wild zone The Hot Zone in 1994 for its association with the Marburg virus after two people who had visited the cave (one in 1980 and another in 1987) contracted the disease and died. Henry Rider Haggard’s hugely popular novel King The The Life of Mammals in December 2002 and the Natural World in
38 asante aug – oct 2012
Photo courtesy
Peter Holthusen ‘Mountain ‘must see’ species for any visitor to Uganda •
Mount Elgon is an extinct shield volcano on the border of Uganda and Kenya, north of the port city of Kisumu and west of Kitale. The mountain ’s slopes support a rich variety of flora and fauna, but it is the world-re nowned cave elephants that are the main draw FoR visitors TO this spectacular mountain.
WE ARE THERE
FOR YOU
METAL & WEAPON DETECTORS
TURNSTILES
CCTV
BAGGAGE & CARGO SCANNERS
FOR ALL YOUR SECURITY SOLUTIONS Access Control | Audio Video Entry Systems | Cash in Transit | Surveillance | Event Management Fire Equipment & Services | Gate Access & Parking Systems | Intruder Alarm Systems Manned GuardingServices | Perimeter Security | Security Training
EXPLOSIVES & NARCOTICS DETECTOR
ACCESS CONTROL
BOLLARDS & BARRIERS
UNDER VEHICLE SURVEILLANCE SYSTEM
SECUREX AGENCIES (K) LTD / Securex Place, Parklands Road / P.O. Box 48399, Nairobi 00100 Tel:+254 (20) 3746321 Cell: 0733/0722 343434 0752/0772 343434 / Email: security@securex.co.ke
destination dar es salaam
Sultans City of the
DAR ES SALAAM by Peter Holthusen.
A
Photos courtesy of Peter Holthusen
the city merits a visit in its own right as Tanzania’s political and economic hub.
40 asante aug – oct 2012
ny traveller flying into Dar es Salaam’s sprawling Julius Nyerere International Airport today could easily be forgiven for failing to remember that on 20 December 2011, the heaviest rains in 57 years resulted in unprecedented flooding that devastated many areas of the city, causing 13 casualties and left nearly 5,000 people homeless . With a population of almost four million and East Africa’s second-largest port, Dar es Salaam, formerly Mzizima, is the largest city in Tanzania. It is also the country’s richest city and a regionally important economic centre. Yet under its veneer of urban bustle, the city remains a down-to-earth, manageable place, with a
picturesque seaport, a fascinating mixture of African, Arabic and Indian influences with extremely close ties to its Swahili roots. Dar es Salaam was founded in 1862 by Sultan Seyyid Majid of Zanzibar who wanted to move his capital to the small port of Mzizima (Swahili for ‘healthy town’), which was then just one of the many bustling fishing villages along the East African coast on the periphery of the Indian Ocean trade routes. He named it from an Arabic phrase bandar as-salām meaning ‘harbour of peace’. A popular but habitually erroneous translation is ‘haven of peace’ resulting from a mix-up of the Arabic words dar (house) and bandar (harbour). However, soon after the
Sultan’s death in 1870, the development of Dar es Salaam fell into decline and relative anonymity, overshadowed by Bagamoyo, an important trading port to the north and the oldest town in Tanzania. It wasn’t until 1887, when the German East Africa Company established a station there, that Dar es Salaam assumed new significance, first as a way-station for Christian missionaries making their way from Zanzibar to the interior, and then as a seat for the German colonial government, which viewed Dar es Salaam’s protected harbour as a better alternative for steamships than the dhow port in Bagamoyo. The town’s growth was facilitated by its role as the centre of German colonial administration and the main contact point between the agricultural mainland and the world of trade and commerce in the Indian Ocean and the Swahili coast. Further industrial expansion soon followed with the construction of the Central Railway Line in 1907. German East Africa was captured by the British during World War I and from then on was referred to as Tanganyika, under the auspices of first The League of Nations (LON), then the Trusteeship Council of the United Nations. To assist in its own post-war economic recovery effort, Britain maintained compulsory cultivation and enforced settlement policies. Dar es Salaam was retained as the territory’s administrative and commercial centre. Under British indirect, separate European (e.g. Oyster Bay) and African (e.g. Kariakoo and Ilala) areas developed at a distance from the city centre. Further political developments, including the formation and growth of the Tanganyika African National Union (TANU), led by a young 39-year-old teacher named Julius Nyerere, resulted in Tanganyika attaining independence from colonial rule with jubilant optimism in 1961. Dar es Salaam continued to serve as its capital, but very often against daunting odds.
When Zanzibar erupted in a violent revolution in January 1964 just weeks after achieving independence from Britain, Nyerere skillfully co-opted its potentially destabilizing forces by giving the island’s politicians a prominent role in a newly proclaimed United Republic of Tanzania, created from the union of Tanganyika with Zanzibar in April 1964. However, in 1973 provisions were made to relocate the capital to Dodoma, a more centrally located city in Tanzania’s interior. The relocation process has yet to be completed, and Dar es Salaam remains Tanzania’s undisputed political and economic capital, even though the legislature and official seat of government were transferred to Dodoma in 1973. Dar es Salaam is Tanzania’s most important city for both business and
government. The city contains unusually high concentrations of trade and other services compared to other parts of the country, which has about 80 percent of its population in rural areas. For example, about one half of Tanzania’s manufacturing employment is located in the city despite the fact that Dar holds only 10 percent of Tanzania’s population. Located in a massive natural harbour on the Indian Ocean, Dar es Salaam is the hub of the Tanzanian transportation system as all of the country’s main railways and several highways originate in or near the city. Its status as an administrative and trade centre has put Dar in position to benefit disproportionately from Tanzania’s high growth rate since the year 2000, so that
AMBASSADOR RESORT HOTEL, JUBA
Your most excellent choice
For more Information call us on )JHI.BMBLBM OFBS.BOHP$BNQ +VCBt5FM &NBJMBNCBTTBEPSIPUFMKVCB!HNBJMDPNtBNCBTTBEPSIPUFMKVCB!ZBIPPDPN
41 asante aug – oct 2012
destination dar es salaam around the waterfront and city centre. In the past 15 years, Dar es Salaam and other Tanzanian cities have experienced a major construction boom, despite a much higher demand for electricity, which is still rationed around the country. With more than 21 stories, The Benjamin William Mkapa Pension Towers on Azikiwe Street is the tallest building in the city and indeed the country. The city centre runs along Samora Avenue from the clock tower to the Askari Monument, which is a memorial to the askari soldiers who fought in the British Carrier Corps in World War I. It is located at the centre of a roundabout between Samora Avenue and Maktaba Street, a place that reportedly also marks the exact centre of downtown Dar, with banks, foreign-exchange bureaus, shops and street vendors. Northwest of Samora Avenue, around India and Jamhuri Streets, is the vibrant Asian quarter, with its warren of narrow streets lined with Indian merchants and traders. On the other side of town, northeast of the Askari Monument, is a quiet area of tree-lined streets with the National Museum & House of Culture, an exciting project which has transformed the old King George V Museum into a modern tribute to African cultural heritage in Tanzania. Proceeding north from here along the coast are first, the upper-middle class area of Upanga and then, after crossing the Selander Bridge, the fast-developing diplomatic and upmarket areas of Oyster Bay and Msasani, with its famous weekend craft market. The city’s only real stretch of sand is at Coco Beach, near Oyster Bay, but better beaches to the north, such as Jangwani Beach, with its selection of swimming pools and two water parks, and the long, white-sand beach south of Kigamboni, around Mjimwema village are only a short drive away and make a relaxing break from the city.
by now its poverty rates are much lower than the rest of the country. Buildings in Dar es Salaam often reflect the city’s colonial past and display a rich mix of architectural styles incorporating Swahili, British, German and Asian traditions. Post World War II modernisation and expansion brought contemporary multi-storied buildings including a hospital complex, a technical institute and a high court. Educational
42 asante aug – oct 2012
facilities comprise the University of Dar es Salaam established in 1961, several excellent libraries and research institutes, and the National Museum & House of Culture. Other historical landmarks include the imposing St Joseph’s Cathedral, the White Father’s Mission House, the Botanical Gardens, The Azania Front Lutheran Church and the old State House, which make for an interesting walking tour
Trips to the nearby islands of the Dar es Salaam Marine Reserve are also a popular day trip from the city and a favourite spot for snorkelling, swimming and sunbathing. Moreover, Bongoyo Island is just a boat ride away from the Msasani Slipway. Although the variety and population of coral and fish species are not as numerous as other sites on Zanzibar, Pemba, and Mafia Island, Bongoyo and the neighbouring island of Mbudya, with its long white beach and resident population of coconut crabs, are well worth a visit. While there aren’t many ‘sights’ in Dar as such, there are numerous craft markets, shops and restaurants to keep most visitors happy. The streets, too, are full of colour and activity, as men weave through traffic on large Chinesemade bicycles, while women clad in brightly hued kangas (printed cotton garments worn by many women throughout East Africa) stand in the shade of government office blocks balancing trays of bananas and mangoes on their heads.
FURTHER INFORMATION
Tanzania Tourist Board
LOCATION: Dar es Salaam is the largest city in
Tanzania and East Africa’s second-largest port.
It is located on the Indian Ocean at 6˚48’ South,
39˚17’ East, in a massive natural harbour, with sandy beaches in some areas to the north and south of
Along the waterfront, colonial-era buildings with their red-tiled roofs jostle for space with sleek, modern high-rises, leading to the vibrant fish market, near Kivukoni Front. Even for those who haven’t fostered an appreciation for seafood, the Dar es Salaam fish market is definitely a place that should be experienced when travelling to Tanzania. Built by the Japanese government as part of an aid programme, it is composed of five open air buildings. One hosts the kitchens where food is prepared for the workers or the more adventurous tourists who visit the place. Another building is used to clean the fish bought off the stands of the adjacent third structure, where the day’s catch is displayed. A fourth building is used for auctioning the fish, while on the other side of the street there is a fifth building where vats of fish are fried throughout the day in boiling oil. It provides an excellent opportunity to try the local food in a safe and friendly environment. Dar es Salaam’s natural, nearly landlocked harbour is the outlet for most of mainland Tanzania’s agricultural and mineral exports and is also a transit port for the Congo River, whose navigable tributary, the Lualaba, can be reached by rail. The Tanzania Zambia Railway Authority (TAZARA) station connects Dar es Salaam to the neighbouring country of Zambia, while the Central Line Railway runs west from Dar to Kigoma on Lake Tanganyika via Dodoma. Dar es Salaam is, in common with most African cities, more romantic to the imagination than to the senses. The road from the station, which is remote from the city centre, lies through a crowded sprawl of pavement stalls and shacks selling, inter alia, pot plants and mosquito nets at bargain prices. Tanzania is a stable African state, save perhaps for the refugee problems caused by Rwanda’s genocide and the Congolese civil war. There has also been a rise in demand for greater autonomy for the neighbouring coral island of Zanzibar, which lies 100 kilometres across the strait, possibly leading to separation and eventual independence. An increasing number of travellers bypass Dar es Salaam completely, by taking advantage of one of the many international flights into Kilimanjaro International Airport (between Arusha and Moshi) for the more popular safari destinations. Yet the city merits a visit in its own right as Tanzania’s political and economic hub. It’s also an agreeable place to break your travels elsewhere in the country, with an array of top-end hotels, inexpensive restaurants, a lively music scene, night clubs, bars, and well-stocked shops, and of course, Zanzibar is only a short ferry or plane ride away.• Air Uganda flies daily to Dar es Salaam, Tanzania.
the city.
LAND AREA: The city has a total surface area of 1,590 square kilometres.
POPULATION: 41 million (July 2010 estimate)
LANGUAGES: Swahili is the official language, although English is widely spoken. TIME: GMT+3
OFFICIAL CURRENCY: The official currency of
Tanzania is the Tanzania Shilling; however visitors are advised to carry US Dollars.
ENTRY REQUIREMENTS: Passports for all visitors must be valid for at least 6 months. Visas for up to 90 Days can be obtained in advance or issued on arrival.
HEALTH: The World Health Organization recommends
that all travellers be covered for diphtheria, tetanus, measles, mumps, rubella, polio and hepatitis B. All visitors must carry their Yellow fever vaccination
cards into Tanzania. Failure to do so, vaccination
will be given before entry into the country and will cost $50. Malaria is a risk throughout the year. RELIGION: Almost all Tanzanians combine the
Christian faith (either Catholic or Protestant) which is the predominant religion representing 45% of
the population, followed by Islam (40%), with their traditional religions.
ELECTRICITY: 240 Volts AC, 50-60 Hz. Plugs may be round or square 3-pin. Adaptors can be very useful. WHEN TO GO: Tanzania has a tropical climate and can be visited during all seasons. The weather is
coolest and driest from late June to September, while October and November can be very pleasant. From
late December until February, temperatures can be
extremely high, but not oppressive. During the rainy
season (March to May), you can save substantially on accommodation costs.
WHAT TO READ: Journey through Tanzania: This
splendid book by the late Mohamed Amin, Duncan Willets and Peter Marshall, is one of the growing range of publications from Camerapix Publishers
International, and is as handsome as the spectacular country it portrays.
etiquette
Art The
of Giving
Brian Johnston gives some cautionary advice on the etiquette of giving (or receiving) business gifts. The world of international business etiquette is a wonderful and confusing place, and the rules of gift giving are no exception. We may think a well-placed gift promotes goodwill, encourages an ongoing relationship, or demonstrates our thanks, but bestow something inappropriate and it may well be the business relationship that gets recycled along with the present. Consider the American on his first trip to Panama, who thought he was being polite when he offered the company director a bunch of yellow roses, quite unwitting that yellow and purple flowers are for mourning throughout Central America. Across the Pacific in China, flowers of any sort are often associated with funerals and hospitals – giving your host a bunch of white flowers is like wishing they’d drop dead. The only exceptions are peach and plum blossoms, symbols of spring and good luck. Flowers are not the least of perils when it comes to gift giving. In the United States, anti-bribery laws severely restrict the value of gifts, and in fact most American businesspeople wouldn’t expect even a modest present. On the other hand, gift giving is more common in Europe, not so much for its monetary value (which can be negligible) but for the taste and thoughtfulness that go into it. The Swiss have the habit of giving Swiss army knives, which delights most people but would horrify Koreans. In Korea, knives or anything sharp are thought to ‘cut’ your luck, and are therefore
44 asante aug – oct 2012
inappropriate. Wooden gifts don’t go down well in the Middle East, silver fails to impress in Mexico, where silver is abundant and cheap. Do give a Spaniard an item of collectable pottery. A highbrow book or an art print will delight the French. In Europe as a general rule, stick to chocolates or flowers when it comes to minor gifts. Some flowers are also associated with funerals (best avoid chrysanthemums or white lilies) and red roses are usually a token of love, but anything else goes. Many people imagine the easy option in gift giving is food or alcohol. Far from it; you can’t possibly know the recipient’s
allergies or personal tastes, not to mention their cultural sensibilities. Lobster may be a wonderful present for some gourmets, but it would offend Jewish businesspeople, since it isn’t kosher. That old fallback of Western societies – a bottle or two of wine – would hardly be appropriate in a Muslim country. If what you give is fraught enough, the number of items you give can be a positive quagmire of superstition. ‘Good things come in pairs’ according to the Chinese – hence the well-known marriage symbol, double happiness. But when it comes to business in China, no number is more highly valued than eight, since it sounds like the world for ‘wealth’ or ‘prosper’. Eight is a number you will see frequently in your business dealings in China, from telephone numbers to street addresses and bank accounts, and a gift of eight items will impress. Western cultures tend to favour fours, long used as a way of bringing order to the universe: think four seasons, compass points and phases of the moon. This is far from an obsession, but many gifted items also come in fours. Yet four is anathema in Vietnam, Korea, Japan and any Chinese culture because its pronunciation is a homophone for ‘death’. Various numerical
combinations are also to be avoided. Fourteen, for example, sounds like ‘want to die’ in Mandarin or ‘certainly die’ in Cantonese – perhaps not the best page of a business agreement on which to affix everyone’s signatures. So you’ve chosen your gift and got your numbers right, remembering that Italians believe 17 is a doomed number. Next comes the wrapping process, which you might consider relatively minor. Not so in Japan, where wrapping presents is a whole art in itself, making it look six times more expensive than it really is. Russians rarely bother to wrap modest gifts, but will also certainly make the effort for something more expensive. Having worked out what gift to give, the next thorny issue is how you give it. As Frenchmen Pierre Corneille once commented, ‘the manner of giving is worth more than the gift.’ This need not trouble anyone in Europe or North America, where you can simply hand your gift over with a gracious word or two. In many parts of eastern Asia, however, the process is a more ceremonious affair. For a start, you should use both hands to both give and receive a present – or indeed anything else, such as pen or a business card. (Observe the receptionists at your hotel, who are all adept at the doublehanded move when taking your credit card.) However, in Islamic countries and in India you should only offer objects with your right hand. The left hand – much to the dismay of many a left-handed Westerner – is considered unclean, and certainly entirely unsuitable for offering gifts.
Almost everywhere in the world, gift giving is accompanied by a selfdeprecating remark. ‘It isn’t much,’ you might say. ‘It’s just a little token of appreciation.’ But in Hong Kong, China, Korea, and especially in Japan, such diffidence is in another whole league. It is polite to ensure that you belittle your gift as you hand it over, claiming that it is small, cheap and inadequate. Even if you’re giving away a gold Rolex to the company director, you might want to mention that it’s downright ugly, and probably entirely useless, and you can’t imagine why you ever thought of such an unseemly offering in the first place. It may be more difficult than you thought just handing your gift over. In Australia, where gift giving is not the norm, the offer of a gift may result in confusion and slight embarrassment. In Chinese cultures, gifts are often declined a number of times in order not to seem greedy, so polite persistence is the key. No such problem in South America and Europe, where gifts are readily accepted, and generally opened on the spot. In the Middle East, on the other hand, gifts are never opened there and then. And beware that you don’t inadvertently turn your business partner’s favourite possession into a present; if you compliment something admiringly, your partner may insist you accept it as a gift. So what makes the perfect gift, graciously given? Everyone likes a present that shows a bit of thought. There’s absolutely no harm in sounding out a colleague or a secretary regarding the recipient’s personal likes or hobbies, and buying an appropriate present accordingly – such courtesy will always be extremely well received. And of course, at the end of the day, it isn’t the size or expense of the gift that matters, but the size of the heart that gives it. Now that’s good etiquette anywhere•
45 asante aug – oct 2012
The Thames Diamond Jubilee Pageant
diAmond jubilee
46 asante aug – oct 2012
O
n the morning of Sunday, 3 June 2012 it was my good fortune to visit London where a flotilla of over 1,000 boats had mustered on the historic River Thames in preparation for Her Majesty The Queen to take part in the spectacular Thames Diamond Jubilee Pageant. Marking 60 years of The Queen’s reign, the Pageant was the highlight of a number of Diamond Jubilee celebrations which took place over the extended Bank Holiday weekend. Up and down the country, neighbours celebrated the Jubilee by taking part in the fourth annual ‘Big Lunch’. With local councils receiving almost 9,500 road closure applications, this year’s event proved to be the biggest and best ever. The idea of mounting a spectacular River Pageant to mark the occasion was put to The Queen in 2010 by the Diamond Jubilee Committee, led by the Mayor of London, Boris Johnson’s Cultural office, who came together to plan and organise a celebratory event to honour this historic milestone. Last year the British Government’s Department for Culture, Media and Sport sent letters to the High Commissioners of every Commonwealth country and to the Lord Lieutenants of every county in the UK inviting them to send a vessel to take part in the Thames Diamond Jubilee Pageant. More than a million people were expected to line the banks of the river to watch the unique spectacle, which was one of the major focal points of celebration during the special Jubilee Bank Holiday weekend. A mix of historic and modern boats took part in the event, from Mississippi paddle
steamers to graceful sailing ships, Viking longboats, kayaks and the famous ‘Little Ships’ of Dunkirk. Each of the participating boats were provided with a specially designed Diamond Jubilee ensign as a lasting souvenir. The organisation of the event was led by Lord Salisbury, the renowned British Conservative politician who lives in one of England’s largest historic houses, Hatfield House in Hertfordshire, once home to Queen Elizabeth I. In 1970, aged 23, he married Hannah Stirling, niece of Lt. Col Sir David Stirling (a co-founder of the SAS) and a descendant of the Lords Lovat, the famous Scottish aristocrats, so he was more than capable of recognising the exacting demands of mounting such a historic spectacle. From the very outset the Pageant was funded entirely by private donations and sponsorships and administered through a specially-created limited company, The Thames Diamond Jubilee Foundation, which is registered as a charity. Lord Salisbury was assisted in his endeavour by Michael Lockett CVO, Chief Executive; and Adrian Evans, Pageant Master. Lord Salisbury said to me at the launch of the initiative in 2011: . It seems entirely right, in view of the Queen’s dedication to the Commonwealth idea, that young people from all parts of the Commonwealth should be beneficiaries of such a legacy”. Her Majesty The Queen came to the throne on 6 February 1952 and her Coronation took place on 2 June 1953. She celebrated her
Opposite: Her Majesty The Queen onboard The Spirit of Chartwell. The Queen’s dress and matching coat were designed by Angela Kelly and created from white boucle threaded throughout with silk ribbon and embellished with Swarovski crystals.
47 asante aug – oct 2012 Photo courtesy of Matt Writtle via Peter Holthusen
diAmond jubilee Photo courtesy of Matt Writtle
Silver Jubilee (25 years) in 1977 and her Golden Jubilee (50 years) in 2002. The first British monarch to mark 50 years on the throne in a significant way was King George III. The only other British monarch to celebrate a Diamond Jubilee was Queen Victoria in 1897. There is a rich.
route was approximately 11 kilometres (7 miles) long. The full route including the mustering and dispersal areas runs Handel’s Water Music premiered in from Hammersmith to the Old Royal London on 17 July 1717, when King George Naval College at Greenwich and is I requested a concert on the River Thames. approximately 22 kilometres (13 miles) The lavish concert was performed for The long. King on his barge and he is said to have enjoyed it so much that he ordered the The flotilla was scheduled to travel at 50 exhausted musicians to play the suites a speed of approximately 4 knots with three times on the trip. The indefatigable the ebbing tide increasing its speed over King Henry VIII owned two Royal barges ground to 6 knots. To ease the flow of – the Lyon and Greyhound – which served the tides, The Port of London Authority his riverside palaces, and were kept at the decided to close the Thames Barrier Royal Bargehouse, at Lambeth. during the Pageant. Over 100 PLA staff participated in the five working groups The Queen and The Duke of Edinburgh they formed, each representing the main took part in a River Progress from vessel groupings (or Squadrons) rowers, Greenwich to Lambeth as part of the Silver the Royal Squadron, historic vessels, Jubilee celebrations in 1977. In the early recreational boats and the Thames evening on the same day a River Pageant passenger boats on 30 of their vessels, involving a flotilla of 140 vessels took running and marshalling the flotilla from place which Her Majesty reviewed from their operational hub at Gravesend in County Hall. Kent. Shortly before I arrived in London participating vessels had already gathered on the Thames between Chiswick and Putney and were scheduled to set off downstream around noon, so I quickly made my way to a suitable vantage point close to the Houses of Parliament. The formal river procession was scheduled to take part between 2pm and 6pm, starting upriver of Battersea Bridge and finishing downriver of Tower Bridge. The majority of the boats mustered between Hammersmith and Battersea and dispersed eastwards from Tower Bridge to West India Docks. The Pageant
48 asante aug – oct 2012
The lead vessel was a floating belfry with a new set of eight church bells which were cast at the famous Whitechapel Bell Foundry ready for the Thames Diamond Jubilee celebrations. The church of St James at Garlickhythe had commissioned the bells which will be installed in their church after the event. The flotilla of man-powered boats, led by The Queen’s beautifully guilded row barge, Gloriana, were the first to leave the start line at Battersea Bridge. This splendid 27 metres (88 foot) boat was the only vessel custom-built for the Thames Diamond Jubilee Pageant, and
was presented to The Queen as a gift after the celebrations, and resembles the barge used by the Lord Mayor of London in the 1800s. The Royal party departed from Cadogan Pier in Chelsea at approximately 3pm onboard The Spirit of Chartwell, the privatelyowned vessel that was meticulously designed to evoke the timeless grandeur of the 1929 Cote d’Azur Pullman railway carriage complete with artefacts from the original train and great ocean liners of yesteryear, and lovingly converted for Her Majesty into a Royal barge. Despite being dogged by typically English weather of wind and rain, it was one of the largest flotillas ever assembled on the river. Rowed boats and working boats and pleasure vessels of all shapes and sizes were beautifully adorned with streamers and Union Flags, their crews and passengers turned out in their finest attire. The armed forces, fire, police, rescue and other services were all afloat and there was an exuberance of historic boats, wooden launches, steam vessels and other boats of note all jostling for position close to the start line at Battersea Bridge. The flotilla was bolstered with hundreds of passenger boats carrying flag-waving members of the public placed centre stage (or rather mid-river) in the nautical celebration of Her Majesty’s 60 year reign. The spectacle was further enhanced with a variety of music barges and boats spouting geysers. Moreover, there were also a number of specially constructed elements such as the floating belfry, its chiming bells
Above: The Royal barge, The Spirit of Chartwell, carrying Her Majesty The Queen and other members of the Royal Family leads the flotilla during the Diamond Jubilee River Pageant in London. With a red, gold and purple colour scheme, the vessel was converted to echo the richly decorated royal barges of the 17th and 18th centuries.
answered by those from the riverbank churches along the route. With the opening ceremony of the London 2012 Olympic and Paralympic Games was just six weeks away, the public that lined the riverbanks and bridges gave a rousing reception to the many boats that had travelled from far and wide to represent UK port cities, the Commonwealth countries and other international interests.
Photo courtesy of Peter Holthusen
Below: An estimated one million rain-soaked people lined the streets of London to watch the Queen’s 1,000 boat Diamond Jubilee Pageant weave its way along the course of the River Thames.
In the shadow of The Tower of London, there was even a gun salute as the flotilla passed under Tower Bridge, whose bascules were raised in salute, before the boats made their way to the finish line through a spectacular ‘Avenue of Sail’, a mile-long stretch of river downstream of the bridge where vessels too large to travel with the rest of the flotilla were moored from Friday, 1st June until Monday, 4th June, and made up by a fleet of traditional Thames sailing barges, oyster smacks, square riggers, naval vessels and other impressive ships. This illustrious fleet of vessels were enhanced by an equally impressive number of historic yachts moored in nearby St Katharine Docks with its vibrant Marina, including Sir Francis Chichester’s ‘Gipsy Moth IV’, in which
he became the first man to sail singlehanded around the world in 1966-67, and Sir Robin Knox-Johnston’s now legendary 10 metres (32 foot) Bermudan ketch Suhaili. The weather certainly took its toll on The Duke of Edinburgh, for the following day he was admitted to the King Edward VII Hospital in London, just hours ahead of The Diamond Jubilee Concert on Monday night, where he underwent treatment for a bladder infection, but the ever-attentive Prince would have insisted on following the proceedings on television from his hospital bed. Some minor last-minute adjustments marked the absence of The Duke of Edinburgh from The Queen’s side during the final day of the Diamond Jubilee celebrations. At a service of thanksgiving at St Paul’s Cathedral on Tuesday, 5th June, Her Majesty in hospital, was a hasty addendum to the sermon delivered by the Archbishop of Canterbury, Rowan Williams. To the congregation, which included the Prime Minister, David Cameron, the Archbishop”. Shortly after the end of Sunday’s festivities on the Thames, the organisers of The Thames Diamond Jubilee Pageant issued a public vote of thanks to the millions of people who braved the weather to line the banks of the river to pay tribute to Her Majesty The Queen – and to watch the 1,000 boat, 11 kilometres ”. Thus, in common with the tradition for which London is renowned The Thames Diamond Jubilee Pageant celebrated Her Majesty’s 60 years of service by magnificently bringing the Thames to life; making it joyously full with boats, resounding with clanging bells, tooting horns and sounding bosun’s whistles; recalling both its unique Royal heritage and its heyday as a working, bustling river. •
49 asante aug – oct 2012
CUISINE
Feathered Creatures for the Table
Throughout history people have hunted down and eaten most living creatures on the earth and in its waters, but until recent times, they weren’t so lucky with birds, says Patricia Hughes Scott.
W
e are by nature omnivorous, more like bears than carnivores, eating flesh but also fruits, roots and vegetable matter – and sweetness in the form of honey. White meat, i.e. birds and fish, is probably the best for us, but we also have an innate desire for variety, and change. Early man probably designed traps to catch birds (and nets and spears to catch fish) but it wasn’t really until the invention of the gun, that the feathered creatures became more available to our table. Sadly, voracious appetites made some bird species extinct – the moa of New Zealand; the dodo of Mauritius; the passenger pigeon of north America and the great auk of
50 asante aug – oct 2012
north Atlantic islands - are some of the creatures gone forever. In French cookbooks of only a few decades ago there were always recipes for cooking grives, a little thrush found in central and southern France. They’ve been trapped and eaten almost out of existence. The trapping of thrushes used to be a big operation every year; and one of the methods was to soak grain with brandy, and scatter it. It attracted the birds in thousands and made it easy to catch them as they staggered around, unable to take off. In fact, there is still an expression heard in country districts – soul comme une grive’ which translates as ‘drunk as a thrush’.
In southern Europe – Turkey, Greece, Italy, also South America, small songbirds are still trapped – the tiny beautiful birds are de-feathered but then cooked whole. They thread the little carcasses on thick wires, and cook them over a glowing fire until they’re brown and crisp, then eat the whole thing.
African Birds Here in Africa we have a huge variety of birds. There are nearly 500 different species of birds on the African continent, south of the Sahara, and another nearly 300 species that are either resident in north western Africa or are winter migrants from northern climes. Ornithologists say they number
Above: Thanksgiving turkey. Opposite page: Ostrich meat.
2,000,000,000 or so (give or take a dozen, I imagine!) On this vast continent we have the distinction of hosting the largest bird in the world – the ostrich. Hunted ruthlessly in the latter part of the last century for the feathers of the male, today the ostrich is pretty much left alone in the wild, except for some tribes who hunt their eggs. But now these huge birds are bred on farms, and can become quite tame. The feathers of the male are used as adornment, the duller brown feathers of the female used in domestic dusters; and the meat is sold in restaurants. The fillet is a delicacy in African restaurants and is becoming popular overseas too. Other ways of eating the ostrich’s other parts are being developed. The neck is considered a delicacy, de-feathered, and stuffed with a mixture of the liver and kidneys, cooked, chopped and mixed with dried fruit, breadcrumbs, fat and seasoning, then fried until brown and crunchy. One rather weird exotic creation for a banquet was an ostrich stuffed with a swan, stuffed with a goose, stuffed with a chicken, stuffed with a pigeon, stuffed with a thrush – how do you start to carve that! Seabirds can be tough and unrewarding to eat, as most have a strong flavour of rotting fish; even wild freshwater birds often taste of fish. Most wild birds are now protected anyway, which is as it should be – we need to preserve the delicate balance of our environment – so what else?
Poultry Geese are not very popular in Africa, although there are a few breeders in South Africa who produce this bird for the table, but it is much more popular in Europe. Duck has become a worldwide phenomenon. China was probably responsible for popularising this specimen of poultry and spreading its reputation to the West. Peking duck is known everywhere, and since that bird is not very different from the English Aylesbury duck, English farmers are now exporting planeloads of these birds to Hong Kong! Ducks are gaining popularity in Africa too. Restaurants are learning that a duck has to be bled of its excess fat before roasting. The white Peking brand is popular but also the darker coloured Muscovy duck is considered tasty. Duck eggs are a speciality gaining in popularity. Game birds are also taking happily to domestic breeding (when, strictly speaking, they become poultry). The guinea fowl is one of the most important of these and they are bred on many African farms and smallholdings for food. The tiny quail breeds well in captivity and their small eggs are considered a delicacy. The turkey is fairly new to Africa, but growing fast in popularity. Originating in north America, the English explorer Sir Walter Raleigh introduced it into England in the reign of Queen Elizabeth 1 in the
16th century and it became, in the 20th century, the most popular Christmas feast. Bred now in many African countries, their meat is on sale all the year round, not just at Christmas time. One wonders if some of the other edible birds in the world could be bred in Africa – grouse, pheasant, partridge, widgeon, woodcock, ptarmigan, snipe and so on, so popular in Europe? Others have survived the transition from a cold climate to tropical heat, e.g. chickens. Chickens are now a staple in so many African homes. The Kenyan coast used to be considered too hot for chicken rearing, but Rene Haller, of Bamburi Nature Reserve fame, now considered a world authority on land reclamation, not only discovered how to fish farm tilapia, but also started successful chicken breeding. “I thought to myself, if I was a chicken, what would I want?” he jokes, but his methods of breeding and egg laying worked, and he went on to be successful in this, as all his other projects. Chicken consumption originated in the ancient races of India, but now in the 21st century it is overtaking beef as the principal supplier of animal protein in the human diet worldwide. Kenyans love chicken meat. It’s a rapidly developing business, and the major supplier to the market has a subsidy programme to encourage farmers to raise these birds. With a short maturing time, chickens are a good ‘cash crop’; the meat is beneficial for human consumption, and it tastes good too•
White meat, i.e. birds and fish, is probably the best for us. 51 asante aug – oct 2012
TIME TABLE TIME TABLE FLIGHT NUMBER FLIGHT NUMBER U7 202 FLIGHT NUMBER U7 202 U7 U7 202 206 U7 206 U7 U7 206 202 U7 202U7 U7 204 206 U7 206 U7 U7 204 204 U7 204 U7 U7 202 204 U7 204 FLIGHT NUMBER FLIGHT NUMBER U7 203 FLIGHT NUMBER U7 U7 207 203 U7 203 U7 U7 205 207 U7 207 U7 U7 205 203 U7 U7 203 207 U7 203 U7 207U7 205 FLIGHT NUMBER U7 205 U7 205 U7 122 U7 205 U7 122 FLIGHT U7 120 NUMBER U7 U7 120 120 FLIGHT NUMBER U7 U7 120 120 U7 120 U7 120 U7 120 FLIGHT NUMBER U7 120 U7 120 U7 123 U7 120 U7 123 FLIGHT U7 121 NUMBER U7 U7 121 119 FLIGHT NUMBER U7 U7 121 119 U7 119U7 119 U7 119 FLIGHT NUMBER U7 119 U7 U7 320 119 U7 119 U7 320 U7 119 U7 320 U7FLIGHT 119 U7 320NUMBER U7 320 FLIGHT NUMBER FLIGHT NUMBER U7 320 U7 U7 321 320 U7 320 U7 U7 321 320 U7 320 U7 321 U7 320 U7 321 U7FLIGHT 320 U7 321 NUMBER U7 321 U7 321 FLIGHT NUMBER FLIGHT NUMBER U7 U7 320 321 U7 321 U7 U7 320 321 U7 321 U7 320 U7 321 U7 340 U7 321 FLIGHT NUMBER
U7
U7 321 U7 U7 321 340 U7 U7 321
341 341
FLIGHT NUMBER U7 341 U7 U7 350 340 U7 341 U7 U7 352 340 U7 352
U7 340 U7 U7 352 341 U7 340U7 341
FLIGHT NUMBER
U7 351 U7FLIGHT 341 U7 353NUMBER U7 341 U7 U7 353 350 U7 U7 353 350 U7 352 FLIGHT NUMBER U7 U7 360 352 U7 350 U7 362 U7 350 U7 352 U7FLIGHT 352 NUMBER U7 352 U7 U7 361 351 U7 U7 363 351 U7 U7 353 353 FLIGHT NUMBER U7 U7 351 353 U7 351 U7 353U7 350 U7 353U7 352
Valid from 01stDecember December2011 2011 Valid from 01st ENTEBBE NAIROBI Flight schedule effective 16 May 2012. ENTEBBE - NAIROBI DEPARTURE TIME ARRIVAL TIME FREQUENCY DEPARTURE TIME ARRIVAL TIME FREQUENCY ENTEBBE - NAIROBI 6:30 Hrs 07:40 Hrs Mon,Tue ,Wed ,Thur, & Fri DEPARTURE ARRIVAL TIME FREQUENCY 6:30 Hrs TIME 07:40 Hrs Mon,Tue ,Wed ,Thur, & Fri 15:35Hrs ,Wed & Fri 06:40 14:30Hrs Hrs 07:50 Hrs Mon - Tue Fri Tue 14:30Hrs 15:35Hrs ,WedSat & Fri 8:30Hrs 9:40Hrs 16:25Hrs 17:40Hrs Mon - Fri 8:30Hrs 9:40Hrs Sat 12:20Hrs 13:25Hrs Sun 19:10 Hrs 20:25Hrs Mon - Fri 12:20Hrs 13:25Hrs SunSat 16:45Hrs 17:50Hrs 16:50Hrs 18:05Hrs Sat & Sun 16:45Hrs 17:50Hrs Sat Thur, Fri&Sun 09:00 18:45 Hrs 10:15 Hrs Sat & Sun Hrs 19:55Hrs Mon,Tue,Wed. 18:45 Hrs 19:55Hrs Mon,Tue,Wed. Thur, Fri&Sun NAIROBI ENTEBBE NAIROBI - ENTEBBE DEPARTURE TIME TIME FREQUENCY NAIROBI -ARRIVAL ENTEBBE DEPARTURE TIME ARRIVAL TIME FREQUENCY 08:20 Hrs 09:30 Hrs Mon - Fri DEPARTURE TIME ARRIVAL TIME FREQUENCY 08:15 Hrs 09:25 Hrs ,Wed ,Thur & Fri 18:10Hrs 19:25Hrs MonMon,Tue - Fri 08:15 Hrs 09:25 Hrs Mon,Tue ,Wed ,Thur & Fri 16:15Hrs 17:20Hrs ,Wed & Fri 20:55Hrs 22:10Hrs Mon - Fri Tue 16:15Hrs 17:20Hrs Tue ,WedSat & Fri 10:15Hrs 11:25Hrs 18:35 Hrs 19:50 Hrs Sat & Sun 10:45Hrs 12:00Hrs Sat & Sun 13:55Hrs 15:00Hrs 10:15Hrs 11:25Hrs SatSun ENTEBBE - JUBA 18:20Hrs 19:25Hrs 13:55Hrs 15:00Hrs SunSat DEPARTURE TIME ARRIVAL TIME FREQUENCY 20:30Hrs 21:40Hrs Mon,Tue,Wed. 18:20Hrs 19:25Hrs Sat Thur, Fri&Sun 07:30Hrs 08:35Hrs Mon,Wed,Fri ENTEBBE JUBA 20:30Hrs 21:40Hrs Mon,Tue,Wed. Thur, Fri&Sun 10:05Hrs 11:10Hrs Tue,Thu DEPARTURE TIME TIME ENTEBBE - ARRIVAL JUBA 15:50Hrs 16:55Hrs Mon-Thu FREQUENCY 10:15Hrs 11:15Hrs Mon, Tue, Wed, Thur & Fri 16:20Hrs 17:20Hrs Fri & SunFREQUENCY DEPARTURE TIME ARRIVAL TIME 13:30Hrs 14:35Hrs Sat Tue, Wed, 15:15Hrs 16:15Hrs FriThur & Fri 10:15Hrs 11:15Hrs Mon, JUBA - ENTEBBE 12:15 HRS 13:15HRS Sat 15:15Hrs 16:15Hrs Fri DEPARTURE TIME ARRIVAL TIME FREQUENCY 15:15Hrs 16:15Hrs Sun 12:15 HRS 13:15HRS 09:10Hrs 10:15Hrs Mon,Wed,Fri Sat JUBA ENTEBBE 15:15Hrs 16:15Hrs Sun 11:45Hrs 12:50Hrs Tue,Thu DEPARTURE TIME ARRIVAL TIME 17:35Hrs 18:40Hrs Mon-Thu FREQUENCY JUBA - ENTEBBE 12:00Hrs 13:00Hrs Mon & Fri 18:00Hrs 19:00Hrs Fri & Sun DEPARTURE TIME ARRIVAL TIME FREQUENCY 12:15Hrs 13:15Hrs Tue, Wed & Thur 15:10Hrs 16:15Hrs Sat 12:00Hrs Mon &Fri Fri ENTEBBE 13:00Hrs - DAR18:00Hrs ES SALAAM 17:00Hrs 12:15Hrs 13:15Hrs Tue, WedSat & Thur DEPARTURE TIME ARRIVAL TIME FREQUENCY 13:55HRS 14:55HRS 10:45Hrs 12:30Hrs Mon,Thu,Fri FriSun 17:00Hrs 18:00Hrs 17:00Hrs 18:00Hrs 10:45Hrs 13:40Hrs Tue,Wed 13:55HRS 14:55HRS Sat ENTEBBE DAR ES SALAAM 09:00Hrs 10:45Hrs Sat 17:00Hrs 18:00Hrs Sun DEPARTURE TIME ARRIVAL TIME FREQUENCY 12:30Hrs 15:25Hrs Sun ENTEBBE ES 15:45Hrs SALAAM 14:00Hrs Mon DAR- DAR ES SALAAM - ENTEBBE DEPARTURE TIME ARRIVAL TIME FREQUENCY DEPARTURE TIME ARRIVAL TIME FREQUENCY 14:45Hrs 16:30Hrs Tue, Wed& Thur 13:00Hrs 14:45Hrs Mon 14:00Hrs 15:45Hrs Mon 10:45Hrs 12:30Hrs Fri & Sat 13:00Hrs 15:55Hrs Thu,FriTue, Wed& 14:45Hrs 16:30Hrs 15:30Hrs 17:15 Hrs SunThur 14:10Hrs 15:55Hrs Tue,Wed 10:45Hrs 12:30Hrs Fri & Sat DAR ES SALAAM ENTEBBE 11:15Hrs 13:00Hrs Sat 15:30Hrs 17:15 Hrs Sun DEPARTURE TIME ARRIVAL TIME FREQUENCY 15:55Hrs 17:40Hrs Sun 16:20Hrs 18:05Hrs Mon DAR ES SALAAM ENTEBBE ENTEBBE --MOMBASA 17:05Hrs 18:50Hrs Tue,Wed&Thur DEPARTURE TIME ARRIVAL TIME FREQUENCY DEPARTURE TIME ARRIVAL TIME FREQUENCY 10:45Hrs 12:25Hrs Tue,Wed 13:10Hrs 14:55Hrs Fri & Sat 16:20Hrs 18:05Hrs Mon 10:45Hrs 13:45 Hrs Thu,Fri 17:50 Hrs 19:35Hrs Sun 17:05Hrs 18:50Hrs Tue,Wed&Thur 12:30Hrs 14:10 Hrs Sun ENTEBBE MOMBASA (Flights available as of 11th December 2011) 13:10Hrs 14:55Hrs Fri & Sat MOMBASAENTEBBE 09:00Hrs 10:40Hrs 17:50 Hrs TIME 19:35Hrs Sun & Sun DEPARTURE ARRIVAL TIME FREQUENCYThur MOMBASA - ENTEBBE (Flights avalable of 11th December 2011) 12:55Hrs 15:55Hrs Tue,Wed ENTEBBE - MOMBASA (Flights available as ofas11th December 2011) 14:15Hrs 15:55Hrs Thu,Fri 11:10Hrs 13:50Hrs 09:00Hrs 10:40Hrs Thur &Thur Sun 14:40Hrs 17:40Hrs Sun 13:00Hrs 14:30Hrs Sun MOMBASA - ENTEBBE (Flights avalable of 11th December 2011) ENTEBBE -as KIGALI ENTEBBE - ZANZIBAR (Flights available as of 11th December 2011) DEPARTURE TIME ARRIVAL TIME FREQUENCY Thur 11:10Hrs 13:50Hrs 09:00Hrs 11:40Hrs Thur 10:55Hrs 10:40Hrs Mon & Wed Sun 13:00Hrs 14:30Hrs 09:00Hrs 11:25Hrs Sun 13:20Hrs 13:05Hrs Tue & Thu ENTEBBE - ZANZIBAR (Flights available as of 11th December 2011) ZANZIBAR - ENTEBBE (Flights16:15Hrs available as of 11th December 2011) 16:30Hrs Fri 09:00Hrs 11:40Hrs Thur 18:30Hrs 18:15Hrs Sun 12:10Hrs 13:50Hrs Thur 09:00Hrs 11:25Hrs Sun KIGALI - ENTEBBE 11:55Hrs 14:30Hrs Sun DEPARTURE TIME ARRIVAL TIME ZANZIBAR - ENTEBBE (Flights ENTEBBE available as of 11th December 2011) FREQUENCY KIGALI 11:10Hrs 12:55Hrs Mon & Wed 12:10Hrs 13:50Hrs Thur DEPARTURE TIME ARRIVAL TIME 13:35Hrs 15:20Hrs Tue & Thu FREQUENCY 11:55Hrs 14:30Hrs Sun& Wed 09:15Hrs 09:00Hrs Mon 16:45Hrs 18:30Hrs Fri ENTEBBE21:55Hrs - KIGALI 18:45Hrs Sun 09:55Hrs 09:40Hrs Tue & Thur ENTEBBE - BUJUMBURA 15:30Hrs 16:30Hrs Fri DEPARTURE TIME ARRIVAL TIME FREQUENCY 07:45Hrs 07:45Hrs Tue & Thu 16:00Hrs 15:45Hrs 09:15Hrs 09:00Hrs Mon &Sun Wed 13:30Hrs 13:30Hrs Fri KIGALI - ENTEBBE 09:55Hrs 09:40Hrs Tue & Thur 18:30Hrs 19:25Hrs Sun DEPARTURE TIME ARRIVAL TIME FREQUENCY 15:30Hrs 16:30Hrs Fri BUJUMBURA - ENTEBBE 09:30Hrs 12:30Hrs 16:00Hrs 15:45Hrs Sun& Wed 08:15Hrs 10:15Hrs Tue & Thu Mon 10:10Hrs 11:55Hrs Tue & Thur 14:00Hrs 16:00Hrs Fri KIGALI - ENTEBBE 19:55Hrs 21:55Hrs Sun 17:00Hrs 18:45Hrs Fri DEPARTURE TIME ARRIVAL TIME FREQUENCY For any information16:15Hrs contact your preferred Travel Agent or our18:00Hrs Sales & Reservation Office on 041 2 165555 in KAMPALA. Sun 09:30Hrs 12:30Hrs Mon & Wed ENTEBBE - BUJUMBURA 10:10Hrs 11:55Hrs Tue & Thur 09:15Hrs 10:00Hrs Mon 17:00Hrs 18:45Hrs Fri & Wed 15:30Hrs 15:30Hrs 16:15Hrs 18:00Hrs SunFri BUJUMBURA - ENTEBBE
ASANTE NEWS
Haandi’s New Outlets at the Coast Mombasa has two new fast food outlets at the new, ultra-modern City Mall, Nyali. Situated on the junction of Links Road and the main Bamburi Road on the way to Malindi, the new shopping mall is connected to the existing Nakumatt Nyali. Haandi ‘Udupi’ serves a potpourri of Indian bazaar delicacies and Haandi ‘Black Bean serves Chinese food. The reasonably priced pre-plated food by the two outlets will be a welcome addition to the culinary attractions of Mombasa, for locals and visitors alike.
Performance Furnishings Creating Offices that Work! Performance Furnishings is a Ugandan company that sells value. Their office furniture is innovative, functional and designed to meet the rigours of the African market while meeting North American standards of quality. Performance ensures consistency and durability, putting strict quality control measures in place so that they can guarantee a conditional two-year warranty. All Performance products are ergonomically designed to enhance user comfort and productivity, which helps transform any space into an efficient working environment. Many Performance products are also GreenGuard Certified to be environmentally friendly and safe for the workplace, meeting some of the most stringent public health standards in the world. After all, your workstation is going to be your business partner for years to come, so you should make sure it’s a healthy one! Choosing the right furniture can be challenging. Performances’ furniture specialists offer on-site service and space planning to help you design and configure your space. Email performanceafrica@gmail.com
NFT Consult are Optimistic NFT Consult specialises in the provision of manpower services, and we view Uganda’s 50th anniversary with pride and optimism. The tumultuous times are long gone and NFT are happy to note that the younger generation have found a more pleasant working climate as business people, artisans, support staff and professionals. The times are looking up with many seeking opportunities for training, further education and apprenticeship as there is more demand for these resources by local, multinationals and international companies, said a company spokesman. The advent of the outsourcing model is especially welcome because of the flexibility accorded to both employers and workers. Employers will only utilize resources as and when needed and workers are in control of their working hours. Training is offered for jobs, careers can be harnessed and – not least – the family’s welfare is taken care of even when we work far from home. NFT Consult are especially optimistic about the future with the opening of borders across East Africa and increased investor interest, notably in the banking, telecommunications, and oil and gas sectors where manpower services mean more knowledge sharing and jobs for Ugandans. We have a lot to celebrate and look forward to after 50 years of independence.
Samsung Galaxy S III Latest News The Samsung Galaxy S III is probably the hottest smartphone found in the market right now. Before its launch in London at the end of May 2012, Samsung had announced that they had already received 9 million pre-orders. Here is a quick look at the highlighted features of the Samsung Galaxy S III
53 asante aug – oct 2012
HEALTHY TRAVELLING These gentle exercises, which you can carry out easily during your flight, will help blood circulation and reduce any tiredness or stiffness that may result from sitting in one place for several hours. Check with your doctor first if you have any health conditions which might be adversely affected by exercise.
Foot Pumps
Knee Lifts
Start with both heels on the
Lift leg with knees bent
floor and point feet upward as
while contracting your thigh
high as you can. Then put both
muscles. Alternate legs.
feet flat on the floor. Then lift
Repeat 20 to 30 times for
heels high, keeping the balls of
each leg.
Other Tips for a Comfortable Flight
•
For your own comfort try and travel light.
•
Wear loose clothing and elasticated stockings made of natural fibre.
•
Increase your normal intake of water and only if need be, drink alcohol but in moderation.
•
Use moisturising.
your feet on the floor. Continue cycle in 30-second intervals.
Knee to Chest Bend forward slightly. Clasp hands around the left knee and hug it to your chest. Hold stretch for 15 seconds. Keeping hands around knee, slowly let it down. Alternate legs. Repeat 10 times.
Shoulder Stretch Reach right hand over left shoulder. Place left hand behind right elbow and gently press elbow toward shoulder. Hold stretch for 15 seconds. Repeat on the other side.
Overhead Stretch Raise both hands straight up over your head. With one hand, grasp the wrist of the opposite hand and gently pull to one side. Hold stretch for 15 seconds. Repeat on the other side.
Forward Flex With both feet on the floor and stomach held in, slowly bend forward and walk your hands down the front of your legs towards your ankles. Hold the stretch for 15 seconds and slowly sit back up.
Shoulder Roll Hunch shoulders forward, then upward, then backward, then downward, using a gentle, circular motion.
Ankle Circles Lift feet off the floor, draw a circle with the toes, simultaneously moving one foot clockwise and the other foot counterclockwise. Reverse circles. Do each direction for 15 seconds. Repeat if desired.
Arm Curl
Neck Roll
Start with arms held at a 90-degree angle: elbows down, hands out in front. Raise hands up to chest and back down, alternating hands. Do this exercise in 30-second intervals.
With shoulders relaxed, drop ear to shoulder and gently roll neck forward and to the other side, holding each position about five seconds. Repeat five times.
54 asante aug – oct 2012
TIPS FOR THE TRAVELLER IN UGANDA
Land
Medical services
Uganda is a compact country, with an area of 236,580 square kilometres – roughly the size of Great Britain.
Uganda has good health services, with some good government and private hospitals and clinics in the major cities. Air rescue services are available.
Climate
Currency
Although situated on the equator, Uganda’s relatively high altitude tempers the heat, and humidity is generally low. Throughout the year sunshine averages about 6 to 10 hours a day. There are two rainy seasons: the main long rains, which start late in February and end in April, and the short rains, which start in October and run until about the middle of December. The region around Lake Victoria, however, receives rain at almost any time of the year.
Topography
Uganda Shilling (UGX). Notes are in denominations of UGX 50,000, 20,000, 10,000, 5,000 and 1,000. Coins are in denominations of UGX 500, 200, 100, 50, 20, 10, 5, 2 and 1. You can change money at banks and hotels. Although the forex bureaux usually have better exchange rates.
Credit cards
International credit cards are accepted in major hotels and shops.
Working hours
It is located on the equator, within the eastern plateau region of the African continent and between the eastern and western ridges of the Great Rift Valley. Near the borders several mountain masses stand out strikingly from the plateaux.
Shops and businesses are generally open from 0830 to 1730 hours on weekdays, with a lunch break between 1300 and 1400 hours. Some businesses are open on Saturday, at least until midday. Small, local shops or kiosks on the side of many roads are generally open much later, until about 2130 hours and on weekends and holidays as well; they stock basic food and household items.
Economy
Public Holidays
Language
2012 1 January 26 January 8 March 6 April 9 April 1 May 3 June 9 June 19 August 9 October 26 October 25 December 26 December
Uganda is blessed with fertile soils that support a wide variety of food and export crops, both annual and perennial. Agriculture is the dominant sector of Uganda’s economy. The major traditional export crops are coffee, cotton, tea, horticulture, tobacco and sugar cane, while groundnuts, maize, beans, sorghum and millet have emerged in recent years as cash crops for the peasant farmers.
English is the official language and is also the medium of instruction in Uganda’s education system, from primary school up to university level. Swahili is also spoken. There are some 30 indigenous languages spoken in the rural areas. The most common of these are Luganda and Luo.
Electric supply
All installations are of British standard and appliances should be fitted with the square, three-pin plugs of British specifications. The voltage is 240 volts, 50 Hz for domestic use. The voltage fluctuates continually, however, and proper surge protectors are advisable for any expensive equipment.
Time
Uganda is three hours ahead of Greenwich Mean Time (GMT). Time remains constant throughout the year.
People
The people are warm, friendly, and full of humour. They are anxious to make friends with visitors and are continually asking guests whether they are comfortable and enjoying themselves. A large number of people speak English.
Excursions
Uganda is beginning to develop an excellent tourist infrastructure, with first-rate roads and communication facilities. Uganda’s national game, forest and recreational parks are indeed some of the spectacular showpieces Africa has to offer. They do have regulations regarding offthe-road driving, game watching, and so on, which are clearly stated at the entrance gates of parks or on leaflets supplied by the tourist offices. Mountaineering safaris to the Ruwenzori Mountains in the western Rift Valley are now becoming a favourite Ugandan expedition. Similar safaris can also be organised to climb Mount Elgon in the east, sharing the border with Kenya. Hotels There are international-standard hotels in Entebbe, Kampala and Jinja, as well as in many of the smaller towns. Camping, rustic bush camps and guest houses are also available. The Kampala Sheraton, the Serena Kampala, the Grand Imperial, and the Nile Hotel, all in the national’s capital are by the best. There are many other less expensive, but quite nice hotels in the city. Outside Kampala, most towns also have a variety of moderately priced and budget hotels. Banking hours There is a wide range of banks in Uganda, particularly in Kampala. Their hours are generally from 0830 to 1400 hours on weekdays, and Saturdays from 0830 to 1200 hours. Forex bureaux keep longer hours – 0900 to 1700 hours on weekdays and 0900 to 1300 hours on Saturdays. ATMs are available in the larger cities. Communications Telephone, telex, fax and airmail services connect Kampala to all parts of the world. Services are available at the General Post Office and its many branches, as well as in the main hotels. International direct dialling is available and now there are a number of Internet cafes.
New Year’s Day Liberation Day International Women’s Day Good Friday Easter Monday Labour Day Martyrs’ Day National Heroes’ Day Eid al-Fitr (End of Ramadan) Independence Day Eid al-Adha (Feast of the Sacrifice) Christmas Day Boxing Day
Note:The two Muslim holidays, Eid al-Fitr and Eid al-Adha are timed according to local sightings of various phases of the moon and the dates given above are approximate.
Customs
Besides personal effects, a visitor may import duty-free spirits (including liquors) or wine up to one litre, perfume and toilet water up to half a litre and 270 grammes of tobacco or 200 cigarettes. Other imported items, not exceeding US$100 may be brought in duty free and without an import licence, provided they are not prohibited or restricted goods, are for personal use, and are not for resale. Note: A special permit is required to export game trophies.
Health requirements
Visitors from areas infected with yellow fever and cholera required certificates on inoculation. All visitors are advised to take an antimalarial prophylactic beginning two weeks before their arrival and continuing for six weeks after their departure. A gamma globulin injection provides some protection against possible infection by hepatitis and is well worth taking.
Visa and immigration requirements
Visa applications may be obtained at Uganda diplomatic missions. Two photographs are required for visas, which are usually issued within 24 hours. Visas are also available at the country’s entry points. Check with the Uganda diplomatic mission in your country if visa is required as some countries are exempted. Taxi services Taxis are immediately available at Entebbe International Airport. They can also be found outside most hotels in Kampala and at most of the country’s major centres. All don’t have meters, so make sure the fare is negotiated in advance. Car rental Several firms operate car hire services in Kampala. Vehicles may be hired with or without driver. For trips outside the city it is possible to hire insured cars appropriate for the trip (a four-wheeldrive vehicle with a driver-translator is recommended). Entebbe International Airport The main point of entry is Entebbe International Airport, about a 30-minute drive south of the capital, Kampala. Although modest, the modern airport does provide automated passenger facilities, currency exchange, postal services, banking facilities, telephoned, duty-free shops, gift shops and a restaurant and bar. Security The same rules apply for Kampala as for almost any city anywhere.Be careful and take the usual precautions to safeguard yourself and your belongings. Do not leave valuables in your car. Walking at night in all major centres is reasonably safe.
55 asante aug – oct 2012
AIR UGANDA CONTACTS AND OFFICES
Kampala Sales Office: Tel: +256 (0) 412 165 555 +256 (0) 312 165 555 Fax: +256 (0) 414 258 267 Email: info@air-uganda.com and klasupervisor@air-uganda.com
Kigali Sales Office: Tel: +250 (0) 252 577 926 +250 (0) 252 577 928 +250 (0) 788 380 926 +250 (0) 722 926 926 Email: saleskigali@air-uganda.com
Jubilee Insurance Centre,1st Floor, Podium Level, Plot 14 Parliament Avenue, Kampala, Uganda. P. O. Box 36591, Kampala, Uganda.
Office No. 26 UTC (Union Trade Centre) Building, Town Centre Kigali, Rwanda.
Head Office: Tel: +256 (0) 414 258 262/4 +256 (0) 417 717 401 Fax: +256 414 500 932 Email: info@air-uganda.com Investment House, Plot 4, Wampewo Avenue, Kololo, P.O.Box 36591, Kampala, Uganda. Entebbe International Airport (Ticketing Office): Tel: +256 (0) 414 321 485 +256 (0) 41771722 Email: ebbticketing@air-uganda.com or info@air-uganda.com 2nd Floor, Passenger Terminal Building, Entebbe, Uganda.
Bujumbura Sales Office: Tel: +257 (0) 22277262 Mobile: +257 (0) 76460000 Email: salesbjm@air-uganda.com 40.Av.du Commerce B.P: 2460 Bujumbura, Burundi. Rue du 18 septembre Galerie la Perle B.P. 2184 Bujumbura - Burundi Tel: +257 222 772 62 Mobile: +257 714 600 00 OR +257 764 600 00
PLEASE NOTE : After working hours: Weekdays (17:45 hrs - 21:00 hrs), Saturday (14:00 hrs - 21:00 hrs) and Sunday (07:30 hrs - 21:00 hrs)
Dar es Salaam Sales Office: Tel: +255 (0) 783 111 983 +255 (0) 222 133 322 Email: reservationsdar@air-uganda.com
Please call our Entebbe ticketing office on Tel: +256 (0) 414 321 485 +256 (0) 417 717 222 for assistance.
Harbour View Towers J-Mall, 1st Floor, Samora Avenue, P.O. Box 22636, Dar es Salaam, Tanzania.
Nairobi Sales Office: Tel: +254 (0) 20 313 933 Email: infoke@air-uganda.com PS Building Kimathi Street 10th Floor, P.O Box 27781- 00100, Nairobi, Kenya. Mombasa Sales Office: Tel: +254 (0) 20 313 933 or +254 (0) 734 605 203 Email: vwamakau@air-uganda.com 1st Floor, TSS Towers, Nkrumah Road, Mombasa, Kenya. Moi International Airport (MIA) Sales Office Tel: +254 735 877 289 Email: airport.mbo@air-uganda.com Unit 1 Terminal Building, Mombasa, Kenya.
Juba Sales Office: Tel: 0977 153 912 Email: info@air-uganda.com Hai Suk Street, (Opp. the Mosque) Juba, Sudan.
ROUTE MAP
ETHIOPIA
SOUTHERN SUDAN Juba
SOMALIA Mogadishu
KENYA
UGANDA Kampala Entebbe
Nairobi Kigali
Mombasa
RWANDA
BURUNDI
Bujumbura
Pemba TANZANIA Dodoma
Zanzibar Dar es Salaam
Mafia
WI MALA Lilongwe
MOZAMBIQUE
INDIAN OCEAN
ABAto corner!
G
A
I
D
N
I
J
U
X
U
E
G
Y
P
T
N
A
G
O
I
R
Y
A
N
O
N
P
A
L
T
M
N
C
H
I
A
A
N
G
I
A
A
C
H
A
D
N
D
R
R
N
R
C
K
E
N
Y
A
E
U
Y
I
D
N
A
L
G
N
E
A
U
S
T
R
I
A
L
E
C
M
A
L
D
I
V
E
S
E
E
T
A
N
Z
A
N
I
A
D
S
Answer Austria, Chad, China, Egypt, England, Germany, Greece, India, Iran, Japan, Kenya, Maldives, Mauritius, Seychelles, Tanzania, Uganda
58 asante aug – oct 2012
word square! How many countries can you find in the following words square? Looks for them from left to right, right to left, up and down, and diagonally. Score: 16 very good; 12-15 Good; 8-11 Fair
Add vowels to the following to complete the sentence (5 words)
Clbrtngfftyyrsfndpndnc. Answer Celebrating fifty years of independence.
S
CROSSWORD PUZZLE & SUDOKU
Clues across 1. Panto provides beer – but not bottled. (2,3)
Crossword '
)
(
6. Fasten, but there’s a snag. (5)
+
*
-
,
.
/
9. Reverse. Sounds harmful to heath. (4,3) 10. Box for a body part? (5)
''
'&
11. Make one to cause a fuss! (5)
'(
12. A dose of flu should produce blushing. (5) 13. Southern alpine mix-up to find dog. (7)
'+
'*
')
',
15. A lettuce for corporate businesses perhaps. (3) 17. Jaunty inside super thing. (4)
'-
'.
18. Trod back around 7” record and remove from country. (6)
'/
19. Food shops sound like they belong to Indian city. (5) 20. Fe and queen for laundry worker. (6) 22. Rise out for male parent. (4)
(&
((
('
(*
(+
24. One world embraces the unused. (3) 25. Window feature in camera. (7) 26. Paste for glaziers. (5) 27. High flying person? (5)
()
(, (-
28. Five in two points for climbers. (5)
(. (/
29. I go in gun after writer for flightless creature. (7) 30. Surrendered in five notes. (5)
)'
)&
31. Just say yes! (5)
3. It’s said the heart grows fonder if you are this. (6) 4. Tap out name of woman. (3)
Answers across 1. On tap | 6. Hitch | 9. Back out | 10. Chest | 11. Scene | 12. Flush | 13. Spaniel | 15. Cos | 17. Pert | 18. Deport | 19. Delis 20. Ironer | 22. Sire | 24. New | 25. Shutter | 26. Putty | 27. Pilot | 28. Vines | 29. Penguin | 30. Ceded | 31. Agree
2. Oh open out for despair. (2,4)
Answers down 2. No hope | 3. Absent | 4. Pat | 5. Skill | 6. Hussies | 7. Itch | 8. Censor | 12. Fever | 13. Spain | 14 Arrow | 15. Cop it | 16. Steer | 18. Dishy | 19. Deputed | 21. Recipe | 22. String | 23. Revere | 25. Stage | 26. Pope | 28. Via
Clues down
5. Southern murder has proficiency. (5)
Sudoku
6. Sue hiss out at shameless women. (7) 7. An irritation in the kitchen. (4) 8. He is used to cutting things out. (6)
Place a number from 1 to 9 in
12. This should raise the temperature! (5)
every empty cell so that each
13. Health resort in European country. (5)
row, each column and each 3x3
14 A right argument for weapon. (5)
box contains all the numbers
15. Encounter trouble – from the police? (3,2)
from 1 to 9.
16. Guide the animal. (5) 18. Attractive type of food presentation? (5) 19. Put in deed and assigned authority. (7) 21. Arranged price before easterly direction. (6) 22. Pop star right inside thin cord. (6)
No number can appear twice in a row, column or 3x3 box.
3 7
60 asante aug – oct 2012
2
8
2
8 4
1
9 5 3
Do not guess – you can work
6
it out by a process of elimination.
9 5
8
1
3 7
7
2
25. Produce on the platform. (5)
28. By way of Latin thoroughfare. (3)
9
7
23. Go backwards (not south) and venerate. (6)
26. Keep open mind to embrace religious leader. (4)
4 6 5
7 8 9
1 6
C
M
Y
CM
MY
CY
CMY
K
K | https://issuu.com/camerapixmagazines/docs/asante_inflight_magazine_aug-oct_2012 | CC-MAIN-2017-17 | refinedweb | 23,615 | 56.89 |
A recent blog post discusses the relative performance between Haskell and C when calculating the billionth iteration of a particular logistic map function:
f(x) = 3.57 * x * (1-x)
A bit curious about how Factor would perform, I decided to do a comparison.
C
A simple implementation in C...
#include <stdio.h> int main() { double x = 0.5; for(int i = 0; i < 1000000000; ++i){ x = 3.57 * x * (1-x); } printf("x=%f\n", x); }
...yields an answer in about 4.5 seconds on my machine:
$ time ./answer x=0.495618 real 0m4.501s user 0m4.495s sys 0m0.005s
Factor
A simple implementation in Factor...
: logistic-chaos ( x -- y ) [ 3.57 * ] [ 1 swap - * ] bi ; inline : answer ( -- n ) 0.5 1,000,000,000 [ logistic-chaos ] times ;
...yields an answer in about 4.5 seconds on my machine!
Note: Part of the speed comes from the Factor compiler using theNote: Part of the speed comes from the Factor compiler using theIN: scratchpad [ answer ] time . Running time: 4.478111574 seconds 0.4956180832934247
inlinerequest to determine that this is always called with floating point numbers. If the word was not inlined, the overhead of generic dispatch on every call would make this calculation take 19 seconds. If the calculation was not compiled into a word (as it is above), and just typed into the listener and executed with the non-optimizing compiler, the calculation would take 57 seconds.
2 comments:
I was surprised by the results, how did you compile the C code ? On my machine, I get:
jon@zik:~/aze$ gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
jon@zik:~/aze$ gcc -O0 -std=c99 -o aze aze.c
jon@zik:~/aze$ time ./aze
x=0.495618
real 0m13.747s
user 0m13.717s
sys 0m0.004s
jon@zik:~/aze$ gcc -O2 -std=c99 -o aze aze.c
jon@zik:~/aze$ time ./aze
x=0.495618
real 0m5.997s
user 0m5.860s
sys 0m0.112s
versus factor:
IN: scratchpad [ answer ] time
Running time: 13.443373655 seconds
Additional information was collected.
dispatch-stats. - Print method dispatch statistics
gc-events. - Print all garbage collection events
gc-stats. - Print breakdown of different garbage collection events
gc-summary. - Print aggregate garbage collection statistics
--- Data stack:
0.4956180832934247
@Jon, Hah! I said Factor was as fast as C not that C couldn't be faster! :)
Yep, without optimizations (in my case just doing "clang foo.c") its as fast, but with optimizations the C program takes half the time or so. | http://re-factor.blogspot.com/2013/07/logistic-map.html | CC-MAIN-2017-13 | refinedweb | 420 | 71.92 |
Dj.
As you already know, Django is a Python web framework. And like most modern framework, Django supports the MVC pattern. First let's see what is the Model-View-Controller (MVC) pattern, and then we will look at Django’s specificity for the Model-View-Template (MVT) pattern.
When talking about applications that provides UI (web or desktop), we usually talk about MVC architecture. And as the name suggests, MVC pattern is based on three components: Model, View, and Controller. Check our MVC tutorial here to know more.
The Model-View-Template (MVT) is slightly different from MVC. In fact the main difference between the two patterns is that Django itself takes care of the Controller part (Software Code that controls the interactions between the Model and View), leaving us with the template. The template is a HTML file mixed with Django Template Language (DTL).
The following diagram illustrates how each of the components of the MVT pattern interacts with each other to serve a user request −
The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.
Dj for the 2.6.x branch or higher than 2.7.3 for the 2.7.x branch.27\;C:\Python27:\>django-admin.py --version
If you see the current version of Django printed on screen, then everything is set.
OR
Launch a "cmd" prompt and type python then −
c:\> python >>> import django >>> print django.get.
Now that we have installed Django, let's start using it. In Django, every web app you want to create is called a project; and a project is a sum of applications. An application is a set of code files relying on the MVT pattern. As example let's say we want to build a website, the website is our project and, the forum, news, contact engine are applications. This structure makes it easier to move an application between projects since every application is independent.
Whether you are on Windows or Linux, just get a terminal or a cmd prompt and navigate to the place you want your project to be created, then use this code −
$ django-admin startproject myproject
This will create a "myproject" folder with the following structure −
myproject/ manage.py myproject/ __init__.py settings.py urls.py wsgi.py
The “myproject” folder is just your project container, it actually contains two elements −
manage.py − This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code −
$ python manage.py help
The “myproject” subfolder − This folder is the actual python package of your project. It contains four files −
__init__.py − Just for python, treat this folder as package.
settings.py − As the name indicates, your project settings.
urls.py − All links of your project and the function to call. A kind of ToC of your project.
wsgi.py − If you need to deploy your project over WSGI.
Your project is set up in the subfolder myproject/settings.py. Following are some important options you might need to set −
DEBUG = True
This option lets you set if your project is in debug mode or not. Debug mode lets you get more information about your project's error. Never set it to ‘True’ for a live project. However, this has to be set to ‘True’ if you want the Django light server to serve static files. Do it only in the development mode.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'database.sql', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } }
Database is set in the ‘Database’ dictionary. The example above is for SQLite engine. As stated earlier, Django also supports −
Before setting any new engine, make sure you have the correct db driver installed.
You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE…
Now that your project is created and configured make sure it's working −
$ python manage.py runserver
You will get something like the following on running the above code −
Validating models... 0 errors found September 03, 2015 - 11:41:50 Django version 1.6.11, using settings 'myproject.settings' Starting development server at Quit the server with CONTROL-C.
A', )
Dj.
A).
Now that we have a working view as explained in the previous chapters. We want to access that view via a URL. Django has his own way for URL mapping and it's done by editing your project url.py file (myproject/url.py). The url.py file looks)), )
When a user makes a request for a page on your web app, Django controller takes over to look for the corresponding view via the url.py file, and then return the HTML response or a 404 not found error, if not found. In url.py, the most important thing is the "urlpatterns" tuple. It’s where you define the mapping between URLs and views. A mapping is a tuple in URL patterns'^hello/', 'myapp.views.hello', name = 'hello'), )
The marked line maps the URL "/home" to the hello view created in myapp/view.py file. As you can see above a mapping is composed of three elements −
The pattern − A regexp matching the URL you want to be resolved and map. Everything that can work with the python 're' module is eligible for the pattern (useful when you want to pass parameters via url).
The python path to the view − Same as when you are importing a module.
The name − In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. Once done, just start the server to access your view via :
So far, we have created the URLs in “myprojects/url.py” file, however as stated earlier about Django and creating an app, the best point was to be able to reuse applications in different projects. You can easily see what the problem is, if you are saving all your URLs in the “projecturl.py” file. So best practice is to create an “url.py” per application and to include it in our main projects url.py file (we included admin URLs for admin interface before).
We need to create an url.py file in myapp using the following code −
from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name = 'hello'),)
Then myproject/url.py will change to the following'^myapp/', include('myapp.urls')), )
We have included all URLs from myapp application. The home.html that was accessed through “/hello” is now “/myapp/hello” which is a better and more understandable structure for the web app.
Now let's imagine we have another view in myapp “morning” and we want to map it in myapp/url.py, we will then change our myapp/url.py to −
from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name = 'hello'), url(r'^morning/', 'myapp.views.morning', name = 'morning'), )
This can be re-factored to −
from django.conf.urls import patterns, include, url urlpatterns = patterns('myapp.views', url(r'^hello/', 'hello', name = 'hello'), url(r'^morning/', 'morning', name = 'morning'),)
As you can see, we now use the first element of our urlpatterns tuple. This can be useful when you want to change your app name.
We now know how to map URL, how to organize them, now let us see how to send parameters to views. A classic sample is the article example (you want to access an article via “/articles/article_id”).
Passing parameters is done by capturing them with the regexp in the URL pattern. If we have a view like the following one in “myapp/view.py”
from django.shortcuts import render from django.http import HttpResponse def hello(request): return render(request, "hello.html", {}) def viewArticle(request, articleId): text = "Displaying article Number : %s"%articleId return HttpResponse(text)
We want to map it in myapp/url.py so we can access it via “/myapp/article/articleId”, we need the following in “myapp/url.py” −
from django.conf.urls import patterns, include, url urlpatterns = patterns('myapp.views', url(r'^hello/', 'hello', name = 'hello'), url(r'^morning/', 'morning', name = 'morning'), url(r'^article/(\d+)/', 'viewArticle', name = 'article'),)
When Django will see the url: “/myapp/article/42” it will pass the parameters '42' to the viewArticle view, and in your browser you should get the following result −
Note that the order of parameters is important here. Suppose we want the list of articles of a month of a year, let's add a viewArticles view. Our view.py becomes −
from django.shortcuts import render from django.http import HttpResponse def hello(request): return render(request, "hello.html", {}) def viewArticle(request, articleId): text = "Displaying article Number : %s"%articleId return HttpResponse(text) def viewArticles(request, month, year): text = "Displaying articles of : %s/%s"%(year, month) return HttpResponse(text)
The corresponding url.py file will look like −
from django.conf.urls import patterns, include, url urlpatterns = patterns('myapp.views', url(r'^hello/', 'hello', name = 'hello'), url(r'^morning/', 'morning', name = 'morning'), url(r'^article/(\d+)/', 'viewArticle', name = 'article'), url(r'^articles/(\d{2})/(\d{4})', 'viewArticles', name = 'articles'),)
Now when you go to “/myapp/articles/12/2006/” you will get 'Displaying articles of: 2006/12' but if you reverse the parameters you won’t get the same result.
To avoid that, it is possible to link a URL parameter to the view parameter. For that, our url.py will become −
from django.conf.urls import patterns, include, url urlpatterns = patterns('myapp.views', url(r'^hello/', 'hello', name = 'hello'), url(r'^morning/', 'morning', name = 'morning'), url(r'^article/(\d+)/', 'viewArticle', name = 'article'), url(r'^articles/(?P\d{2})/(?P\d{4})', 'viewArticles', name = 'articles'),)
Dj.
A.
Page redirection is needed for many reasons in web application. You might want to redirect a user to another page when a specific action occurs, or basically in case of error. For example, when a user logs in to your website, he is often redirected either to the main home page or to his personal dashboard. In Django, redirection is accomplished using the 'redirect' method.
The 'redirect' method takes as argument: The URL you want to be redirected to as string A view's name.
The myapp/views looks like the following so far −
def hello(request): today = datetime.datetime.now().date() daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek}) def viewArticle(request, articleId): """ A view that display an article based on his ID""" text = "Displaying article Number : %s" %articleId return HttpResponse(text) def viewArticles(request, year, month): text = "Displaying articles of : %s/%s"%(year, month) return HttpResponse(text)
Let's change the hello view to redirect to djangoproject.com and our viewArticle to redirect to our internal '/myapp/articles'. To do so the myapp/view.py will change to −
from django.shortcuts import render, redirect from django.http import HttpResponse import datetime # Create your views here. def hello(request): today = datetime.datetime.now().date() daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] return redirect(" def viewArticle(request, articleId): """ A view that display an article based on his ID""" text = "Displaying article Number : %s" %articleId return redirect(viewArticles, year = "2045", month = "02") def viewArticles(request, year, month): text = "Displaying articles of : %s/%s"%(year, month) return HttpResponse(text)
In the above example, first we imported redirect from django.shortcuts and for redirection to the Django official website we just pass the full URL to the 'redirect' method as string, and for the second example (the viewArticle view) the 'redirect' method takes the view name and his parameters as arguments.
Accessing /myapp/hello, will give you the following screen −
And accessing /myapp/article/42, will give you the following screen −
It is also possible to specify whether the 'redirect' is temporary or permanent by adding permanent = True parameter. The user will see no difference, but these are details that search engines take into account when ranking of your website.
Also remember that 'name' parameter we defined in our url.py while mapping the URLs −
url(r'^articles/(?P\d{2})/(?P\d{4})/', 'viewArticles', name = 'articles'),
That name (here article) can be used as argument for the 'redirect' method, then our viewArticle redirection can be changed from −
def viewArticle(request, articleId): """ A view that display an article based on his ID""" text = "Displaying article Number : %s" %articleId return redirect(viewArticles, year = "2045", month = "02")
To −
def viewArticle(request, articleId): """ A view that display an article based on his ID""" text = "Displaying article Number : %s" %articleId return redirect(articles, year = "2045", month = "02")
Note − There is also a function to generate URLs; it is used in the same way as redirect; the 'reverse' method (django.core.urlresolvers.reverse). This function does not return a HttpResponseRedirect object, but simply a string containing the URL to the view compiled with any passed argument.
Django comes with a ready and easy-to-use light engine to send e-mail. Similar to Python you just need an import of smtplib. In Django you just need to import django.core.mail. To start sending e-mail, edit your project settings.py file and set the following options −
Let's create a "sendSimpleEmail" view to send a simple e-mail.
from django.core.mail import send_mail from django.http import HttpResponse def sendSimpleEmail(request,emailto): res = send_mail("hello paul", "comment tu vas?", "paul@polo.com", [emailto]) return HttpResponse('%s'%res)
Here is the details of the parameters of send_mail −
subject − E-mail subject.
message − E-mail body.
from_email − E-mail from.
recipient_list − List of receivers’ e-mail address.
fail_silently − Bool, if false send_mail will raise an exception in case of error.
auth_user − User login if not set in settings.py.
auth_password − User password if not set in settings.py.
connection − E-mail backend.
html_message − (new in Django 1.7) if present, the e-mail will be multipart/alternative.
Let's create a URL to access our view −
from django.conf.urls import patterns, url urlpatterns = paterns('myapp.views', url(r'^simpleemail/(?P<emailto> [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/', 'sendSimpleEmail' , name = 'sendSimpleEmail'),)
So when accessing /myapp/simpleemail/polo@gmail.com, you will get the following page −
The method returns the number of messages successfully delivered. This is same as send_mail but takes an extra parameter; datatuple, our sendMassEmail view will then be −
from django.core.mail import send_mass_mail from django.http import HttpResponse def sendMassEmail(request,emailto): msg1 = ('subject 1', 'message 1', 'polo@polo.com', [emailto1]) msg2 = ('subject 2', 'message 2', 'polo@polo.com', [emailto2]) res = send_mass_mail((msg1, msg2), fail_silently = False) return HttpResponse('%s'%res)
Let's create a URL to access our view −
from django.conf.urls import patterns, url urlpatterns = paterns('myapp.views', url(r'^massEmail/(?P<emailto1> [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/(?P<emailto2> [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})', 'sendMassEmail' , name = 'sendMassEmail'),)
When accessing /myapp/massemail/polo@gmail.com/sorex@gmail.com/, we get −
send_mass_mail parameters details are −
datatuples − A tuple where each element is like (subject, message, from_email, recipient_list).
fail_silently − Bool, if false send_mail will raise an exception in case of error.
auth_user − User login if not set in settings.py.
auth_password − User password if not set in settings.py.
connection − E-mail backend.
As you can see in the above image, two messages were sent successfully.
Note − In this example we are using Python smtp debuggingserver, that you can launch using −
$python -m smtpd -n -c DebuggingServer localhost:1025
This means all your sent e-mails will be printed on stdout, and the dummy server is running on localhost:1025.
Sending e-mails to admins and managers using mail_admins and mail_managers methods
These methods send e-mails to site administrators as defined in the ADMINS option of the settings.py file, and to site managers as defined in MANAGERS option of the settings.py file. Let's assume our ADMINS and MANAGERS options look like −
ADMINS = (('polo', 'polo@polo.com'),)
MANAGERS = (('popoli', 'popoli@polo.com'),)
from django.core.mail import mail_admins from django.http import HttpResponse def sendAdminsEmail(request): res = mail_admins('my subject', 'site is going down.') return HttpResponse('%s'%res)
The above code will send an e-mail to every admin defined in the ADMINS section.
from django.core.mail import mail_managers from django.http import HttpResponse def sendManagersEmail(request): res = mail_managers('my subject 2', 'Change date on the site.') return HttpResponse('%s'%res)
The above code will send an e-mail to every manager defined in the MANAGERS section.
Parameters details −
Subject − E-mail subject.
message − E-mail body.
fail_silently − Bool, if false send_mail will raise an exception in case of error.
connection − E-mail backend.
html_message − (new in Django 1.7) if present, the e-mail will be multipart/alternative.
Sending HTML message in Django >= 1.7 is as easy as −
from django.core.mail import send_mail from django.http import HttpResponse res = send_mail("hello paul", "comment tu vas?", "paul@polo.com", ["polo@gmail.com"], html_message=")
This will produce a multipart/alternative e-mail.
But for Django < 1.7 sending HTML messages is done via the django.core.mail.EmailMessage class then calling 'send' on the object −
Let's create a "sendHTMLEmail" view to send an HTML e-mail.
from django.core.mail import EmailMessage from django.http import HttpResponse def sendHTMLEmail(request , emailto): html_content = "<strong>Comment tu vas?</strong>" email = EmailMessage("my subject", html_content, "paul@polo.com", [emailto]) email.content_subtype = "html" res = email.send() return HttpResponse('%s'%res)
Parameters details for the EmailMessage class creation −
Subject − E-mail subject.
message − E-mail body in HTML.
from_email − E-mail from.
to − List of receivers’ e-mail address.
bcc − List of “Bcc” receivers’ e-mail address.
connection − E-mail backend.
Let's create a URL to access our view −
from django.conf.urls import patterns, url urlpatterns = paterns('myapp.views', url(r'^htmlemail/(?P<emailto> [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/', 'sendHTMLEmail' , name = 'sendHTMLEmail'),)
When accessing /myapp/htmlemail/polo@gmail.com, we get −
This is done by using the 'attach' method on the EmailMessage object.
A view to send an e-mail with attachment will be −
from django.core.mail import EmailMessage from django.http import HttpResponse def sendEmailWithAttach(request, emailto): html_content = "Comment tu vas?" email = EmailMessage("my subject", html_content, "paul@polo.com", emailto]) email.content_subtype = "html" fd = open('manage.py', 'r') email.attach('manage.py', fd.read(), 'text/plain') res = email.send() return HttpResponse('%s'%res)
Details on attach arguments −
filename − The name of the file to attach.
content − The content of the file to attach.
mimetype − The attachment's content mime type.
Creating.
It is generally useful for a web app to be able to upload files (profile picture, songs, pdf, words.....). Let's discuss how to upload files in this chapter.
Before starting to play with an image, make sure you have the Python Image Library (PIL) installed. Now to illustrate uploading an image, let's create a profile form, in our myapp/forms.py −
#-*- coding: utf-8 -*- from django import forms class ProfileForm(forms.Form): name = forms.CharField(max_length = 100) picture = forms.ImageFields()
As you can see, the main difference here is just the forms.ImageField. ImageField will make sure the uploaded file is an image. If not, the form validation will fail.
Now let's create a "Profile" model to save our uploaded profile. This is done in myapp/models.py −
from django.db import models class Profile(models.Model): name = models.CharField(max_length = 50) picture = models.ImageField(upload_to = 'pictures') class Meta: db_table = "profile"
As you can see for the model, the ImageField takes a compulsory argument: upload_to. This represents the place on the hard drive where your images will be saved. Note that the parameter will be added to the MEDIA_ROOT option defined in your settings.py file.
Now that we have the Form and the Model, let's create the view, in myapp/views.py −
#-*- coding: utf-8 -*- from myapp.forms import ProfileForm from myapp.models import Profile def SaveProfile(request): saved = False if request.method == "POST": #Get the posted form MyProfileForm = ProfileForm(request.POST, request.FILES) if MyProfileForm.is_valid(): profile = Profile() profile.name = MyProfileForm.cleaned_data["name"] profile.picture = MyProfileForm.cleaned_data["picture"] profile.save() saved = True else: MyProfileForm = Profileform() return render(request, 'saved.html', locals())
The part not to miss is, there is a change when creating a ProfileForm, we added a second parameters: request.FILES. If not passed the form validation will fail, giving a message that says the picture is empty.
Now, we just need the saved.html template and the profile.html template, for the form and the redirection page −
myapp/templates/saved.html −
<html> <body> {% if saved %} <strong>Your profile was saved.</strong> {% endif %} {% if not saved %} <strong>Your profile was not saved.</strong> {% endif %} </body> </html>
myapp/templates/profile.html −
<html> <body> <form name = "form" enctype = "multipart/form-data" action = "{% url "myapp.views.SaveProfile" %}" method = "POST" >{% csrf_token %} <div style = "max-width:470px;"> <center> <input type = "text" style = "margin-left:20%;" placeholder = "Name" name = "name" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <input type = "file" style = "margin-left:20%;" placeholder = "Picture" name = "picture" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <button style = "border:0px;background-color:#4285F4; margin-top:8%; height:35px; width:80%; margin-left:19%;" type = "submit" value = "Login" > <strong>Login</strong> </button> </center> </div> </form> </body> </html>
Next, we need our pair of URLs to get started: myapp/urls.py
from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns( 'myapp.views', url(r'^profile/',TemplateView.as_view( template_name = 'profile.html')), url(r'^saved/', 'SaveProfile', name = 'saved') )
When accessing "/myapp/profile", we will get the following profile.html template rendered −
And on form post, the saved template will be rendered −
We have a sample for image, but if you want to upload another type of file, not just image, just replace the ImageField in both Model and Form with FileField.
Sometimes)..
To.day ==.
Before.
Dj.
Ajax essentially is a combination of technologies that are integrated together to reduce the number of page loads. We generally use Ajax to ease end-user experience. Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.
Another way of using Ajax in Django is to use the Django Ajax framework. The most commonly used is django-dajax which is a powerful tool to easily and super-quickly develop asynchronous presentation logic in web applications, using Python and almost no JavaScript source code. It supports four of the most popular Ajax frameworks: Prototype, jQuery, Dojo and MooTools.
First thing to do is to install django-dajax. This can be done using easy_install or pip −
$ pip install django_dajax $ easy_install django_dajax
This will automatically install django-dajaxice, required by django-dajax. We then need to configure both dajax and dajaxice.
Add dajax and dajaxice in your project settings.py in INSTALLED_APPS option −
INSTALLED_APPS += ( 'dajaxice', 'dajax' )
Make sure in the same settings.py file, you have the following −
TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages' ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'dajaxice.finders.DajaxiceFinder', ) DAJAXICE_MEDIA_PREFIX = 'dajaxice'
Now go to the myapp/url.py file and make sure you have the following to set dajax URLs and to load dajax statics js files −
from dajaxice.core import dajaxice_autodiscover, dajaxice_config from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings Then dajax urls: urlpatterns += patterns('', url(r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')),) urlpatterns += staticfiles_urlpatterns()
Let us create a simple form based on our Dreamreal model to store it, using Ajax (means no refresh).
At first, we need our Dreamreal form in myapp/form.py.
class DreamrealForm(forms.Form): website = forms.CharField(max_length = 100) name = forms.CharField(max_length = 100) phonenumber = forms.CharField(max_length = 50) email = forms.CharField(max_length = 100)
Then we need an ajax.py file in our application: myapp/ajax.py. That's where is our logic, that's where we put the function that will be saving our form then return the popup −
from dajaxice.utils import deserialize_form from myapp.form import DreamrealForm from dajax.core import Dajax from myapp.models import Dreamreal @dajaxice_register def send_form(request, form): dajax = Dajax() form = DreamrealForm(deserialize_form(form)) if form.is_valid(): dajax.remove_css_class('#my_form input', 'error') dr = Dreamreal() dr.website = form.cleaned_data.get('website') dr.name = form.cleaned_data.get('name') dr.phonenumber = form.cleaned_data.get('phonenumber') dr.save() dajax.alert("Dreamreal Entry %s was successfully saved." % form.cleaned_data.get('name')) else: dajax.remove_css_class('#my_form input', 'error') for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') return dajax.json()
Now let's create the dreamreal.html template, which has our form −
<html> <head></head> <body> <form action = "" method = "post" id = "my_form" accept- {{ form.as_p }} <p><input type = "button" value = "Send" onclick = "send_form();"></p> </form> </body> </html>
Add the view that goes with the template in myapp/views.py −
def dreamreal(request): form = DreamrealForm() return render(request, 'dreamreal.html', locals())
Add the corresponding URL in myapp/urls.py −
url(r'^dreamreal/', 'dreamreal', name = 'dreamreal'),
Now let's add the necessary in our template to make the Ajax work −
At the top of the file add −
{% load static %} {% load dajaxice_templatetags %}
And in the <head> section of our dreamreal.html template add −
We are using the JQuery library for this example, so add −
<script src = "{% static '/static/jquery-1.11.3.min.js' %}" type = "text/javascript" charset = "utf-8"></script> <script src = "{% static '/static/dajax/jquery.dajax.core.js' %}"></script>
The Ajax function that will be called on click −
<script> function send_form(){ Dajaxice.myapp.send_form(Dajax.process,{'form':$('#my_form').serialize(true)}); } </script>
Note that you need the “jquery-1.11.3.min.js” in your static files directory, and also the jquery.dajax.core.js. To make sure all dajax static files are served under your static directory, run −
$python manage.py collectstatic
Note − Sometimes the jquery.dajax.core.js can be missing, if that happens, just download the source and take that file and put it under your static folder.
You will get to see the following screen, upon accessing /myapp/dreamreal/ −
On submit, you will get the following screen −
39 Lectures 3.5 hours
36 Lectures 2.5 hours
28 Lectures 2 hours
20 Lectures 1 hours
35 Lectures 3 hours
79 Lectures 10 hours | https://www.tutorialspoint.com/django/django_quick_guide.htm | CC-MAIN-2022-21 | refinedweb | 4,501 | 51.04 |
Let’s have a glance at the decision making statements in the C programming language: its types & syntax.
What is Decision Making Statements in C Programming?
Suppose, you are looking to find whether a given number is even or odd, then what will you do? You will divide that number by 2 and if the remainder will be zero, the number will be called as even number, otherwise an odd number. Likewise, in the programming language, decision-making statements execute a statement on the basis of conditions.
Example:
if(number%2==0 { printf("number is even"); } else { printf("number is odd"); }
Decision-making statements are also known as conditional statements.
Types of Decision Making Statements in C
In c programming language there are following decision-making statements:
- if statements
- if-else statements
- nested if statements
- switch statement
- nested switch statements
Let’s have a look at all the decision making statements along with its syntax one by one.
if statement
It executes the statement within its body if the stated boolean condition is true. In if statement, a single statement can be added without inserting curly braces { }
Syntax of if statement
if( expression ) { statement 1;//statement to be executed when the condition is true } statement 2;
Example of if statement in C programming language
#include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); if (number < 0) { printf("You entered %d.\n", number); } printf("The if statement is easy."); return 0; }
if-else statement
It executes the statement(s) followed by if -statement if the boolean condition is true otherwise it will execute the statement(s) followed by the else statement.
Syntax of if-else statement
if( expression ) { statement 1;//statement to be executed when the condition is true } else { statement 2;//statement to be executed when the condition is false }
Example of the if-else statement in C programming language
#include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); if (number%2 == 0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; }
Nested if statements
It allows the use of a conditional statement(s) inside another conditional statement.
Syntax of nested if statement
if( expression ) { if( expression1 ) { statement 1;//statement to be executed when the condition is true } else { statement 2; //statement to be executed when the condition is false } } else { statement 3; //statement to be executed when the condition is false }
Example of nested if statement in C programming language
#include <stdio.h> int main() { int number1, number2; printf("Enter two integers: "); scanf("%d %d", &number1, &number2); if (number1 >= number2) { if (number1 == number2) { printf("Result: %d = %d",number1,number2); } else { printf("Result: %d > %d", number1, number2); } } else { printf("Result: %d < %d",number1, number2); } return 0; }
Switch statement
It allows you to test the variable for equality to the value list.
Syntax of the switch statement
switch(n) // n is any variable { case 1: statement(s); break; case n: statement(s); break; default: statement(s); break; }
Example of the switch statement in C programming language
#include<stdio.h> void main( ) { int a, b, c, choice; while(choice != 3) { printf("\n 1. Press 1 for addition"); printf("\n 2. Press 2 for subtraction"); printf("\n Enter your choice"); scanf("%d", &choice); switch(choice) { case 1: printf("Enter 2 numbers"); scanf("%d%d", &a, &b); c = a + b; printf("%d", c); break; case 2: printf("Enter 2 numbers"); scanf("%d%d", &a, &b); c = a - b; printf("%d", c); break; default: printf("you have passed a wrong key"); printf("\n press any key to continue"); } } }
Nested switch statements
it has one switch statement inside another switch statement.
Syntax of the nested switch statement
switch(n) { case 1: statement(s); switch(ch2) { case 1: statement(s); break; case n: statement(s); } break; case 2: statement(s); }
Example of the nested switch statement in C programming language
#include<stdio.h> int main() { int a,b; printf("1.School of Computer Science\n"); printf("2.School of Business\n"); printf("3.School of Engineering\n"); printf("make your selection\n"); scanf("%d",&a); switch (a) { case 1: break; case 2: printf("Available Departments\n" printf("1.Department of commerce\n"); printf("2.Department of purchasing\n"); printf("Make your selection.\n"); scanf("%d",&b); switch(b) { case 1: printf("You chose Department of commerce\n" ); break; case 2: printf("You chose Department of purchasing" ); break; } break; } } | https://www.codeatglance.com/decision-making-statements-in-c/ | CC-MAIN-2020-40 | refinedweb | 739 | 50.67 |
The Inti::Gtk namespace contains Inti's GUI toolkit interface. This chapter introduces Inti::Gtk. There are two "Hello, World" programs in the chapter; if you've never used a GUI toolkit, you might want to look at the section called Simple Hello, World, if you're more experienced with GUI toolkits and C++ you could jump straight to the section called Larger Hello, World.
The first step in any Inti::Gtk application is to initialize the library; this is done with the Inti::Gtk::init() function.Initializing the library involves connecting to the user's display, and parsing command line arguments that Inti::Gtk understands.
Next the program creates some widgets. Widgets are simply GUI objects on the screen, in this case a window and a push button.
To make the button appear inside the window, use the add() method:Without this line, the window would be empty, and the button wouldn't appear on the screen (because all widgets must be inside a window before they can be displayed).
Widgets should cause something to happen when the user interacts with them. Signals allow you to execute code in response to user actions. You can think of a signal as a list of functions or methods to be invoked when some interesting event occurs. Adding a function or method to be invoked is called connecting to the signal. Invoking the list of functions is referred to as emitting the signal.
This short "Hello, World" connects to two signals.First it connects the quit() method of Main::Loop to the destroy signal of the window; this causes the application to exit when the window is closed. Second, it connects the function on_button_clicked() to the clicked signal; when the user clicks the button, on_button_clicked() will be called.
There are two final steps to take, after connecting signals. First, the show_all() method of Gtk::Widget recursively shows a widget and each of its children. So the following code makes the window and button appear on the screen:
Finally, the program enters the main loop. The main loop is simply an infinite loop that sleeps when nothing is happening, and wakes up if the user interacts with the application. A Main::Loop object was created at the start of main():The run() method enters the main loop: Remember that the Main::Loop::quit() method was connected to the window's destroy signal. The quit() method causes the run() method to return, and at that point the end of main() will be reached and the program will exit.
That's all there is to a simple "Hello, World." The next section introduces some more of Inti::Gtk's features, and goes into more detail about the features described so far. | http://sourceware.org/inti/inti-manual/gtk-hello.html | CC-MAIN-2014-15 | refinedweb | 456 | 70.13 |
The JavaBeans technology is a significant extension and enhancement of the Java language that makes it possible for programmers to rapidly build applications by assembling objects and testing them during design time. This makes reuse of the software more productive. This article demonstrates how to use JavaBeans in Java builder tools such as JBuilder and Forte for rapid application development.
JavaBeans
JavaBeans is a software component architecture that extends the power of the Java language to enable well-formed objects to be manipulated visually in a builder tool such as Forte during design time. Such well-formed objects are referred to as Java beans or simply beans. The classes that define the beans, referred to as JavaBeans components, bean components, or simply components, must conform to the JavaBeans component model with the following:
A bean must be a public class.
A bean component must have a public default constructor (one that takes no arguments), although it can have other constructors, if needed. For example, a bean named MyBean either must have a constructor with the signature public MyBean(); or must have no constructor if its superclass has a default constructor.
A bean component must implement the Serializable interface to ensure a persistent state. JavaBeans can be used in a wide variety of tools, such as Lotus, Delphi, MS Visual Basic, and MS Word. Bean persistence may be required when JavaBeans are used in other tools. Some tools are needed to save the beans and restore them later. Bean persistence ensures that the tools can reconstruct the properties and consistent behaviors of the bean to the state in which it was saved.
A bean component usually has properties with public accessor methods that enable them to be seen and updated visually by a builder tool. To enable the properties to be manipulated, the accessor methods must conform to the naming patterns or must be specified explicitly, using the BeanInfo interface. According to the accessor method-naming pattern, the method must be named get<PropertyName>() for getting the property value and set<PropertyName>() for setting the property value.
A bean component may have events with public registration methods that enable it to add and remove listeners. If the bean plays a role as the source of events, it must provide registration methods.
The first three requirements must be observed by all beans and, therefore, are referred to as minimum JavaBeans component requirements. The last two requirements are dependent on implementations. It is possible to write a bean without accessor methods and event-registration methods.
A JavaBeans component is a special kind of Java class. The relationship of a JavaBeans component and a Java class is illustrated in Figure 1.
Figure 1 A JavaBeans component is a serializable public class with a default constructor. | http://www.informit.com/articles/article.aspx?p=25279&seqNum=3 | CC-MAIN-2017-22 | refinedweb | 461 | 52.19 |
This is a very beginners' question. But I cannot find answer...
I want to run ALL lines under
try
except
for i in range(0,100):
try:
print "a"
print "b"
print i, C
print "d"
except:
print i, "fail"
try
print C
C
print i, "fail"
except
NOT ALL
try
a
b
0 0 Fail
a
b
1 1 Fail
a
b
2 2 Fail
...
0 Fail
1 Fail
2 Fail
...
try
You could temporarily redirect stdout and only print in the except:
import sys from StringIO import StringIO for i in range(0,100): sys.stdout = StringIO() try: print "a" print "b" print i, C print "d" except Exception as e: sys.stdout = sys.__stdout__ print i, "fail" # or print e sys.stdout = sys.__stdout__
Which would give you:
0 fail 1 fail 2 fail 3 fail 4 fail 5 fail 6 fail 7 fail 8 fail 9 fail 10 fail 11 fail 12 fail 13 fail 14 fail 15 fail 16 fail 17 fail 18 fail 19 fail 20 fail 21 fail 22 fail 23 fail 24 fail 25 fail 26 fail 27 fail 28 fail 29 fail 30 fail 31 fail 32 fail 33 fail 34 fail 35 fail 36 fail 37 fail 38 fail 39 fail 40 fail 41 fail 42 fail 43 fail 44 fail 45 fail 46 fail 47 fail 48 fail 49 fail 50 fail 51 fail 52 fail 53 fail 54 fail 55 fail 56 fail 57 fail 58 fail 59 fail 60 fail 61 fail 62 fail 63 fail 64 fail 65 fail 66 fail 67 fail 68 fail 69 fail 70 fail 71 fail 72 fail 73 fail 74 fail 75 fail 76 fail 77 fail 78 fail 79 fail 80 fail 81 fail 82 fail 83 fail 84 fail 85 fail 86 fail 87 fail 88 fail 89 fail 90 fail 91 fail 92 fail 93 fail 94 fail 95 fail 96 fail 97 fail 98 fail 99 fail
But there are no doubt much better ways to do whatever it is you are trying to do in your real logic.
Bar seeing into the future you cannot print in real time if all calls are going to be successful as you have not seen them all so you would need to store the output and see if there were any errors.
import sys from StringIO import StringIO stdo = StringIO() errs = False for i in range(0, 100): sys.stdout = stdo try: print "a" print "b" print i print "d" except Exception as e: sys.stdout = sys.__stdout__ errs = True print i, "fail" sys.stdout = stdo sys.stdout = sys.__stdout__ if not errs: print(stdo.getvalue())
Any error will show in real time but you will have to wait until the end to see if all are successful. | https://codedump.io/share/2kEbSWf0vZj4/1/python-try--except-how-to-make-sure-all-command-under-try-is-executed | CC-MAIN-2017-04 | refinedweb | 470 | 74.76 |
Contiki is an open source operating system for connecting tiny, low-cost, low-power microcontrollers to the Internet. It is preferred because it supports various Internet standards, rapid development, a selection of hardware, has an active community to help, and has commercial support bundled with an open source licence.
Contiki is designed for tiny devices and thus the memory footprint is far less when compared with other systems. It supports full TCP with IPv6, and the devices power management is handled by the OS. All the modules of Contiki are loaded and unloaded during run time; it implements protothreads, uses a lightweight file system, and various hardware platforms with sleepy routers (routers which sleep between message relays).
One important feature of Contiki is its use of the Cooja simulator for emulation in case any of the hardware devices are not available.
Installation of Contiki
Contiki can be downloaded as Instant Contiki, which is available in a single download that contains an entire Contiki development environment. It is an Ubuntu Linux virtual machine that runs in VMware Player, and has Contiki and all the development tools, compilers and simulators used in Contiki development already installed. Most GB, approximately () and unzip it.
Step 3: Open the Virtual Machine and open the Contiki OS; then wait till the login screen appears.
Step 4: Input the password as user; this shows the desktop of Ubuntu (Contiki).
Running the simulation
To run a simulation, Contiki comes with many prebuilt modules that can be readily run on the Cooja simulator or on the real hardware platform. There are two methods of opening the Cooja simulator window.
Method 1: In the desktop, as shown in Figure 1, double click the Cooja icon. It will compile the binaries for the first time and open the simulation windows.
Method 2: Open the terminal and go to the Cooja directory:
pradeep@localhost$] cd contiki/tools/cooja pradeep@localhost$] ant run
You can see the simulation window as shown in Figure 2.
Creating a new simulation
To create a simulation in Contiki, go to File menu ? New Simulation and name it as shown in Figure 3.
Select any one radio medium (in this case) -> Unit Disk Graph Medium (UDGM): Distance Loss and click Create.
Figure 4 shows the simulation window, which has the following windows.
Network window: This shows all the motes in the simulated network.
Timeline window: This shows all the events over the time.
Mote output window: All serial port outputs will be shown here.
Notes window: User notes information can be put here.
Simulation control window: Users can start, stop and pause the simulation from here.
Adding the sensor motes
Once the simulation window is opened, motes can be added to the simulation using Menu: Motes-> Add Motes. Since we are adding the motes for the first time, the type of mote has to be specified. There are more than 10 types of motes supported, go to Add Motes?Select any of the motes given above?MicaZ mote. You will get the screen shown in Figure 5.
Step 2: Cooja opens the Create Mote Type dialogue box, which gives. Then, click Compile.
Step 3: Once compiled without errors, click Create (Figure 5).
Step 4: Now the screen asks you to enter the number of motes to be created and their positions (random, ellipse, linear or manual positions).
In this example, 10 motes are created. Click the Start button in the Simulation Control window and enable the mote’s Log Output: printf() statements in the View menu of the Network window. The Network window shows the output Hello World in the sensors. Figure 6 illustrates this.
This is a simple output of the Network window. If the real MicaZ motes are connected, the Hello World will be displayed in the LCD panel of the sensor motes. The overall output is shown in Figure 7.
The output of the above Hello World application can also be run using the terminal.
To compile and test the program, go into the hello-world directory:
pradeep@localhost $] cd /home/user/contiki/examples/hello-world pradeep@localhost $] make
This will compile the Hello World program in the native target, which causes the entire Contiki operating system and the Hello World application to be compiled into a single program that can be run by typing the following command (depicted in Figure 8):
pradeep@localhost$] ./hello-world.native This will print out the following text: Contiki initiated, now starting process scheduling Hello, world
The program will then appear to hang, and must be stopped by pressing Control + C.
Developing new modules
Contiki comes with numerous pre-built modules like IPv6, IPV6 UDP, hello world, sensor nets, EEPROM, IRC, Ping, Ping-IPv6, etc. These modules can run with all the sensors irrespective of their make. Also, there are modules that run only on specific sensors. For example, the energy of a sky mote can be used only on Sky Motes and gives errors if run with other motes like Z1 or MicaZ.
Developers can build new modules for various sensor motes that can be used with different sensor BSPs using conventional C programming, and then be deployed in the corresponding sensors.
Here is the C source code for the above Hello World application.
#include "contiki.h" #include <stdio.h> /* For printf() */ /*---------------------------------------------------------------------------*/ PROCESS(hello_world_process, "Hello world process"); AUTOSTART_PROCESSES(&hello_world_process); /*---------------------------------------------------------------------------*/ PROCESS_THREAD(hello_world_process, ev, data) { PROCESS_BEGIN(); printf("Hello, world\n"); PROCESS_END(); }
The Internet of Things is an emerging technology that leads to concepts like smart cities, smart homes, etc. Implementing the IoT is a real challenge but the Contiki OS can be of great help here. It can be very useful for deploying applications like automatic lighting systems in buildings, smart refrigerators, wearable computing systems, domestic power management for homes and offices, etc.
References
[1]
sir, can we implement cross layer design approach in wireless sensor networks using this contiki and cooja simulator? if means, how its can be possible? share with me links to proceed. | https://www.opensourceforu.com/2014/10/contiki-os-connecting-microcontrollers-to-the-internet-of-things/ | CC-MAIN-2021-25 | refinedweb | 996 | 54.22 |
Timeline
Oct 30, 2008:
- 3:29 PM Changeset [8243] by
- Added featurelimit to ArcXML format. Added un-rendering fix for …
- 12:59 PM Changeset [8242] by
- more merging of Vector layer (removing old style code)
- 12:59 PM Changeset [8241] by
- merging in renderers
- 12:59 PM Changeset [8240] by
- merging in Format changes
- 12:01 PM Ticket #1803 (Latitude tile origin in WMS Layer moves randomly making it unusable ...) closed by
- wontfix: This is demonstrating a known/expected behavior when laying over …
- 11:55 AM Documentation edited by
- (diff)
- 10:36 AM Ticket #1798 (Spanish translation) reopened by
- just for hoots, probably safer to reopen this ticket so we dont forget …
- 10:16 AM Ticket #1803 (Latitude tile origin in WMS Layer moves randomly making it unusable ...) created by
- Our WMS server does tile caching and we noticed that, using openlayer, …
- 10:02 AM Ticket #1799 (Catalan translation) closed by
- fixed: (In [8239]) Adding Catalan language dictionary from Oscar Fonts. …
- 10:02 AM Changeset [8239] by
- Adding Catalan language dictionary from Oscar Fonts. Thanks for the …
- 9:58 AM Ticket #1798 (Spanish translation) closed by
- fixed: (In [8238]) Adding Spanish language dictionary from Miguel Montesinos …
- 9:58 AM Changeset [8238] by
- Adding Spanish language dictionary from Miguel Montesinos and Oscar …
- 5:52 AM Changeset [8237] by
- set the CLASS_NAME to the complete class name (add OpenLayers.Layer.)
- 3:47 AM Changeset [8236] by
- FixedZoomLevels CLASS_NAME was wrong (included .js): correct it. (No …
- 3:42 AM Ticket #1802 (Add the possibility to check if an instance inherits from a given class) reopened by
- And *also* doesn't work. […]
- 3:40 AM Ticket #1802 (Add the possibility to check if an instance inherits from a given class) closed by
- invalid: You're doing the check wrong: […] is the way to do it, not […]
- 3:38 AM Ticket #1802 (Add the possibility to check if an instance inherits from a given class) reopened by
- Yes, you missed that that doesn't work. >>> …
- 3:35 AM Ticket #1802 (Add the possibility to check if an instance inherits from a given class) closed by
- invalid: No need to do this. You can just use plain JavaScript: […] I'm …
- 3:32 AM Ticket #1802 (Add the possibility to check if an instance inherits from a given class) created by
- It would be cool to be able to do something like that: […] Please …
- 3:22 AM Ticket #1801 (Danish translations) created by
- Danish translation strings.
- 3:20 AM Ticket #1799 (Catalan translation) reopened by
- Please don't close a ticket that has not been reviewed yet.
- 3:20 AM Ticket #1798 (Spanish translation) reopened by
- Please don't close a ticket that has not been reviewed yet.
- 3:19 AM Ticket #1800 (Ship OL with more themes ?) created by
- Here's a green version of the default blue theme. If some one want to …
- 2:29 AM Ticket #1799 (Catalan translation) closed by
- fixed
- 2:27 AM Ticket #1799 (Catalan translation) created by
- Catalan 'ca' localization strings.
- 2:17 AM Documentation edited by
- (diff)
- 2:16 AM Documentation edited by
- (diff)
- 2:03 AM Documentation edited by
- (diff)
- 1:13 AM Ticket #1798 (Spanish translation) closed by
- fixed
Oct 29, 2008:
- 4:51 PM CLA edited by
- adding oscar fonts (diff)
- 4:50 PM Release/2.8 edited by
- uncommenting release information. even though it points to dead … (diff)
- 4:46 PM Sponsorship/Uses edited by
- adding wiki-related sponsorship use (diff)
- 1:24 PM Ticket #1798 (Spanish translation) created by
- Localized strings for spanish language 'es'
- 1:03 PM Printing edited by
- (diff)
- 12:41 PM Changeset [8235] by
- Change that has no impact because features sent by the save strategy …
- 12:38 PM Changeset [8234] by
- Example of editing features where local and remote projections differ.
- 12:20 PM Changeset [8233] by
- Strategies that manage protocol reads and commits also handle geometry …
- 9:30 AM Changeset [8232] by
- fixed rollback support in WFSV format
- 7:53 AM Changeset [8231] by
- safeToIgnore, fromFeatureVersion support on Rollback
- 6:21 AM Ticket #1797 (Google layers won't get resized properly on map.updateSize()) created by
- We had the same problems as described in ticket #830 before 2.7, but …
Oct 28, 2008:
- 5:01 PM Ticket #1766 (When zoom changed, the markers screen position do not changed) closed by
- fixed
- 4:51 PM Changeset [8230] by
- Marker icons should be moved when the map zoom changes. Thanks to …
- 4:48 PM Ticket #1759 (replace unnecessary, undocumented 'drawn' property on OpenLayers.Marker) closed by
- fixed: Lets say this re-open state is a dupe of #1766 and close this.
- 4:36 PM Changeset [8229] by
- Updating change to match patch for #1766.
- 4:27 PM Changeset [8228] by
- still not working correctly, but at least visible now
- 4:03 PM Changeset [8227] by
- Fewer characters to read. No functional change.
- 3:58 PM Changeset [8226] by
- changes from landgate branch (diff (update) parsing; featureVersion …
- 3:57 PM Changeset [8225] by
- fixing requires statement
- 3:55 PM Changeset [8224] by
- improvements to WFSV Diff parsing, and allowing featureVersion option …
- 3:55 PM Changeset [8223] by
- Fix for #1766.
- 3:54 PM Changeset [8222] by
- Reading common gml elements in feature members.
- 3:51 PM Changeset [8221] by
- Updated build profile.
- 1:01 PM Changeset [8220] by
- Including additional controls in build.
- 11:19 AM Changeset [8219] by
- updates from upstream
- 11:10 AM Changeset [8218] by
- merge r8148:HEAD from topp/wfs sandbox
- 10:51 AM Changeset [8217] by
- Push boundedBy reading to gml parser (with r8216).
- 10:46 AM Changeset [8216] by
- Read boundedBy element and set bounds on geometry.
- 10:11 AM three/RemoveOverlayBaseLayerDichotomy created by
-
- 9:11 AM Changeset [8215] by
- Removing dupes, a bit of space, no functional change.
- 9:07 AM Changeset [8214] by
- Commas, spaces, nothing to see here.
Oct 27, 2008:
- 8:03 PM Changeset [8213] by
- Making sure the word 'style' appears in the style examples. No …
- 3:59 PM Changeset [8212] by
- better rollback support, updates from wfs sandbox
- 1:26 PM Changeset [8211] by
- when handler deactivates, we need to remove cursor css class
- 1:14 PM Changeset [8210] by
- adding changes for handlers, mostly drag for now
- 12:02 PM Changeset [8209] by
- basic example
- 12:01 PM Changeset [8208] by
- adding button images
- 12:00 PM Ticket #1359 (HOWTO: Enable zoom out with right-dblclick) closed by
- fixed: (In [8207]) fix propogate/propagate typo in click handler. thanks to …
- 12:00 PM Changeset [8207] by
- fix propogate/propagate typo in click handler. thanks to chris r. for …
- 11:46 AM Changeset [8206] by
- adding cursor images
- 11:41 AM Ticket #1794 (update trac/roadmap and trunk/openlayers/news.txt) closed by
- fixed: thanks for spotting this, jrf! I have updated these accordingly.
- 11:40 AM Changeset [8205] by
- filling cursor sandbox with trunk
- 11:37 AM Changeset [8204] by
- remove cursor sandbox to startover from scratch
- 11:36 AM Release/Procedure edited by
- moving the news.txt update up a knotch... otherwise you don't get the … (diff)
- 9:58 AM Changeset [8203] by
- add updates to news.txt for 2.6 and 2.7 releases
- 9:54 AM Release edited by
- adding links to 2.8 release (diff)
- 9:53 AM Release/Procedure edited by
- adding stage for updating news.txt (diff)
- 9:29 AM Changeset [8202] by
- retroactively update news.txt for 2.7 release
- 7:51 AM Ticket #1796 (KML.js style url fetch depth calculation broken causing style urls to ...) created by
- Summary: 1. Create a GML layer referencing a KML document that has …
- 3:41 AM Changeset [8201] by
- fixing file type info on these images
- 3:38 AM Changeset [8200] by
- progress toward a functioning popup; still not appearing though :(
- 3:37 AM Changeset [8199] by
- adding FramedPuff.js to the list of files
- 3:36 AM Changeset [8198] by
- making the isAlphaImage property updated with the selected image
- 3:35 AM Changeset [8197] by
- making pixels always be integers, in case that matters to some browsers
Oct 26, 2008:
- 3:22 PM Changeset [8196] by
- progress towards a puff popup that leaves the box
- 4:47 AM Changeset [8195] by
- making an animated popup using jquery
- 4:43 AM Ticket #1795 (consider using Packer) created by
- Per this discussion: …
- 4:42 AM Ticket #1794 (update trac/roadmap and trunk/openlayers/news.txt) created by
- These appear to be out of date: …
Oct 25, 2008:
- 7:27 AM Ticket #1793 (Allow Easy Registering of 'rightclick'/'dblrightclick' Handlers on ...) reopened by
- Creating a control that does this with the click handler is easy, but …
- 7:20 AM Ticket #1793 (Allow Easy Registering of 'rightclick'/'dblrightclick' Handlers on ...) closed by
- invalid: click-handler.html provides examples showing how to create controls …
Oct 24, 2008:
- 3:17 PM Changeset [8194] by
- Fix a typo in documentation pointed out by MonkZ on IRC.
- 2:00 PM Changeset [8193] by
- improving filterDelete on WFS.v1 protocol
- 12:17 PM Changeset [8192] by
- build requirements
- 11:44 AM Changeset [8191] by
- Adding build config for trimet.
- 11:05 AM Changeset [8190] by
- merge r8147:HEAD from trunk
- 9:49 AM Ticket #1793 (Allow Easy Registering of 'rightclick'/'dblrightclick' Handlers on ...) created by
- As brought up by Chris R on the dev@ mailing list, registering right …
- 9:26 AM Sponsorship/Uses edited by
- (diff)
- 1:29 AM Ticket #1785 (Layer.Vector.drawFeature should fail safely if layer is not drawn) closed by
- fixed: (In [8189]) the test to check if layer is drawn before we draw feature …
- 1:29 AM Changeset [8189] by
- the test to check if layer is drawn before we draw feature is moved to …
Oct 23, 2008:
- 8:57 PM Styles edited by
- Update the wiki to reflect the new api for OpenLayers.Rule (diff)
- 3:56 PM Changeset [8188] by
- Test that the format can read and optionally write things like …
- 3:53 PM Changeset [8187] by
- Test reading and writing of gml:MultiCurve.
- 3:41 PM Changeset [8186] by
- Testing that the format can do things like read and optionally write …
- 3:40 PM Changeset [8185] by
- merge from trunk. (Most importantly, merging the moveTo method into Map)
- 3:34 PM Changeset [8184] by
- Testing that we do the right thing by default, including writing …
- 3:28 PM Changeset [8183] by
- Reading and writing gml:Surface
- 2:59 PM Ticket #1359 (HOWTO: Enable zoom out with right-dblclick) reopened by
- as noted by chris r. on the mailing list: […]
- 2:32 PM Changeset [8182] by
- merging in more of Rule, Map, and Vector layer from trunk
- 12:14 PM Changeset [8181] by
- Successfully reading and writing gml:Curve.
- 11:36 AM Changeset [8180] by
- latest wfs(t/v) support from topp/wfs(v) sandboxes
- 11:28 AM Changeset [8179] by
- merge from trunk. Minor change to Vespucci.Application needed. …
- 10:39 AM Ticket #1792 (OpenLayers.Format.GeoJSON doesn't work with GeometryCollection + ...) created by
- 1. Construct GeoJSON object with a GeometryCollection containing other …
- 9:41 AM Ticket #1791 (ZoomBox drag wonky with left-right mouse clicks.) created by
- A good test is this url: …
- 7:49 AM Changeset [8178] by
- Mark loadURL as an API function, since we treat it as one.
- 7:24 AM Changeset [8177] by
- proper indentation
- 7:21 AM Changeset [8176] by
- proper indentation
- 7:10 AM Changeset [8175] by
- no need to do hiding here, just use closeOnPan
- 7:10 AM Changeset [8174] by
- haha. I added onMove and did not use it anywhere; taking that out …
- 5:17 AM Changeset [8173] by
- an attempt at implementing ticket #1726, but it does not work, see …
Oct 22, 2008:
- 9:03 PM Sponsorship/Uses edited by
- adding bunker info (diff)
- 7:24 PM Changeset [8172] by
- merge from trunk -- broke the click handler?
- 5:22 PM Changeset [8171] by
- merge from trunk
- 5:18 PM Changeset [8170] by
- merge from trunk
- 4:44 PM Ticket #1790 (Filter updates: FE v1.1.0 support and cleanup) created by
- In order to support WFS 1.1, we need to be able to write filters using …
- 3:13 PM Changeset [8169] by
- More short test names, still no functional change.
- 3:12 PM Changeset [8168] by
- Shortening test names. No functional change.
- 1:29 PM Sponsorship/Uses edited by
- (diff)
- 1:28 PM Sponsorship/Uses edited by
- (diff)
- 1:27 PM Sponsorship/Uses edited by
- (diff)
- 1:26 PM Sponsorship/Uses edited by
- (diff)
- 1:11 PM Sponsorship/Uses edited by
- (diff)
- 1:09 PM Changeset [8167] by
- better WFSV
- 1:08 PM Sponsorship/Uses created by
-
- 11:36 AM Ticket #1789 (Popup of OpenLayers.Layer.Text does not work in Firefox 3.0) created by
- I have set up a Map with OpenLayers.Layer.Text layer, when I click on …
- 11:08 AM Ticket #1788 (Measure Control getLength Measures Innaccurate in East-West Direction ...) created by
- I am using OpenLayers.Control.Measure in my application to give the …
- 9:03 AM Ticket #1787 (WFS-T delete and update have improper typeName) created by
- I'm working with WFS-T, I noticed that it is expected that layerName …
- 6:51 AM Ticket #1786 (Firebug upgrade) created by
- I just realized that the new version of firebuglite totally rocks. …
- 4:48 AM Changeset [8166] by
- made log diagnostics more informative for soliciting advice
- 4:28 AM Changeset [8165] by
- adding log messages to show that events are firing, but FramedCloud is …
Oct 21, 2008:
- 7:05 PM Changeset [8164] by
- more toward a popup out of the map; does not pan map into get in view
- 11:11 AM Changeset [8163] by
- correcting version, url, and namespace in example
- 11:11 AM Changeset [8162] by
- some wfsv writers for WFSV format (for GetLog)
- 11:10 AM Changeset [8161] by
- changes from wfs sandbox
- 11:10 AM Changeset [8160] by
- defering to superclass more in WFSV protocol
- 11:08 AM Changeset [8159] by
- wfsv classes in openlayers.js
- 10:00 AM Changeset [8158] by
- fixed GetLog on WFSV protocol
- 9:59 AM Changeset [8157] by
- changes from wfs sandbox
- 4:50 AM Ticket #1785 (Layer.Vector.drawFeature should fail safely if layer is not drawn) created by
- If user calls drawFeature on a vector layer that hasn't already been …
Oct 20, 2008:
- 6:58 PM Changeset [8156] by
- tabs for spaces. no functional changes
- 6:49 PM Changeset [8155] by
- moving comments back to original (trunk) state. this will make merging …
- 6:42 PM Changeset [8154] by
- bad spellings. no functional change
- 2:39 PM Changeset [8153] by
- Edits to sponsorship doc for clarity, style, and brevity.
- 12:31 PM Changeset [8152] by
- Satisfying servers that are more strict about XML than they are about …
- 10:06 AM Changeset [8151] by
- add 'deprecated' comment to docs
- 9:02 AM Changeset [8150] by
- properly positions the popup. the mouseover/mouseout events make it …
- 8:11 AM Changeset [8149] by
- some WFSV classes and example to test against
- 7:55 AM Changeset [8148] by
- wfsv sandbox
Oct 19, 2008:
- 10:23 PM Changeset [8147] by
- merge r8064:HEAD from trunk
- 10:02 PM Changeset [8146] by
- All operations working with strict flag on.
- 10:00 PM Changeset [8145] by
- Pusing GetFeature and Query writers into the format.
- 7:31 PM Changeset [8144] by
- fixed a problem: the popup's this.map.div.left should have been …
- 4:29 PM Changeset [8143] by
- partial progress on popups out of div... need to move to other …
- 9:26 AM Ticket #1784 (YahooGeocoderControl) created by
- Attached is a control and example that wraps Yahoo Map Web Services …
- 3:31 AM Ticket #1783 (Vector Layer above Googlemaps layer(BUG or license problem?)) closed by
- invalid: At a glance, it appears that you're not using the mercator mode of the …
- 3:21 AM Ticket #1783 (Vector Layer above Googlemaps layer(BUG or license problem?)) created by
- Platform: Linux, Mozilla Firefox 3.03, Windows XP IE 7.0 Using …
Oct 18, 2008:
- 12:39 PM Changeset [8142] by
- making this branch dir better named
- 12:31 PM Changeset [8141] by
- making a branch of the release v2.7 to being making wild popups
- 12:15 PM Changeset [8140] by
- stunted beginnings of the popups-outside-map-div work. non functional, …
Oct 17, 2008:
- 3:44 PM Changeset [8139] by
- working transactions and response parsing for 1.0 and 1.1
- 3:16 PM Changeset [8138] by
- response parsing for wfs 1.1
- 1:50 PM Changeset [8137] by
- Properly update.
- 1:48 PM Changeset [8136] by
- Properly insert and delete.
- 1:36 PM Changeset [8135] by
- Reorder call to super and actually read response.
- 11:55 AM Changeset [8134] by
- Set xy to true by default for WFS transactions. Allow format options …
- 11:00 AM Changeset [8133] by
- write schemaLocations
- 9:48 AM Changeset [8132] by
- lowerCorner and upperCorner do not contain pos, they are equivalent to post
- 9:26 AM Ticket #1782 (Multipoly rendering skips 2nd - Nth poly when first poly is outside ...) created by
- OpenLayers.Geometry.MultiPolygons* are not rendered properly when the …
- 7:25 AM Changeset [8131] by
- don't expect this to work quite yet
- 1:06 AM Ticket #1762 (Missing semi-colons) closed by
- fixed: (In [8130]) Add missing semi-colons. (closes #1762)
- 1:06 AM Changeset [8130] by
- Add missing semi-colons. (closes #1762)
Oct 16, 2008:
- 11:44 PM Ticket #1781 (Create OpenLayers.Layer.OpenStreetMap) created by
-
- 11:41 PM Ticket #1780 (Fix tests in Google Chrome) created by
-
- 2:42 PM three edited by
- cosmetic fixes (diff)
- 2:42 PM three edited by
- added API cleanup (diff)
- 2:20 PM three edited by
- (diff)
- 2:20 PM three/MultipleSymbolizers created by
-
- 2:17 PM three/SingleRendererRoot created by
-
- 2:15 PM three edited by
- (diff)
- 2:14 PM three created by
-
- 2:10 PM Ticket #1105 (uniform XMLHttpRequest) closed by
- duplicate: Yeah, this was a dupe of #1565, satisfied with r7335.
- 1:36 PM Changeset [8129] by
- merge in classes from trunk
- 1:35 PM Changeset [8128] by
- merge popup from trunk
- 12:19 PM Printing edited by
- updated print.php to use alpha transparency (diff)
- 12:09 PM Changeset [8127] by
- merge popups from trunk
- 11:46 AM Changeset [8126] by
- merge from trunk
- 11:36 AM Printing edited by
- (diff)
- 6:44 AM Changeset [8125] by
- more "../tarballs" -> "tarballs"
- 4:41 AM SphericalMercator edited by
- url to mapserver was wrong (diff)
Oct 15, 2008:
- 3:18 PM Changeset [8124] by
- A few suggested tweaks.
- 2:53 PM Changeset [8123] by
- transpose and
- 2:50 PM Changeset [8122] by
- Add some sponsorship related documents.
- 11:08 AM Ticket #1759 (replace unnecessary, undocumented 'drawn' property on OpenLayers.Marker) reopened by
- Haven't checked the validity, but #1766 says that r8091 broke stuff.
- 9:09 AM Changeset [8121] by
- merging in protocols
- 9:00 AM Changeset [8120] by
- merge from trunk
- 8:30 AM Changeset [8119] by
- merge from trunk
- 4:27 AM CLA edited by
- (diff)
Oct 14, 2008:
- 7:36 PM Changeset [8118] by
- Starting to feel like it's time for a WFS format after all.
- 1:14 PM Changeset [8117] by
- Remove filterFormat in favor of extending this.format with properties …
- 12:46 PM Printing edited by
- (diff)
- 12:31 PM Changeset [8116] by
- Sandbox cleanup
- 7:44 AM CLA edited by
- (diff)
- 7:44 AM CLA edited by
- (diff)
- 5:29 AM Ticket #1779 (Invalid WFS transaction generated) created by
- I'm currently trying the Protocol.WFS new features and I'm a problem. …
Oct 13, 2008:
Oct 10, 2008:
- 5:58 PM Changeset [8115] by
- Fixed map.destroy function call.
- 5:46 PM Changeset [8114] by
- Added map.destroy() to initializer to clear memory leak problem in IE.
- 5:02 PM Changeset [8113] by
- Merge with trunk (v2.7).
- 4:39 PM Changeset [8112] by
- Filter cloning updates. When modifying a filter that will later be …
- 4:37 PM Changeset [8111] by
- Unbreaking firebug.
- 4:35 PM Changeset [8110] by
- Examples and loader updates.
- 4:35 PM Changeset [8109] by
- Creating WFS 1.1 protocol and pulling out 1.1 specific code.
- 4:33 PM Changeset [8108] by
- Updating filter parser to use common xml methods. Splitting version …
- 4:31 PM Printing edited by
- (diff)
- 4:31 PM Changeset [8107] by
- Updating sld parser to use common xml methods.
- 4:30 PM Printing edited by
- (diff)
- 4:30 PM Changeset [8106] by
- Adding matchCase attribute for equal type comparisons. Condensing the …
- 2:26 PM Changeset [8105] by
- Added ArcXML 'accuracy', in addition to using Vector features in …
- 12:51 PM Changeset [8104] by
- merge with trunk
- 9:41 AM Changeset [8103] by
- Added support for spatial queries with OpenLayers.Geometry.Polygon objects.
- 5:38 AM Ticket #1778 (Openlayers fails to draw features when the map's div container has ...) created by
- If you have a OpenLayers Map displayed inside a div, and the div has …
- 5:36 AM Changeset [8102] by
- Separating jsdoc declarations. (See #1229)
- 3:25 AM Ticket #1762 (Missing semi-colons) reopened by
- I found some more missing semicolons. Apparently JSLint does not find …
- 2:38 AM Ticket #1777 (worldwind layer incorrectly positioning the tiles at high levels) created by
- OS : Windows XP, navigator Firefox 3.0.3 Using a worldwind layer …
Oct 9, 2008:
- 11:00 AM Ticket #1776 (OpenLayers.Format.GeoJSON.write does not reproject most of the points ...) created by
- 1) GeoJSON layer on the map, with a Projection that differs from the …
- 7:13 AM Ticket #1775 (Add annotation marker and layer objects) created by
- I have created an Annotation marker object (a child of Marker) and an …
- 6:09 AM Ticket #1774 (Ability to cancel a Protocol request) created by
- Add the ability to cancel a OpenLayers.Protocol.Response.
- 1:36 AM Ticket #1773 (wfs-layer shifting while using Googlemaps as basemap) created by
- Hello, I am working with OpenLayers 2.6 and Googlemaps as basemap on …
- 12:48 AM Ticket #1772 (Remove layer declaration from Strategy.Cluster and Strategy.Paging) closed by
- fixed: (In [8101]) remove unneeded layer declaration. r=elemoine (closes #1772)
- 12:48 AM Changeset [8101] by
- remove unneeded layer declaration. r=elemoine (closes #1772)
- 12:08 AM Ticket #1772 (Remove layer declaration from Strategy.Cluster and Strategy.Paging) created by
- The variable is already declared in the parent class. Tests pass on FF3
- 12:05 AM Ticket #1551 (moveTo does not work with multiple baselayers) closed by
- invalid: At any time there is exactly one baselayer visible on the map. If you …
Oct 8, 2008:
- 10:57 PM Ticket #751 (Marker.Label) closed by
- invalid: This new addon is no longer needed, because of it can be implemented …
- 9:16 PM Ticket #1771 (Patch: Always zoom in/out while drawing the zoom box) created by
- Currently, if the user draws zoombox on the map, and the zoombox is …
- 12:09 PM Ticket #1770 (Patch for keeping the box in OverView map always in the center) created by
- Someone (me) could need, that the box, displaying current extend in …
- 11:45 AM Ticket #1769 (Patch for modification of the default key (Ctrl), which has to be ...) created by
- In OpenLayers/Control/Navigation.js, the default key, which has to be …
- 6:13 AM Ticket #1768 (Add per-layer DPI support) created by
- It may be desirable to support different DPI settings on a per-layer …
- 6:09 AM Changeset [8100] by
- Basic (and buggy) events support for protocols (see #1767)
- 5:50 AM Ticket #1762 (Missing semi-colons) closed by
- fixed: (In [8099]) Add missing semi-colons. r=pagameba (closes #1762)
- 5:50 AM Changeset [8099] by
- Add missing semi-colons. r=pagameba (closes #1762)
- 2:48 AM Ticket #1767 (OpenLayers.Protocol events) created by
- Protocols should send events before and after doing CRUD requests. …
Oct 7, 2008:
- 9:12 PM Ticket #1766 (When zoom changed, the markers screen position do not changed) created by
- With the patch from Tickets: #1759, when zoom changed, the markers …
- 2:37 PM Changeset [8098] by
- add proxy jsp page openlayers-proxy-apache.jsp
- 1:55 PM Changeset [8097] by
- Added a Paged implementation of GML to deter parsing any features …
- 8:21 AM Ticket #1765 (Faster GML Attribute Parsing) created by
- Hi all, I recently edited the GML Format's parseAttributes() function …
- 8:15 AM Changeset [8096] by
- Edited GML attribute parsing (making it 33% faster) by removing …
Oct 6, 2008:
- 5:06 PM Ticket #1764 (map.removeControl() does not fully remove the control) created by
- map.removeControl() does not fully remove a control, it only makes the …
- 3:59 AM Ticket #1763 (Formatting of GPX tracks) created by
- When loading a gpx track in a OpenLayers.Layer.GML object, any given …
Oct 5, 2008:
- 11:11 PM Ticket #1762 (Missing semi-colons) created by
- From Paul Spencer on the users ml: […]
- 12:48 AM Release/2.8 created by
-
Oct 4, 2008:
- 10:17 PM Changeset [8095] by
- filter example
- 10:17 PM Changeset [8094] by
- filter encoding 1.0 and 1.1
- 10:16 PM Changeset [8093] by
- set up for wfs 1.1
- 10:05 PM Changeset [8092] by
- adding filter example
- 1:16 PM Ticket #1759 (replace unnecessary, undocumented 'drawn' property on OpenLayers.Marker) closed by
- fixed: btw elemoine, i break that func up into 2 lines for debugging …
- 1:13 PM Changeset [8091] by
- getting rid of unnecessary, undocumented 'drawn' property on marker. …
- 9:47 AM Ticket #1761 (Small marker icons placement shifts) created by
- For marker icons below a certain size ("size" as in OpenLayers.Size), …
- 9:43 AM Ticket #1760 (Support for ArcGIS Server) created by
- This may be supported and I am unaware but be able to integrate with …
- 7:48 AM Ticket #1759 (replace unnecessary, undocumented 'drawn' property on OpenLayers.Marker) created by
- it is not listed anywhere, but we are pinning a 'drawn' flag onto the …
- 6:21 AM Changeset [8090] by
- Set up for wfs 1.0.0 and 1.1.0.
- 6:17 AM Ticket #1758 (load gears_init.js only when needed) closed by
- fixed: (In [8089]) Only load gears_init.js if you need it. r=many (closes #1758)
- 6:17 AM Changeset [8089] by
- Only load gears_init.js if you need it. r=many (closes #1758)
- 6:12 AM Ticket #1758 (load gears_init.js only when needed) created by
- It is causing a number of people a number of problems to have …
- 5:58 AM Changeset [8088] by
- correct the function name
- 5:38 AM Changeset [8087] by
- tarballs should be in the same dir.
- 5:27 AM Changeset [8086] by
- Updating to 2.7
- 3:53 AM Changeset [8085] by
- Adding title for pretty.
- 2:42 AM Documentation edited by
- (diff)
- 1:44 AM Changeset [8084] by
- stray D in website. my bad.
- 1:41 AM Changeset [8083] by
- Making a box for play from the small room in a big building across the …
Oct 3, 2008:
- 8:36 AM Ticket #1755 (trac default version) closed by
- fixed: done
- 7:20 AM Ticket #1757 (update of MapGuide example) created by
- 1. update the MapGuide OS server URL to a more stable implementation …
- 7:14 AM Ticket #1756 (remove synchronous behaviour for MapGuide overlay layers) created by
- current implementation of MapGuide overlay layers has a synchronous …
- 2:59 AM Ticket #1755 (trac default version) created by
- Default selected option in the version combobox in the ticket …
- 2:56 AM Ticket #1754 (select feature by box shouldn't select anything if layer is not in range) created by
- Currently the selectBox callback method in SelectFeature control …
- 2:41 AM Changeset [8082] by
- 2.7 release, yay
Oct 2, 2008:
- 3:06 AM Ticket #1753 (FeatureCollection additional members are dropped) created by
- If a GeoJSON FeaturesCollection contains additional members they are …
- 12:32 AM Changeset [8081] by
- add a clean version of the snapping code
- 12:22 AM Changeset [8080] by
- copy trunk to sandbox/camptocamp/snapping/
- 12:21 AM Changeset [8079] by
- wrong path
- 12:16 AM Changeset [8078] by
- copy trunk to sandbox/camptocamp/snapping/
- 12:15 AM Changeset [8077] by
- new snapping sandbox
- 12:14 AM Changeset [8076] by
- Wrong sandbox name, sorry …
- 12:13 AM Changeset [8075] by
- Creating sandbox
Oct 1, 2008:
- 10:09 PM Printing edited by
- (diff)
- 4:39 PM Ticket #1752 (NavToolbar example misleads because map is too small to see controls) created by
- The NavToolbar example at …
- 4:26 PM Ticket #1751 (Many Controls missing summary documentation) created by
- The API documentation for OpenLayers lacks summaries for many of the …
- 1:48 PM Changeset [8074] by
- Moved DrawFeature.html test to correct place after merge.
- 1:45 PM Changeset [8073] by
- Added missing files to dzwarg sandbox from most recent trunk merge.
- 1:43 PM Changeset [8072] by
- Added missing files to dzwarg sandbox from most recent trunk merge.
- 1:20 PM Changeset [8071] by
- Merged with trunk
- 1:18 PM Changeset [8070] by
- Added missing files to dzwarg sandbox from previous trunk merge.
- 1:16 PM Changeset [8069] by
- Added missing files to dzwarg sandbox from previous trunk merge.
- 9:30 AM Changeset [8068] by
- Fixed bugs in ArcXML.js, fleshed out tests for ArcXML format.
- 7:00 AM Changeset [8067] by
- Apply defaults to ArcIMS options before initializing.
- 6:01 AM Ticket #1378 (clicking next to the map causes selection of controls) reopened by
- I'm reopening this ticket because it seems like some buttons in some …
Sep 30, 2008:
- 12:13 PM Ticket #1750 (framedCloud.css should be remove) created by
- I don't think we really need a separate css file only for one unique …
Note: See TracTimeline for information about the timeline view. | http://trac.osgeo.org/openlayers/timeline?from=2008-10-30T02%3A17%3A23-0700&precision=second | CC-MAIN-2016-22 | refinedweb | 4,960 | 57.91 |
Name: gm110360 Date: 09/25/2002 FULL PRODUCT VERSION : java version "1.4.0_01" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0_01-b03) Java HotSpot(TM) Client VM (build 1.4.0_01-b03, mixed mode) FULL OPERATING SYSTEM VERSION : Microsoft Windows XP [Version 5.1.2600] A DESCRIPTION OF THE PROBLEM : Here is a stack trace from an OutOfMemoryError. java.lang.OutOfMemoryError <<no stack trace available>> EXPECTED VERSUS ACTUAL BEHAVIOR : It should have the trace because trace is 1-line deep, there is not a large memory requirement for that. A way to do that is to allocate memory for say a 1024 bytes stack trace in case of memory error. Also developers dont understand why sometimes the stack trace gets printed and sometimes not in case of an OutOfMemory error. I dont understand myself why such an error is so fatal, if memory gets low, and the user tries to allocate a new byte [], the system should check before trying to allocate if memory is sufficient (I guess it does that) and then throw an Error. In that case, the system should reserve some memory (from the startup of VM) for stack trace. REPRODUCIBILITY : This bug can be reproduced always. ---------- BEGIN SOURCE ---------- import java.util.*; import java.util.List.*; public class Test { private static final int RATIO = 20; public static void main(String[] args) { try { List list = new ArrayList(); while (true) { iterate(list); //recurse(list); } }catch (Throwable thr) { thr.printStackTrace(); } } private static void recurse(List list) { iterate(list); recurse(list); } private static void iterate(List list) { long free = Runtime.getRuntime().freeMemory(); int newSize = (int)free/RATIO; //System.out.println(free+","+newSize+","+(free-newSize)); byte[] bytes = new byte[newSize]; list.add(bytes); } } You can try to iterate or recurse. If the RATIO is set correctly, you will get an exception without trace: ---------- END SOURCE ---------- CUSTOMER WORKAROUND : Put debug statements around the code to locate where the code failed. Hard to do for code that is provided as package. (Review ID: 164948) ====================================================================== | https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4753347 | CC-MAIN-2022-27 | refinedweb | 334 | 56.55 |
Tested and works on esp8266/esp32
16-Channel 12-bit PWM/Servo Driver – I2C interface – PCA9685 Module lets you add more IOs to your microcontroller boards. The Module has chainable I2C interface meaning for even more IOs more boards can be daisy chained. Its and excellent product for Robots that require lots of Servo motors to control using single microcontroller.See product page link for more information about the hardware.
mos.yml, add:
config_schema: - ["i2c.enable", true] libs: - origin:
init.js, add:
load('api_pwm_servo.js');
main.c, add:
#include "mgos_arduino_PWMServoDriver.h"
Adafruit_PWMServoDriver.create()
Create an instance of PWM servo driver, which has the methods described below.
Example:
load("api_pwm_servo.js"); let myServo = Adafruit_PWMServoDriver.create();
myServo.close()
Close a servo instance; no other methods can be called on this instance
after calling
Return value: none.
myServo.begin()
Reset onewire and servo state. Return value: none.
myServo.setPWMFreq(freq)
This function can be used to adjust the PWM frequency (from 40 to 1000 Hz),.
Return value: none.
Example:
load("api_pwm_servo.js"); let myServo = Adafruit_PWMServoDriver.create(); myServo.begin(); myServo.setPWMFreq(100);
myServo.setPWM(channel, on, off)
This function sets the start (
on) and end (
off) of the high segment of
the PWM pulse on a specific channel. You specify the 'tick' value
between 0..4095 when the signal will turn on, and when it will turn of.
channel (a number from
0 to
15) indicates which of the 16 PWM
outputs should be updated with the new values.
Return value: none.
Example:
load("api_pwm_servo.js"); let myServo = Adafruit_PWMServoDriver.create(); myServo.begin(); // Generate square wave at 100 Hz myServo.setPWMFreq(100); myServo.setPWM(0, 0, 2047);
myServo.setPin(channel, val, invert)
This is a wrapper for
myServo.setPWM(), where
on will always be 0,
and
off is the
val given to this function. Additionally,
invert
can be set to
true to invert the output.
Return value: none.
Example:
edit this docedit this doc
load("api_pwm_servo.js"); let myServo = Adafruit_PWMServoDriver.create(); myServo.begin(); // Generate square wave at 100 Hz myServo.setPWMFreq(100); myServo.setPin(0, 2047, false); | https://mongoose-os.com/docs/mongoose-os/api/arduino/arduino-adafruit-pwm-servo.md | CC-MAIN-2022-05 | refinedweb | 342 | 53.68 |
I do not understand why the
sizeof
sizeof( 2500000000 ) // => 8 (8 bytes).
sizeof( 1250000000 * 2 ) // => 4 (4 bytes).
sizeof
sizeof
2500000000 doesn't fit in an
int, so the compiler correctly interprets it as a
long (or
long long, or a type where it fits).
1250000000 does, and so does
2. The parameter to
sizeof isn't evaluated, so the compiler can't possibly know that the multiplication doesn't fit in an
int, and so returns the size of an
int.
Also, even if the parameter was evaluated, you'd likely get an overflow (and undefined behavior), but probably still resulting in
4.
Here:
#include <iostream> int main() { long long x = 1250000000 * 2; std::cout << x; }
can you guess the output? If you think it's
2500000000, you'd be wrong. The type of the expression
1250000000 * 2 is
int, because the operands are
int and
int and multiplication isn't automagically promoted to a larger data type if it doesn't fit.
So here, gcc says it's
-1794967296, but it's undefined behavior, so that could be any number. This number does fit into an
int.
In addition, if you cast one of the operands to the expected type (much like you cast integers when dividing if you're looking for a non-integer result), you'll see this working:
#include <iostream> int main() { long long x = (long long)1250000000 * 2; std::cout << x; }
yields the correct
2500000000. | https://codedump.io/share/Vrpo87PasOqB/1/in-c-sizeof-operator-returns-8-bytes-when-passing-25m-but-4-bytes-when-passing-125m--2 | CC-MAIN-2017-04 | refinedweb | 241 | 69.41 |
Created on 2018-02-24 17:38 by cheryl.sabella, last changed 2018-02-28 23:12 by miss-islington.
Based on timing test on msg312733, StringTranslatePseudoMappingTest and a defaultdict have about the same performance, so this replaces the custom class with the stdlib functionality.
Tal had written this on the original issue21765:
---- :)
-----
So maybe I misunderstood and this shouldn't be a defaultdict?
I forget about this defaultdict behavior: "this value is inserted in the dictionary for the key, and returned." Reason: when default_factory returns a mutable, d[key] must return the same possibly mutated object with each call. I agree that defaultdict is not the right replacement.
We need to pass to str.translate a dict that can be used by subscripting, newchar = d[char]. So partial(non-defaults.get, default_value) will not work. Instead, we need a __getitem__ that returns the same.
In msg312444 I suggested simplifying STPM (including the name) because it has unneeded complexity. Remove the buggy .get override. Combine the _get stuff in __init__ (also removed) with current __getitem__ and simplify and we get what we actually need (untested, at yet).
def __getitem__
return self._non_defaults.get(self._default_value)
Actually, we could hard-code the default value as 'X' as we never need anything else.
How about ParseMap for the name?
New PR submitted. Really glad I worked on this today. I learned a lot of things that were new to me. :-)
I simplified ParseMap to a dict subclass with one override -- __getitem__ and then the tests. They run faster. I suspect translate is faster.
For efficiency I suggest to initialize the mapping with dict.fromkeys(range(128), 'x') rather of an empty dict.
It is also possible to use regular expressions:
_trans = re.compile(r'''[^(){}\[]"'\\\n#]+''')
code = _trans.sub('x', code)
code = code.replace('{', '(')
code = code.replace('}', ')')
code = code.replace('[', '(')
code = code.replace(']', '(')
code = code.replace('\nx', '\n')
I didn't check what way is more efficient.
To me, it is plausible but not slam-dunk obvious that preloading ascii to 'x' mappings will make ascii lookup faster.
On #21765, where the pyparse special translation was a side-issue, Tal Einat claimed that the unpublished regex he tried was 100x slower.
A similar regular expression version was mentioned on issue21765 and I had run some tests on it yesterday to verify. On my system, it ran at a factor of 10x slower, so if the translate finished in 0.003, the regex took 0.03. This was consistent for me, regardless of how big I made the document.
The reason for not using a defauldict was to keep the 'x' mappings out of the dictionary so that it wouldn't grow and take up space. Although, I did realize yesterday that it wasn't really boundless because most values in source code would be ASCII. Running both the version the doesn't add the 'x' mappings and the `fromkeys`, there doesn't seem to be much of a difference in time when processing the doc.
I settled on the following to compare ParseMap implementations.
from idlelib.pyparse import Parser
import timeit
class ParseGet(dict):
def __getitem__(self, key): return self.get(key, ord('x'))
class ParseMis(dict):
def __missing__(self, key): return ord('x')
for P in (ParseGet, ParseMis):
print(P.__name__, 'hit', 'miss')
p = p=P({i:i for i in (10, 34, 35, 39, 40, 41, 91, 92, 93, 123, 125)})
print(timeit.timeit(
"p[10],p[34],p[35],p[39],p[40],p[41],p[91],p[92],p[93],p[125]",
number=100000, globals = globals()))
print(timeit.timeit(
"p[11],p[33],p[36],p[45],p[50],p[61],p[71],p[82],p[99],p[125]",
number=100000, globals = globals()))
ParseGet hit miss
1.104342376
1.112531999
ParseMis hit miss
0.3530207070000002
1.2165967760000003
ParseGet hit miss
1.185322191
1.1915449519999999
ParseMis hit miss
0.3477272720000002
1.317010653
Avoiding custom code for all ascii chars will be a win. I am sure that calling __missing__ for non-ascii will be at least as fast as it is presently. I will commit a revision tomorrow.
I may then compare to Serhiy's sub/replace suggestion. My experiments with 'code.translate(tran)' indicate that time grows sub-linearly up to 1000 or 10000 chars. This suggests that there are significant constant or log-like terms.
Don't use ord('x'). Use just 'x' or b'x'[0].
Replacing an expression with a less clear equivalent expression makes no sense to me. Anyway, having __missing__ return 120 reduces the benchmark miss time from 1.2-1.3 to .93, making ParseMis always faster than ParseGet and reducing the penalty for non-ascii chars.
re.sub + str.replace is slower than translate
import re
import timeit
class ParseMap(dict):
def __missing__(self, key): return 120 # ord('x')
trans = ParseMap((i,120) for i in range(128))
trans.update((ord(c), ord('(')) for c in "({[")
trans.update((ord(c), ord(')')) for c in ")}]")
trans.update((ord(c), ord(c)) for c in "\"'\\\n#")
trans_re = re.compile(r'''[^(){}\[]"'\\\n#]+''')
code='\t a([{b}])b"c\'d\n'*1000 # n = 1, 10, 100, 1000
print(timeit.timeit(
'code.translate(trans)',
number=10000, globals = globals()))
print(timeit.timeit(
"code1 = trans_re.sub('x', code)\n"
"code2 = code1.replace('{', '(')\n"
"code3 = code2.replace('}', ')')\n"
"code4 = code3.replace('[', '(')\n"
"code5 = code4.replace(']', '(')\n"
r"code6 = code5.replace('\nx', '\n')",
number=10000, globals = globals()))
n trans re
1 .06 .09
10 .08 .17
100 .28 1.00
1000 2.2 8.9
Multiply by 100 to get microseconds or seconds for 1000000.
The mapping passed to str.translate must map ints representing codepoints to either either ints or strings. Translate can extract binary codepoints for the new string from either. Ints are slightly faster, so I am inclined not to switch.
import timeit
class ParseMapN(dict):
def __missing__(self, key): return 120
class ParseMapS(dict):
def __missing__(self, key): return 'x'
trans1 = ParseMapN.fromkeys(range(128), 120)
trans1.update((ord(c), ord('(')) for c in "({[")
trans1.update((ord(c), ord(')')) for c in ")}]")
trans1.update((ord(c), ord(c)) for c in "\"'\\\n#")
trans2 = ParseMapN.fromkeys(range(128), 'x')
trans2.update((ord(c), '(') for c in "({[")
trans2.update((ord(c), ')') for c in ")}]")
trans2.update((ord(c), c) for c in "\"'\\\n#")
for i in (1, 10, 100, 1000):
code = '\t a([{b}])b"c\'d\n' * i
print('N ', i)
print(timeit.repeat(
'code.translate(trans1)',
number=10000, globals = globals()))
print('S ', i)
print(timeit.repeat(
'code.translate(trans2)',
number=10000, globals = globals()))
N 1 [0.056562504, 0.056747570, 0.05654651, 0.056460749, 0.056428776]
S 1 [0.060795346, 0.062304155, 0.061043432, 0.062349345, 0.061191301]
N 10 [0.076474600, 0.076463227, 0.076560984, 0.076581582, 0.076010091]
S 10 [0.080739106, 0.080798745, 0.08034192, 0.080987501, 0.080617369]
N 100 [0.28529922, 0.28383868, 0.283949046, 0.284461512, 0.284291203]
S 100 [0.289629521, 0.288535418, 0.289154560, 0.28811548, 0.28862180]
N1000 [2.23882157, 2.2383192, 2.2384120, 2.2377972, 2.23854982]
S1000 [2.24242237, 2.2426845, 2.2424623, 2.2420030, 2.24254871]
The pattern of all S repeats being greater than all corresponding N repeats was true for 2 other runs.
New changeset f0daa880a405c8de6743e44fa46006754aa145c9 by Terry Jan Reedy (Cheryl Sabella) in branch 'master':
bpo-32940: IDLE: Simplify StringTranslatePseudoMapping in pyparse (GH-5862)
New changeset 7e5763469e2fc9d08a3f6b6205f87f20a1bdd465 by Miss Islington (bot) in branch '3.7':
bpo-32940: IDLE: Simplify StringTranslatePseudoMapping in pyparse (GH-5862)
New changeset 32f5392f64f004382e26a988b1145d2dc96c4978 by Miss Islington (bot) in branch '3.6':
bpo-32940: IDLE: Simplify StringTranslatePseudoMapping in pyparse (GH-5862) | https://bugs.python.org/issue32940 | CC-MAIN-2020-34 | refinedweb | 1,270 | 70.19 |
Reading: Deitel & Deitel, Chapter 3, sections 3.1 - 3.11
Functions
The programs that we have seen so far involve only a single function, main, but any program of any size will involve multiple functions. Beginning programmers have a tendency to put all of their code in main, but this quickly leads to a large function which is hard to read and hard to debug. Good programs consist of lots of small functions, each of which usually does only one thing.
Here is a small program which demonstrates the use of function calls
in C or C++.
1 #include <iostream> 2 using namespace std; 3 int square(int); 4 int main() 5 { 6 int x, xsquared; 7 cout << "Enter a number: "; 8 cin >> x; 9 xsquared = square(x); 10 cout << "The square of " << x << " is " << xsquared << endl; 11 return 0; 12 } 13 int square(int n) 14 { 15 int nsquared; 16 nsquared = n * n; 17 return nsquared; 18 }
3 int square(int);
This is called a function prototype. If a function is to be called before it is defined, there must be a prototype. This tells the compiler that there will be a function defined later called square, which takes one argument of type int, and returns an integer. An argument is a value which is passed from the calling function to the called function. There is no limit on the number or type of arguments that a function can have. The return type of a function can be any type which has been defined. In addition, a function can be of type void which means that it does not return anything. Notice that a function cannot return more than one value.
9 xsquared = square(x);
This is where the function square is called or invoked. When a function is called, processing of the calling function (main in this case) stops, and processing is transferred to the code of the called function (square in this case). The next statement executed is the first statement of the called function.
The function square
is passed one argument, in this case, the variable x.
The function square will return an integer value, which is
copied to the variable xsquared.
13 int square(int n) 14 { 15 int nsquared; 16 nsquared = n * n; 17 return nsquared; 18 }
return-value-type function-name (parameter list)
{
declarations and statements
}
The variable n is a formal parameter. Ordinarily, when a function is called, the value of each argument, called the actual parameter, is computed and this value is copied to the formal parameter. (This parameter passing method is known as call-by-value; another method, call-by-reference, is described later in this worksheet.)
Line 17 is a return statement. Any function other than a
void function must have at least one return statement, in which
a value is returned. The keyword return must be followed by
an expression which is of the same type as the type of the
function. Functions of type void may also have one or more
return statements which are not followed by any expression.
Once a return statement is encountered in a function, processing
returns to the calling function. Any code which directly follows
a return statement is called dead code because it will never be
executed; you should never have dead code in your programs.
Note: since
return can be followed by an expression,
the
square function could be written more briefly:
int square(int n) { return n * n; }
There is no limit to the number and type of arguments that a
function can take. A void function called fctn which takes
three arguments, two integers and a floating point number, would have
a function prototype like this:
void fctn(int, int, double);
and when it is actually declared, the first line of the declaration would look like this:
void fctn(int n1, int n2, double f1)
When calling a function, the order of the actual parameters determines which values get copied to the formal parameters. The value of the first argument (first actual parameter) is copied to the first formal parameter, the value of the second argument is copied to the second formal parameter, and so on. The compiler will check to confirm that the number and type of actual parameters conform to the number and type of formal parameters. It also checks to make sure that the number and type of formal parameters in the function definition agrees with the function prototype.
Exercise 1: Write a function sum which takes three arguments, all double precision floating point numbers, and returns the sum of these three. Write a main which prompts the user to enter three floating point numbers and passes them to sum, which will return a value to main. main should print this value on the screen.
Scope of variables
Variables defined inside of a function are local to that function. No other function knows about them or can use them. An attempt to access the variable x declared in the function square from outside would result in a compiler error.
It is possible to declare variables outside of any function. These
variables are called global, and all functions defined after
the declaration of a global variable can use it.
Here is an example:
#include <iostream> using namespace std; int x; // a global variable int main() { ... x = 17; // main can access the global variable x ... } void SomeFunction() { x = 46; // any other function can also access x }
Global variables should be used sparingly because they make programs harder to debug and modify. If many functions can modify a global variable, it is easy to lose track of which functions are doing what in a large program.
Two or more functions can have local variables of the same name. If a function declares a local variable which has the same name as a global variable, this declaration masks the global variable and any reference inside that function to the variable of that name would be assumed to be the local variable, not the global variable. In the above example, suppose SomeFunction had declared a local variable called x inside it. Now there are two variables with the name x, one global and one local. In the statement x = 46; the reference to x would be to the local variable, not the global variable.
Call-by-value vs. Call-by-reference
Parameter passing in C and C++ is normally call-by-value.
When a function is called, and one or more variables are passed
as arguments, the called function makes copies of the values of
these arguments. This means that ordinarily a called function cannot change
the value of a variable in the calling function. Here is an example:
#include<iostream> using namespace std; void Silly(int); // function prototype int main() { int x; x = 17; Silly(x); cout << x << endl; return 0; } void Silly(int n) { n = 46; }
This program will print 17, not 46, because in Silly a copy of the value of x is made and assigned to n, so changing the value of n in the called function has no effect on the value of the actual parameter in the calling function. Note that the variable n in Silly could have been called x, without changing the functioning of the program.
C++ (but not C) allows a different type of parameter passing called
call-by-reference. In call-by-reference the called function,
instead of making a copy of the value of a parameter, identifies
the formal parameter with the address of the
actual parameter. This means that the called function can change the
value of a variable in the calling function. To make a parameter
a reference parameter, precede its name with an
&. You must also
follow the type in the argument list of the function prototype with
an
&. Here is an example:
#include<iostream> using namespace std; void Silly(int &); // function prototype int main() { int x; x = 17; Silly(x); cout << x << endl; return 0; } void Silly(int & n) { n = 46; }This program will print 46.
Exercise 2: What would the following program print? (answer on last page)
#include <iostream> using namespace std; int y,z; int function(int, int &); int main() { int v,w,x,y; w = 1; x = 2; y = 3; z = 4; v = function(w,x); cout << v << " " << w << " " << x << " " << y << " " << z << endl; return 0; } int function(int m, int & n) { int w; w = 5; m = 6; n = 7; y = 8; z = 9; return 10; }
Arrays as function arguments
Arrays can be used as arguments to functions, but array parameter passing is always call-by-reference; in other words, the function can change individual values in an array and the changes will be retained when control returns to the calling function.
When arrays are passed as arguments, it is not necessary to pass in
the array size; rather, the fact that a variable is an array is
signified by following the variable name with a pair of empty square
brackets (
[]). Here is an example:
1 #include <iostream> 2 using namespace std; 3 void fctn(int[]); // function prototype 4 int main() 5 { 6 int a[5]; 7 for (int i = 0; i < 5; ++i) 8 a[i] = i; 9 fctn(a); 10 for (i = 0; i < 5; ++i) 11 cout << a[i] << ' '; 12 cout << endl; 13 return 0; 14 } 15 16 void fctn(int z[]) 17 { 18 z[1] = 345; 19 z[3] = 678; 20 }
The advantage of this method is that a single function can be passed arrays of different sizes, but the disadvantage is that the function does not know how large an array is. Often, the solution to this problem is to pass in another parameter to the function which gives the size of the array.
Library functions
There are an enormous number of library functions for C and C++, far too many to exhaustively list here, but here is a small list of commonly used functions. Many of these require that you use additional include files. If so, these are listed as well.
Character Handling
int isalpha(char c) returns 1 if c is in the range A .. Z or a .. z, otherwise it returns 0.
int isdigit(char c) returns 1 if c is in the range 0 .. 9, otherwise it returns 0.
char tolower(char c) If c is an upper case letter, it returns the lower case version; otherwise it returns c.
char toupper(char c) If c is a lower case letter, it
returns the upper case version; otherwise it returns c.
Mathematics
#include <math.h>
double cos(double x) returns the cosine of x where x is measured in radians. There is a complete set of trig. functions like this.
double sqrt(double x) returns the square root of x.
double log(double x) returns the natural logarithm of x.
String Handling
strcpy(char s1[], char s2[]) copies the characters in s2 into s1 up to and including the first null character.
int strcmp(char s1[], char s2[]) returns a positive integer if s1 is lexically greater than s2 (i.e. would follow it alphabetically), a negative number if s1 is lexically less than s2, or zero if the two strings are the same up to the first null character.
strcat(char s1[], char s2[]) concatenates s2 onto the end of s1. For example if s1 is the string cat and s2 is the string bird, after calling this function, s1 would be the string catbird. Note that the size of the array s1 must be large enough to accommodate the longer string.
Character Input
#include<iostream>
cin.getline(char s[], int max) reads a line of input from standard input (normally the keyboard) into the string s up to a maximum of max characters or until the user hits the Return key. This differs from
cin >> s; because the cin.getline
function includes spaces as well while
cin >> s; will read
characters into s only up until the first space. The size
of the array s should always be at least one larger than max
because a
\0 is appended onto the end of the string.
Exercise 3: It is instructive to see what is involved
in writing some of these library functions. Write your own version
of the functions strcpy and strcat, calling them
mystrcpy and mystrcat. Here is a main to test
your functions. Remember that you can assume that all strings are
terminated with a
'\0'.
#include <iostream> using namespace std; // put your function prototypes here int main() { char mystring[80]; mystrcpy(mystring,"Programming"); mystrcat(mystring, " is fun!"); cout << mystring << endl; // should print "Programming is fun!" }
Random Numbers
Many applications, simulations in particular, require the use of
random numbers, and so there are a number of library functions which
generate random numbers. The function int rand() returns a
random integer in the range
..
each time that it is
called.
Random number sequences are based on a seed, i.e. an initial
value. The default value of the seed is zero, and this means that you
will get the same sequence of random numbers each time that you run
your program. If you want a different sequence of random numbers each
time that you run the program, you must initialize the seed to a
different random value each time. The function that initializes the
seed is void srand(int). One way to do this is by using the
current time, which would be different each time the program is run.
To do this, include this statement in your program before you start calling
rand()
srand((unsigned)time(NULL));
If you use the time function, include the header file time.h.
Here is a short program which displays ten random numbers.
#include <iostream> #include <time.h> using namespace std; int main() { int n; srand((unsigned)time(NULL)); for (int i=0;i<10;i++) { n = rand(); cout << n << endl; } return 0; }
Most applications need a random number in a defined range. For
example, a dice throwing simulation would require a random number
in the range 1 .. 6. To convert from the return value of rand()
to an integer in this range, use the modulo function. Any number
modulo 6 will return a value in the range 0 .. 5, so the following
statement will assign a random value in the range 1 .. 6 to x
each time that it is called.
x = rand() % 6 + 1;
Answer to Exercise 2
10 1 7 3 9 | http://www.cs.rpi.edu//~lallip/cs2/wksht2/ | crawl-003 | refinedweb | 2,411 | 68.2 |
Raspberry Pi OS
Introduction
Raspberry clean (
sudo apt-get clean in older releases of apt).
Upgrading from Previous Operating System Versions
The latest version of Raspberry Pi OS is based on Debian Bullseye. The previous version was based on Buster. If you want to perform an in-place upgrade from Buster to Bullseye (and you’re aware of the risks) see the instructions in the forums..
Playing Audio and Video
The simplest way of playing audio and video on Raspberry Pi is to use the installed OMXPlayer application.
This is hardware accelerated, and can play back many popular audio and video file formats. OMXPlayer uses the OpenMAX (
omx) hardware acceleration interface (API) which is the officially supported media API on Raspberry Pi. OMXPlayer was developed by the Kodi Project’s Edgar Hucek.
The OMXPlayer Application
The simplest command line is
omxplayer <name of media file>. The media file can be audio or video or both. For the examples below, we used an H264 video file that is included with the standard Raspberry Pi OS installation.
omxplayer /opt/vc/src/hello_pi/hello_video/test.h264
By default the audio is sent to the analog port. If you are using a HDMI-equipped display device with speakers, you need to tell omxplayer to send the audio signal over the HDMI link.
omxplayer --adev hdmi /opt/vc/src/hello_pi/hello_video/test.h264
When displaying video, the whole display will be used as output. You can specify which part of the display you want the video to be on using the window option.
omxplayer --win 0,0,640,480 /opt/vc/src/hello_pi/hello_video/test.h264
You can also specify which part of the video you want to be displayed: this is called a crop window. This portion of the video will be scaled up to match the display, unless you also use the window option.
omxplayer --crop 100,100,300,300 /opt/vc/src/hello_pi/hello_video/test.h264
If you are using the Raspberry Pi Touch Display, and you want to use it for video output, use the display option to specify which display to use.
n is 5 for HDMI, 4 for the touchscreen. With the Raspberry Pi 4 you have two options for HDMI output.
n is 2 for HDMI0 and 7 for HDMI1.
omxplayer --display n /opt/vc/src/hello_pi/hello_video/test.h264
How to Play Audio
How to Play Video.
An Example Video
A video sample of the animated film Big Buck Bunny is available on your Raspberry Pi. To play it
Options During Playback
There are a number of options available during playback, actioned by pressing the appropriate key. Not all options will be available on all files. The list of key bindings can be displayed using
omxplayer --keys:
Playing in the Background &
Using a USB webcam
Rather than using the Raspberry Pi camera module, you can use a standard USB webcam to take pictures and video on your Raspberry Pi.
First, install the
fswebcam package:
sudo apt install fswebcam
If you are not using the default
pi user account, you need to add your username to the
video group, otherwise you will see 'permission denied' errors.
sudo usermod -a -G video <username>
To check that the user has been added to the group correctly, use the
groups command.'.
The webcam used in this example has a resolution of
1280 x 720 so to specify the resolution I want the image to be taken at, use the
-r flag:
fswebcam -r 1280x720 image2.jpg
This command will show the following information:
--- Opening /dev/video0... Trying source module v4l2... /dev/video0 opened. No input was specified, using the first. --- Capturing frame... Corrupt JPEG data: 1 extraneous bytes before marker 0xd5 Captured frame in 0.00 seconds. --- Processing captured image... Writing JPEG image to 'image2.jpg'.
Picture now taken at the full resolution of the webcam, with the banner present.
Removing the Banner
Now add the
--no-banner flag:
fswebcam -r 1280x720 --no-banner image3.jpg
which shows the following information:
--- 'image3.jpg'.
Now the picture is taken at full resolution with no banner.
Automating Image Capture
You can write a Bash script which takes a picture with the webcam. The script below saves the images in the
/home/pi/webcam directory, so create the
webcam subdirectory first with:
mkdir webcam
To create a script, open up your editor of choice and write the following example code:
#!/bin/bash DATE=$(date +"%Y-%m-%d_%H%M") fswebcam -r 1280x720 --no-banner /home/pi/webcam/$DATE.jpg
This script will take a picture and name the file with a timestamp. Say we saved it as
webcam.sh, we would first make the file executable:
chmod +x webcam.sh
Then run with:
./webcam.sh
Which would run the commands in the file and give the usual output:
--- '/home/pi/webcam/2013-06-07_2338.jpg'.
Time-Lapse Captures
You can use
cron to schedule taking a picture at a given interval, such as every minute to capture a time-lapse.
First above):
* * * * * /home/pi/webcam.sh 2>&1
Save and exit and you should see the message:
crontab: installing new crontab
Ensure your script does not save each picture taken with the same filename. This will overwrite the picture each time.
Useful Utilities
There are several useful command line
tvservice
tvservice is a command line application used to get and set information about the display, targeted mainly at HDMI video and audio.
Typing
tvservice by itself will display a list of available command line options.
-o, --off
Powers off the display output.
A better option is to use the vcgencmd display_power option, as this will retain any framebuffers, so when the power is turned back on the display will be the returned to the previous power on state.
-e, --explicit="Group Mode Drive"
Power on the HDMI with the specified settings
Group can be one of
CEA,
DMT,
CEA_3D_SBS,
CEA_3D_TB,
CEA_3D_FP,
CEA_3D_FS.
Mode is one of the modes returned from the
-m, --modes option.
Drive can be one of
HDMI,
DVI.
-c, --sdtvon="Mode Aspect [P]"
Power on the SDTV (composite output) with the specified mode,
PAL or
NTSC, and the specified aspect,
4:3,
14:9,
16:9. The optional
P parameter can be used to specify progressive mode.
-m, --modes=Group
where Group is
CEA or
DMT.
Shows a list of display modes available in the specified group.
-s, --status
Shows the current settings for the display mode, including mode, resolution, and frequency.
-a, --audio
Shows the current settings for the audio mode, including channels, sample rate and sample size.
-d, --dumpid=filename
Save the current EDID to the specified filename. You can then use
edidparser <filename> to display the data in a human readable form.
-j, --json
When used in combination with the
--modes options, displays the mode information in JSON format.
vcgencmd
The
vcgencmd tool is used to output information from the VideoCore GPU on the Raspberry Pi. You can find source code for the
vcgencmd utility on Github.
To get a list of all commands which
vcgencmd supports, use
vcgencmd commands. Some useful commands and their required parameters are listed below.
vcos
The
vcos command has two useful sub-commands:
versiondisplays the build date and version of the firmware on the VideoCore
log statusdisplays the error log status of the various VideoCore firmware areas
get_camera
Displays the enabled and detected state of the Raspberry Pi camera:
1 means yes,
0 means no. Whilst all firmware except cutdown versions support the camera, this support needs to be enabled by using raspi-config.
get_throttled
Returns the throttled state of the system. This is a bit pattern - a bit being set indicates the following meanings:
measure_temp
Returns the temperature of the SoC as measured by its internal temperature sensor;
on Raspberry Pi 4,
measure_temp pmic returns the temperature of the PMIC.
measure_clock [clock]
This returns the current frequency of the specified clock. The options are:
e.g.
vcgencmd measure_clock arm
otp_dump
Displays the content of the OTP (one-time programmable) memory inside the SoC. These are 32 bit values, indexed from 8 to 64. See the OTP bits page for more details.
get_config [configuration item|int|str]
Display value of the configuration setting specified: alternatively, specify either
int (integer) or
str (string) to see all configuration items of the given type. For example:
vcgencmd get_config total_mem
returns the total memory on the device in megabytes.
get_mem type
Reports on the amount of memory addressable by the ARM and the GPU. To show the amount of ARM-addressable memory use
vcgencmd get_mem arm; to show the amount of GPU-addressable memory use
vcgencmd get_mem gpu. Note that on devices with more than 1GB of memory the
arm parameter will always return 1GB minus the
gpu memory value, since the GPU firmware is only aware of the first 1GB of memory. To get an accurate report of the total memory on the device, see the
total_mem configuration item - see
get_config section above.
codec_enabled [type]
Reports whether the specified CODEC type is enabled. Possible options for type are AGIF, FLAC, H263, H264, MJPA, MJPB, MJPG, MPG2, MPG4, MVC0, PCM, THRA, VORB, VP6, VP8, WMV9, WVC1. Those highlighted currently require a paid for licence (see the this config.txt section for more info), except on the Pi 4 and 400, where these hardware codecs are disabled in preference to software decoding, which requires no licence. Note that because the H.265 HW block on the Raspberry Pi 4 and 400 is not part of the VideoCore GPU, its status is not accessed via this command.
mem_oom
Displays statistics on any OOM (out of memory) events occurring in the VideoCore memory space.
hdmi_timings
Displays the current HDMI settings timings. See Video Config for details of the values returned.
display_power [0 | 1 | -1] [display]
Show current display power state, or set the display power state.
vcgencmd display_power 0 will turn off power to the current display.
vcgencmd display_power 1 will turn on power to the display. If no parameter is set, this will display the current power state. The final parameter is an optional display ID, as returned by
tvservice -l or from the table below, which allows a specific display to be turned on or off.
Note that for the 7" Raspberry Pi Touch Display this simply turns the backlight on and off. The touch functionality continues to operate as normal.
vcgencmd display_power 0 7 will turn off power to display ID 7, which is HDMI 1 on a Raspberry Pi 4.
To determine if a specific display ID is on or off, use -1 as the first parameter.
vcgencmd display_power -1 7 will return 0 if display ID 7 is off, 1 if display ID 7 is on, or -1 if display ID 7 is in an unknown state, for example undetected.
vcdbg
vcdbg is an application to help with debugging the VideoCore GPU from Linux running on the the ARM. It needs to be run as root. This application is mostly of use to Raspberry Pi engineers, although there are some commands that general users may find useful.
sudo vcdbg help will give a list of available commands.
log
Dumps logs from the specified subsystem. Possible options are:
e.g. To print out the current contents of the message log:
vcdbg log msg
reloc
Without any further parameters, lists the current status of the relocatable allocator. Use
sudo vcdbg reloc small to list small allocations as well.
Use the subcommand
sudo vcdbg reloc stats to list statistics for the relocatable allocator.
Python
Python is a powerful programming language that’s easy to use easy to read and write and, with Raspberry Pi, lets you connect your project to the real world. Python syntax is clean, with an emphasis on readability, and uses standard English keywords.
Thonny
The easiest introduction to Python is through Thonny, a Python 3 development environment. You can open Thonny from the Desktop or applications menu.
Thonny gives you a REPL (Read-Evaluate-Print-Loop), which is a prompt you can enter Python commands into. Because it’s a REPL, you even get the output of commands printed to the screen without using
You can use variables if you need to but you can even use it like a calculator. For example:
>>> 1 + 2 3 >>>>> "Hello " + name 'Hello Sarah'
Thonny
Python files in Thonny
To create a Python file in Thonny, click
File > New and you’ll be given a.
Using the Command Line
You can write a Python file in a standard editor, and run it as a Python script from the command line. Just navigate to the directory the file is saved in (use
cd and
ls for guidance) and run with
python3, e.g.
python3 hello.py.
Other Ways of Using Python
The standard built-in Python shell is accessed by typing
python3 in the terminal.
This shell is a prompt ready for Python commands to be entered. You can use this in the same way as Thonny, Raspberry Pi OS archives, and can be installed using apt, for example:
sudo apt update sudo apt install python-picamera
This is a preferable method of installing, as it means that the modules you install can be kept up to date easily with the usual
sudo apt update and
sudo apt full-upgrade commands.
pip
Not all Python packages are available in the Raspberry Pi OS archives, and those that are can sometimes be out of date. If you can’t find a suitable version in the Raspberry Pi OS archives, you can install packages from the Python Package Index (known as PyPI).
To do so, install pip:
sudo apt install python3-pip
Then install Python packages (e.g.
simplejson) with
pip3:
sudo pip3 install simplejson. Raspberry Pi OS is pre-configured to use piwheels for pip. Read more about the piwheels project at.
GPIO and the 40-pin Header.
Any of the GPIO pins can be designated (in software) as an input or output pin and used for a wide range of purposes.
Voltages
Two 5V pins and two 3V3 pins are present on the board, as well as a number of ground pins (0V), which are unconfigurable. The remaining pins are all general purpose 3V3 pins, meaning outputs are set to 3V3 and inputs are 3V3-tolerant..
More
As well as simple input and output devices, the GPIO pins can be used with a variety of alternative functions, some are available on all pins, others on specific pins.
PWM (pulse-width modulation)
Software PWM available on all pins
Hardware PWM available on GPIO12, GPIO13, GPIO18, GPIO19
SPI
Data: (GPIO2); Clock (GPIO3)
EEPROM Data: (GPIO0); EEPROM Clock (GPIO1)
Serial
TX (GPIO14); RX (GPIO15)
GPIO pinout
A handy reference can be accessed on the Raspberry Pi by opening a terminal window and running the command
pinout. This tool is provided by the GPIO Zero Python library, which is installed by default on the Raspberry Pi OS desktop image, but not on Raspberry Pi OS Lite.
For more details on the advanced capabilities of the GPIO pins see gadgetoid’s interactive pinout diagram.
Permissions
In order to use the GPIO ports your user must be a member of the
gpio group. The
pi user is a member by default, other users need to be added manually.
sudo usermod -a -G gpio <username>
GPIO in Python
Using the GPIO Zero library makes it easy to get started with controlling GPIO devices with Python. The library is comprehensively documented at gpiozero.readthedocs.io.
LED
To control an LED connected to GPIO17, you can use this code:
from gpiozero import LED from time import sleep led = LED(17) while True: led.on() sleep(1) led.off() sleep(1)
Run this in an IDE like Thonny, and the LED will blink on and off repeatedly.
LED methods include
on(),
off(),
toggle(), and
blink().
Button
To read the state of a button connected to GPIO2, you can use this code:
from gpiozero import Button from time import sleep button = Button(2) while True: if button.is_pressed: print("Pressed") else: print("Released") sleep(1)
Button functionality includes the properties
is_pressed and
is_held; callbacks
when_pressed,
when_released, and
when_held; and methods
wait_for_press() and
wait_for_release.
Button + LED
To connect the LED and button together, you can use this code:
from gpiozero import LED, Button led = LED(17) button = Button(2) while True: if button.is_pressed: led.on() else: led.off()
Alternatively:
from gpiozero import LED, Button led = LED(17) button = Button(2) while True: button.wait_for_press() led.on() button.wait_for_release() led.off()
or:
from gpiozero import LED, Button led = LED(17) button = Button(2) button.when_pressed = led.on button.when_released = led.off | https://www.raspberrypi.com/documentation/computers/os.html | CC-MAIN-2021-49 | refinedweb | 2,781 | 62.98 |
The ABCs of ETFs
Investing primer: The pros and cons of different funds
Why invest in a fund, a cluster of stocks, rather than the stocks themselves? The reasons are twofold.
First, a fund provides cheaper diversification for those investors with smaller amounts of capital. Buying each component of a fund spreads out your risk in the same way, but you can rack up significant brokerage fees in the process.
The second reason is true for most investors across the board: some funds can get you into sectors that otherwise present significant hurdles to play. Examples include the commercial real estate sector or the convertible bond sector, since regular retail investors would be hard pressed to purchase a commercial building or to participate in a convertible debt financing.
Many different types of funds beckon to investors now, and knowing how they work will help you maximize your gain from them. We'll highlight three to set up the fourth: open-end funds, closed-end funds, hedge funds, and the one we like now to balance risk and reward, exchange-traded funds (ETFs).
Open-End Funds
How they work. Most mutual funds advertised and sold right now are open-end funds. An open-end fund does not restrict the amount of shares that can be issued or redeemed at any time. Usually, at the end of each trading day, additional shares will be created or redeemed in relation to the fund's net asset value (NAV), the fund's total asset less its total liability. An investor who wishes to buy or sell units of an open-end fund deals directly with the fund itself, rather than other investors.
Open-end funds can either be "passive" or "active." A passive open-end fund allocates its holdings according to the S&P 500, Russell 2000, or some other index. The fund manager attempts to track the index as closely as possible. In contrast, an active open-end fund will attempt to beat the index it's tracking by timing the market or selectively choosing the companies within a sector. In reality, most fund managers for mutual funds these days are not even human - they are algorithms that pick stocks.
Advantages. Open-end funds can be found everywhere, are readily accessible, and straightforward to understand. In fact, if you walk into a major bank, they can likely offer you several open-end funds depending on your risk tolerance and the sector of your choice. Choosing a fund manager that delivers positive excess return (also called "alpha") may provide consistent, market-beating performance. Finally, the reinvestment of returns without incurring additional transaction costs could be beneficial for small investors.
Disadvantages. Mutual funds (both open-end and closed-end) tend to have higher expenses than ETFs, money taken out of your investment each year. For a passive open-end mutual fund that tracks the same index as an ETF, it's often cheaper to purchase the ETF instead. For one thing, mutual funds tend to have more trades compared to an ETF, which makes the tax bill larger - costs that are passed on to fundholders. Also, with an active open-end fund, an investor is paying for the expertise of the fund manager (or in most cases, the stock-selecting computer) on top of the diversification benefits the fund is providing.
Open-end funds may have minimum purchase requirements as well as restrictions on the number of times that the fund can be bought or sold within a period of time. In a time of tremendous panic, many investors could sell their fund holdings, leading to a liquidity crisis for the fund and potentially large losses, as the fund sells as much holdings as possible to pay back its fundholders.
Closed-End Funds
How they work. Like the open-end variety, closed-end funds start with an amount of money that they then use for investments. The main difference here is that a closed-end fund issues a limited amount of shares at the beginning and no more for the life of the fund. After the initial offering by the fund, new investors would need to buy the units of the fund from other investors via the secondary market.
Thus several closed-end funds are traded on exchanges - though they're not to be confused with ETFs, however much fund companies have occasionally tried to market them as such. For one thing, closed-end funds are often actively managed, whereas ETFs are most often passively managed. Secondly, ETFs need to disclose their holdings continuously, whereas closed-end funds can disclose holdings as infrequently as every quarter.
Lastly, ETFs tend to trade at or around their NAVs, a feature often not the case for closed-end funds. In fact, a closed-end fund could deviate quite far from net asset value. Since by definition it can't create more shares, the unit price at any given time reflects its assets but also expectations of its future performance - that is, investor demand.
Advantages. Units of closed-end funds traded on an exchange can be bought or sold at any time, with neither trading restrictions nor minimum investment requirements. Compared to active open-end funds, closed-end funds tend to have a slightly better expense ratio because they are rarely advertised. And since closed-end funds do not deal directly with investors, they're less vulnerable to a "run on the bank" situation than an open-end fund.
Disadvantages. Since most closed-end funds are active, they tend to have a higher expense ratio than ETFs or index funds. However, the bigger problem for a closed-end fund is the fact that the unit price on the exchange is often not in line with its NAV. An investor looking to buy into such a fund first needs to perform the due diligence; he must determine the appropriate discount or premium to apply to the NAV to come up with a target price. That's not easy for the average investor.
Another feature to look out for is that since active funds are constantly rebalancing in an effort to time the market and to improve risk-adjusted returns, your portfolio allocation may be shifting without your knowledge. For that matter, this is also true of actively managed open-end funds. Both can lead to poor risk management.
Hedge Funds
How they work. Like the funds we've already talked about, hedge funds take a collection of money and purchase assets with it. However, hedge funds can only be offered to qualified individuals with a net worth of over US$1,000,000 or income of over US$200,000 per year. This structure allows hedge funds to purchase and use investment vehicles that a traditional fund, whether open- or closed-end, cannot - leverage, derivative contracts, short selling, and the like. This flexibility allows hedge fund managers to pursue investment strategies outside the bounds of traditional "long-only" funds. Hedge funds are highly deregulated compared with mutual funds.
Advantages. Hedge funds can have some of the highest returns in all of Wall Street. An example would be John Paulson's hedge fund that bet against Lehman Brothers in 2007, returning more than US$15 billion to his investors in just one year. Moreover, hedge funds can get investors into sectors that even mutual funds cannot enter, such as distressed securities, options, and other more exotic derivatives.
Disadvantages. Hedge funds can be highly risky, especially depending on the sector and strategy of the fund. Also, hedge funds generally prefer to work in secrecy and drop the cloak of confidentiality around their trades, so fund holdings are usually disclosed once a quarter at most.
Hedge fund units are highly illiquid, and holders won't receive their investments until the fund dissolves, which could be several years. In addition, some hedge funds also charge a very high expense ratio - especially the ones with strategies that involve more trading and more leverage, such as a fixed-income arbitrage hedge fund. Hedge funds also face the same portfolio allocation risk as actively managed open- and closed-end funds.
Exchange-Traded Funds (ETFs)
How they work. ETFs, too, hold a collection of assets: stocks, bonds, commodities, futures contracts, derivative contracts, and others among them. The fund manager then creates or redeems new shares as necessary based on the assets and available cash in the fund at the time. Large institutional investors and ETF specialists can deal with the fund manager directly to create or redeem these shares, generally in large quantities by delivering "baskets" of the underlying asset held by the ETF. For example, if the ETF were based on U.S. Treasury bills, an ETF market maker could purchase more shares from the ETF fund manager by delivering an amount of T-bills to the ETF, and vice versa if they wished to redeem shares from the ETF.
The participation of these institutional investors and ETF specialists ensures an ETF will trade around its NAV per share. If the ETF trades at a price significantly higher than its NAV, these "market makers," as we call them, would take the opportunity to sell the ETF and buy the baskets of assets to create more ETF shares for profit without risk. This action, known as arbitrage, exerts a downward pressure on the ETF's price to meet its NAV. Conversely, prices that drop below the NAV get a bump upward when arbitrageurs buy to take advantage of the riskless profit.
Advantages. In addition to their inherent tracking of NAV, ETFs have some of the lowest expense ratios among all the funds. They typically charge about 0.25% to 1% per year and sometimes as low as 0.07%, in contrast to the 1.0% to 1.5% of the average mutual fund. May not sound like much, but it can add up significantly in the long run.
Another advantage of ETFs is that they can be traded like any other security, which means they can be shorted and investors can purchase options on them - a flexibility that experienced investors in particular appreciate. Finally, the holdings of ETFs are announced at the beginning of each trading day, which lets you know exactly what you own at any time. As we said, most other funds generally disclose their holdings much less often, such as once per quarter
Disadvantages. ETFs have no trading restrictions, and their simplicity can lure investors into overtrading and high transaction costs. One needs to keep strategy in mind. If you're starting with less capital but thinking long-term, the usual mutual fund strategy - making a small initial investment and regularly adding to it - can work against you with an ETF.
Due to the transaction costs, a higher-expense mutual fund could actually outperform an ETF in the short run. ETF investments are best made with several large chunks of capital, rather than many small ones.
Potential Pitfalls of ETFs
The combination of high investor interest and the advent of more and more exotic ETFs that cover virtually every imaginable sector is giving rise to several risk factors with which you should become familiar. Among them:
Closed-end funds posing as ETFs. Many closed-end funds, trying to catch the ETF bandwagon, have relabeled their funds with the words "ETF" in their names. These funds may look the same and also trade on exchanges, but they're not ETFs. Compared with a closed-end fund, ETFs generally have more transparency, better tax implications, and lower expense ratios.
Leveraged ETFs. Leveraged ETFs are funds that track 200% or even 300% of an index's daily returns by using options and derivatives. The key word here, however, is "daily," which means that over the long run, these ETFs may not truly mimic the price action of the underlying asset as well as they should be. Case in point: the price of gold vs. the leveraged gold bull ETF vs. the leveraged gold bear ETF:
If you had bought spot gold in the past 12 months, you'd be up 27%. In contrast, the Horizon BetaPro Gold Bull (T.HGU) would have garnered you only 9%, and the Horizon BetaPro Gold Bear (T.HGD) would have shaved you a disastrous 62.5%.
In an environment where there is no clear trend for the underlying index of the ETF, leveraged ETFs based on the index will suffer. This means even if you bought both the bull and the bear, you are at risk of losing money. This effect would only compound if you were buying a triple-leveraged fund. Unfortunately, leveraged funds are a necessary evil when you want to bet against an index or a commodity, since there does not exist a "bear" ETF with high enough liquidity that does not leverage.
Tracking error. Similar to the leveraged-fund example above, some ETFs do not actually track the underlying commodity or index as well as we may believe. You'll find this most often with commodity ETFs, which often track not the actual physical commodity but the futures.
Consider the United States Natural Gas Fund (UNG), which has risen about 12% between mid-November and mid-December. Nice. But in the same time frame, the Henry Hub spot price for natural gas rose 110%, frustrating many investors who thought they would reap much higher rewards. What was the cause of such discrepancy? The UNG uses swaps and Henry Hub futures to proxy actual natural gas. While the spot price was shooting up 110%, the Henry Hub futures price only rose 16%. So before you buy, be sure to know exactly what the ETF is tracking.
In Casey's Energy Opportunities, Marin Katusa and his team provide a solid education in all things energy... and beyond. For just $39 per year, you can become a veritable expert and profit from the prudent investments they recommend. Click here to find out more...
TweetTweet | http://www.safehaven.com/article/15861/the-abcs-of-etfs | CC-MAIN-2016-50 | refinedweb | 2,323 | 60.14 |
Many.
An example
I have created a service within my Web site that enables users to send e-mail to anonymized recipients. Rather than a traceable address, recipients can create a local anonym where they can get mail. You can read about the goals and architecture of Gnosis-Anon at its home page (see Resources). At the same URL, you can enter a query into an HTML form, and in return be presented with an HTML page informing you of an anonym. From there, you need to either write down the information or cut-and-paste the information into a tool other than your Web browser.
Suppose you want to utilize the anonym automatically in an application such as a Mail User Agent (MUA) or Mail Transport Agent (MTA). You might do some screen-scraping like the following:
Listing 1. get-anonym-cgi.py
#!/usr/bin/env python
from urllib import urlencode, urlopen
from sys import argv base_url = '' query = urlencode({'duration':argv[1], 'email':argv[2]}) html_answer = urlopen(base_url+'?'+query).readlines() result = "NO ANONYM FOUND!"
for line in html_answer: if line.find("<dt>Anonym:</dt>") >= 0: start = line.find('<dd>')+4 end = line.find('</dd>') result = line[start:end] break
print result
You can run this with a command line like the following:
Listing 2. Running get-anonym-cgi
% get-anonym-cgi.py perm mertz@gnosis.cx .rNCOolqsVQYu@gnosis.cx
This works if I do not change the format of the HTML -- but that's a big if. A more robust (and simpler) client application might look like this:
Listing 3. get-anonym-xmlrpc.py
#!/usr/bin/env python
import sys, xmlrpclib server = xmlrpclib.Server("") print server.anonym(sys.argv[1], sys.argv[2])
This XML-RPC application behaves exactly the same as the CGI-based one -- except that it will not break if the layout of the Web page changes slightly.
Setting up the XML-RPC server
Writing an XML-RPC server is not much different from writing a CGI script. The actual calculation or lookup code is identical; you only need to change the format of the output and do a little extra work parsing the inputs for CGI. My CGI script looks something like this:
Listing 4. encode_address.py
#!/usr/bin/env python
import cgi query = cgi.FieldStorage() email = query.getvalue('email','test@test.lan') duration = query.getvalue('duration', 'Unknown') anonym = FIND_THE_ANONYM(duration, email) html_template = open('template').read() html = html_template % (email, anonym, duration) print"Content-Type: text/html"
print html
This leaves out the details of how
FIND_THE_ANONYM() works and what the HTML template looks like, but those details are unimportant here. An XML-RPC server is even easier to program:
Listing 5. anonym-xmlrpc-server.py
#!/usr/bin/env python
from SimpleXMLRPCServer import SimpleXMLRPCServer class Anonym: def anonym(self, duration, email): return FIND_THE_ANONYM(duration, email) def container_test(self): return {'spam':'eggs', 'bacon':'toast'} server = SimpleXMLRPCServer(('', 8000)) server.register_instance(Anonym()) server.serve_forever()
As you can see, the same lookup function is used; its return value is what is returned to a remote call to the
.anonym() method. On the wire, return values are encoded as XML-RPC, but Python's
xmlrpclib module automatically translates XML-RPC encoded structures back into native data structures, as do analogous libraries in other languages. The method
.container_test() in Listing 5 can be called remotely as well, in which case the client will see a Python dictionary.
A few notes
These code examples use Python, but implementations of both XML-RPC clients and servers exist for a large number of programming languages. Moreover, XML-RPC itself is completely language-neutral; multiple clients written in different languages can call the same server, and none of them will care what language the server was written in. like the eight-line version in Listing 5.
Resources
- Dave Winer has created an XML-RPC interace to Google, which includes usage examples.
- Google chooses to implement a programmatic API in the somewhat heavier-weight XML dialect of SOAP. The principle is the same as the XML-RPC version.
- A prior article by the author, "XML-RPC as object model" looks at the data model of XML-RPC. (developerWorks, December 2001)
- Find information and lookups for the Gnosis-Anon Mail Transport Agent here.
-. | http://www.ibm.com/developerworks/xml/library/x-tipxmlrpc/index.html | CC-MAIN-2013-48 | refinedweb | 705 | 56.45 |
In this tutorial, we’ll introduce you to the Flutter SnackBar class, one of the many widgets that implement Material Design in Flutter. We’ll go over some of the widget’s most important features, outline steps for customizing and displaying a SnackBar in a Flutter app, and go over some real-world examples to show how SnackBar works in practice.
To follow along, you should have a basic understanding of Flutter app development and some experience using the SDK to build cross-platform applications.
Without further ado, let’s get started!
What is the SnackBar class?
SnackBar is a Flutter widget that enables you to temporarily display a pop-up message in your app. It usually appears at the bottom of the app’s screen.
For example, you might use the SnackBar widget to let the user know when a selected item has been added to cart or deleted, or to indicate that a form was sent or an image uploaded successfully.
Considerations for implementing a SnackBar in a Flutter app
When implementing a SnackBar, you should consider the following features and/or functions:
Frequency
This entails how long a SnackBar is displayed in the app. Always keep in mind that the SnackBar shouldn’t distract the end user from the main goal of the app.
This is one reason why a SnackBar is typically placed at the bottom of the app screen. The recommended duration for a SnackBar to display in a Flutter app is four to 10 seconds — no longer.
Actions
Though, as mentioned previously, a SnackBar may disappear from the app’s screen after a certain duration without the user’s interaction, it’s a good practice to implement some kind of interactive element to accompany your message.
For example, you might create an action button with a label such as “Dismiss” or “Try again” and attach it to the SnackBar widget.
Informativeness
One of the most common and crucial use cases for the SnackBar widget in a Flutter app is to convey important information about the app’s processes. For a simple example, the SnackBar might show a message like “Successful” when the user clicks a button to submit a form, upload a file, etc.
Building, displaying, and customizing the SnackBar
To get started building, displaying, and styling your SnackBar, first complete the following steps:
- Launch Android Studio or another IDE of your choice
- Start a new Flutter project
- Select Flutter Application and name the project something like “snackbardemo”
NOTE: If you run into the “Null safety features” error while trying to compile and run the code, you can fix it by upgrading Flutter to version 2.12 or higher.
To upgrade to the latest version of Flutter, click on the terminal tab in Android Studio and run the following command:
flutter upgrade
Next, clear out the code except for
void main() => runApp(MyApp());, which is what Flutter generates when a new project is created. We’re doing this because we want to build from the ground up.
You should now have something like this in your editor:
import 'package:flutter/material.dart'; void main() => runApp(MyApp());
Now, change
MyApp() to
const SnackBarDisplay():
void main() => runApp(SnackBarDisplay());
void main() is the main entry point for Dart programs. Flutter uses the
runApp() function or method as the root widget of the app.
Here, we are creating a widget, which we’ll name
SnackBarDisplay. This will be the root of our app.
Input the code below after
void man(). The
SnackBarDisplay extends the
StatelessWidget, making
SnackBarDisplay a widget.
class SnackBarDisplay extends StatelessWidget { const SnackBarDisplay({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Displaying a SnackBar', home: Scaffold( backgroundColor: (Colors.grey), appBar: AppBar( title: const Text('Displaying a SnackBar'), backgroundColor: Colors.black12, ), body: const SnackBarPage(), ), ); } }
We are making use of the Material Design library to create the app’s structure. Material is an open-source design system owned by Google for customizing Android, Flutter, iOS, and web apps. As mentioned previously, Flutter has a wide variety of Material widgets.
The
Scaffold widget provides the default app bar, a title, and a body property, which holds the widget tree for our home screen,
home: Scaffold(). The
Scaffold widget is required to display a SnackBar.
backgroudColor: (Colors.grey) is used to change the default background of the Flutter app.
Next, create the SnackBar section by using the code below. Here when the user clicks on the button, the SnackBar is displayed:
class SnackBarPage extends StatelessWidget { const SnackBarPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Center( child: ElevatedButton( onPressed: () { final snackBar = SnackBar( content: const Text('Hi, I am a SnackBar!'), backgroundColor: (Colors.black12), action: SnackBarAction( label: 'dismiss', onPressed: () { }, ), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); }, child: const Text( 'Click to Display a SnackBar', ), ), ); } }
In the code above, we have the build widget —
Widget build(BuildContext context) — and what’s worth nothing here is the
BuildContext argument, which specifies where the widget is built.
In this example, we’re building a custom widget button,
ElevatedButton, which will be on the center of the app’s screen. The
ElevatedButton is a child widget placed on the
return Center.
Then, we use the
ScaffoldMessenger class to display the SnackBar.
Finally, run the program. You should see something like this:
Clicking on the button will show the SnackBar with the following message: “Hi, I am a SnackBar!”
Conclusion
I hope you found this tutorial insightful. Flutter makes it easy to build apps across mobile platforms and the web. At the core of Flutter is widgets. The SnackBar widget makes it easy to share important and informative messages with your users to help them get the most out of your Flutter app.
You can learn more about Flutter by browsing through our collection of Flutter articles and tutorials.
Happy coding!. | https://blog.logrocket.com/how-to-display-and-customize-a-snackbar-in-flutter/ | CC-MAIN-2022-05 | refinedweb | 971 | 53 |
Payback, NPV, IRR
Please help with the attached Corporate Finance Question regarding Payback, NPV, and IRR.
I am looking for the calculations and work shown (any formulas) on how the answer was obtained.
Corporate Finance Question: P10-21 of capital.
Year (t) Cash inflows (CFt) should be a little t
1 $20,000
2 $25,000
3 $30,000
4 $35,000
5 $40,000
a.) Calculate the payback period for the proposed investment.
b.) Calculate the net present value (NPV) for the proposed investment.
c.) Calculate the internal rate of return (IRR), rounded to the nearest whole percent, for the proposed investment.
d.) Evaluate the acceptability of the proposed investment using NPV and IRR. What recommendation would you make relative to implementation of the project? Why?
Solution Preview
See the attached file.
a.) Payback period
The formula to calculate payback period of a project depends on whether the cash flow per period from the project is even or uneven. When cash inflows are uneven, we need to calculate the cumulative net cash flow for each period and then use the following formula for payback period:
Payback period = A + (B/C)
Where,
A is the last period with a negative cumulative cash flow;
B is the absolute value of cumulative cash flow at the end of the period A;
C is the total cash flow during the period after A
Therefore, the payback period for this investment would be calculated as follows:
Year Cash Flow Net Cash Flow (NCF)
Initial Outlay -95,000 -95,000
Year 1 20,000 -75,000
Year 2 25,000 -50,000
Year 3 30,000 -20,000
Year 4 35,000 15,000
Year 5 40,000 55,000
We can see that after ...
Solution Summary
The solution determines the payback, NPV and IRR | https://brainmass.com/business/capital-budgeting/payback-npv-irr-531866 | CC-MAIN-2018-09 | refinedweb | 300 | 58.01 |
Custom Django Views for Happier Ajaxjquery (6), django (72), javascript (18)
This post continues where Intro to Unintrusive JavaScript with Django left off. In the first segment we persisted against writing custom views to service the Ajax aspects of the app, and it lead to a lot of ugly code and awkward functionality.
In this second segment we're going to make that plunge and write two custom views to handle the Ajax, and open up a world of simple JavaScript with 90% less awful.
Updating
notes/urls.py
First we're going to update the
notes/urls.py file
to include two new urls. Once updated, the file
should look like this:'^ajax_create/$','notes.views.ajax_create_note'), (r'^note/(?P<slug>[-\w]+)/update/$','notes.views.update_note'), (r'^note/(?P<slug>[-\w]+)/ajax_update/$','notes.views.ajax_update_note'), )
All we did here was add the
^ajax_create/% and
^note/(?P<slug>[-\w]+)/ajax_update/$' urls.
Writing the
ajax_create_note view
Next we have to actually write our two new views:
ajax_create_note and
ajax_update_note.
Because it's easy, we're going to go ahead and keep passing them the same data in the same format as we were before.
The big difference is that we'll be returning our responses serialized into JSON, which is the recommended diet for all JavaScript lifeforms.
First add these imports at the top of the
notes/views.py
file:
from django.utils import simplejson from django.http import HttpResponse
And then add this function as well:
def ajax_create_note(request): success = False to_return = {'msg':u'No POST data sent.' } if request.method == "POST": post = request.POST.copy() if post.has_key('slug') and post.has_key('title'): slug = post['slug'] if Note.objects.filter(slug=slug).count() > 0: to_return['msg'] = u"Slug '%s' already in use." % slug else: title = post['title'] new_note = Note.objects.create(title=title,slug=slug) to_return['title'] = title to_return['slug'] = slug to_return['url'] = new_note.get_absolute_url() success = True else: to_return['msg'] = u"Requires both 'slug' and 'title'!" serialized = simplejson.dumps(to_return) if success == True: return HttpResponse(serialized, mimetype="application/json") else: return HttpResponseServerError(serialized, mimetype="application/json")
As mentioned, the only big difference between
ajax_create_note
and
create_note is that we're serializing the output.
If we were sufficiently industrious, we could refactor the two methods pretty far, but for this tutorial we'll leave them are they are.
Now we need to update the JavaScript in the
notes/note_list.html
template to take advantage of this changes.
Updating the
notes/note_list.html template
First we need to modify the
create_note JavaScript method
to send data to the new url.
Change this line from:
var args = { type:"POST", url:"/create/", data:data, complete:done };
to this:
var args = { type:"POST", url:"/ajax_create/", data:data, complete:done };
After that, the only change we need to make here is to strip the
regex crap out of
done and replace it with some
blissful simplicity (and a security vulnerability, ahem).
The new
done function looks like this:
var done = function(res, status) { var txt = res.responseText; var data = eval('('+txt+')'); if (status == "success") { var newLi = $('<li><a href="'+data.url+'">'+data.title+'</a></li>'); $("#notes").prepend(newLi); $("#title").val(""); $("#slug").val(""); } else display_error(data.msg, $(".new")); }
The first thing we do is convert the incoming JSON into
a JavaScript datastructure via the
eval function.
This is the simplest way to convert JSON into a usable1
JSON.
This isn't safe, because you are literally executing the recieved JSON, and if there were any malicious instructions contained within it, you'd execute those as well.
For the time being we're going to skim over that problem, but you can take a look at this article under the header 'JSON Via Parse' to get an idea of how to be more secure.
Now you can go ahead and run the development server and test out the front page.
It's going to work the same way as before, but isn't relying on the haphazard regular expressions to strip out necessary content.
Writing the
ajax_update_note view
Next we're going to create the
ajax_update_note
view in our
notes/views.py file. Once again there
will be a lot of overlap between the Ajax and non-Ajax
update views, and the big difference will simply be
serializing the output.
Open up
notes/views.py.
def ajax_update_note(request, slug): success = False to_return = { 'msg': u"No POST data recieved." } if request.method == "POST": post = request.POST.copy() note = Note.objects.get(slug=slug) to_return['msg'] = "Updated successfully." success = True if post.has_key('slug'): slug_str = post['slug'] if note.slug != slug_str: if Note.objects.filter(slug=slug_str).count() > 0: to_return['msg'] = u"Slug '%s' already taken." % slug_str to_return['slug'] = note.slug success = False else: note.slug = slug_str to_return['url'] = note.get_absolute_url() if post.has_key('title'): note.title = post['title'] if post.has_key('text'): note.text = post['text'] note.save() print success print to_return print request.method serialized = simplejson.dumps(to_return) if success == True: return HttpResponse(serialized, mimetype="application/json") else: return HttpResponseServerError(serialized, mimetype="application/json")
Read through and make sure you're comfortable with everything there, and then we're off into JavaScript land once more.
Updating the
notes/note_detail.html template
Open up
notes/note_detail.html.
In the
perform_upate function, we'll once again
change the
args dictionary. This time it will end up
looking like this:
var args = { type:"POST", url:"ajax_update/", data:data, complete:done };
We only changed the url we're posting to. Now, however, we're going to change things up a bit more. One of the biggest problems with our first implementation was that it would send unnecessary updates.
We couldn't improve upon it easily because we were lacking
some crucial information, but no longer. The
ajax_update_note
view is returning us all the information we need to maintain
a simple history of the data, and to only submit changes when
changes have actually occured.
Further, for the field where errors are likely to occur (slug) we have enough information to rollback failed updates, and also redirect to the note's new url when the slug is successfully updated.
We'll begin with the history. Delete the
initialTitleChange
and
initialSlugChange values, and replace them with this
code:
var history = { title: $("#title").val(), slug: $("#slug").val() };
Next we'll need to update the
title_to_span and
slug_to_span
functions to check against the value stored in the history before
sending an update.
var title_to_span = function() { var title = $("#title"); if (title.val() != history['title']) { perform_update("title", title.val()); history['title'] = title.val() } var span = $('<span id="title"><em>'+title.val()+'</em></span>'); span.hover(title_to_input,function() {}); title.replaceWith(span); }
The changes are at lines 3 through 5. Before sending an update
we check that it differs from the current value. If we do send
an update, then we update the current value stored in
history.
We'll also do the same for
slug_to_span.
var slug_to_span = function() { var slug = $("#slug"); if (slug.val() != history['slug']) { perform_update("slug", slug.val()); history['slug'] = slug.val(); } var span = $('<span id="slug"><em>'+slug.val()+'</em></span>'); span.hover(slug_to_input,function() {}); slug.replaceWith(span); }
We could do the same for the textfield as well, but we'll skip on that for the time being.
Finally we need to update the
done function a bit.
var done = function(res, status) { var txt = res.responseText; var data = eval('('+txt+')'); if (status == "success") { display_success("Updated successfully.", $(".text")); if (data.url) { window.location = data.url } } else { display_error(data.msg, $(".text")); if (data.slug) { history['slug'] = data.slug; $("#slug").text(data.slug); } } }
We begin by evaluating the returned JSON into a JavaScript datastructure. Then we have the standard logic for displaying success and error messages, as well as some custom logic for handling updates to the slug field.
Specifically, if we successfully update the slug, then we
use JavaScript to redirect to the new url where the note
exists, and if we fail to update the slug, then we revert
the value in the slug field (and
history.slug) to
its actual current value (instead of what we attempted to
change it to).
With those changes, the Ajax on the
note_detail.html
template evolves from a burdensome mess of awfulness into
something that provides a quicker and more pleasant experience
than that provided by the original non-Ajax version.
Download
You can download the Git repository for part two here.
Moving Forward
By writing these two extra views we were able to really simplify the JavaScript, as well as improve the usability of the app. Although it's too bad we can't gain the same benefits using only one view, with great Ajax comes great reponsibility.
Or something like that.
In the next segment we're going to take a look at how authentication has to be reexamined for Ajax applications.
Because I just had this discussion with the person sitting here with me, I'll launch into a brief mention of the correct usage of 'a' and 'an in the English language.
You use 'an' infront of words that begin with a vowel sound, not necessarily with a vowel. This is why people who write about Cocoa and an
NSStringor an
NSMutableDictionary.
On the other hand, words like usable start with a consonant sound despite beginning with a vowel.↩ | https://lethain.com/custom-django-views-for-happier-ajax/ | CC-MAIN-2021-21 | refinedweb | 1,544 | 58.99 |
Testing django mixins
You may read all these books and tutorials that tell you - test your code! This blog post is to help you test your django mixins.
Why is it worth to test mixins?
You come to django world and you discover mixins - at the beginning, you think it awesome! Let write more of those!
So you write this self-contained mixin - right now there is a time to test it. It can assure that your piece of code works as expected and can save you a lot of trouble.
Ok, you are ready to write some test. How to do it?
How to test mixins?
Imagine that you have this simple
TemplateView with mixin:
from django.views.generic import TemplateView
class SomethingMixin(object):
def get_context_data(self, **kwargs):
context = super(SomethingMixin, self).get_context_data(**kwargs)
context['has_something'] = True
return context
class ExampleTemplateView(SomethingMixin, TemplateView):
template_name = 'example.html'
SomethingMixin is adding a new key to the context. Let's write some
tests:
from django.test import SimpleTestCase
from django.views.generic import TemplateView
from .views import SomethingMixin
class SomethingMixinTest(SimpleTestCase):
class DummyView(SomethingMixin, TemplateView):
pass
def test_something_mixin(self):
dummy_view = self.DummyView()
context = dummy_view.get_context_data()
self.assertTrue(context['has_something'])
I created a simple empty
DummyView to use
SomethingMixin. I'm using
only
TemplateView because I don't need more advanced views to test if
a key is in context. In
test_something_mixin I instantiate
dummy_view. Then take context test if it has a key that I'm interested
in.
And that's all! I have my mixin tested. If mixin become more and more complex you may need more tests.
Feel free to comment! Examples based on this gist. | https://krzysztofzuraw.com/blog/2017/how-to-test-django-mixins/ | CC-MAIN-2022-21 | refinedweb | 276 | 53.98 |
Topic Modelling with NMF in Python
Want to share your content on python-bloggers? click here.
In the previous tutorial, we explained how we can apply LDA Topic Modelling with Gensim. Today, we will provide an example of Topic Modelling with Non-Negative Matrix Factorization (NMF) using Python. If you want to get more information about NMF you can have a look at the post of NMF for Dimensionality Reduction and Recommender Systems in Python.
Again we will work with the ABC News dataset and we will create 10 topics. Let’s start coding by loading the data and the required libraries!
import pandas as pd from sklearn.decomposition import NMF from sklearn.feature_extraction.text import TfidfVectorizer documents = pd.read_csv('news-data.csv', error_bad_lines=False) documents.head()
Note that the dataset contains 1,103,663 documents
NFM for Topic Modelling
The idea is to take the documents and to create the TF-IDF which will be a matrix of M rows, where M is the number of documents and in our case is 1,103,663 and N columns, where N is the number of unigrams, let’s call them “words”. Then, from this matrix, we try to generate another two matrices such as the Features which will be of M rows and 10 columns, where 10 is the number of topics and the Components which will be of 10 rows (topics) and N columns (words). The product of Features and Components will approximate the TF-IDF.
So keep in mind that:
- The Components Matrix represents topics
- The Features Matrix combines topics into documents
Build the TF-IDF Matrix
The first step is to create the TF-IDF matrix as follows.
# use tfidf by removing tokens that don't appear in at least 50 documents vect = TfidfVectorizer(min_df=50, stop_words='english') # Fit and transform X = vect.fit_transform(documents.headline_text)
Build the NMF Model
At this point, we will build the NMF model which will generate the Feature and the Component matrices.
# Create an NMF instance: model # the 10 components will be the topics model = NMF(n_components=10, random_state=5) # Fit the model to TF-IDF model.fit(X) # Transform the TF-IDF: nmf_features nmf_features = model.transform(X)
It important to check the dimensions of the 3 tables:
TF-IDF Dimensions:
X.shape
(1103663, 11213)
Features Dimensions:
nmf_features.shape
(1103663, 10)
Components Dimensions:
model.components_.shape
(10, 11213)
We should add the column names to the Components matrix since these are the tokens (words) from the TF-IDF. Note, that based on our tokenizer we included any token of two or more characters that is why you will see some numbers. We could have also removed them. Both approaches are correct.
# Create a DataFrame: components_df components_df = pd.DataFrame(model.components_, columns=vect.get_feature_names()) components_df
Get the Words of the Highest Value for each Topic
We have created the 10 topics using NMF. Let’s have a look at the 10 more important words for each topic.
for topic in range(components_df.shape[0]): tmp = components_df.iloc[topic] print(f'For topic {topic+1} the words with the highest value are:') print(tmp.nlargest(10)) print('\n')
Output:
For topic 1 the words with the highest value are: man 8.396817 charged 3.117248 murder 1.367349 jailed 0.891809 missing 0.880894 stabbing 0.727232 guilty 0.637090 arrested 0.600157 death 0.587411 sydney 0.532504 Name: 0, dtype: float64 For topic 2 the words with the highest value are: interview 7.471284 extended 0.393083 michael 0.383856 david 0.226665 john 0.222362 james 0.211161 nrl 0.202279 smith 0.179707 ben 0.172380 andrew 0.169546 Name: 1, dtype: float64 For topic 3 the words with the highest value are: police 6.886678 probe 0.814901 investigate 0.795326 missing 0.679711 search 0.637454 death 0.497555 hunt 0.420141 officer 0.329780 seek 0.313185 shooting 0.300862 Name: 2, dtype: float64 For topic 4 the words with the highest value are: new 8.436840 zealand 0.571164 laws 0.402800 year 0.368542 home 0.265268 york 0.242442 centre 0.234176 hospital 0.233369 deal 0.220119 opens 0.190645 Name: 3, dtype: float64 For topic 5 the words with the highest value are: rural 6.200143 national 2.804131 qld 2.662080 news 2.342136 nsw 1.211054 podcast 0.768686 reporter 0.525871 sa 0.477365 health 0.234591 north 0.219903 Name: 4, dtype: float64 For topic 6 the words with the highest value are: abc 6.010566 news 2.209571 weather 2.192629 business 1.925450 sport 1.640363 market 1.310986 entertainment 0.926865 analysis 0.924629 talks 0.227601 speaks 0.194431 Name: 5, dtype: float64 For topic 7 the words with the highest value are: crash 5.455308 car 2.480800 dies 1.841566 killed 1.837934 fatal 1.451367 woman 1.178756 road 0.986225 driver 0.875721 plane 0.778262 injured 0.651799 Name: 6, dtype: float64 For topic 8 the words with the highest value are: court 7.931729 accused 2.308421 face 2.058921 murder 1.515629 faces 1.053453 charges 1.052557 told 0.869612 case 0.766514 high 0.689719 sex 0.600428 Name: 7, dtype: float64 For topic 9 the words with the highest value are: country 3.850864 hour 3.468195 wa 1.608666 nsw 1.492966 2014 1.090257 2015 1.075701 podcast 1.054856 vic 0.755764 tas 0.658372 2013 0.643352 Name: 8, dtype: float64 For topic 10 the words with the highest value are: govt 2.101926 council 2.040503 says 1.651489 plan 1.185716 water 1.081075 health 0.794900 urged 0.715581 australia 0.661426 report 0.548353 funding 0.529309 Name: 9, dtype: float64
As we can see the topics appear to be meaningful. For example, Topic 3 seems to be about missing persons and investigations (police, probe, investigation, missing, search, seek etc)
Get the Topic of a Document
Since we defined the topics, we will show how you can get the topic of each document. Let’s say that we want to get the topic of the 55th document:
‘funds to help restore cossack’
my_document = documents.headline_text[55] my_document
Output:
'funds to help restore cossack'
We will need to work with the Features matrix. So let’s get the 55th row:
pd.DataFrame(nmf_features).loc[55]
Output:
0 0.000000 1 0.000000 2 0.001271 3 0.000000 4 0.000000 5 0.000000 6 0.000000 7 0.000000 8 0.000000 9 0.011652 Name: 55, dtype: float64
We look for the Topic with the maximum value which is the one of index 9 which is the 10th in our case (note that we started from 1 instead of 0). If we see the most important words of Topic 10 we will see that it contains the “funding“!
Note that if we wanted to get the index in once, we could have typed:
pd.DataFrame(nmf_features).loc[55].idxmax()
Output:
9
Finally, if we want to see the number of documents for each topic we can easily get it by typing:
pd.DataFrame(nmf_features).idxmax()
Output:
0 773063 1 186097 2 305808 3 27576 4 648375 5 374427 6 142751 7 209596 8 621162 9 397901 dtype: int64
In Closing
We provided a walk-through example of Topic Modelling using NMF. We need to stress out that the number of topics is arbitrary and it is difficult to find the optimum one. In our example, we can see that some topics can be merged, which implies that it would better to choose fewer topics. Finally, keep in mind that Matrix Factorization is a very powerful tool that has many applications in Data Science.
Want to share your content on python-bloggers? click here. | https://python-bloggers.com/2021/01/topic-modelling-with-nmf-in-python/ | CC-MAIN-2021-10 | refinedweb | 1,309 | 81.09 |
#include <SSLIOP_Endpoint.h>
Inheritance diagram for TAO_SSLIOP_Endpoint:
Constructor.
Destructor.
[virtual]
Implements TAO_Endpoint.
Get the credentials for this endpoint.
Set the credentials for this endpoint.
Return a copy of the corresponding endpoints by allocating memory.
Return a hash value for this object.
Mutator to our IIOP counterpart.
true
Accessor to our IIOP counterpart.
Two endpoints are equivalent iff their iiop counterparts are equivalent, and, if both have non-zero ssl ports, their ssl ports are the same.
Return the SSLIOP-specific ACE_INET_Addr.
Get the Quality-of-Protection settings for this endpoint.
Set the Quality-of-Protection settings for this endpoint.
Return SSL component corresponding to this endpoint.
Get the establishment of trust settings for this endpoint.
Set the establishment of trust settings for this endpoint.
[friend]
[private]
SSLIOP-specific credentials for this endpoint object..
Cache the SSL tagged component in a decoded format. Notice that we do not need to marshal this object!
Establishment of trust settings for this endpoint object. | https://www.dre.vanderbilt.edu/Doxygen/5.4.3/html/tao/ssliop/classTAO__SSLIOP__Endpoint.html | CC-MAIN-2022-40 | refinedweb | 160 | 54.9 |
- Redux Form
- Getting Started
Getting Started With
redux-form #
The basic implementation of
redux-form is simple. However, to make the most of
it, it's recommended to have basic knowledge on:
- Redux state container,
- React and Higher-Order Components (HOCs).
Overview #
To connect your React form components to your Redux store you'll need the following
pieces from the
redux-form package:
- Redux Reducer:
formReducer,
- React HOC
reduxForm()and
<Field/>component.
It's important to understand their responsibilities:
Data flow #
The diagram below represents the simplified data flow. Note that in most cases you don't need to worry about the action creators for yourself, as they're already bound to dispatch for certain actions.
Let's go through a simple example. We have a form component wrapped with
reduxForm(). There is one text input inside, wrapped with
<Field/>. The data
flows like this:
- User clicks on the input,
- "Focus action" is dispatched,
formReducerupdates the corresponding state slice,
- The state is then passed back to the input.
Same goes for any other interaction like filling the input, changing its state or submitting the form.
With
redux-form comes a lot more: hooks for validation and formatting
handlers, various properties and action creators. This guide describes the basic
usage – feel free to dig deeper.
Basic Usage Guide #
Step 1 of 4: Form reducer #
The store should know how to handle actions coming from the form components. To
enable this, we need to pass the
formReducer to your store. It serves for
all of your form components, so you only have to pass it once. }) const store = createStore(rootReducer)
Now your store knows how to handle actions coming from the form components.
NOTE: The key used to pass the
redux-form reducer should be named
form. If you need a custom key for some reason see
getFormState config
for more details.
Step 2 of 4: Form component #
To make your form component communicate with the store, we need to wrap it with
reduxForm(). It will provide the props about the form state and function to
handle the submit process.
import React from 'react' import { Field, reduxForm } from 'redux-form' let ContactForm = props => { const { handleSubmit } = props return <form onSubmit={handleSubmit}>{/* form body*/}</form> } ContactForm = reduxForm({ // a unique name for the form form: 'contact' })(ContactForm) export default ContactForm
Once we have the form component ready, it's time to add some inputs.
NOTE: If the
()() syntax seems confusing, you can always break it down
into two steps:
// ... // create new, "configured" function createReduxForm = reduxForm({ form: 'contact' }) // evaluate it for ContactForm component ContactForm = createReduxForm(ContactForm) export default ContactForm
Step 3 of 4: Form
<Field/> Components #
The
<Field/> component connects each input to the store. The basic usage goes
as follows:
<Field name="inputName" component="input" type="text" />
It creates an HTML
<input/> element of type
text. It also passes additional
props such as
value,
onChange,
onBlur, etc. Those are used to track and
maintain the input state under the hood.
NOTE:
<Field/> component is much more powerful. Apart from basic input
types, it can take a class or a stateless component. When you're ready, go to
the docs to find out
more.
Let's finish up our contact form:) export default ContactForm
From now on, the store should be populated based on actions coming from your form component. We can now handle the submission.
Step 4 of 4: Reacting to submit #
The submitted data is passed as JSON object to your
onSubmit function. Let's
console.log it out:
import React from 'react' import ContactForm from './ContactForm' class ContactPage extends React.Component { submit = values => { // print the form values to the console console.log(values) } render() { return <ContactForm onSubmit={this.submit} /> } }
You can now take it from here. We recommend to check out the examples. The common next steps could also be:
- setting the initial form values,
- implementing the validation,
- creating dynamic forms with arrays of fields. | https://redux-form.com/8.2.0/docs/gettingstarted.md/ | CC-MAIN-2019-39 | refinedweb | 652 | 55.34 |
A. There are really two APIs buried in this specification and
one of them is actually quite interesting. Java is about to get a standardized API for working with scripting languages and it's not just about web applications any more.
While the original focus of JSR-223 was indeed to develop a standard API for deploying scripted pages in web applications, over the past year the expert group has actually spent most of its time on the lower level, prerequisite API for exposing scripting language engines to the Java platform. The new javax.script package provides a standardized script engine API, similar to
the IBM/Apache BSF (Bean Scripting Framework), but takes the integration much further, offering: a more powerful discovery mechanism, fine grained namespace and script environment management, powerful application integration, and other advanced features.
Since much of the specification is aimed at scripting engine developers, some of these user APIs may not be immediately obvious. I'll just run down some of the important points here and leave the details for an upcoming article.
The reference implementation is available from the JSR-223 home page:
The download includes javax.script engine implementations for JavaScript, PHP, and Groovy.
Interestingly, despite numerous references to the
BeanShell Java scripting language in the
specification, the development of a BeanShell engine by the spec lead, and the participation of
the primary BeanShell developer (me) in the spec development, the Sun download
does not include a BeanShell engine implementation or examples. (The politics of Groovy continue to amaze me.) But not to fear, the next release of BeanShell will include an engine implementation as part of its own distribution.
Check it out!
I
Posted by: megadix on February 11, 2005 at 04:47 AM
Sorry, the "Post comment" function of java.net is a bit broken...I re-post my comment:
I'm a big Beanshell fan, so I'll check this out. I Just hope that binding BSH to a JSR will not hurt...
Posted by: megadix on February 11, 2005 at 04:48 AM
Here's the TSS thread on this topic:
Posted by: dward1 on February 11, 2005 at 09:37 AM
So for those on the outside, what exactly are the "politics of Groovy"?
Posted by: rms7326 on February 11, 2005 at 09:44 AM
Sounds neat. I'm most interested in the BeanShell implementation so I'll wait for that. Hope it all works with a SecurityManager (unsigned Java Web Start environment).
Posted by: markswanson on February 11, 2005 at 12:43 PM
FWIW, I am in the inside, and I do not know what are "the politics of groovy".
- eduard/o
Posted by: pelegri on February 11, 2005 at 02:01 PM
Argh! It never ceases to amaze me that the kludge that is Groovy gets the mindshare. BeanShell should have been included. It is the best and cleanest implementation of a scripting engine on top of the JVM.
Posted by: zatoichi on February 13, 2005 at 05:48 AM
I agree on all counts.
But I would go beyond and make this api a standart for managing Virtual machines as well. If you think about it, this is ideal to control other virtual machines , java programs, and native programs., processes...
If one stops to think about it the virtual machine is a scripting engine (so is the .Net pear) . Even native programs have context (args, stdin, stdout) so this abstraction could go even further.
Posted by: levmatta on February 15, 2005 at 10:31 AM
As a great fan of beanshell I was really impressed by the "beanshellism" of the API *grin* looks like you had great influence upon it so far. I'm glad that your namespaces idea got in there, as I like it very much :-) I'm *very* excited about the next releases of beanshell, when the method extensions, closures and this API gets in there :-)) (not that I expect everything in the next release all ready...)
Posted by: patricbechtel on February 21, 2005 at 09:31 AM
Про Яву можете почитать еще здесь новости дня, компьютеры. Про спорт здесь спорт, новости спорта, а про футбол здесь футбол, новости футбола. теннис.
Posted by: kolenchits on May 17, 2005 at 06:51 AM
"But not to fear, the next release of BeanShell will include an engine implementation as part of its own distribution."
This blog is ne quite a bit old, but I can't find a beanshell version with javax.script support. About which version are you thinking?
Would be great to have javax.script support soon :-)
Posted by: zero on April 03, 2006 at 08:43 PM
I have created a BeanShell plugin for JDK 6 jconsole. So you don't have to wait for BeanShell JSR-233 script engine ;-)
see A BeanShell Plugin for JConsole.
By the way BeanShell is really neat! I am looking forward to the BeanShell JSR-233 script engine and JSR-274 completion!
cheers,
-- daniel
Posted by: dfuchs on August 11, 2006 at 07:39 AM | http://weblogs.java.net/blog/pat/archive/2005/02/the_new_javaxsc.html | crawl-002 | refinedweb | 839 | 61.46 |
Learning objectives
Upon completion of this chapter, you will be able to
- Understand SMIL fundamentals.
- Understand how and why SMIL is used.
- Locate and use SMIL technical specifications, tutorials and open source SMIL tools.
- Create simple SMIL markup.
- Watch your SMIL file come to life in a SMIL viewer.
IntroductionEdit
With the explosion of the late 90's popularity of the internet, The World Wide Web Consortium (W3C) saw the need to extend the capabilities of the web with respect to information structure and media presentation. This is how they arrived at XML, the extensible language for describing information structure. Furthermore, SMIL is built upon XML: it is a specialized language to describe the presentation of media objects. Since the W3C (and everyone else) doesn't know what media types will be around in the future (virtual environments, brainwave-synch experiences, psychic/holographic/video), XML was an appropriate choice in designing SMIL to be extended to support these media.
In order to integrate this technology with HTML and extend the application of media in HTML, the W3C decided to make a push towards modularizing these languages or protocols. SMIL is one of many modular languages which 'plug-in' to the larger framework of XML.
What is SMIL?Edit
SMIL (pronounced "smile") is an acronym for Synchronized Multimedia Integration Language. It is thought of as an open-standard version of PowerPoint for the internet. SMIL is an XML-based language, similar in appearance to HTML, that allows for the authoring of interactive audiovisual presentations. SMIL enables the streaming of audio and video with images, text or other media types. It is a language describing the temporal and spacial placement of one or more media objects. Although SMIL can be written with a simple text editor, hand-writing SMIL documents can be a time-consuming and complicated endeavor. Therefore it is better to use a tool for generating complicated SMIL documents.
World Wide Web Consortium (W3C) SYMM groupEdit
Since November 1997, the W3C SYMM group has been developing the SMIL language. It finalized SMIL 1.0 in June of 1998 and SMIL 2.0 in August of 2001.
Why SMIL?Edit
Although plug-ins and media players have the ability to show many different types of media with varying support for interaction, only SMIL offers the ability to define the presentation in the form of text as a script. This feature could be called media composition. This is a powerful ability when you think about it: text presentations can be generated from other applications. Also, SMIL offers accessibility options and powerful features not present in these media players.
- Macromedia products such as Flash, which require a plug-in to view flash inside a web page.
- RealAudio's Realplayer
- Microsoft's PowerPoint
- OpenOffice.org's Impress
- Apple's Quicktime
- Microsoft has already created a proprietary alternative to SMIL. It is called Microsoft's Synchronized Accessible Media Interchange (SAMI), which plays ASX files through Windows Media Player (WiMP).
Given that SMIL is extensible, the SMIL language has the ability to show many of proprietary objects which are used by the above players. SMIL was designed to be the overarching language for describing the presentation of all media, all layouts and interactive controls. Therefore, SMIL is not a substitute for flash, mpeg-4, or HTML. Rather, it is a new standard for describing and using all of these.
SMIL HistoryEdit
SMIL is still being developed. Currently, attempts are being made to make SMIL easier to use in web browsers. Since SMIL is XML, the W3C developed the latest standard as an addendum to the hybrid of XML and HTML (XHTML). The following is an outline of the history of SMIL.
- The SMIL 1.0 specification defined the layout and time sequence of multimedia elements.
- The HTML+TIME specification introduced Timing, Linking, Media, and Content controls to HTML elements.
- The SMIL 2.0 specification brought interactivity (i.e.: HTML+TIME) such as media linking and controls.
- BHTML proposal included transitions to be used in SMIL 2.0
- Finally, the XHTML+SMIL specification extends SMIL 2.0 capabilities to XHTML elements.
When fully realized and implemented in the latest web browsers, XHTML+SMIL will be able to define how media elements can be controlled. HTML supports only static images and links. Web browsers use plug-ins to show videos and other media objects, so the control and interaction of the objects is left to the implementation of the plug-in. With XHTML+SMIL, the supported objects can be placed, moved or displayed according to a time-frame, interacted with using custom controls, and linked to other media objects, web pages or presentations. And since XML is extensible, support for more media objects is on the horizon. This technology has the potential to make the WWW far more interactive, allowing presenters far more control over presentations.
The current SMIL 2.0 is comprehensive and fairly complete. It is divided into modules which describe different aspects of the presentation. For example, there is a structure module to describe the structure of the SMIL document itself, and there is a metadata module for describing what the SMIL document is all about. Modularity is useful for extending the SMIL schemas on a module-to-module basis when necessary, without causing unwanted interactions with the elements in other modules.
Implementing SMILEdit
Common SMIL implementationsEdit
- Internet or Intranet presentations.
- Slide show presentations.
- Presentations which link to other SMIL files.
- Presentations which have Control buttons (stop, start, next, ...)
- Defining sequences and duration of multimedia elements.
- Defining position and visibility of multimedia elements.
- Displaying multiple media types such as audio, video, text
- Displaying multiple files at the same time.
- Displaying files from multiple web servers.
Currently, SMIL's most widespread usage is with MMS. MMS (Multimedia Messaging System) is a mobile device technology that is used as an envelope for sending multimedia messages to cellphones. SMIL content is placed inside the MMS message along with any associated media binaries. In this context, MMS is a kind of transport mechanism for SMIL.
SMIL files and MIME TypesEdit
- SMIL files have the extension *.smil (but can also have *.sml, *.smi)
- SMIL files contain tags and content necessary for showing a presentation. This includes the layout of multimedia elements, the timeline for the elements and the source for the multimedia files.
In order for a MIME user-agent to recognize SMIL 2.0 files, the user-agent needs to be defined:
- application/smil [deprecated]
- application/smil+xml [current MIME type]
- application/xhtml+smil [MIME type for embedding smil in XHTML]
When adding this new mime-type to a web browser, the definition will need to include the 'smil' extension.
SMIL SchemaEdit
The following hyperlink will direct you to the SMIL 2.0 Schemas, provided by the W3C.org. The main schema is a general description of SMIL 2.0 modules. It is followed by each module's schema. The main schema contains the include statements for all of the module's schemas.
W3C.Org's SMIL Schema description
SMIL Namespace DeclarationsEdit
SMIL 2.0 files need to have the following namespace declaration in the beginning <smil> tag:
SMIL 2.0 namespace
SMIL 1.0 files have the following namespace declaration:
SMIL 1.0 namespace
If no default namespace is declared within the
<smil>
root element, the document will be processed as SMIL 1.0.
SMIL SyntaxEdit
Guidelines and RulesEdit
SMIL documents look a lot like HTML. SMIL files need to be written according to the following rules:
- SMIL documents must follow the XML rules of well-formedness.
- SMIL tags are case sensitive.
- All SMIL tags are written with lowercase letters.
- SMIL documents must start with a <smil> tag and end with a </smil> closing tag.
- SMIL documents must contain a <body> tag for storing the contents of the presentation.
- SMIL documents can have a <head> element (like HTML) for storing metadata information about the document itself, as well as presentation layout information.
SMIL templateEdit
SMIL 1.0 template
A Simple SMILEdit
Abbreviated SMIL markup
<?xml version="1.0" encoding="ISO-8859-1"?> <smil xmlns=""> <head> <!-- The layout section defines regions in which to place content --> <layout> ... </layout> <!-- Transitions defined in head act on content defined in body --> <transition id="fade" type="fade" dur="1s"/> <transition id="push" type="pushWipe" dur="0.5s"/> </head> <!-- The body section defines the content to be used and how it will be displayed --> <body> <par> <img src="imagefile.jpg" transIn="fade"/> <video src="soundfile.aif" transOut="push"/> </par> </body> </smil>
An example SMILEdit
Example SMIL which has in-line text and an image
<smil xmlns=""> <head> <layout> <root-layout <region id="text1_region" left="0" top="0" width="160" height="120"/> <region id="text2_region" left="160" top="120" width="160" height="120"/> <region id="text3_region" left="80" top="60" width="160" height="120"/> <region id="image_region" left="0" top="0" width="320" height="240"/> </layout> </head> <body> <seq> <text src="data:text/plain,First%20Slide" region="text1_region" dur="2s"/> <text src="data:text/plain,Second%20Slide" region="text2_region" dur="3s"/> <text src="data:text/plain,Third%20Slide" region="text3_region" dur="3s"/> <img src="sample_jpg.jpg" region="image_region" dur="3s"/> </seq> </body> </smil>
Note that when using in-line text instead of referring to separate plain-text files as the text source, you will have to encode the text for any non-alphanumeric characters. This example uses '%20' in lines {13,14,15} as a space character. Also note that in line {13} the source for the text content begins with 'data:text/plain'. In SMIL 2.0 this is the default mime-type for text sources, so specifying it here is optional. In SMIL 1.0, however, this would have to be specified in order to use inline text.
SMIL 2.0 ModulesEdit
SMIL 2.0 divides the language description by functionality into ten modules. Each module contains elements to describe structure, content, actions or attributes. The following 10 modules are associated with the SMIL 2.0 namespace.
1. Timing 2. Time Manipulations 3. Animation 4. Content Control 5. Layout 6. Linking 7. Media Objects 8. Metainformation 9. Structure 10. Transitions
The timing module provides a framework of elements to decide whether elements appear concurrently, in sequence, or out of order and called by interactive events such as clicking on a hyperlink.
The time manipulations module provides the ability to associate media objects with time-related information such the as length of time a media object should be displayed, and a description of the timeline used as a frame of reference for the timing module.
The animation module allows media objects to be placed on a timeline defined by the time manipulations module.
The content control module allows for choices of which content is played, depending on such things as language and playback capabilities, using tags such as switch present a test of the system's capabilities.
The layout module contains elements that describe the spacial placement of media objects in the presentation.
The linking module describes hyperlinks and linking references to media objects.
The media objects module describes the pathing and typing of media objects.
The metainformation module contains elements that describe meta information about the SMIL file itself or the media objects it contains.
The structure module is a framework to describe the structure of the SMIL file such as the head and body and SMIL elements.
The transitions module is a framework to describe transitions such as wiping and fading between the presentation of media objects.
Viewing a SMIL fileEdit
In order to view a SMIL presentation, a client will need to have a SMIL player installed on his/her computer. Currently, Apple's Quicktime player, Windows Media Player (WiMP) and RealNetworks RealPlayer are among the most popular media players. slowly incorporating SMIL and other XML-related technologies such as SVG and MathML into their browsers, but progress is slow. It is possible they are waiting for these XML-based languages to mature.
Embedding SMIL files into XHTML web pagesEdit
As mentioned, SMIL is not yet native to web browsers, so in order to put SMIL in a web page, one must embed it and open it in a plug-in. Embedding SMIL files into web pages is somewhat beyond the scope of this chapter. However, should you have a need to do this, the following links are included as references to help you.
- Embedding a SMIL file is easy to do with Apple's Quicktime media player.
- Use the Windows Media Player to view SMIL files in a web page on a non-IE browser.
- The Internet Explorer 5.5+ browser has support for SMIL.
- Visit this W3Schools page for details on how to use SMIL in IE-only web pages.
SMIL for phonesEdit
As mentioned, SMIL is often used in the latest cellular phones. Phones and vendors have varied support for MMS (multimedia messaging service), but generally, MMS uses SMIL to define the layout of multimedia content. If the MMS message contains a SMIL file, it will include other media objects, which can be text or binary (text is treated here as a media object or file to be referenced in a smil file).
Just a general note on MMS: the telecommunications industry needed a system in order to charge for messages by throughput as well as a system for pushing multimedia messages from phone to phone, computer to phone or phone to computer. MMS is a standard, international system for these purposes. SMIL was adopted because it was a well-defined, standard language to describe the layout and timing of the content inside MMS messages. In adhering to these (and other) standards developed by the 3GPP in partnership with the European Telecommunications Standards Institution (ETSI) and the W3C, the industry was able to ensure interoperability of new services between vendors, providing mutual benefit and equal opportunity.
SMIL tools and SMIL InfoEdit
Given that WikiBooks is a publicly-available 'open' book, it would be inappropriate to include information about or links to any commercial SMIL tools. In other words, everything that is not free or open source is not considered here.
Just a sidenote: some commercial tools cost upwards of $800. It is therefore in our best interest to evaluate, provide feedback for, and contribute to opensource projects.
The following are useful links (March 18th, 2004) to free and opensource tools, current SMIL projects, specifications, and tutorials:
- The official W3C SMIL page
- X-Smiles - a Java-based, "an open XML browser for exotic devices." Supports XSLT, XSLFO, SMIL, XForms and SVG.
- Ambulant's Open SMIL Player
- W3school's excellent tutorial on SMIL.
- PerlySMIL is a perl script for generating SMIL files from perl.
- LimSee2 - is an opensource, Java application for generating SMIL. It is this author's experience that several media-related Java dependencies must be properly installed before LimSee2 will work properly.
SMIL in netbeans?Edit
One can create a SMIL file in Netbeans just as one would create an XML file. Just type it up and save it as a SMIL file. You can check for well-formedness, but validation might be trickier. As mentioned previously, SMIL 2.0 requires a namespace declaration, so don't forget it.
For our simple exercises, just type up a well-formed SMIL document and save it as .smil That's it!
SummaryEdit
We've seen how SMIL could be used to make standalone presentations. Yet the future of SMIL may be in the connection of mobile devices to the internet. As XML standards and SMIL tools reach maturity, SMIL will be increasingly implemented in order to define interactive presentations in the same way that Macromedia FLASH does, only this presentation will be native to web browsers and micro browsers used in mobile devices. Since SMIL is an open standard and it is extensible, there will likely be other applications which will use also SMIL.
Visionaries foresee the increasing ubiquity of the internet in our homes and work, on computers and mobile devices. This ubiquity is also called 'pervasive computing'. Mobile commerce would be an example of pervasive computing as cellular phones and portable devices become more useful for business and location-based services. SMIL is a language which facilitates this trend by providing either a pretty face for future business services or value-added multimedia content.
SMIL ExercisesEdit
-.
- Take an existing Openoffice.org present (or PowerPoint) presentation and turn it into a SMIL file. Double check it in a SMIL browser.
- Embed one of the previously created SMIL files into an XHTML web page and store the SMIL file and web page on a server. Confirm that the SMIL file works for two different computers.
SMIL AnswersEdit
ReferencesEdit
Ayars, J., Bulterman, D., Cohen, A., et al. (ed., 2001). Synchronized Multimedia Integration Language (SMIL 2.0). Retrieved April 4, 2004 from the World Wide Web Consortium Dot Org Web Site:
Castagno, Roberto (ed., 2003, January). Multimedia Messaging Service (MMS); Media formats and codes. Retrieved April 4, 2004 from the Third Generation Partnership Project (3GPP) Dot Org Web Site:
Michel, T. (2004, March). Syncronized Multimedia (n.a., n.d). Retrieved April 4, 2004 from the World Wide Web Consortium Web Dot Org Site:
Newman, D., Patterson, A., Schmitz, P. (ed., 2002, January). XHTML+SMIL. Retrieved April 4, 2004 from the World Wide Web Consortium Dot Org Web Site:
SMIL Tutorial Home (n.d.). Retrieved April 4, 2004 from the W 3 Schools Dot Com Web Site: | https://en.m.wikibooks.org/wiki/XML_-_Managing_Data_Exchange/SMIL | CC-MAIN-2014-15 | refinedweb | 2,904 | 56.45 |
Providing Technology Training and Mentoring For Modern Technology Adoption
In this tutorial, you will learn how to use Eclipse to write Java code.
Eclipse is a Java Integrated Development Environment (IDE). It is a GUI-driven and tool-assisted program that we can use to develop Java code in an effective and efficient manner. While developing Java code does not necessarily require an IDE (all the exercises in this lab guide could be achieved by using a simple text editor and the command line compiler), using an IDE will greatly simplify development and decrease coding time. As such, we will use Eclipse to develop all our code in this tutorial.
Install Eclipse before you start working on this tutorial.
It can be downloaded from here.
We will begin by launching Eclipse and exploring some of its facets.
1. Open a file browser and navigate to C:\Software\eclipse.
2. Run eclipse.exe by double clicking on the file.
The Workspace Launcher dialog will appear.
3. Change the Workspace to C:\workspace as shown below.
4. Click OK.
Eclipse will start, and the Welcome screen may be shown.
5. Close the Welcome screen.
6. From the menu bar, select Window | Perspective | Open Perspective | Java.
What has happened? Simple: you have changed perspective. A perspective in Eclipse is a collection of views chosen to achieve a specific task. We are currently looking at the Java perspective, for which Eclipse opens the appropriate views.
A view is simply a tiled window in the Eclipse environment. For example, in the screen shot above, you can see the Package Explorer view, the Task List view, and part of the Outline view.
Look at your Eclipse environment and locate the following views:
The Problems view. This should be at the bottom of the Eclipse environment. Any coding/compile errors you make will be displayed here and (in a fit of unbridled pessimism) you will most likely be referring to this view quite a bit.
The Package Explorer. This is on the left of the IDE.
This will allow us to navigate through the Java classes we will be creating shortly.
7. Open the Javadoc view. To find it, click the Javadoc tab next to the Problems tab.
8. You can switch between the two views by clicking the appropriate tabs.
9. Similarly, locate the Declaration view.
The big empty space in the middle of the IDE does not look very interesting right now; that is because it is the Code view – and we currently do not have any code to display. Do not worry about it for now.
10. Each view can be moved and resized. Click on the Package Explorer tab and drag it over the area where the Problems view is. Note that the view “docks”. Experiment with resizing and moving. Don't worry about “messing up” the perspective, because we will reset it in a moment.
11. From the menu bar, select Window | Perspective |Reset Perspective and click OK in the box that appears. All the views should “reset” to their original layouts. Note that it is possible to Save a perspective that you have changed. This allows you to customize exactly which views you want open and how you want them laid out. This is something you will probably do as you become more experienced with Eclipse.
Before we can create any Java code, we first need to create a Java Project. A project in Eclipse is essentially a folder for related files. We will create a new project and then create our classes in that project. Later on, if we work on a completely unrelated Java class, we could then create a separate, new project and create those classes in there. This helps keep our code environment organized.
1. From the menu bar select File | New | Java Project
Eclipse can actually handle many different types of projects, depending on the code that needs to be developed. In our case, we will create a simple Java project.
The New Java Project wizard will begin.
Here, we will describe the details of the Java project that will contain our simple HelloWorld Java.
2. Set the Project name: to be SimpleProject and click Finish.
The project will be created. How do you know the project was created? Simple. Look in the Package Explorer view.
You should see the newly created project listed there. Our Java code will go in this project.
Recall that in Java, all code must be contained within a Java class. Within a class, code is typically placed within methods, and any class can have a main method which will serve as its “executable” method.
We will now create a Java class called “HelloWorld” that will have a single main method, and this method will simply print out “Hello World” to the console.
1. In the Package Explorer view, right click on SimpleProject and select New | Class
The New Java Class window will appear.
This wizard will create a new Java class for us, and allows us to specify some options on the class. When we click the Finish button on this wizard, Eclipse will generate a new Java class according to the options we specify here. Wizards like this are one of the reasons that Eclipse is so useful; while it would have been possible to generate the class ourselves, Eclipse does it much faster.
Most importantly, we need to give the class a name.
Java classes should also belong to a package, for naming convention reasons. Think of a package as a name prefix. Imagine you are working at an insurance company in a Claims department, and you create a class called Account. However, imagine that another developer that you are working with (same company, but in the Billing division) also creates a class called Account. These two classes are completely different, but have the same name. How would we know which one to use?
The answer is that each class can be placed in a package. A package is a string of characters separated by periods (e.g. com.mycompany.www). The characters can be anything (although typical Java naming convention usually has your company name or URL as a part of the package name), and it is pre-pended to the class name. So a “fully qualified” class name is the name of the class preceded by its package.
In the example above, the Billing department could be assigned a different package name from the Claims department; so there could be com.insuranceco.billing.Account and com.insuranceco.claims.Account as two separate entities. Even though the classes are both called Account, they belong to unique packages, thus allowing for differentiation.
In any case, we will use the New Java Class dialog to specify a class name and package name for our new class.
2. For the Package enter com.simple and for the name, enter HelloWorld
3. In the section What method stubs would you like to create? make sure that the box for public static void main(String[] args) is checked.
This means that when the class is created, Eclipse will automatically generate the main method for us.
You can ignore the rest of the options for now.
4. Click Finish
Eclipse will now generate the Java class. A lot has now changed in the various views. Firstly, the empty space that was in the center of the environment is now showing Java code. This is the Code Editor view, and it is showing the results of the New Java Class wizard's generation. Examine it.
Firstly, notice that the class this view is currently showing is called HelloWorld.java. You can tell this by looking at the name of the tab.
This Code Editor view is editable. You can place the cursor inside this view and type away; this is where you will do your coding. However, before we examine the code, let us examine some of the other views.
5. Examine the Package Explorer view.
6. The Package Explorer provides us with a high-level navigable view of each project and their contents. At the moment, the only project is our SimpleProject
Note the tree structure. The top level is our project (SimpleProject) and immediately underneath that is the package com.simple
Beneath the package is our class, HelloWorld.java. If you double-clicked on it (or any other class that might be listed here), Eclipse would open it in the code editor window.
If we created new packages/classes in the project, they would similarly appear here in the tree structure.
7. Examine the Outline view.
This view presents a summary of the class that is currently open in the code editor view. At the moment, it is examining the HelloWorld class (as represented by the green C) that belongs to the com.simple package. The outline is also showing that the class currently has one method: a static public method called main(String[]). We know it is a public method because of the green circle next to it, and we know that the method is static because of the S. (We will discuss the concept of static and public modifiers later on).
Remember that this view is just a summary of the Java class. As we add/remove code from the actual Java class, this view will update accordingly.
Turn your attention back to the code editor window. Let us examine the actual Java code now. All this code has been generated for us by Eclipse as a convenience.
Notice that the code is color coded. Keywords are in purple, comments are in blue and the remaining text is in black. Also notice the use of curly braces '{' and '}' to denote where classes and methods end and begin.
8. Look at the first line:
package com.simple;
This the package declaration. This should always be the first line in a Java class. This line simply states that the following class belongs to the com.simple package.
9. Examine the next line:
public class HelloWorld {
Here, we declare the class. We are saying that this is a new class that is called HelloWorld and that it is public (we will discuss public modifiers later).
This is followed by an opening curly brace '{'. Later, at the end of the file, this should be matched with a corresponding closing curly brace '}'. Locate this closing brace now.
Any code in between these braces will be considered belonging to this class. This shows the use of braces to indicate scope.
An unmatched curly brace pair will be flagged as an error and the code will refuse to compile. An important part of Java programming is learning how to properly open/close scope.
10. Examine the next few lines:
public static void main(String[] args) {
// TODO Auto-generated method stub
}
This is a method. The first line declares the method. It is a public method that is static, and its return type is void. It also takes one argument: an array of String objects. This argument is called args.
Remember that main is a special method. Since this HelloWorld class has such a main method, it can be “run”. When the class is run, any code inside this method will be executed. Not all classes will necessarily have main methods, however.
Again, note the use of curly braces to denote where the method begins and ends. Just like the class declaration, any code that is in between these braces will be a part of this method.
Currently, the body of the method only has one line and that line is a comment that was placed there by Eclipse. A comment is a piece of non-code text that is placed within code as a note to the person reading the code. It can form the basis of documentation, or simply serve as helpful reminders as to what the code is doing for anyone reading the code. Comments in Java can either be preceded with a // sequence, or surrounded by a /* and */ sequence. Remember that this is non-code which means the compiler will not attempt to process it.
Keeping this in mind, we can see that the method currently does nothing. Let us change this now.
11. Using the editor, delete the line
// TODO Auto-generated method stub
12. Replace it with the following line:
System.out.println("Hello World");
What is this line doing? This line is invoking the println method of System.out and passing the string “Hello World” to it. System.out is an object that is provided by the Java language itself and represents the “console” (the default location where Java outputs to; typically, the screen).
println is a method that is provided for System.out and it takes one argument: a String object representing what needs to be printed. (Objects will be discussed in more detail in class)
Pay special close attention to the brackets '(' and ')' as well as the trailing semi-colon. Every Java statement should end with a semi-colon.
13. Your code is complete. Save your code by going to File → Save or by typing Ctrl-S.
14. Check the Problems view. It should be empty.
If you had made any code mistakes (e.g. typos, syntax errors, etc), an item would have appeared in the list.
If any errors are there right now, go back and double check the code you typed in. Correct any mistakes you find. Do not proceed until there are no problems listed here.
15. Your code is now complete. The next step is to run it.
Now that we have completed writing the code, we can run it to see the results. Running Java code implies launching an instance of the Java Virtual Machine (JVM), and then loading the appropriate Java class and executing its main method. Fortunately for us, Eclipse makes that simple.
1. Click anywhere in the code editor and select Run | Run As | Java Application from the menu bar.
Troubleshooting
If you don't see the option Java Application under Run | Run As, click in the code editor and try again. Alternatively, you can select HelloWorld.java in the Package Explorer view. As you can see, Eclipse is context sensitive.
A new view (the Console view) should appear in the same area where the Problems view is. Any text sent to the console (e.g. by a call to System.out.println()) will appear in this view.
Voila! Our Java code has executed and Hello World has been printed. Congratulations. You have written and run your first Java class.
Just as an exercise, let us change the code a little.
1. Let us now introduce an error to see what sort of error handling features that Eclipse offers. Delete the closing " mark from the println statement and save your code.
What happens?
Note that a red X has appeared in the tab title (next to “HelloWorld.java”). This indicates there is an error in the class.
2. Also note that in the left margin a similar red X has appeared on the same line that the error occurs on. Finally, note that the un-closed string (“Hello World); is itself underlined in red.
3. Float the mouse cursor over the red underline.
A little pop up appears with a description of the problem. This is a hint to tell you what the corrective action should be. Do no fix it yet though!
4. Locate the Problems view. Expand Errors.
Note that the error in our code has been detected. You may have to resize the Description field to see the whole text. This view shows what resource (Java file) the error occurs in, and even shows the line number. This becomes invaluable if you are working on multiple Java files. Finally, if you double click on the error listed doing so will open the editor on the exact spot where the error is. Again, this is invaluable if you are working with multiple Java files.
5. Finally, click on the red X in the left margin.
6. Two boxes pop-up. Ignore the box in yellow; it is the box in white that is interesting. Eclipse has located the error and is actually suggesting a fix!
7. Double click where it says Insert missing quote
Eclipse has indeed added a closing quote mark, but unfortunately in the wrong location (after the semi-colon, instead of before the closing bracket). Let us see what this “fix” does.
8. Save the file.
9. Look at the Problems view. There are now two errors! So while the fix suggested by Eclipse was on the right track, it ended up doing more harm than good.
10. Fix the errors properly (by putting the quote in the right place, immediately after World and save the file. Make sure all the errors are gone.
From this, you should see that the error handling features of Eclipse are quite thorough; however, you should also see that it is not perfect. Additionally, Eclipse can only catch compile time errors (i.e. syntax errors and errors in the actual code) and not run time errors. The difference should become clear to you as work through the rest of these lab exercises.
11. Immediately after the existing System.out line, add another line of code as follows.
System.out.println("Goodbye, cruel world!");
If you are not particularly conscious about using tabs, spacing, and line breaks properly in your code (i.e. code style), it can end up looking a little disorganized. Fortunately, Eclipse can format code for us so it looks neatly arranged.
12. Right click anywhere in the code editor and select Source | Format.
If your code was not “neatly” written, it will be miraculously re-formatted to look perfectly neat and organized.
Note that in the tab for the code editor (where the file name HelloWorld.java is displayed) an asterisk has appeared. This is to indicate that the file was changed, but has not been saved.
13. Save the file. Notice that the asterisk in the code editor tab disappears, indicating the file has been saved. This means the file is “current”. There should be no errors. It should look like the following.
14. Run the code again. (To do this, go to the menu bar and select Run | Run As | Java Application.)
The console window should show your new updated output.
15. Close Eclipse by select File | Exit.
16. Confirm by clicking OK.
Don't worry about losing the state of your project; the next time you open Eclipse, it will remember what your last state was.
In this tutorial, you explored Eclipse and coded your first Java class.
You saw that a Java class has a name and (usually) a package. It has methods and its method/class scope is determined by braces. You learned how to print something to the console by invoking the System.out.println command.
Using Eclipse , you created a Java project to contain the HelloWorld.java class. You learned about perspectives and views, and used wizards to generate some code for you. Finally, you also saw some of the error-handling features of Eclipse.
Your email address will not be published. Required fields are marked * | https://www.webagesolutions.com/blog/archives/4536 | CC-MAIN-2019-47 | refinedweb | 3,206 | 75.61 |
how to translate the windows python script to linux version
Hello
Getting the import module error while i run the script in linux, below are the import statements
from soaptest.api import *
from com.parasoft.api import *
from java.lang import *
from java.text import *
from java.util import *
from java.io import *
These works fine in windows, however in linux its failing:
"ImportError: No module named soaptest.api" occurs.
Can someone direct , how can it be rectified in linux
0
Hi Jas,
There should not be any changes between Windows and Linux for the importation of libraries.
I have tested the import of these libraries on Linux and did not receive this message.
Have you noticed any other unexpected behavior with SOATest? It may be possible that you have a corrupted installation, with missing libraries. | https://forums.parasoft.com/discussion/comment/8242 | CC-MAIN-2018-34 | refinedweb | 136 | 68.16 |
On Sun, Dec 12, 2010 at 10:55 PM, Noel J. Bergman <noel@devtech.com> wrote:
>> b) This upcoming release still has com.sun packages in it.
>
> Is there any concern regarding permitted use of the com.sun package?
>
> Other than that, which may be ado about nothing, I'm fine with the proposal.
The com.sun namespace comes with the original donation from Sun, which
we have a full Software Grant on.
The original intent of the Jini specification was that only the
net.jini.* namespace was supposed to be used by application built on
top, but very early this was breached both by recommendation and by
lack of enforcement. So, at the moment, there are a handful of classes
in the com.sun.* space which is considered part of the 'official' API,
or at least recommended as 'work-around' for certain recurring issues
people have.
Looking back in history, Jini v1.0 had some classes in com.sun.* which
in subsequent releases got 'promoted' to net.jini.* namespace, and
that should be the recommended move forward here too.
Cheers
--
Niclas Hedhman, Software Developer - New Energy for Java
I live here;
I work here;
I relax here;
---------------------------------------------------------------------
To unsubscribe, e-mail: general-unsubscribe@incubator.apache.org
For additional commands, e-mail: general-help@incubator.apache.org | https://mail-archives.eu.apache.org/mod_mbox/incubator-general/201012.mbox/%3CAANLkTik4W-UjoZnPLpTF8pDAaC3JxFTcWqueuipF+-xA@mail.gmail.com%3E | CC-MAIN-2021-21 | refinedweb | 217 | 59.19 |
# Digital Forensics Tips&Tricks;: How to Connect an Encase Image to the Virtual Machine
I pretty often meet the question: how to attach an Encase image (.e01) to the virtual machine as a primary bootable disk? Sometimes a digital forensics experts need to boot up the image of the researching machine. It's not so hard actually, but this task has it's hidden stones which ones must be counted.
For this case I'll use a VMware Workstation for Windows and VirtualBox for Linux as a virtualization platforms.
**Windows Part**
1. Open FTK Imager and mount the .e01 image as a **physical** (only) device in **Writable** mode

2. Notice a resulting device name. In this case it's a **PhysicalDrive3**
3. Open VMware Workstation and create a new VM, but **don't create a virtual disk** (or remove one if exist). You have to choose **Use a Physical Disk** in New VM wizard or add a new virtual disk as primary to the existing VM. You remember that our .e01 image is **PhysicalDrive3** now

4. So, you just need to start a VM and watching some IT magic

**Linux Part**
1. The mostly typical tool using to attach .e01 images is ewfmount.py script. But there is a one hard limitation — this image being attached in **Read-only mode**. It's inappropriate for virtual machine. Therefore we'll use **xmount** command like:
```
sudo xmount --in ewf --cache --out vdi
```
The main features of xmount for us — it mounts the image in Read-Write mode and it can take a lot of image types on input. You can check for xmount syntax [here](https://github.com/mika/xmount/blob/master/README).

2. Ok, now we have a .vdi image in /mnt/windows\_mount
3. Let's open a VirtualBox and create a new VM with our .vdi image (choose existing disk) as a primary disk

4. Finally just boot up the VM and enjoy!
 | https://habr.com/ru/post/444940/ | null | null | 379 | 51.44 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
Filter a one2many field with a search view
In a form view of a project.project model, I display related calendar.event records through a one2many field as a kanban
I'd like to filter that kanban view, but it doesn't work as described below.
On the form, I added the following field:
<field name="event_ids" mode="kanban"/>
The kanban shows up nicely on the form. Actually, a kanban view has been applied by default: the one that has the lowest sequence id.
As the system selected a kanban view, I assumed a search view is also applied by default.
The search view with the lowest sequence id is the following:
<record model="ir.ui.view" id="view_calendar_event_mysearch">
<field name="name">calendar.event.mysearch</field>
<field name="model">calendar.event</field>
<field name="arch" type="xml">
<search string="My search view">
<field name="allday"/>
<filter string="Full day events" name="filter_on_fullday" domain="[('allday','=',True)]"/>
</search>
</field>
</record>
If the search view would have been called from an action, I could have indicated a default filter in the act_window, like:
<field name="context">{'search_default_filter_on_fullday': 1}</field>
which made me think I could define a context on the field, like:
<field name="event_ids" mode="kanban" context="{'search_default_filter_on_fullday': 1}"/>
I must be missing something in my reasoning, because it doesn't work.
Maybe, no search view is selected by default. Can someone confirm?
How can I force a search view? And once a search view is applied, would it use the default filter?
If there is a search view, how can I tell the search view to execute the filter?
Thank you for your help.
Here is the solution.
In order to filter a one2many field on a form, the trick is to make a computed field, from the initial one2many field.
In my case, event_ids is the field I want to filter, in order to show only full day events.
In the model, I simply added a computed field, as follows:
event_fullday_ids = fields.One2many('calendar.event', string='Full day events', compute='_get_event_fullday_ids')
And the function is:
def _get_event_fullday_ids(self):
self.event_fullday_ids = self.event_ids.search([('allday', '=', True)])
Then, instead of showing
<field name="event_ids" mode="kanban"/> on the form
I put this instead:
<field name="event_fullday_ids" mode="kan | https://www.odoo.com/forum/help-1/question/filter-a-one2many-field-with-a-search-view-103761 | CC-MAIN-2017-09 | refinedweb | 405 | 65.01 |
Code Inspection and Quick-Fixes in XAML
The key features of ReSharper's code analysis are also supported in XAML. You can find the detailed information on these features in the corresponding topics of the Code Analysis section. In the main topic of the section, you can also find the feature matrix and check what exactly is supported in XAML.
In this topic, you can find some examples of using code analysis features in XAML.
Code Inspection
ReSharper detects various problems in XAML files, such as unresolved symbols, incorrect document structure, unused import directives, and so on. Whenever a problem is encountered, ReSharper highlights it and displays some description in a tooltip. In the example below, ReSharper warns that the namespace alias is not used inside the current file and highlights it in grey:
In the following example, ReSharper highlights a problem with resolving a method inside an event subscription:
The analysis is performed by applying Code Inspections to the current document or in any specified scope.
To look through the list of available inspections for XAML, open the Alt+R, O ), and then expand the XAML node.page of ReSharper options (_2<<.
Remove type qualifier
When the type, to which the style should be applied, is specified in the
TargetType attribute, there is no need to add a qualifier for each property of the
Button class. ReSharper detects such cases and offers the quick-fix.
| https://www.jetbrains.com/help/resharper/Code_Analysis_in_XAML.html | CC-MAIN-2021-04 | refinedweb | 236 | 50.16 |
Besides working on Pex, for the last year I have been driving forward a new research project, SPUR.
SPUR is a “Trace-based JIT Compiler for CIL”, and it works especially well for dynamic languages, in particular JavaScript.
Now, what does “Trace-based JIT Compiler for CIL” mean anyway? In a nutshell, it translates .NET code to machine code, similar to how the normal .NET Framework would do it. What is new in our research prototype is that SPUR optimizes the code while it is running.
Consider the following example. It is written in C#, and it shows a basic problem that appears in dynamic languages such as JavaScript, where all values are (potentially boxed) objects. An interface IDictionary describing a general mapping from objects to objects is used in method ArraySwap with the implicit assumption that it is a dense array, mapping integers to doubles.
interface IDictionary {
int GetLength();
object GetElement(object index);
void SetElement(object index, object value);
}
...
void ArraySwap(IDictionary a) {
for (int i = 0; i < a.GetLength() - 1; i++) {
var tmp = a.GetElement(i);
a.SetElement(i, a.GetElement(i + 1));
a.SetElement(i + 1, tmp);
}
}
Is this ArraySwap method efficient? Without knowing more about the particular IDictionary implementation that is going to be passed in, that is hard to tell. Let us use the following implementation of IDictionary, which can only store floating point values in a dense array:
class DoubleArray : IDictionary {
private double[] _elements;
...
public int GetLength() {
return _elements.Length;
}
public object GetElement(object index) {
return (object)_elements[(int)index];
}
public void SetElement(object index, object value) {
_elements[(int)index] = (double)value;
}
}
Now it becomes clear that the arguments and results of GetElement and SetElement are going to be continually boxed, type-checked for proper types, and unboxed. Wouldn’t it be nice if the entire code could be automatically optimized as a whole, to get rid of all the fluff?
Our current research prototype of SPUR does exactly this kind of optimization for us fully automatically: First, SPUR monitors which portions of the code are executed a lot. Then SPUR collects traces of the hot code paths, in order to analyze and optimize the traces. Only a few simple checks, called guards, need to remain in place which ensure that all explicit and implicit branching decisions that were observed during tracing will repeat later on. If not, then the optimized code will jump back into unoptimized code. Here, we need guards to ensure that the actual dictionary is not null and actually has type DoubleArray, that a._elements is not null, and also that “i” is a valid index, and fulfills the loop condition. All virtual method calls can be inlined, all boxing, type-checks and unboxing code eliminated. Most guards can be hoisted out of the loop, and code similar to the following is produced by SPUR for the loop, preceeded by the hoisted guards. Note the slim loop body which no longer performs any virtual method calls, boxing or unboxing, but just the actual work. After the transformation, the code runs about four times faster.
if (a == null ||
a.GetType() != typeof(DoubleArray))
{ ... /* transfer back to unoptimized code */ }
var elements = a._elements;
if (elements == null)
{ ... /* transfer back to unoptimized code */ }
var length1 = elements.Length - 1;
while (true) {
if (i < 0 || i >= length1)
{ ... /* transfer back to unoptimized code */ }
double tmp = elements[i];
elements[i] = elements[i + 1];
elements[i + 1] = tmp;
i++;
}
This works well for any .NET program, and it works especially well for dynamic languages, in particular JavaScript. You can read about the current status of this research project in this technical report.
There is an interesting relation between Pex and SPUR: Both analyze program traces, gathered from monitoring actual program executions. While Pex is looking for branches in the code that can be “flipped” (if so, Pex generates another test input, possibly uncovering a bug), SPUR is looking for branches that cannot be “flipped” (if so, SPUR can remove it, and make the code run faster). | http://blogs.msdn.com/b/nikolait/archive/2010/03/28/spur-a-trace-based-jit-compiler-for-cil.aspx | CC-MAIN-2014-23 | refinedweb | 666 | 55.44 |
Web Application Development with JSP and XML Part III: Developing JSP Custom Tags
By Qusay H. Mahmoud
01 Aug 2001 | TheServerSide.com care to learn its syntax. While JavaBeans.
This article presents a brief overview of custom tags, then it shows:
- How to develop and deploy simple tags
- How to develop and deploy advanced tags: parameterized tags and tags with a body
- How to describe tags with the Tag Library Descriptor (TLD)
Finally, some programming guidelines are also provided.
Overview of Tags
If you have experience with HTML, you already know about the types of tags that can be used. Basically there are two types of tags, and both can have attributes (information about how the tag should do its job):
- Bodyless Tags: A bodyless tag is a tag that has a start tag but does not have a matching end tag. It has the syntax:
<tagName attributeName="value" anotherAttributeName="anotherValue"/>
Bodyless tags are used to represent certain functions, such as presenting an input field, or displaying an image. Here is an example of a bodyless tag in HTML:
<IMG SRC="/articles/content/JSP-XML3/fig10.gif">
- Tags with a Body: A tag with a body has a start tag and a matching end tag. It has the syntax:
<tagName attributeName="value" anotherAttributeName="anotherValue"> ...tag body... </tagName>
Tags with a body are used to perform operations on the body content, such as formatting. Here is an example of a tag with a body in HTML:
<H2>Custom Tags</H2>
JSP Custom Tags
JSP custom tags are merely Java classes that implement special interfaces. Once they are developed and deployed, their actions can be called from your HTML using XML syntax. They have a start tag and an end tag. They may or may not have a body. A bodyless tag can be expressed as:
<tagLibrary:tagName />
And, a tag with a body can be expressed as:
<tagLibrary:tagName> body </tagLibrary:tagName>
Again, both types may have attributes that serve to customize the behavior of a tag. The following tag has an attribute called
name, which accepts a String
value obtained by evaluating the variable
yourName:
<mylib:hello
Or, it can be written as a tag with a body as:
<mylib:hello> <%= yourName %> </mylib:hello>
Note: Any data that is a simple string, or can be generated by evaluating a simple expression, should be passed as an attribute and not as body content.
Benefits of Custom Tagsprogrammer.
Defining a Tag
A tag is a Java class that implements a specialized interface. It is used to encapsulate the functionality from a JSP page. As we mentioned earlier, a tag can
be bodyless or with a body. To define a simple bodyless tag, your class must implement the
Tag interface. Developing tags with a body is discussed later.
Sample 1 shows the source code for the
Tag interface that you must implement:
Sample 1: Tag.java
public interface Tag { public final static int SKIP_BODY = 0; public final static int EVAL_BODY_INCLUDE = 1; public final static int SKIP_PAGE = 5; public final static int EVAL_PAGE = 6; void setPageContext(PageContext pageContext); void setParent(Tag parent); Tag getParent(); int doStartTag() throws JspException; int doEndTag() throws JspException; void release(); }
All tags must implement the
Tag interface (or one of its subinterfaces) as it defines all the methods the JSP runtime engine calls to execute a tag. Table 1
provides a description of the methods in the
Tag interface.
My First Tag
Now, let's look at a sample tag that when invoked prints a message to the client.
There are a few steps involved in developing a custom tag. These steps can be summarized as follows:
- Develop the tag handler
- Create a tag library descriptor
- Test the tag
1. Develop the Tag Handler
A tag handler is an object invoked by the JSP runtime to evaluate a custom tag during the execution of a JSP page that references the tag. The methods of the tag handler are called by the implementation class at various points during the evaluation of the tag. Every tag handler must implement a specialized interface. In this example, the simple tag implements the
Tag interface as shown in Sample 2.
Sample 2: HelloTag.java
package tags; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class HelloTag implements Tag { private PageContext pageContext; private Tag parent; public HelloTag() { super(); }; } public void release() { } public void setPageContext(PageContext pageContext) { this.pageContext = pageContext; } public void setParent(Tag parent) { this.parent = parent; } public Tag getParent() { return parent; } }
The two important methods to note in
HelloTag are
doStartTag and
doEndTag. The
doStartTag method is invoked when the start tag is encountered. In this example, this method returns
SKIP_BODY because a simple tag has no body. The
doEndTag method is invoked when the end tag is encountered. In this example, this method returns
SKIP_PAGE because we do not want to evaluate the rest of the page; otherwise it should return
EVAL_PAGE.
To compile the
HelloTag class, assuming that Tomcat is installed at: c:tomcat:
- Create a new subdirectory called tags, which is the name of the package containing the
HelloTagclass. This should be created at: c:tomcatwebappsexamplesweb-infclasses.
- Save HelloTag.java in the tags subdirectory.
- Compile with the command:
c:tomcatwebappsexamplesweb-infclassestags> javac -classpath c:tomcatlibservlet.jar HelloTag.java
2. Create a Tag Library Descriptor
The next step is to specify how the tag will be used by the JSP runtime that executes it. This can be done by creating a Tag Library Descriptor (TLD), which is an XML document. Sample 3 shows a sample TLD:
Sample 3: mytaglib.tld
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.// DTD JSP Tag Library 1.1//EN" " web-jsptaglibrary_1_1.dtd"> <!-- a tag library descriptor --> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>first</shortname> <uri></uri> <info>A simple tab library for the examples</info> <tag> <name>hello</name> <tagclass>tags.HelloTag</tagclass> <bodycontent>empty</bodycontent> <info>Say Hi</info> </tag> </taglib>
First we specify the tag library version and JSP version. The
<shortname> tag specifies how we are going to reference the tag library from the JSP page. The
<uri> tag can be used as a unique identifier for your tag library.
In this TLD, we only have one tag named
hello whose class is specified using the
<tagclass> tag. However, a tag library can have as many tags as you like. The
<bodycontent> tells us that this tag will not have a body; otherwise an error will be produced. On the other hand, if you like to evaluate the body of the tag, that value would be:
tagdependent: meaning that any body of the tag would be handled by the tag itself, and it can be empty.
JSP: meaning that the JSP container should evaluate any body of the tag, but it can also be empty.
Save mytaglib.tld in the directory: c:tomcatwebappsexamplesweb-infjsp.
3. Test the Tag
The final step is to test the tag we have developed. In order to use the tag, we have to reference it, and this can be done in three ways:
- Reference the tag library descriptor of an unpacked tag library. For example:
<@ taglib uri="/WEB-INF/jsp/mytaglib.tld" prefix="first" %>
- Reference a JAR file containing a tag library. For example:
<@ taglib uri="/WEB-INF/myJARfile.jar" prefix='first" %>
- Define a reference to the tag library descriptor from the web-application descriptor (web.xml) and define a short name to reference the tag library from the JSP. To do this, open the file: c:tomcatwebappsexamplesweb-infweb.xml and add the following lines before the end line, which is
<web-app>:
<taglib> <taglib-uri>mytags</taglib-uri> <taglib-location>/WEB-INF/jsp/ mytaglib.tld</taglib-location> </taglib>
Now, write a JSP and use the first syntax. Sample 4 shows an example:
Sample 4: Hello.jsp
<%@ taglib <B>My first tag prints</B>: <first:hello/> </BODY> </HTML>
The
taglib is used to tell the JSP runtime where to find the descriptor for our tag library, and the
prefix specifies how we will refer to tags in this library. With this in place, the JSP runtime will recognize any usage of our tag throughout the JSP, as long as we precede our tag name with the prefix
first as in
<first:hello/>.
Alternatively, you can use the second reference option by creating a JAR file. Or, you can use the third reference option simply by replacing the first line in Sample 4 with the following line:
<%@ taglib uri="mytags" prefix="first" %>
Basically, we have used the
mytags name, which was added to web.xml, to reference the tag library. For the rest of the examples in this article, this reference will be used.
Now, if you request Hello.jsp from a browser, you would see something similar to Figure 1.
Figure 1: First Custom Tag
The custom tag developed in Sample 4 is a simple tag, the goal of it was just to give you a flavor of the effort involved in developing custom tags. You may have noticed that even this simple tag required us to implement a number of methods, some of which have very simple implementations. To minimize the effort involved, the JSP designers provided a template to be used for implementing simple tags. The template is the
TagSupport abstract class. It is a convenience class that provides default implementations for all the methods in the
Tag interface.
Therefore, an easier way to write simple tags is to extend the
TagSupport class rather than implementing the
Tag interface. You can think of the
TagSupport abstract class as an adapter. Having said that, the
HelloTag class in Sample 4 can be easily written as shown in Sample 5.
Sample 5: Extending the TagSupport class
package tags; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class HelloTag extends TagSupport {; } }
Parameterized Tags
We have seen how to develop simple tags. Now, let's see how to develop parameterized tags--tags that have attributes. There are two new things that that need to be added to the previous example to handle attributes:
- Add a set method
- Add a new tag to mytagslib.tld
Adding a set method and changing the output message results in Sample 5.
Sample 5: A tag with an attribute
package tags; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class HelloTagParam extends TagSupport { private String name; public void setName(String name) { this.name = name; } public int doStartTag() throws JspException { try { pageContext.getOut().print("Welcome to JSP Tag Programming, " +name); } catch (IOException ioe) { throw new JspException("Error: IOException while writing to client"); } return SKIP_BODY; } public int doEndTag() throws JspException { return SKIP_PAGE; } }
The next thing we need to do is add a new tag to mytaglib.tld. The new tag is shown in Sample 6. This snippet of code should be added to mytaglib.tld right before the last line,
</taglib>:
Sample 6: revising mytaglib.tld
<tag> <name>helloparam</name> <tagclass>tags.HelloTagParam</tagclass> <bodycontent>empty</bodycontent> <info>Tag with Parameter</info> <attribute> <name>name</name> <required>false</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag>
We have added a new tag named
helloparam. Notice the new
<attribute> tag, which specifies that the
helloparam tag accepts an attribute whose name is
name. The
<required> tag is set to
false, meaning that the attribute is optional; the
<rtexprvalue> tag is set to
false specifying that no run time evaluation will be done.
Nothing needs to be added to the web.xml web-application descriptor file since we are using the same tag library: mytaglib.tld.
Now, we can test the new tag. The source code in Sample 7 shows how to test it using a name attribute "JavaDuke".
Sample 7: HelloTagParam.jsp
<%@ taglib <B>My parameterized tag prints</B>: <P> <first:helloparam </BODY> </HTML>
If you request HelloTagParam.jsp from a web browser, you would see an output similar to that in Figure 2.
Figure 2: Testing a parameterized tag
Tag Libraries
A tag library is a collection of JSP custom tags. The Jakarta Taglibs Project provides several useful tag libraries for XML parsing, transformations, email, databases, and other uses. They can be easily downloaded and used.
Here we develop our tag library. As an example, we develop a simple math library that provides two tags, one for adding two numbers, and the other for subtracting one number from another number. Each tag is represented by one class. The source code for the two classes,
Add.java and
Subtract.java, is shown in Sample 8.
Sample 8: Add.java and Subtract.java
package tags; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class Add("The sum of: " + num1 + " and " + num2 + " is: " + ( num1+num2)); } catch (IOException ioe) { throw new JspException("Error: IOException while writing to client"); } return SKIP_BODY; } } // Subtract.java package tags; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class Subtract("If you subtract: " + num2 + " from " + num1 + ", you get: "+ (num1 - num2)); } catch (IOException ioe) { throw new JspException("Error: IOException while writing to client"); } return SKIP_BODY; } }
The source code is easy to understand. Notice one thing we have repeated in
Add.java and
Subract.java is the call to
pageContext.getOut.print. A better way to do this would be to get a
JspWriter object then then use it to print to the client:
JspWriter out = pageContext.getOut(); out.print("first line"); out.print("second line");
The next step is to revise the tag library descriptor file, mytaglib.tld, and add descriptions to the two new tags. Sample 9 shows the description for the new tags. Add the following snippet of XML to
mytaglib.tld, right before the last line.
Sample 9: revising mytaglib.tld
<tag> <name>add</name> <tagclass>tags.Add</tagclass> <bodycontent>empty</bodycontent> <info>Tag with Parameter</info> <attribute> <name>num1</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> <attribute> <name>num2</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag> <tag> <name>sub</name> <tagclass>tags.Subtract</tagclass> <bodycontent>empty</bodycontent> <info>Tag with Parameter</info> <attribute> <name>num1</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> <attribute> <name>num2</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag>
As you can see, each tag requires two attributes that must be named
num1 and
num2.
Now, we can test our math tag library using the test driver shown in Sample 10.
Sample 10: math.jsp
<%@ taglib <B>Calling first tag</B> <P> <math:add <P> <B>Calling second tag</B> <P> <math:sub </BODY> </HTML>
If you request math.jsp from a web browser, you would see an output that is similar to Figure 3.
Figure 3: Testing the math tag library
Tags with a Body
A tag handler for a tag with a body is implemented differently depending on whether the body needs to be evaluated once or multiple times.
- Single Evaluation: if the body needs to be evaluated once, the tag handler should implement the
Taginterface, or extend the
TagSupportabstract class; the
doStartTagmethod needs to return
EVAL_BODY_INCLUDE, and if it does not need to be evaluated at all then it should return
BODY_SKIP.
- Multiple Evaluation: if the body needs to be evaluated multiple times, the
BodyTaginterface should be implemented. The
BodyTaginterface extends the
Taginterface and defines additional methods (
setBodyContent,
doInitBody, and
doAfterBody) that enable a tag handler to inspect and possibly change its body. Alternatively, and similarly to the
TagSupportclass, you can extend the
BodyTagSupportclass, which provides default implementations for the methods in the
BodyTaginterface. Typically, you need to implement
doInitBodyand
doAfterBodymethods. The
doInitBodyis called after the body content is set but before it is evaluated, and the
doAfterBodyis called after the body content is evaluated.
Single Evaluation
Here is an example of single evaluation where we extend the
BodyTagSupport class. This example reads the body content, converts it to lowercase, then writes the output back to the client. Sample 11 shows the source code. The body content is retrieved as a string, converted to lowercase, then written back to the client.
Sample 11: ToLowerCaseTag.java
package tags; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class ToLowerCaseTag extends BodyTagSupport { public int doAfterBody() throws JspException { try { BodyContent bc = getBodyContent(); // get the bodycontent as string String body = bc.getString(); // getJspWriter to output content JspWriter out = bc.getEnclosingWriter(); if(body != null) { out.print(body.toLowerCase()); } } catch(IOException ioe) { throw new JspException("Error: "+ioe.getMessage()); } return SKIP_BODY; } }
The next step is to add a tag to the tag library descriptor file, mytaglib.tld. The new tag descriptor is:
<tag> <name>tolowercase</name> <tagclass>tags.ToLowerCaseTag</tagclass> <bodycontent>JSP</bodycontent> <info>To lower case tag</info> </tag>
Note that when you write a tag with a body, the
<bodycontent> tag's value must be either
JSP or
jspcontent, as discussed earlier.
A test driver for this example is shown in Sample 12.
Sample 12: lowercase.jsp
<%@ taglib <first:tolowercase> Welcome to JSP Custom Tags Programming. </first:tolowercase> </BODY> </HTML>
If you request
lowercase.jsp from a web browser, you would see something similar to Figure 4.
Figure 4: Testing the lowercase tag
Multiple Evaluations
Let's now see an example of a body tag evaluated multiple times. The example accepts a string and prints the string as many times as indicated in the JSP. The source code is shown in Sample 13:
Sample 13: LoopTag.java
package tags; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class LoopTag extends BodyTagSupport { int times = 0; BodyContent bodyContent; public void setTimes(int times) { this.times = times; } public int doStartTag() throws JspException { if (times>0) { return EVAL_BODY_TAG; } else { return SKIP_BODY; } } public void setBodyContent(BodyContent bodyContent) { this.bodyContent = bodyContent; } public int doAfterBody() throws JspException { if (times >1) { times--; return EVAL_BODY_TAG; } else { return SKIP_BODY; } } public int doEndTag() throws JspException { try { if(bodyContent != null) { bodyContent.writeOut( bodyContent.getEnclosingWriter()); } } catch(IOException e) { throw new JspException( "Error: "+e.getMessage()); } return EVAL_PAGE; } }
In this example, the methods implemented play the following roles:
- The
doStartTagmethod gets called at the start of the tag. It checks if the loop needs to be performed.
- The
setBodyContentis called by the JSP container to check for more than one loop.
- The
doAfterBodymethod is called after each evaluation; the number of times the loop needs to be performed is decreased by one, then it returns
SKIP_BODYwhen the number of times is not greater than one.
- The
doEndTagmethod is called at the end of the tag, and the content (if any) is written to the enclosing writer.
Similarly to previous examples, the next step is to add a new tag descriptor to mytaglib.tld. The following lines show what needs to be added:
<tag> <name>loop</name> <tagclass>tags.LoopTag</tagclass> <bodycontent>JSP</bodycontent> <info>Tag with body and parameter</info> <attribute> <name>times</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
Note that the
<rtexprvalue> tag specifies that evaluations will be performed at runtime.
A test driver is shown in Sample 14.
Sample 14: loops.jsp
<%@ taglib <first:loop Welcome to Custom Tags Programming.<BR> </first:loop> </BODY> </HTML>
Finally, if you request loops.jsp from a browser, you would see output similar to that in Figure 5.
Figure 5: Testing loops.jsp
Programming Guidelines
Here are a few guidelines to keep in mind when developing JSP tag libraries:
- Keep it simple: if a tag requires several attributes, try to break it up into several tags.
- Make it usable: consult the users of the tags (HTML developers) to achieve a high degree of usability.
- Do not invent a programming language in JSP: do not develop custom tags that allow users to write explicit programs.
- Try not to reinvent the wheel: there are several JSP tag libraries available, such as the Jakarta Taglibs Project. Check to see if what you want is already available so you do not have to reinvent the wheel.
Conclusion
In Web Application Development with JSP and XML Part II: JSP with XML in mind, we have seen how to parse XML documents. But even the untrained eye would have noticed that we have embedded lots of the parsing (or logic) code in JSP. Even though we have used JavaBeans to encapsulate much of the Java code, we still ended up with JavaServer Pages mixing program logic with presentation.
Custom tags help you improve the separation of program logic (parsing and iteration in Part II), and presentation. The various examples in this article show how to develop and deploy simple and advanced custom tags. As an exercise, you may want to rewrite the SAX and DOM examples in Part II as tag libraries. Also, you may wish to look at what the Jakarta Taglibs Project has to offer for XML parsing and XSL transformations. It provides tag libraries for other things as well.
For more information
Javaserver PagesTM, Dynamically Generated Web Content
Javaserver PagesTM Tag Libraries
Jakarta Taglibs Project
The Jakarta Taglibs Project--Part I
A Standard Tag Library for JavaServer PagesTM
About the author
Qusay H. Mahmoud provides Java consulting and training services. He has published dozens of articles on Java, and is the author of Distributed Programming with Java (Manning Publications, 1999). | http://www.theserverside.com/news/1365035/Web-Application-Development-with-JSP-and-XML-Part-III-Developing-JSP-Custom-Tags | CC-MAIN-2015-22 | refinedweb | 3,537 | 55.64 |
#include <stdint.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <ipxe/crypto.h>
#include <ipxe/hash_df.h>
#include <ipxe/entropy.h>
Go to the source code of this file.
Entropy source.
This algorithm is designed to comply with ANS X9.82 Part 4 (April 2011 Draft) Section 13.3. This standard is unfortunately not freely available.
Definition in file entropy.c.
Definition at line 44 of file entropy.c.
Referenced by repetition_count_test().
Definition at line 48 of file entropy.c.
Referenced by adaptive_proportion_test().
Window size for the adaptive proportion test.
ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.3.1.1 allows five possible window sizes: 16, 64, 256, 4096 and 65536.
We expect to generate relatively few (<256) entropy samples during a typical iPXE run; the use of a large window size would mean that the test would never complete a single cycle. We use a window size of 64, which is the smallest window size that permits values of H_min down to one bit per sample.
Definition at line 156 of file entropy.c.
Referenced by adaptive_proportion_test().
case APC_N_H ( 16, h ) : return c16; \ case APC_N_H ( 64, h ) : return c64; \ case APC_N_H ( 256, h ) : return c256; \ case APC_N_H ( 4096, h ) : return c4096; \ case APC_N_H ( 65536, h ) : return c65536;
Define a row of the adaptive proportion cutoff table.
Definition at line 177 of file entropy.c.
Calculate cutoff value for the repetition count test.
Calculate number of samples required for startup tests.
Calculate cutoff value for the adaptive proportion test.
Look up value in adaptive proportion test cutoff table.
This is the cutoff value for the Repetition Count Test defined in ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.2.
This is the table of cutoff values defined in ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.3.1.2.
This is the cutoff value for the Adaptive Proportion Test defined in ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.3.1.2.
ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.5 requires that at least one full cycle of the continuous tests must be performed at start-up.
Definition at line 61 of file entropy.c.
References linker_assert, MIN_ENTROPY, and min_entropy_per_sample().
{ double max_repetitions; unsigned int cutoff; /* The cutoff formula for the repetition test is: * * C = ( 1 + ( -log2(W) / H_min ) ) * * where W is set at 2^(-30) (in ANS X9.82 Part 2 (October * 2011 Draft) Section 8.5.2.1.3.1). */ max_repetitions = ( 1 + ( MIN_ENTROPY ( 30 ) / min_entropy_per_sample() ) ); /* Round up to a whole number of repetitions. We don't have * the ceil() function available, so do the rounding by hand. */ cutoff = max_repetitions; if ( cutoff < max_repetitions ) cutoff++; linker_assert ( ( cutoff >= max_repetitions ), rounding_error ); /* Floating-point operations are not allowed in iPXE since we * never set up a suitable environment. Abort the build * unless the calculated number of repetitions is a * compile-time constant. */ linker_assert ( __builtin_constant_p ( cutoff ), repetition_count_cutoff_not_constant ); return cutoff; }
Perform repetition count test.
This is the Repetition Count Test defined in ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.2.
Definition at line 104 of file entropy.c.
References EPIPE_REPETITION_COUNT_TEST.
Referenced by get_entropy().
{ static noise_sample_t most_recent_sample; static unsigned int repetition_count = 0; /* A = the most recently seen sample value * B = the number of times that value A has been seen in a row * C = the cutoff value above which the repetition test should fail */ /* 1. For each new sample processed: * * (Note that the test for "repetition_count > 0" ensures that * the initial value of most_recent_sample is treated as being * undefined.) */ if ( ( sample == most_recent_sample ) && ( repetition_count > 0 ) ) { /* a) If the new sample = A, then B is incremented by one. */ repetition_count++; /* i. If B >= C, then an error condition is raised * due to a failure of the test */ if ( repetition_count >= repetition_count_cutoff() ) return -EPIPE_REPETITION_COUNT_TEST; } else { /* b) Else: * i. A = new sample */ most_recent_sample = sample; /* ii. B = 1 */ repetition_count = 1; } return 0; }
Perform adaptive proportion test.
This is the Adaptive Proportion Test for the Most Common Value defined in ANS X9.82 Part 2 (October 2011 Draft) Section 8.5.2.1.3.
Definition at line 264 of file entropy.c.
References ADAPTIVE_PROPORTION_WINDOW_SIZE, and EPIPE_ADAPTIVE_PROPORTION_TEST.
Referenced by get_entropy().
{ static noise_sample_t current_counted_sample; static unsigned int sample_count = ADAPTIVE_PROPORTION_WINDOW_SIZE; static unsigned int repetition_count; /* A = the sample value currently being counted * B = the number of samples examined in this run of the test so far * N = the total number of samples that must be observed in * one run of the test, also known as the "window size" of * the test * B = the current number of times that S (sic) has been seen * in the W (sic) samples examined so far * C = the cutoff value above which the repetition test should fail * W = the probability of a false positive: 2^-30 */ /* 1. The entropy source draws the current sample from the * noise source. * * (Nothing to do; we already have the current sample.) */ /* 2. If S = N, then a new run of the test begins: */ if ( sample_count == ADAPTIVE_PROPORTION_WINDOW_SIZE ) { /* a. A = the current sample */ current_counted_sample = sample; /* b. S = 0 */ sample_count = 0; /* c. B = 0 */ repetition_count = 0; } else { /* Else: (the test is already running) * a. S = S + 1 */ sample_count++; /* b. If A = the current sample, then: */ if ( sample == current_counted_sample ) { /* i. B = B + 1 */ repetition_count++; /* ii. If S (sic) > C then raise an error * condition, because the test has * detected a failure */ if ( repetition_count > adaptive_proportion_cutoff() ) return -EPIPE_ADAPTIVE_PROPORTION_TEST; } } return 0; }
Get entropy sample.
This is the GetEntropy function defined in ANS X9.82 Part 2 (October 2011 Draft) Section 6.5.1.
Definition at line 333 of file entropy.c.
References adaptive_proportion_test(), get_noise(), rc, and repetition_count_test().
Referenced by get_entropy_input_tmp().
{ static int rc = 0; noise_sample_t noise; /* Any failure is permanent */ if ( rc != 0 ) return rc; /* Get noise sample */ if ( ( rc = get_noise ( &noise ) ) != 0 ) return rc; /* Perform Repetition Count Test and Adaptive Proportion Test * as mandated by ANS X9.82 Part 2 (October 2011 Draft) * Section 8.5.2.1.1. */ if ( ( rc = repetition_count_test ( noise ) ) != 0 ) return rc; if ( ( rc = adaptive_proportion_test ( noise ) ) != 0 ) return rc; /* We do not use any optional conditioning component */ *entropy = noise; return 0; }
Create next nonce value.
This is the MakeNextNonce function defined in ANS X9.82 Part 4 (April 2011 Draft) Section 13.3.4.2.
Definition at line 393 of file entropy.c.
Referenced by get_entropy_input_tmp().
Obtain entropy input temporary buffer.
This is (part of) the implementation of the Get_entropy_input function (using an entropy source as the source of entropy input and condensing each entropy source output after each GetEntropy call) as defined in ANS X9.82 Part 4 (April 2011 Draft) Section 13.3.4.2.
To minimise code size, the number of samples required is calculated at compilation time.
Definition at line 419 of file entropy.c.
References __attribute__, data, entropy_disable(), entropy_enable(), entropy_hash_df_algorithm, get_entropy(), hash_df(), make_next_nonce(), memset(), nonce, and rc.
{ static unsigned int startup_tested = 0; struct { uint32_t nonce; entropy_sample_t sample; } __attribute__ (( packed )) data;; uint8_t df_buf[tmp_len]; unsigned int i; int rc; /* Enable entropy gathering */ if ( ( rc = entropy_enable() ) != 0 ) return rc; /* Perform mandatory startup tests, if not yet performed */ for ( ; startup_tested < startup_test_count() ; startup_tested++ ) { if ( ( rc = get_entropy ( &data.sample ) ) != 0 ) goto err_get_entropy; } /* 3. entropy_total = 0 * * (Nothing to do; the number of entropy samples required has * already been precalculated.) */ /* 4. tmp = a fixed n-bit value, such as 0^n */ memset ( tmp, 0, tmp_len ); /* 5. While ( entropy_total < min_entropy ) */ while ( num_samples-- ) { /* 5.1. ( status, entropy_bitstring, assessed_entropy ) * = GetEntropy() * 5.2. If status indicates an error, return ( status, Null ) */ if ( ( rc = get_entropy ( &data.sample ) ) != 0 ) goto err_get_entropy; /* 5.3. nonce = MakeNextNonce() */ data.nonce = make_next_nonce(); /* 5.4. tmp = tmp XOR * df ( ( nonce || entropy_bitstring ), n ) */ hash_df ( &entropy_hash_df_algorithm, &data, sizeof ( data ), df_buf, sizeof ( df_buf ) ); for ( i = 0 ; i < tmp_len ; i++ ) tmp[i] ^= df_buf[i]; /* 5.5. entropy_total = entropy_total + assessed_entropy * * (Nothing to do; the number of entropy samples * required has already been precalculated.) */ } /* Disable entropy gathering */ entropy_disable(); return 0; err_get_entropy: entropy_disable(); return rc; } | http://dox.ipxe.org/entropy_8c.html | CC-MAIN-2019-39 | refinedweb | 1,321 | 51.44 |
Hi,I am simulating visitors that walk along user build paths. The road is tile based so I am using point graph and randomizing their paths a little (so first question - what graph can be better for this?). When user updates road it can make some parts unreachable from start node and agents that are on those parts must be removed. What is the best way to do that? I was thinking just check if the start tile is reachable from each agent. If this is the best way - how can I do it?
Thanks a lot.
Hi
After the graph update you can use the PathUtilities.IsPathPossible method to check which agents should be removed.
You may want to call AstarPath.active.FlushGraphUpdates to ensure that the graph update is applied immediately.
@aron_granberg Thanks! That worked perfectly.
One more question - how can I get node for object? I have list of objects with tags that create graph. So can I get directly a corresponding GraphNode for some of these objects or is GetClosestNode the best option here?
Hi
No such mapping is maintained by the system. You can use GetNearest to get it. Each PointNode does have a field called 'gameObject' which is a reference to the gameObject that is was created from so you can do
using System.Linq;
var graph = AstarPath.active.astarData.pointGraph;
var node = graph.nodes.FirstOrDefault(n => n.gameObject == targetObject);
However that would not be particularly performant if you are doing lookups very often.
Thanks. Everything worked just fine.
@aron_granberg I believe there is a bug in AIPath.cs script. You call virtual OnEnable from Start().So it gets called twice. For example, if I override it and subscribe to event - I subscribe 2 times.
`protected virtual void Start () { startHasRun = true; OnEnable(); }
/** Run at start and when reenabled.
* Starts RepeatTrySearchPath.
*
* \see Start
*/
protected virtual void OnEnable () {
lastRepath = -9999;
canSearchAgain = true;
lastFoundWaypointPosition = GetFeetPosition();
if (startHasRun) {
//Make sure we receive callbacks when paths complete
seeker.pathCallback += OnPathComplete;
StartCoroutine(RepeatTrySearchPath());
}
}
` | http://forum.arongranberg.com/t/unreachable-nodes-in-point-graph/3473 | CC-MAIN-2018-26 | refinedweb | 333 | 68.87 |
DataFu 1.0
September 4, 2013
DataFu is an open-source collection of user-defined functions for working with large-scale data in Hadoop and Pig.
About two years ago, we recognized a need for a stable, well-tested library of Pig UDFs that could assist in common data mining and statistics tasks. Over the years, we had the initial release of DataFu.
Since then, the project has continued to evolve. We have accepted contributions from a number of sources, improved the style and quality of testing, and adapted to the changing features and versions of Pig. During this time DataFu has been used extensively at LinkedIn for many of our data driven products like "People You May Known" and "Skills and Endorsements." The library is used at numerous companies, and it has also been included in Cloudera's Hadoop distribution (CDH) as well as the Apache BigTop project. DataFu has matured, and we are proud to announce the 1.0 release.
This release of DataFu has a number of new features that can make writing Pig easier, cleaner, and more efficient. In this post, we are going to highlight some of these new features by walking through a large number of examples. Think of this as a HowTo Pig + DataFu guide.
Examples quick reference
UDF quick reference
Counting events
Let's consider a hypothetical recommendation system. In this system, a user will be recommended an item (an impression). The user can then accept that recommendation, explicitly reject that recommendation, or just simply ignore it. A common task in such a system would be to count how many times users have seen and acted on items. How could we construct a pig script to implement this task?
Setup
Before we start, it's best to define what exactly we want to do, our inputs and our outputs. The task is to generate, for each user, a list of all items that user has seen with a count of how many impressions were seen, how many were accepted, and how many were rejected.
In summary, our desired output schema is:
features: {user_id:int, items:{(item_id:int, impression_count:int, accept_count:int, reject_count:int)}}
For input, we can load a record for each event:
A naive approach.
The best approach: DataFu
The two grouping operations in the last example operate on the same set of data. It would be great if we could just get rid of one of them somehow.
One thing that we have noticed is that even very big data will frequently get reasonably small once you segment it sufficiently. In this case, we have to segment down to the user level for our output. That's small enough to fit in memory. So, with a little bit of DataFu, we can group up all of the data for that user, and process it in one pass:
So, let's step through this example and see how it works and what our data looks like along the way.
Group the features
First we group all of the data together by the user, getting a few bags with all of the respective event data in the bag.
features_grouped = COGROUP impressions BY user_id, accepts BY user_id, rejects BY user_id; --features_grouped: {group: int,impressions: {(user_id: int,item_id: int,timestamp: long)},accepts: {(user_id: int,item_id: int,timestamp: long)},rejects: {(user_id: int,item_id: int,timestamp: long)}}
CountEach
Next we count the occurences of each item in the impression, accept and reject bag.
DEFINE CountEach datafu.pig.bags.CountEach('flatten'); features_counted = FOREACH features_grouped GENERATE group as user_id, CountEach(impressions.item_id) as impressions, CountEach(accepts.item_id) as accepts, CountEach(rejects.item_id) as rejects; --features_counted: {user_id: int,impressions: {(item_id: int,count: int)},accepts: {(item_id: int,count: int)},rejects: {(item_id: int,count: int)}}
CountEach is a new UDF in DataFu that iterates through a bag counting the number of occurrences of each distinct tuple. In this case, we want to count occurrences of items, so we project the inner tuples of the bag to contain just the
item_id. Since we specified the optional 'flatten' argument in the constructor, the output of the UDF will be a bag of each distinct input tuple (item_id) with a count field appended.
BagLeftOuterJoin
Now, we want to combine all of the separate counts for each type of event together into one tuple per item.
DEFINE BagLeftOuterJoin datafu.pig.bags.BagLeftOuterJoin(); features_joined = FOREACH features_counted GENERATE user_id, BagLeftOuterJoin( impressions, 'item_id', accepts, 'item_id', rejects, 'item_id' ) as items; --features_joined: {user_id: int,items: {(impressions::item_id: int,impressions::count: int,accepts::item_id: int,accepts::count: int,rejects::item_id: int,rejects::count: int)}}
This is a join operation, but unfortunately, the only join operation that pig allows on bags (in a nested foreach) is
CROSS. DataFu provides the BagLeftOuterJoin UDF to make up for this limitation. This UDF performs an in-memory hash join of each bag using the specified field as the join key. The output of this UDF mimics what you would expect from this bit of not (yet) valid Pig:
features_joined = FOREACH features_counted { items = JOIN impressions BY item_id LEFT OUTER, accepts BY item_id, rejects BY item_id; GENERATE user_id, items; }
Because
BagLeftOuterJoin is a UDF and works in memory, a separate map-reduce job is not launched. This fact will save us some time as we'll see later on in the analysis.
Coalesce
Finally, we have our data in about the right shape. We just need to clean up the schema and put some default values in place.
DEFINE Coalesce datafu.pig.util.Coalesce(); features = FOREACH features_joined { projected = FOREACH items GENERATE impressions::item_id as item_id, impressions::count as impression_count, Coalesce(accepts::count, 0) as accept_count, Coalesce(rejects::count, 0) as reject_count; GENERATE user_id, projected as items; } --features: {user_id: int,items: {(item_id: int,impression_count: int,accept_count: int,reject_count: int)}}
The various counts were joined together using an outer join in the previous step because a user has not necessarily performed an accept or reject action on each item that he or she has seen. If they have not acted, those fields will be null.
Coalesce returns its first non-null parameter, which allows us to cleanly replace that null with a zero, avoiding the need for a bincond operator and maintaining the correct schema. Done!
Analysis
Ok great, we now have three ways to write the same script. We know that the naive way will trigger six mapreduce jobs, the better way two, and the DataFu way one, but does that really equate to a difference in performance?
Since we happened to have a dataset with a few billion records in it lying around, we decided to compare the three. We looked at two different metrics for evaluation. One is the best case wall clock time. This metric is basically the sum of the slowest map and reduce task for each job (using pig default parallelism estimates). The other is total compute time which is the sum of all map and reduce task durations.
As we can see, the DataFu version provides a noticable improvement in both metrics. Glad to know that work wasn't all for naught.
Creating a custom purpose UDF
Many UDFs, such as those presented in the previous section, are general purpose. DataFu serves to collect these UDFs and make sure they are tested and easily available. If you are writing such a UDF, then we will happily accept contributions. However, frequently when you sit down to write a UDF, it is because you need to insert some sort of custom business logic or calculation into your pig script. These types of UDFs can easily become complex, involving a large number of parameters or nested structures.
Positional notation is bad
Even once the code is written, you are not done. You have to maintain it.
One of the difficult parts about this maintenance is that, as the pig script that uses the UDF changes, a developer has to be sure not to change the parameters to the UDF. Worse, because a standard UDF references fields by positions, it's very easy to introduce a subtle change that has an unintended side effect that does not trigger any errors during runtime, for example, when two fields of the same type swap positions.
Aliases can be better
Using aliases instead of positions makes it easier to maintain a consistent mapping between the UDF and the pig script. If an alias is removed, the UDF will fail with an error. If an alias changes position in a tuple, the UDF does not need to care. The alias also has some semantic meaning to the developer which can aid in the maintenance proces.
AliasableEvalFunc
Unfortunately, there is a problem using aliases. As of Pig 11.1 they are not available when the UDF is exec'ing on the back-end; they are only available on the front-end. The solution to this is to capture a mapping of alias to position on the front-end, store that mapping into the UDF context, retreive it on the back-end, and use it to look up each position by alias. You also need to handle a few issues with complex schemas (nested tuples and bags), keeping track of UDF instances, etc. To make this process simpler, DataFu provides
AliasableEvalFunc, an extension to the standard
EvalFunc with all of this behavior included.
Mortgage payment example
Using
AliasableEvalFunc is pretty simple; the primary difference is that you need to override
getOutputSchema instead of
outputSchema and have access to the alias, position map through a number of convenience methods. Consider the following example:
In this script we retrieve by alias from the input tuple a couple of different types of fields. One of these fields is a bag, and we also want to get values from the tuples in that bag. To avoid having namespace collisions among the different levels of nested tuples, AliasableEvalFunc prepends the name of the enclosing bag or tuple. Thus, we use
getPrefixedAliasName to find the field
interest_rate inside the bag named
interest_rates. That's all there is to using aliases in a UDF. As an added benefit, being able to dump schema information on errors helps in developing and debugging the UDF (see
datafu.pig.util.DataFuException).
LinearRegression example
Having access to the schema opens up UDF development possibilities. Let's look back at the recommendation system example from the first part. The script in that part generated a bunch of features about the items that users saw and clicked. That's a good start to a recommendation workflow, but the end goal is to select which items to recommend. A common way to do this is to assign a score to each item based on some sort of machine learning algorithm. A simple algorithm for this task is linear regression. Ok, let's say we've trained our first linear regression model and are ready to plug it in to our workflow to produce our scores.
We could develop a custom UDF for this model that computes the score. It is just a weighted sum of the features. So, using
AliasableEvalFunc we could retrieve each field that we need, multiply by the correct coefficient, and then sum these together. But, then every time we change the model, we are going to have to change the UDF to update the fields and coefficients. We know that our first model is not going to be very good and want to make it easy to plug in new models.
The model for a linear regression is pretty simple; it's just a mapping of fields to coefficient values. The only things that will change between models are which fields we are interested in and what the coefficient for those fields will be. So, let's just pass in a string representation of the model and then let the UDF do the work of figuring out how to apply it.
Nice, that's clean, and we could even pass that model string in as a parameter so we don't have to change the pig script to change the model either -- very reusable.
Now, the hard work, writing the UDF:
Ok, maybe not that hard... The UDF parses out the mapping of field to coeffcient in the constructor and then looks up the specified fields by name in the exec function. So, what happens when we change the model? If we decide to drop a field from our model, it just gets ignored, even if it is in the input tuple. If we add a new feature that's already available in the data it will just work. If we try and use a model with a new feature and forget to update the pig script, it will throw an error and tell us the feature that does not exist (as part of the behavior of
getDouble()).
Combining this example with the feature counting example presented earlier, we have the basis for a recommendation system that was easy to write, will execute quickly, and will be simple to maintain.
Sampling the data
Working with big data can be a bit overwhelming and time consuming. Sometimes you want to avoid some of this hassle and just look at a portion of this data. Pig has built-in support for random sampling with the
Sample operator. But sometimes a random percentage of the records is not quite what you need. Fortunately, DataFu has a few sampling UDFs that will help in some situations, and as always, we would be happy to accept any contributions of additional sampling UDFs, if you happen to have some lying around.
These things always are easier to understand with a bit of code, so let's go back to our recommendation system context and look at a few more examples.
Example 1. Generate training data
We had mentioned previously that we were going to use a machine learning algorithm, linear regression, to generate scores for our items. We waived our hands and it happened previously, but generally this task involves some work. One of the first steps is to generate the training data set for the learning algorithm. In order to make this training efficient, we only want to use a sample of all of our raw data.
Setup
Given impression, accepts, rejects and some pre-computed features about a user and items, we'd like to generate a training set, which will have all of this information for each user_id, item_id pair, for some sample of users.
So, from this input:
We want to produce this type of output:
{user_id, item_id, is_impressed, is_accepted, is_rejected, feature_1, feature_2}
One key point on sampling here: We want the sampling to be done by user_id. This means that if we choose one user_id to be included in the sample, all the data for that user_id should be included in the sample. This requirement is needed to preserve the original characteristics of raw data in the sampled data as well.
Naive approach?
A sample of DataFu -- SampleByKey
Yep.
We can use the
SampleByKey FilterFunc to do this with only one group operation. And, since the group is operating on the already sampled (significantly smaller) data this job will be far more efficient.
SampleByKey lets you designate which fields you want to use as keys for the sampling, and guarantees that for each selected key, all other records with that key will also be selected, which is exactly what we want. Another charasteritic of
SampleByKey is that it is deterministic, as long as the same salt is given on initialization. Thanks to this charastristic, we were able to sample the data seperately before we join them from the above example.
Example 2. Recommending your output
Ok, we've now created some training data that we used to create a model which will produce a score for each recommendation. So now we've got to pick which items to show the user. But, we've got a bit of a problem, we only have limited real-estate on the screen to present our recommendations, so how do we select which ones to show? We've got a score from our model so we could just always pick the top scoring items. But then we might be showing the same recommendations all the time, and we want to shake things up a bit so things aren't so static (OK, yes, I admit this is a contrived example; you wouldn't do it this way in real life). So let's take a sample of the output.
Setup
With this input:
We want to produce the exact same output, but with fewer items per user -- let's say no more than 10.
Naive approach
We can randomize using Pig's default Sample command..
Fortunately,
WeightedSample can do exactly that. It will randomly select from the candidates, but the scores of each candidate will be used as the probability of whether the candidate will be seleceted or not. So, the tuples with higher weight will have a higher chance to be included in sample - perfect.
Additional Examples
If you've made it this far into the post, you deserve an encore. So here are two more examples of how DataFu can make writing pig a bit simpler for you:
Filtering with In
One case where conditional logic can be painful is filtering based on a set of values. Suppose you want to filter tuples based on a field equalling one of a list of values. In Pig this can be achieved by joining a list of conditional checks with OR:
However as the number of items to check for grows this becomes very verbose. The
In filter function solves this and makes the
resulting code very concise:.
This code uses the insight that the input1 bag will be empty when there is no match, and flattening this will remove the entire record. If the input2 or input3 bags are empty we don't want flattening them to remove the record though, so we replace them with a bag having a single tuple with null elements. When these are flattened we get a single tuple with null elements. But, we want our output to have the correct schema, so we have to specify it manually. Once, we do all of this, the approach successfully replicates the left join behavior. It's more efficient, and it's really ugly to type and read.
To clean up this code we have created
EmptyBagToNullFields, which replicates the same logic as in the example above, but in a much more concise and readable fashion.:
Then all you need to do is call your macro
features = left_outer_join(input1, val1, input2, val2, input3, val3);
Wrap-up
So, that's a lot to digest, but it's just a highlight into a few interesting pieces of DataFu. Check out the DataFu 1.0 release as there's even more in store.
We hope that it proves valuable to you and as always welcome any contributions. Please let us know how you're using the library — we would love to hear from you.
Additional Credits
Thanks to Matt Hayes, Evion Kim, and Sam Shah for contributions to this post.
Update: DataFu is now an Apache Incubator project. All links in this blog post have been updated to point to the new Apache DataFu homepage. This blog post has also been cross-posted on the Apache DataFu Blog. | https://engineering.linkedin.com/datafu/datafu-10 | CC-MAIN-2016-30 | refinedweb | 3,232 | 59.84 |
Opened 7 years ago
Closed 7 years ago
#14496 closed enhancement (fixed)
unify the three implementations of gaussian q-binomial coefficients
Description
In sage 5.8, one can find the gaussian q-binomial coefficients in (at least) three places :
- sage.combinat.sf.kfpoly.q_bin
- sage.combinat.q_analogues.q_binomial
- sage.rings.arith.gaussian_binomial
The syntax is not quite the same for q_bin as for the two others.
Some timings:
sage: timeit("sage.combinat.sf.kfpoly.q_bin(7,5)") 625 loops, best of 3: 819 µs per loop sage: timeit("sage.combinat.q_analogues.q_binomial(12,5)") 625 loops, best of 3: 1.12 ms per loop sage: timeit("sage.rings.arith.gaussian_binomial(12,5)") 625 loops, best of 3: 294 µs per loop
The parents :
sage: sage.combinat.sf.kfpoly.q_bin(7,5).parent() Fraction Field of Univariate Polynomial Ring in t over Integer Ring sage: sage.combinat.q_analogues.q_binomial(12,5).parent() Univariate Polynomial Ring in q over Integer Ring sage: sage.rings.arith.gaussian_binomial(12,5).parent() Fraction Field of Univariate Polynomial Ring in q over Integer Ring
The behaviour with an added integer parameter
sage: sage.combinat.sf.kfpoly.q_bin(7,5,2) 114429029715 sage: sage.combinat.q_analogues.q_binomial(12,5,2) DOES NOT WORK sage: sage.rings.arith.gaussian_binomial(12,5,2) 114429029715
The behaviour with a polynomial parameter
sage: w=polygen(ZZ,'w') sage: sage.combinat.sf.kfpoly.q_bin(4,2,w) w^8 + w^7 + 2*w^6 + 2*w^5 + 3*w^4 + 2*w^3 + 2*w^2 + w + 1 sage: sage.combinat.q_analogues.q_binomial(6,2,w) w^8 + w^7 + 2*w^6 + 2*w^5 + 3*w^4 + 2*w^3 + 2*w^2 + w + 1 sage: sage.rings.arith.gaussian_binomial(6,2,w) w^8 + w^7 + 2*w^6 + 2*w^5 + 3*w^4 + 2*w^3 + 2*w^2 + w + 1 sage: sage.combinat.sf.kfpoly.q_bin(4,2,w).parent() Univariate Polynomial Ring in w over Integer Ring sage: sage.combinat.q_analogues.q_binomial(6,2,w).parent() Univariate Polynomial Ring in w over Integer Ring sage: sage.rings.arith.gaussian_binomial(6,2,w).parent() Fraction Field of Univariate Polynomial Ring in w over Integer Ring
Maybe it would be better to have a single function ?
Attachments (3)
Change History (35)
comment:1 Changed 7 years ago by
comment:2 Changed 7 years ago by
- Cc fwclarke added
- Status changed from new to needs_review
comment:3 Changed 7 years ago by
- Status changed from needs_review to needs_work
This looks good. It's certainly nice to have integer parameters giving integer results.
But
n//d can causes problems if
q takes a real value, and similarly in some other cases. Perhaps this should be a "
try:", with the exception giving
n/d or even
gaussian_binomial(n, k)(q). [It is surely not necessary to introduce
var when this occurs before.]
I also don't like the way (inherited from the existing code) that
n plays two very different rôles; the line
n = prod([1 - q**i for i in range(n-k+1,n+1)])
is particularly bad style. It would make the code more readable to call them "
numerator" and "
denominator" (possibly abbreviated)
comment:4 Changed 7 years ago by
- Status changed from needs_work to needs_review
Here is a new version of the patch. I have modified the names d and n and introduced a try statement. I am not sure what kind of exceptions I need to catch.
Still it remains to choose if one keeps the gaussian_binomial or rather the q_binomial function.
comment:5 Changed 7 years ago by
- Component changed from PLEASE CHANGE to combinatorics
comment:6 Changed 7 years ago by
- Status changed from needs_review to needs_work
- There's a doctest failure at line 341 of
sage/combinat/sf/kfpoly.py. I don't know what's being computed here, so I don't know what's going wrong.
- I thought the standard spacing was as
def gaussian_binomial(n, k, q=None):
- I think
TypeErroris enough; I never saw anything else when I was testing your code.
- Is it intentional not to alter
sage/combinat/q_analogues.py?
So it's nearly ready for a positive review.
comment:7 Changed 7 years ago by
- Status changed from needs_work to needs_info
Here is a new patch.
Point 1 is indeed a problem. I do not understand either what is computed in the weight function. The procedure q_bin was returning 1 for any negative values of n and any k. This is not a very natural behaviour.
Point 4 : I have chosen that the name to be kept would be q_binomial.
There is another problem remaining. The existing algorithm in sage.combinat.q_analogues uses cyclotomic polynomials and become faster than the naive one when the arguments are big (and of similar size ?), but is much slower in some cases (when n is small or k is small ?).
sage: timeit("sage.combinat.q_analogues.q_binomial(85,3)") 625 loops, best of 3: 246 µs per loop sage: timeit("sage.combinat.q_analogues.q_binomial_via_cyclotomic(85,3)") 125 loops, best of 3: 2.78 ms per loop sage: timeit("sage.combinat.q_analogues.q_binomial(85,43)") 25 loops, best of 3: 9.21 ms per loop sage: timeit("sage.combinat.q_analogues.q_binomial_via_cyclotomic(85,43)") 25 loops, best of 3: 8.18 ms per loop
So one needs to keep both and find a strategy of choice..
comment:8 Changed 7 years ago by
I'll take a look at why the weight function in SF fails; but the best way to fix it is in the weight, have a check for negative
n or
k and just circumvent the call to
q_binomial() and return 1.
As for the speed of the naive vs. cyclotomic polys, I would pick a cutoff value which you think is about the breakeven point(s) for the two, and call which ever function is faster based on that.
Also, have you tried implementing it by computing the q-binomial, then substituting in a user defined
q value to the result (in particular, have you compared the speed)? I'm thinking this might be slower than just computing it outright if
q is in
GF(3) for example... If you haven't, I can write it up and run the tests.
Thanks for noticing this and working on it,
Travis
comment:9 Changed 7 years ago by
Good idea, I have done just that in the new patch, so there is no doctest failure now.
There remains to choose a strategy..
comment:10 follow-up: ↓ 11 Changed 7 years ago by
Some timings were given in the ticket #13166
According to my own timings, it seems that for n <= ~ 78 the naive algorithm is faster than the cyclotomic algorithm for computing the gaussian polynomial.
comment:11 in reply to: ↑ 10 Changed 7 years ago by
According to my own timings, it seems that for n <= ~ 78 the naive algorithm is faster than the cyclotomic algorithm for computing the gaussian polynomial.
I get much the same. For
gaussian_binomial(2*k, k) I found the naive method faster for
k < 30, and the cyclotomic method faster for `k > 30'.
One point about the naive method:
sage: %timeit gaussian_binomial(50, 4) 1000 loops, best of 3: 287 µs per loop sage: %timeit gaussian_binomial(50, 46) 100 loops, best of 3: 3.41 ms per loop
Since the code contains two loops of length
k, it's obviously better to evaluate
gaussian_binomial(n, k) as
gaussian_binomial(n, n-k) if
k > n/2.
comment:12 Changed 7 years ago by
Here is a new patch
- using the minimum of k and n-k in the naive algo
- implementing the following strategy :
if n <= 70 or k <= N/4 or q is not a polynomial, use the naive algo
otherwise use the cyclotomic algo
I have found this strategy using some timings (I only timed the polynomial case).
comment:13 Changed 7 years ago by
- Reviewers set to Francis Clarke, Travis Scrimshaw
- Status changed from needs_info to needs_review
comment:14 Changed 7 years ago by
- Type changed from task to enhancement
comment:15 Changed 7 years ago by
- Status changed from needs_review to needs_work
Two points remain, I think:
- On speed, I see that you are not using the cyclotomic method when
qis not a polynomial. But by using
cyclotomic_valuethe faster method can be efficient for "scalar" values too.
- I don't see any reason why
gaussian_binomialshould be deprecated. This terminology is in common use, and a mathematician who knows only this name should not be told that it is "wrong". She should be able to use it without necessarily ever knowing that some people use a different name. Doesn't deprecation mean that eventually the function will disappear from Sage? This would only cause confusion. Surely the two should be synonyms, as are, for example, the number-field methods
ring_of_integersand
maximal_order.
comment:16 Changed 7 years ago by
Here is a new patch.
For point 2, I have now defined gaussian_binomial as being an alias to q_binomial. The global namespace only contains gaussian_binomial, as before the patch.
For point 1, I have made some changes in the choice of algo, mainly about symbolic inputs. But I do not think that it is really worth spending more time on trying harder to enhance the speed for arbitrary inputs. This function is supposed to be used mainly without 3rd argument.
comment:17 Changed 7 years ago by
- Status changed from needs_work to needs_review
comment:18 Changed 7 years ago by
Hey Frederic and Francis,
I've uploaded a review patch which does two things I wanted, an input for the algorithm and handling objects which may not have division (by computing it using a formal variable and then substituting in
q). If you're happy with my changes, feel free to set this to a positive review.
Best,
Travis
comment:19 Changed 7 years ago by
hello,
it seems to me that at the end you can write simply
return q_binomial(n, k)(q)
because then the polygen import will be done inside the function
comment:20 Changed 7 years ago by
Yep, that works. I've uploaded the updated patch.
comment:21 Changed 7 years ago by
- Status changed from needs_review to needs_work
I was about to say positive review, when I noticed two things:
gaussian_polynomial(5, 2, 7r)fails. But this caused by a feature of
cyclotomic_value, so should probably be ignored.
gaussian_binomial(4, 2, Zmod(6)(2), algorithm='naive')fails. This can be very simply rectified by excepting a
ZeroDivisionErroras well as a
TypeErrorjust before the "last attempt".
comment:22 follow-up: ↓ 23 Changed 7 years ago by
- Status changed from needs_work to needs_review
Point 2 is done. I vote to ignore point 1 (anyway, who cares about that ?)
comment:23 in reply to: ↑ 22 Changed 7 years ago by
- Status changed from needs_review to positive_review
comment:24 Changed 7 years ago by
- Status changed from positive_review to needs_work
dochtml.log:[combinat ] /mazur/release/merger/sage-5.10.beta2/local/lib/python2.7/site-packages/sage/combinat/q_analogues.py:docstring of sage.combinat.q_analogues.q_binomial:141: WARNING: Duplicate explicit target name: "ch2006". dochtml.log:[combinat ] /mazur/release/merger/sage-5.10.beta2/local/lib/python2.7/site-packages/sage/combinat/q_analogues.py:docstring of sage.combinat.q_analogues.q_binomial:141: WARNING: duplicate citation CH2006, other instance in /mazur/release/merger/sage-5.10.beta2/devel/sage/doc/en/reference/combinat/sage/combinat/q_analogues.rst
comment:25 Changed 7 years ago by
ah, well, sorry.
This is because I defined an alias in an incorrect way, using
gaussian_binomial = q_binomial
But what is the correct way ?
comment:26 Changed 7 years ago by
Hum, it seems that I have used the correct way to create an alias. But as the doc is duplicated (instead of saying that one function is an alias for the other), it will necessarily create a conflict any time it contains a reference. I am surprised that this problem has never been met before !
One can compare the situation to the definition of charpoly and characteristic_polynomial in sage.misc.functional, which does not contain a reference, hence dos not raise this problem.
comment:27 Changed 7 years ago by
There are two workarounds I can see:
- Put the reference in a place that isn't duplicated such as at the module level.
- Write in
gaussian_binomial()which calls
q_binomial()and it's doc just says "see
q_binomial()"
Option 2 is more work and less clean IMO. Option 1 isn't perfect to me either but is the lesser of 2 evils. Up to you; either way would be okay with me.
comment:28 Changed 7 years ago by
- Cc andrew.mathas added
comment:29 Changed 7 years ago by
- Status changed from needs_work to positive_review
ok, this should be good now. Back to positive review
comment:30 Changed 7 years ago by
Hey Frederic,
Two minor things on the doc for
gaussian_binomial():
- There should be periods '.' at the end of the sentences.
- The 'this function' is slightly ambiguous to me, I would explicitly put
:func:`q_binomial()`to avoid this.
Otherwise I'm also happy with the patch. Thanks.
comment:31 Changed 7 years ago by
Done, and thanks for the review
comment:32 Changed 7 years ago by
- Merged in set to sage-5.10.beta2
- Resolution set to fixed
- Status changed from positive_review to closed
Here is already a seemingly faster function. There remains to deprecate the two others. The most annoying one is q_bin, with a different syntax and with a global variable inside. | https://trac.sagemath.org/ticket/14496 | CC-MAIN-2019-51 | refinedweb | 2,275 | 54.83 |
Build an InstantSearch Results Page
On this page
Scope of this tutorial
This tutorial will teach you how to implement a simple instant search refreshing the whole view “as you type” by using Algolia’s engine and the Swift API Client.
Note that as of July 2017, we have released a library to easily build instant search result pages with Algolia, called InstantSearch iOS. We highly recommend that you use InstantSearch iOS to build your search interfaces. You can get started with either the Getting started guide, the InstantSearch repo or Example apps.
Let’s see how it goes with a simple use-case: searching for movies.
Covered subjects include:
- results as you type
- highlighting the matched words
- infinite scrolling
Records
For this tutorial, we will use an index of movies but you could use any of your data. To import your own data into an Algolia index, please refer to our import guide.
Here is an extract of what our records look like:
Initialization
The whole application has been built in Swift with Xcode.
New project
The first thing we need to do is to create a new Swift project: iOS > Application > Single View Application.
Dependencies
The following code depends on the following third-party libraries:
- AFNetworking to easily load images asynchronously
- Algolia Search API Client for Swift to communicate with Algolia’s REST API.
- a simple extension of UILabel with highlighting support to highlight the matching words
You can install all the dependencies with CocoaPods. Add the following lines in a
Podfile file:
And then type
pod install in your command line and open the generated Xcode Workspace.
For the
UILabel extension, just drag and drop the file in your project.
UI
Storyboard
Let’s start building the UI. In the Storyboard,
we remove the basic UI generated by Xcode and we drag-n-drop a
Navigation Controller.
Then, we set the
Style attribute of the
Table View Cell to
Right Detail and
Identifier to
movieCell.
Search bar
Since iOS 8,
UISearchDisplayController is deprecated and you should now use
UISearchController.
Unfortunately, at the time of writing,
Interface Builder is not able to create the new
UISearchController so we must create it in code.
Let’s remove
ViewController.swift and create a new subclass of
UITableViewController:
File > New File > iOS > Source > Cocoa Touch Class.
In the new file that we have just created,
we add the search bar initialization in the
viewDidLoad method and a new property
searchController:
Then, we have to implement two protocols:
UISearchBarDelegate and
UISearchResultsUpdating. Let’s add them:
We have two more things to do in the Storyboard:
- select the Navigation Controller and check the attribute
Is the initial View Controller,
- and set the
Custom Classof the table view to our subclass of
UITableViewController.
We can launch the application and see the result.
Search logic
Movie model
Let’s first create a model that has the same structure as our records. In our case, we create
MovieRecord in a new file.
Search movies
In the
viewDidLoad method, we initialize the Algolia Search API Client.
Don’t forget to add
import AlgoliaSearch at the beginning of the file.
We will store the results of the search query in an array.
All the logic goes inside the
updateSearchResultsForSearchController method.
We use an closure to asynchronously process the results once the API returns the matching hits.
Inside the closure, we need to check that the result is newer than
the result currently displayed because we cannot ensure the ordering of the network calls/answers.
We transform the resulting JSON hits into our movie model. Don’t forget to add
import SwiftyJSON too.
Display the matching movies
At this point, we have the result of the query saved in the
movies array but we don’t display anything to the user yet.
We can now implement the method of
UITableViewController so the controller will update the view.
Add
import AFNetworking at the beginning of the file so we can use AFNetworking to asynchronously
load the images from their URL, embed it inside the
UIImageView and cache it to avoid further reloading.
Infinite scroll
As you can see, we currently load 15 results per search. We now have to implement another method that will load the next page of the displayed query.
We should call this method inside
tableView(tableView: UITableView, cellForRowAtIndexPath: NSIndexPath), just before the return.
See it in action
Check the source code on GitHub.
Filtering your results
There are multiple ways to filter your results using Algolia. You can filter by date, by numerical value and by tag. You can also use facets, which are a filter with the added benefits of being able to retrieve and display the values to filter by.
Filtering
There are several ways:
Note::
Filtering / Navigation
facet method and
sum values. The values are available in the
facets_stats attribute of the JSON answer. | https://www.algolia.com/doc/guides/building-search-ui/getting-started/how-to/build-an-instant-search-results-with-swift/ | CC-MAIN-2019-26 | refinedweb | 811 | 62.07 |
Delegates are a nice feature of .NET that really make coding callbacks simple. This article is not going to describe how to create delegates and events - there are many other articles on CodeProject that give you this information. One thing that delegates can't do is to remember when an event is invoked so that the data can be sent to any new delegates that get added to the event.
This problem was given to me at work because events were being triggered before all of the parts of the system were created and attached. This lead to some components not having the correct data. This needed to be resolved in a way that was the most generic.
The first step is to create some delegates and a class with events for them. For the events, the normal declaration was replaced by the accessors for the events.
__event void add_E(MyDel* p) { Console::WriteLine("Add E"); pE = static_cast<MyDel*> (Delegate::Combine(pE,p)); } __event void remove_E(MyDel* p) { Console::WriteLine("Remove E"); pE = static_cast<MYDEL*> (Delegate::Remove(pE, p)); } __event void raise_E() { Console::WriteLine("Raise E"); if (pE != 0) pE->Invoke(); }
This creates an event named
E. Then a class was created to receive the events.
public __gc class EventReceiver { public: void H1() { Console::WriteLine("EventReceiver - H1"); } int H2(int i, float f) { Console::WriteLine("EventReceiver - H2 with args {0} and {1}", i.ToString(), f.ToString()); return 0; } };
Then in the main of this sample, instances of the two classes were created and then delegates attached to the event
E. So far, this is just like any other delegate/event project if you were going to create the accessors manually. Of course, the compiler normally creates the accessors for you automatically.
EventSource* pE = new EventSource(); EventReceiver* pR = new EventReceiver(); EventReceiver2* pR2 = new EventReceiver2(); // hook event handlers for pR Console::WriteLine("EventReceiver - hooking events"); pE->E += new MyDel(pR, &EventReceiver::H1); pE->E2 += new MyDel2(pR, &EventReceiver::H2); // raise the E event pE->E();
The next step is to give the event a bit of memory to remember when it was raised. If the delegate had variables, then those would have to be saved also. For the event
E in this sample, only a
bool to say it had been invoked is needed. So, two changes to the code are required - first to the
raise_ accessor and then to the
add_ accessor.
__event void add_E(MyDel* p) { Console::WriteLine("Add E"); pE = static_cast<MyDel*> (Delegate::Combine(pE,p)); if(m_eInvoked == true) p->Invoke(); } __event void raise_E() { Console::WriteLine("Raise E"); if (pE != 0) { m_eInvoked = true; pE->Invoke(); } }
Using this method, the programmer can control which events get this memory enhancement and which do not. For events that are the typical "fire-and-forget" type of events, this might not be needed. For others things, a "fire-and-forget" type of event might reset other variables for other events. An example of this might be paper being inserted into a printer, one event might be to send what paper is available in the printer and another event could be a signal that paper has been removed. The paper removal event could clear a stored variable for what paper is available.
The sample code expands this sample to two receiving instances and two events.
I looked into using event accessors in C# as well as MC++. I setup class and accessor functions for adding and removing delegates, and then went to add an accessor for raising the event. The compiler would not let me add a function for raising the event. I found this to be strange and puzzling because it is showing that MC++ has more functionality than C#. After looking into it some more, I found that you have to use a custom function to raise the event instead of an accessor. After this was in place, the C# code looked similar to the MC++ code. The code is included in this article but not in the download unless people want it included later.
public class EventSource { // private variables for E event private MyDel pE; private bool m_eInvoked; public EventSource() { m_eInvoked=false; } public event MyDel E { add { Console.WriteLine("Add E"); pE += value; if(m_eInvoked==true) value(); } remove { Console.WriteLine("Remove E"); pE -= value; } } public void RaiseE() { m_eInvoked = true; if(pE != null) pE(); } };
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/mcpp/EventsMemory.aspx | crawl-002 | refinedweb | 729 | 61.97 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.