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
|
|---|---|---|---|---|---|
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
Tools & Languages: Objective-C
2010-12-08,. Times is a registered trademark of Heidelberger Druckmaschinen AG, available from Linotype Library GmbH.
Who Should Read This Document 9 Organization of This Document 9 Conventions 10 See Also 11 The Runtime System 11 Memory Management 11
Chapter 1
Objects, Classes, and Messaging 13
The Runtime System 13 Objects 13 Object Basics 13 id 14 Dynamic Typing 14 Memory Management 15 Object Messaging 15 Message Syntax 15 Sending Messages to nil 17 The Receiver’s Instance Variables 18 Polymorphism 18 Dynamic Binding 19 Dynamic Method Resolution 19 Dot Syntax 19 Classes 23 Inheritance 23 Class Types 26 Class Objects
.CONTENTS Messages to self and super 43 An Example: Using self and super 44 Using super 45 Redefining self 46 Chapter 3 Allocating and Initializing Objects 49 Allocating and Initializing Objects 49 The Returned Object 49 Implementing an Initializer 50 Constraints and Conventions 50 Handling Initialization Failure 52 Coordinating Classes 53 The Designated Initializer 55 Combining Allocation and Initialization 57 Chapter 4 Protocols 59 Declaring Overview 69 Property Declaration and Implementation 69 Property Declaration 70 Property Declaration Attributes 70 Property Implementation Directives 73 Using Properties 74 Supported Types 74 Property Redeclaration 75 Copy 75 dealloc 76 Core Foundation 77 4 2010-12-08 | © 2010 Apple Inc. All Rights Reserved.
All Rights Reserved. .CONTENTS Example: Declaring Properties and Synthesizing Accessors 77 Subclassing with Properties 79 Performance and Threading 79 Runtime Difference 80 Chapter 6 Categories and Extensions 81 Adding Methods to Classes 81 How You Can Use Categories 82 Categories of the Root Class 83 Extensions 83 Chapter 7 Associative References 87 Adding Storage Outside a Class Definition 87 Creating Associations 87 Retrieving Associated Objects 88 Breaking Associations 88 Complete Example 88 Chapter 8 Fast Enumeration 91 The for…in Syntax 91 Adopting Fast Enumeration 91 Using Fast Enumeration 92 Chapter 9 Enabling Static Behavior 95 Default Dynamic Behavior 95 Static Typing 95 Type Checking 96 Return and Parameter Types 97 Static Typing to an Inherited Class 97 Chapter 10 Selectors 99 Methods and Selectors 99 SEL and @selector 99 Methods and Selectors 100 Method Return and Parameter Types 100 Varying the Message at Runtime 100 The Target-Action Design Pattern 101 Avoiding Messaging Errors 101 5 2010-12-08 | © 2010 Apple Inc.
All Rights Reserved.CONTENTS Chapter 11 Exception Handling 103 Enabling Exception-Handling 103 Exception Handling 103 Catching Different Types of Exception 104 Throwing Exceptions 104 Chapter 12 Threading 107 Document Revision History 109 Glossary 113 6 2010-12-08 | © 2010 Apple Inc. .
Mid. . and Low 44 Chapter 3 Allocating and Initializing Objects 49 Figure 3-1 Figure 3-2 Figure 3-3 Figure 3-4 Incorporating an inherited initialization method 54 Covering an inherited initialization method 55 Covering the designated initializer 56 The initialization chain 57 Chapter 5 Declared Properties 69 Listing 5-1 Listing 5-2 Listing 5-3 Listing 5-4 Declaring a simple property 70 Using @synthesize 73 Using @dynamic with NSManagedObject 74 Declaring properties for a class 78 Chapter 7 Associative References 87 Listing 7-1 Establishing an association between an array and a string 87 Chapter 11 Exception Handling 103 Listing 11-1 An exception handler 104 Chapter 12 Threading 107 Listing 12-1 Listing 12-2 Locking a method using self 107 Locking a method using a custom semaphore 107 7 2010-12-08 | © 2010 Apple Inc. and Messaging 13 Figure 1-1 Figure 1-2 Figure 1-3 Listing 1-1 Listing 1-2 Listing 1-3 Some drawing program classes 24 Rectangle instance variables 25 The inheritance hierarchy for NSCell 30 Accessing properties using dot syntax 20 Accessing properties using bracket syntax 20 Implementation of the initialize method 32 Chapter 2 Defining a Class 35 Figure 2-1 Figure 2-2 The scope of instance variables (@package scope not shown) 41 The hierarchy of High.Figures and Listings Chapter 1 Objects. All Rights Reserved. Classes.
FIGURES AND LISTINGS 8 2010-12-08 | © 2010 Apple Inc. All Rights Reserved. .
and to do so in a simple and straightforward way. one of the first object-oriented programming languages. This document also provides a foundation for learning about the second component. Organization of This Document The following chapters cover all the features Objective-C adds to standard C. Who Should Read This Document 2010-12-08 | © 2010 Apple Inc. It fully describes the version of the Objective-C language released in Mac OS X v10. not on the C language itself.6 and iOS 4. Objective-C is defined as a small but powerful set of extensions to the standard ANSI C language. Its additions to C are mostly based on Smalltalk.INTRODUCTION Introduction The Objective-C language is a simple computer language designed to enable sophisticated object-oriented programming. it assumes some prior acquaintance with that language. Most object-oriented development environments consist of several parts: ● ● ● ● An object-oriented programming language A library of objects A suite of development tools A runtime environment This document is about the first component of the development environment—the programming language. Who Should Read This Document The document is intended for readers who might be interested in: ● ● Programming in Objective-C Finding out about the basis for the Cocoa application frameworks This document both introduces the object-oriented model that Objective-C is based upon and fully documents the language. All Rights Reserved. sufficiently different from procedural programming in ANSI C that you won’t be hampered if you’re not an experienced C programmer.0. however. 9 . Objective-C Runtime Programming Guide. Because this isn’t a document about C. the Objective-C application frameworks—collectively known as Cocoa. It concentrates on the Objective-C extensions to C. Object-oriented programming in Objective-C is. The runtime environment is described in a separate document. Objective-C is designed to give C full object-oriented programming capabilities.
} 10 Conventions 2010-12-08 | © 2010 Apple Inc. often substantial parts.INTRODUCTION Introduction ● ● ● ● ● ● ● ● ● ● ● ● “Objects. .. Italic denotes words that represent something else or can be varied. ellipsis points indicates the parts. Computer voice denotes words or characters that are to be taken literally (typed as they appear). the syntax: @interfaceClassName(CategoryName) means that @interface and the two parentheses are required. Classes. that have been omitted: . For example. .(void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]. Where example code is shown... Conventions This document makes special use of computer voice and italic fonts. All Rights Reserved. but that you can choose the class name and category name.
All Rights Reserved. you should read Object-Oriented Programming with Objective-C. Objective-C Runtime Reference describes the data structures and functions of the Objective-C runtime support library. Your programs can use these interfaces to interact with the Objective-C runtime system. 11 . It spells out some of the implications of object-oriented design and gives you a flavor of what writing an object-oriented program is really like. You should also consider reading it if you have used other object-oriented development environments such as C++ and Java because they have many expectations and conventions different from those of Objective-C. Memory Management Objective-C supports two mechanisms for memory management: automatic garbage collection and reference counting: ● Garbage Collection Programming Guide describes the garbage collection system used in Mac OS X. The Runtime System Objective-C Runtime Programming Guide describes aspects of the Objective-C runtime and how you can use it. Object-Oriented Programming with Objective-C is designed to help you become familiar with object-oriented development from the perspective of an Objective-C developer. ● See Also 2010-12-08 | © 2010 Apple Inc.) Memory Management Programming Guide describes the reference counting system used in iOS and Mac OS X. (Not available for iOS—you cannot access this document through the iOS Dev Center. you can add classes or methods. or obtain a list of all class definitions for loaded classes.INTRODUCTION Introduction See Also If you have never used object-oriented programming to create applications. For example.
All Rights Reserved.INTRODUCTION Introduction 12 See Also 2010-12-08 | © 2010 Apple Inc. .
generally. For others to find out something about an object. it dynamically performs operations such as creating objects and determining what method to invoke. you don’t need to interact with the runtime directly. see Objective-C Runtime Programming Guide. and Messaging This chapter describes the fundamentals of objects. it can’t mistakenly perform methods intended for other types of objects. The Runtime System 2010-12-08 | © 2010 Apple Inc. The runtime system acts as a kind of operating system for the Objective-C language. it’s what makes the language work. Moreover. Objective-C provides a data type to identify an object variable without specifying a particular class of the object.CHAPTER 1 Objects. these operations are known as the object’s methods. It also introduces the Objective-C runtime. Whenever possible. and messaging as used and implemented by the Objective-C language. an object hides both its instance variables and its method implementations. All Rights Reserved. there has to be a method to supply the information. an object sees only the methods that were designed for it. In Objective-C. however. In Objective-C. an object bundles a data structure (instance variables) and a group of procedures (methods) into a self-contained programming unit. An object associates data with the particular operations that can use or affect that data. Typically. but also a runtime system to execute the compiled code. hiding them from the rest of the program. an object’s instance variables are internal to the object. a rectangle would have methods that reveal its size and position. In essence. object-oriented programs are built around objects. Just as a C function protects its local variables. the language requires not just a compiler. classes. you get access to an object’s state only through the object’s methods (you can specify whether subclasses or other objects can access instance variables directly by using scope directives. Classes. The Runtime System The Objective-C language defers as many decisions as it can from compile time and link time to runtime. 13 . To understand more about the functionality it offers. Object Basics An object associates data with the particular operations that can use or affect that data. though. Objects As the name implies. Therefore. For example. see “The Scope of Instance Variables” (page 40)). the data they affect are its instance variables (in other environments they may be referred to as ivars or member variables).
and Messaging id In Objective-C.CHAPTER 1 Objects. id. determine whether an object implements a particular method or discover the name of its superclass. such as method return values. id replaces int as the default data type. Classes. discussed later.) Dynamic typing in Objective-C serves as the foundation for dynamic binding. and the class name can serve as a type name. see Objective-C Runtime Programming Guide. 14 Objects 2010-12-08 | © 2010 Apple Inc. (For strictly C constructs. and the other basic types of Objective-C are defined in the header file objc/objc. Since the Class type is itself defined as a pointer: typedef struct objc_class *Class. an id with a value of 0. The functions of the runtime system use isa to find this information at runtime. Objects with the same behavior (methods) and the same kinds of data (instance variables) are members of the same class. The isa instance variable identifies the object’s class—what kind of object it is. a program typically needs to find more specific information about the objects it contains. it yields no information about an object.” Dynamic Typing The id type is completely nonrestrictive. Every object thus has an isa variable that tells it of what class it is an instance. the isa variable is frequently referred to as the “isa pointer.) The keyword nil is defined as a null object. See “Class Types” (page 26) and “Enabling Static Behavior” (page 95). such as function return values. By itself. Using the runtime system. Object classes are discussed in more detail under “Classes” (page 23). nil. } *id.h. Objects are thus dynamically typed at runtime. int remains the default type. This type is the general type for any kind of object regardless of class and can be used for instances of a class and for class objects themselves. you can. id anObject. (To learn more about the runtime. the runtime system can find the exact class that an object belongs to. All Rights Reserved. id is defined as pointer to an object data structure: typedef struct objc_object { Class isa. for example. except that it is an object. Classes are particular kinds of objects. object identifiers are of a distinct data type: id. . each object has to be able to supply it at runtime. At some point. The isa variable also enables objects to perform introspection—to find out about themselves (or other objects). For the object-oriented constructs of Objective-C. just by asking the object. The compiler records information about class definitions in data structures for the runtime system to use. Since the id type designator can’t supply this specific information to the compiler. It’s also possible to give the compiler information about the class of an object by statically typing it in source code using the class name. Whenever it needs to.
It also discusses the scope or “visibility” of an object’s instance variables. it is important to ensure that objects are deallocated when they are no longer needed—otherwise your application’s memory footprint becomes larger than necessary. When a message is sent. including how you can nest message expressions. All Rights Reserved. Classes. you send it a message telling it to apply a method. Objective-C offers two mechanisms for memory management that allow you to meet these goals: ● Reference counting.0]. the runtime system selects the appropriate method from the receiver’s repertoire and invokes it. Reference counting is described in Memory Management Programming Guide. ● Garbage collection. Methods can also take parameters. It is also important to ensure that you do not deallocate objects while they’re still being used. Because the method name in a message serves to “select” a method implementation. and the concepts of polymorphism and dynamic binding. the message is simply the name of a method and any parameters that are passed to it. In source code. and the message tells it what to do. method names in messages are often referred to as selectors. this message tells the myRectangle object to perform its display method. Message Syntax To get an object to do something. and Messaging Memory Management In any program. where you pass responsibility for determining the lifetime of objects to an automatic “collector. For example. which causes the rectangle to display itself: [myRectangle display]. A message with a single parameter affixes a colon (:) to the name and puts the parameter right after the colon: [myRectangle setWidth:20. In Objective-C. sometimes called arguments. message expressions are enclosed in brackets: [receiver message] The receiver is an object. Object Messaging 2010-12-08 | © 2010 Apple Inc. The message is followed by a “. where you are ultimately responsible for determining the lifetime of objects.” Garbage collection is described in Garbage Collection Programming Guide.CHAPTER 1 Objects. 15 .” as is normal for any statement in C.) Object Messaging This section explains the syntax of sending messages. (Not available for iOS—you cannot access this document through the iOS Dev Center.
the commas are not considered part of the name. . b. 16 Object Messaging 2010-12-08 | © 2010 Apple Inc. an Objective-C method declaration is simply a C function that prepends two additional parameters (see “Messaging” in the Objective-C Runtime Programming Guide). however. as the following Python example illustrates: def func(a. include anything else. All Rights Reserved.0 y: 50. The imaginary message below tells the myRectangle object to set its origin to the coordinates (30. For all intents and purposes. the imaginary makeGroup: method is passed one required parameter (group) and three parameters that are optional: [receiver makeGroup:group. the second parameter is effectively unlabeled and it is difficult for a reader of this code to determine the kind or purpose of the method’s parameters. including the colons.0 :50. the structure of an Objective-C method declaration differs from the structure of a method that uses named or keyword parameters in a language like Python. Thing=DefaultThing): pass In this Python example. In principle. The selector name does not. Thus. (Unlike colons. 50. the color of one rectangle is set to the color of another: [myRectangle setPrimaryColor:[otherRect primaryColor]]. memberTwo. or NO if it’s drawn in outline form only. Like standard C functions. The following example sets the variable isFilled to YES if myRectangle is drawn as a solid rectangle. because it takes two parameters. Here. Methods that take a variable number of parameters are also possible.0]. None of these characteristics about parameters are true for Objective-C. so the selector in the preceding example is named setOriginX:y:. which would be invoked as follows: [myRectangle setOrigin:30.0.0]. though they’re somewhat rare. Thing and NeatMode might be omitted or might have different values when called. Classes. and can possibly have additional named parameters. Extra parameters are separated by commas after the end of the method name. // This is a bad example of multiple parameters While syntactically legal. // This is a good example of // multiple parameters A selector name includes all the parts of the name. can have default values. memberThree]. Objective-C's method names are interleaved with the parameters such that the method’s name naturally describes the parameters expected by the method. Thus. methods can return values. and Messaging For methods with multiple parameters. can be in a different order.) In the following example. It has two colons. In some languages. a Rectangle class could instead implement a setOrigin:: method with no label for the second parameter. such as return type or parameter types. Important: The subparts of an Objective-C selector name are not optional.CHAPTER 1 Objects.0): [myRectangle setOriginX: 30. setOrigin:: does not interleave the method name with the parameters. BOOL isFilled. Note that a variable and a method can have the same name. NeatMode=SuperNeat. isFilled = [myRectangle isFilled]. One message expression can be nested inside another. nor can their order be varied. memberOne. the terms “named parameters” and “keyword parameters” carry the implications that the parameters can vary at runtime.
0) { // implementation continues. it is valid to send a message to nil—it simply has no effect at runtime. // this is valid if ([anObjectMaybeNil methodThatReturnsADouble] == 0. Classes. If the method returns anything other than the aforementioned value types. the return value of a message sent to nil is undefined. All Rights Reserved. 17 . The value returned from a message to nil may also be valid: ● If the method returns an object. Other struct data types will not be filled with zeros. id anObjectMaybeNil = nil. then mother is sent to nil and the method returns nil. any integer scalar of size less than or equal to sizeof(void*). } Object Messaging 2010-12-08 | © 2010 Apple Inc. a long double. ● ● The following code fragment illustrates a valid use of sending a message to nil. a float.. a double.0 for every field in the struct. Sending Messages to nil In Objective-C.CHAPTER 1 Objects. then a message sent to nil returns 0. then a message sent to nil returns 0 (nil). If the spouse object here is nil. as defined by the Mac OS X ABI Function Call Guide to be returned in registers. then a message sent to nil returns 0. For example: Person *motherInLaw = [[aPerson spouse] mother]. If the method returns a struct. ● If the method returns any pointer type. or a long long..) operator that offers a compact and convenient syntax for invoking an object’s accessor methods. There are several patterns in Cocoa that take advantage of this fact. The dot operator is typically used in conjunction with the declared properties feature (see “Declared Properties” (page 69)) and is described in “Dot Syntax” (page 19). and Messaging Objective-C also provides a dot (.
it must send a message to the object asking it to reveal the contents of the variable. an object can be operated on by only those methods that were defined for it. plays a significant role in the design of object-oriented programs. The primaryColor and isFilled methods shown earlier are used for just this purpose. This convention simplifies Objective-C source code.CHAPTER 1 Objects. each kind of object that receives a display message could display itself in a unique way. if it returns any struct type. if it does. If it requires information about a variable stored in another object. messages don’t behave in the same way that function calls do. they don’t need to bring the receiver to itself.4 and earlier. Together with dynamic binding. They might even be objects that will be developed later.4 and earlier. This feature. 18 Object Messaging 2010-12-08 | © 2010 Apple Inc. any floating-point type. Therefore. the primaryColor method illustrated above takes no parameters. as long as the message returns an object. . any pointer type. in Mac OS X v10. In particular. But. any pointer type. referred to as polymorphism. If you write code that sends a display message to an id variable. Message parameters bring information from the outside to the receiver. messages in Objective-C appear in the same syntactic positions as function calls in standard C. because methods “belong to” an object. void. The Receiver’s Instance Variables A method has automatic access to the receiving object’s instance variables. A method has automatic access only to the receiver’s instance variables. If the message sent to nil returns anything other than the aforementioned value types (for example. yet it can find the primary color for otherRect and return it. It can’t confuse them with methods defined for other kinds of object. even if another object has a method with the same name. In Mac OS X v10. or any integer scalar of size less than or equal to sizeof(void*). For example. See “Defining a Class” (page 35) for more information on referring to instance variables. by other programmers working on other projects. a message to nil also is valid. For example. Messages are sent to receivers much as letters are delivered to your home. without having to declare them as parameters. you should not rely on the return value of messages sent to nil unless the method’s return type is an object. You don’t need to pass them to the method as parameters. or any integer scalar of size less than or equal to sizeof(void*). Therefore. or any vector type) the return value is undefined. All Rights Reserved. Every method assumes the receiver and its instance variables. a message sent to nil returns nil.5. without you having to choose at the time you write the code what kinds of objects they might be. It also supports the way object-oriented programmers think about objects and messages. and Messaging Note: The behavior of sending messages to nil changed slightly with Mac OS X v10. two objects can respond differently to the same message. any object that has a display method is a potential receiver. it permits you to write code that might apply to any number of different kinds of objects. A Circle and a Rectangle would respond differently to identical instructions to track the cursor. Classes. Polymorphism As the earlier examples illustrate.
an Objective-C statement can achieve a variety of results. the choice of receiver can be made dependent on factors such as user actions. Dot Syntax Objective-C provides a dot (. because binding of methods to messages does not occur until runtime). Because messages do not select methods until runtime (from another perspective. 19 . however. When used with objects. Object Messaging 2010-12-08 | © 2010 Apple Inc. See “Dynamic Method Resolution” in Objective-C Runtime Programming Guide for more details. printf("myInstance value: %d". Dot syntax does not directly get or set an instance variable. The code example above is exactly equivalent to the following: [myInstance setValue:10]. “calls” the method.) This dynamic binding of methods to messages works hand in hand with polymorphism to give object-oriented programming much of its flexibility and power. All Rights Reserved. these differences in behavior are isolated to the methods themselves. and Paste. An application’s objects can each respond in its own way to copy messages. printf("myInstance value: %d". Classes. dot syntax acts as “syntactic sugar”—it is transformed by the compiler into an invocation of an accessor method. This mechanism is discussed in the section “Messaging” in Objective-C Runtime Programming Guide. not by varying the message but by varying the object that receives the message. (For more on this routine. a runtime messaging routine looks at the receiver and at the method named in the message. and Messaging Dynamic Binding A crucial difference between function calls and messages is that a function and its parameters are joined together in the compiled code. myInstance. When a message is sent.CHAPTER 1 Objects. it doesn’t even have to enumerate the possibilities. Because each object can have its own version of a method. see “Messaging” in Objective-C Runtime Programming Guide. but a message and a receiving object aren’t united until the program is running and the message is sent. Dot syntax uses the same pattern that accessing C structure elements uses: myInstance. It locates the receiver’s implementation of a method matching the name.) operator that offers an alternative to square bracket notation ([]) to invoke accessor methods. users determine which objects receive messages from menu commands such as Cut.value). the exact method invoked to respond to a message can be determined only at runtime. An object that displays text would react to a copy message differently from an object that displays scanned images. An object that represents a set of shapes would respond differently to a copy message than a Rectangle would. The message goes to whatever object controls the current selection. for example. Objective-C takes dynamic binding one step further and allows even the message that’s sent (the method selector) to be a variable determined at runtime. Copy.value = 10. The code that sends the message doesn’t have to be concerned with them. [myInstance value]). and passes it a pointer to the receiver’s instance variables. not when the code is compiled. Receivers can be decided as the program runs. Therefore. Dynamic Method Resolution You can provide implementations of class and instance methods at runtime using dynamic method resolution. When executing code based upon the Application Kit (AppKit).
the set accessor method for age is not invoked: age = 10. the compiler—at best—generates only an undeclared method warning that you invoked a nonexistent setter method. .0. Classes.age = 10. All Rights Reserved. A further advantage is that the compiler can signal an error when it detects an attempt to write to a read-only declared property. BOOL hidden = [graphic hidden]. the setter method is named by capitalizing the symbol following the dot and prefixing it with “set.0. Listing 1-1 Accessing properties using dot syntax Graphic *graphic = [[Graphic alloc] init]. Using dot syntax to set a value calls the associated setter accessor method.CHAPTER 1 Objects. // @"Hello" is a constant NSString object. If you do not use self. 20. CGFloat xLoc = graphic.. If you instead use square bracket syntax for accessing variables. NSColor *color = [graphic color]. the system calls the associated getter accessor method. Listing 1-2 Accessing properties using bracket syntax Graphic *graphic = [[Graphic alloc] init]. BOOL hidden = graphic. } graphic.color. int textCharacterLength = graphic. An advantage of dot syntax is that its representation is more compact and may be more readable than the corresponding square bracket notation. for example: self. NSColor *color = graphic. particularly when you want to access or modify a property that is a property of another object (that is a property of another object. In the following example. the getter method has the same name as the symbol following the dot.text.0).” If you don’t want to use default accessor names. By default. but instead use square bracket syntax. Listing 1-1 illustrates several use cases. CGFloat xLoc = [graphic xLoc]. 20 Object Messaging 2010-12-08 | © 2010 Apple Inc.text = @"Hello".textHidden != YES) { graphic. General Use When you use dot syntax to get a value. if you want to access an object’s own instance variable using accessor methods. if (graphic. you access the instance variable directly. or the equivalent: [self setAge:10]. int textCharacterLength = [[graphic text] length]. and so on). and the code fails at runtime. 10. you must explicitly call out self. The statements in Listing 1-2 compile to exactly the same code as the statements using dot syntax shown in Listing 1-1 (page 20).hidden.bounds = NSMakeRect(10. 120.0. and Messaging As a corollary. you can change them by using the declared properties feature (see “Declared Properties” (page 69)).xLoc. By default.length.
Classes. 10. // An example of using a setter.0. 20.address. 21 . the following pairs are all equivalent: // Each member of the path is an object. as an alternative to using square bracket syntax.origin.length /= 4.address. which is equivalent to the following square bracket statements: [data setLength:[data length] + 1024]. [data setLength:[data length] * 2].contentView.y. doing so introduces no additional thread dependencies. y = window. All Rights Reserved. Because using dot syntax is simply a way to invoke accessor methods. x = [[[person address] street] name].bounds. and Messaging if ([graphic isTextHidden] != YES) { [graphic setText:@"Hello"]. For example. ● The following statement invokes the aProperty getter method and assigns the return value to aVariable: Object Messaging 2010-12-08 | © 2010 Apple Inc.street.0.CHAPTER 1 Objects. [data setLength:[data length] / 4]. } [graphic setBounds:NSMakeRect(10. data. Performance and Threading Whether you invoke accessor methods with dot syntax or square bracket syntax.length *= 2.origin. the result is the same as sending the equivalent message to nil.0)]. As a result. the two coding techniques result in exactly the same performance. For example. 120. // The path contains a C struct. the compiler generates equivalent code. the meaning of compound assignments is well defined.length += 1024.name. x = person. [[[person address] street] setName: @"Oxford Road"]. person. For properties of the appropriate C language type.name = @"Oxford Road". Dot Syntax Usage Use the Objective-C dot syntax to invoke an accessor method. say you have an instance of the NSMutableData class: NSMutableData *data = [NSMutableData dataWithLength:1024]. nil Values If a nil value is encountered during property traversal. data.y.0.street. You could update the length property of the instance using dot syntax and compound assignments: data. y = [[window contentView] bounds]. // This will crash if window is nil or -contentView returns nil.
fooIfYouCan = myInstance. or if the setName: method returns anything but void. anObject. ● The following statement invokes the setName: setter method on the anObject object. That is. It then assigns to the xOrigin variable the value of the origin.aProperty. this pattern is strongly discouraged. .). ● The following statement generates a compiler warning (warning: value returned from property not used.CHAPTER 1 Objects. /* Code fragment.origin. All Rights Reserved. namely for invoking an accessor method. ● The following statement invokes the bounds method on the aView object.floatProperty = ++i. and Messaging aVariable = anObject.retain. the rightmost assignment is preevaluated and the result is passed to the setIntegerProperty: and setFloatProperty: setter methods. NSInteger i = 10.bounds. ● The following code generates a compiler warning that setFooIfYouCan: does not appear to be a setter method because it does not return (void). The compiler issues a warning if the setName: method does not exist. passing @"New Name" as the method’s parameter: anObject. if the property name does not exist. It does not generate a compiler warning unless there is a mismatch between the type for flag and the method’s return type. ● The following statement invokes the lockFocusIfCanDraw method and assigns the return value to flag. Nonetheless.lockFocusIfCanDraw. flag = aView.integerProperty = anotherObject. The data type of the preevaluated result is coerced as required at each point of assignment. */ anObject.x structure element of the NSRect object returned by the bounds method. */ . anObject. otherwise the compiler issues a warning. /* Method declaration. Incorrect Use of Dot Syntax The code patterns that follow are strongly discouraged because they do not conform to the intended use of dot syntax. Classes. ● The following statements result in the assignment of the value of 11 to two properties: the integerProperty property of the anObject object and the floatProperty property of the anotherObject object. xOrigin = aView.(BOOL) setFooIfYouCan: (MyClass *)newFoo. The type of the aProperty property and the type of the aVariable variable must be compatible.x.name = @"New Name". 22 Object Messaging 2010-12-08 | © 2010 Apple Inc.
the names of instances typically begin with a lowercase letter (such as myRectangle). Even so. but the methods are shared. Inheritance links all classes together in a hierarchical tree with a single class at its root. By convention. This pattern is strongly discouraged because simply adding a setter for a property does not imply readwrite access. */ @property(readonly) NSInteger readonlyProperty. 23 . the objects it builds are instances of the class. It doesn’t need to duplicate inherited code. NSText objects. The objects that do the main work of your program are instances created by the class object at runtime. and it defines a set of methods that all objects in the class can use. and they all have a set of instance variables cut from the same mold. Classes An object-oriented program is typically built from a variety of objects. */ . for example.readonlyProperty = 5. this code works at runtime. Figure 1-1 illustrates the hierarchy for a few of the classes used in a drawing program. All Rights Reserved. The new class simply adds to or modifies what it inherits. class names begin with an uppercase letter (such as Rectangle). Inheritance Class definitions are additive.CHAPTER 1 Objects. it declares the instance variables that become part of every member of the class. The compiler creates just one accessible object for each class.) The class object is the compiled version of the class. NSWindow objects. /* Property declaration. /* Method declaration. because the setter method is present. Each object gets its own instance variables. When writing code that is based upon the Foundation framework. a class object that knows how to build new objects belonging to the class. Every class (except a root class) has a superclass one step nearer the root. All instances of a class have the same set of methods. NSFont objects. The class definition is a prototype for a kind of object. (For this reason it’s traditionally called a factory object. Classes. /* Code fragment.(void) setReadonlyProperty: (NSInteger)newValue. A program based on the Cocoa frameworks might use NSMatrix objects. and many others. and Messaging ● The following code generates a compiler warning because the readonlyProperty property is declared with readonly access (warning: assignment to readonly property 'readonlyProperty'). Programs often use more than one object of the same kind or class—several NSArray objects or NSWindow objects. each new class that you define is based on another class from which it inherits methods and instance variables. NSDictionary objects. In Objective-C. and any class (including a root class) can be the superclass for any number of subclasses one step farther from the root. Classes 2010-12-08 | © 2010 Apple Inc. Be sure to explicitly set property access correctly in a property’s declaration statement. that root class is typically NSObject. you define objects by defining their class. */ self.
Others you might want to adapt to your own needs by defining a subclass. a graphic. and an object of type NSObject. and Messaging Figure 1-1 Some drawing program classes NSObject Graphic Image Text Shape Line Rectangle Square Circle Figure 1-1 shows that the Square class is a subclass of the Rectangle class. every class you create must be the subclass of another class (unless you define a new root class). Each successive subclass further modifies the cumulative total of what’s inherited. and NSObject. You can thus create very sophisticated objects by writing only a small amount of code and reusing work done by the programmers of the framework. All Rights Reserved. Inheritance is cumulative. Cocoa includes the NSObject class and several frameworks containing definitions for more than 250 additional classes. Inheriting this ability from the NSObject class is much simpler and much more reliable than reinventing it in a new class definition.CHAPTER 1 Objects. A class that doesn’t need to inherit any special behavior from another class should nevertheless be made a subclass of the NSObject class. as well as those defined specifically for Square. . Plenty of potential superclasses are available. Some are classes that you can use off the shelf and incorporate them into your program as is. Shape is a subclass of Graphic. When you define a class. It imparts to the classes and instances of classes that inherit from it the ability to behave as objects and cooperate with the runtime system. So a Square object has the methods and instance variables defined for Rectangle. you link it to the hierarchy by declaring its superclass. The Square class defines only the minimum needed to turn a rectangle into a square. Some framework classes define almost everything you need. This is simply to say that an object of type Square isn’t only a square. Classes. the Rectangle class is a subclass of Shape. Shape. The NSObject Class NSObject is a root class. It defines the basic framework for Objective-C objects and object interactions. 24 Classes 2010-12-08 | © 2010 Apple Inc. Every class but NSObject can thus be seen as a specialization or an adaptation of another class. a shape. Graphic. it’s also a rectangle. but leave some specifics to be implemented in a subclass. and so doesn’t have a superclass. Instances of the class must at least have the ability to behave like Objective-C objects at runtime. and Graphic is a subclass of NSObject.
Shape. When you use one of the object-oriented frameworks provided by Cocoa. This type of inheritance is a major benefit of object-oriented programming.. they inherit only methods. It can simply define new methods and rely on the instance variables it inherits. the new object contains not only the instance variables that were defined for its class but also the instance variables defined for its superclass and for its superclass’s superclass. width.. For instance. Square might not declare any new instance variables of its own. and identify them to the runtime system. For this reason. and for its superclass’s superclass. Note that the variables that make the object a rectangle are added to the ones that make it a shape. all the way back to the root class. Any new class you define in your program can therefore make use of the code written for all the classes above it in the hierarchy. float float BOOL NSColor . For example. But because they don’t have instance variables (only instances do). Classes. Inheriting Instance Variables When a class object creates a new instance. and so on. and Messaging Note: Implementing a new root class is a delicate task and one with many hidden hazards. if it needs any instance variables at all. the isa instance variable defined in the NSObject class becomes part of every object. For more information. filled. The class must duplicate much of what the NSObject class does. such as allocate instances. 25 .. isa connects each object to its class. connect them to their class. Figure 1-2 shows some of the instance variables that could be defined for a particular implementation of a Rectangle class and where they may come from. a Square object can use methods defined in the Rectangle. and NSObject classes as well as methods defined in its own class. Figure 1-2 Class NSPoint NSColor Pattern . height. you should generally use the NSObject class provided with Cocoa as the root class. *fillColor. linePattern. Classes 2010-12-08 | © 2010 Apple Inc. Class objects also inherit from the classes above them in the hierarchy. Rectangle instance variables isa.. Graphic. and the ones that make it a shape are added to the ones that make it a graphic. Inheriting Methods An object has access not only to the methods defined for its class but also to methods defined for its superclass. see NSObject Class Reference and the NSObject Protocol Reference. origin. All Rights Reserved. *primaryColor. all the way back to the root of the hierarchy. You have to add only the code that customizes the standard functionality to your application.CHAPTER 1 Objects. your programs can take advantage of the basic functionality coded into the framework classes. declared in NSObject declared in Graphic declared in Shape declared in Rectangle A class doesn’t have to declare instance variables. Thus.
you can’t override an inherited variable by declaring a new one with the same name. The NSObject class is the canonical example of an abstract class in Cocoa. on the other hand.) Unlike some other languages. When it does. 26 Classes 2010-12-08 | © 2010 Apple Inc. Objective-C does not have syntax to mark classes as abstract. A redefined method can also incorporate the very method it overrides. The type is based not just on the data structure the class defines (instance variables). Although overriding a method blocks the original version from being inherited. Class Types A class definition is a specification for a kind of object. For example. . instances of the new class perform it rather than the original. Because an object has memory allocated for every instance variable it inherits. Classes. The new method overrides the original. Abstract Classes Some classes are designed only or primarily so that other classes can inherit from them. it can’t override inherited instance variables. (Because abstract classes must have subclasses to be useful. Graphic defines a display method that Rectangle overrides by defining its own version of display. it would be a generic object with the ability to do nothing in particular. the compiler will complain. but also on the behavior included in the definition (methods). instances of which you might occasionally use directly. Abstract classes often contain code that helps define the structure of an application. and Messaging Overriding One Method with Another There’s one useful exception to inheritance: When you define a new class. you can implement a new method with the same name as one defined in a class farther up the hierarchy. The abstract class is typically incomplete by itself. the implementation of the method is effectively spread over all the classes. nor does it prevent you from creating an instance of an abstract class. the new method serves only to refine or modify the method it overrides. When several classes in the hierarchy define the same method. in effect. When you create subclasses of these classes. provides an example of an abstract class. The Graphic method is available to all kinds of objects that inherit from the Graphic class—but not to Rectangle objects. If you try. instances of your new classes fit effortlessly into the application structure and work automatically with other objects. but each new version incorporates the version it overrides. which instead perform the Rectangle version of display. defines a data type. The class. but contains useful code that reduces the implementation burden of its subclasses. Although a subclass can override inherited methods. they’re sometimes also called abstract superclasses.CHAPTER 1 Objects. These abstract classes group methods and instance variables that can be used by a number of subclasses into a common definition. All Rights Reserved. and subclasses of the new class inherit it rather than the original. rather than replace it outright. other methods defined in the new class can skip over the redefined method and find the original (see “Messages to self and super” (page 43) to learn how). The NSView class. You never use instances of the NSObject class in an application—it wouldn’t be good for anything.
Objects are always typed by a pointer. Type Introspection Instances can reveal their types at runtime. Classes. id hides it.. given the declaration described here. because inheritance makes a Rectangle object a kind of Graphic object (as shown in the example hierarchy in Figure 1-1 (page 24)). Because this way of declaring an object type gives the compiler information about the kind of object it is. it’s more than that because it also has the instance variables and method capabilities of Shape and Rectangle objects. objects are statically typed as pointers to a class. 27 . The isMemberOfClass: method. but it’s a Graphic object nonetheless. also defined in the NSObject class.. Just as id is actually a pointer. Static Typing You can use a class name in place of id to designate an object’s type: Rectangle *myRectangle. All Rights Reserved. In addition. defined in the NSObject class. Later sections of this chapter discuss methods that return the class object. and reveal other information. Static typing to the superclass is possible here because a Rectangle object is a Graphic object. An object can be statically typed to its own class or to any class that it inherits from. however. report whether an object can respond to a message. the compiler considers myRectangle to be of type Graphic. Introspection isn’t limited to type information. Static typing makes the pointer explicit. However. if the myRectangle object is allocated and initialized as an instance of Rectangle. it’s known as static typing. as an argument to the sizeof operator: int i = sizeof(Rectangle). Static typing permits the compiler to do some type checking—for example. and related methods. See “Enabling Static Behavior” (page 95) for more on static typing and its benefits. isMemberOfClass:. checks more generally whether the receiver inherits from or is a member of a particular class (whether it has the class in its inheritance path): if ( [anObject isKindOfClass:someClass] ) . The isKindOfClass: method. For purposes of type checking. a Rectangle instance can be statically typed to the Graphic class: Graphic *myRectangle.. it can make your intentions clearer to others who read your source code. For example. In addition. it is treated as one.CHAPTER 1 Objects. See NSObject Class Reference for more on isKindOfClass:. to warn if an object could receive a message that it appears not to be able to respond to—and to loosen some restrictions that apply to objects generically typed id. and Messaging A class name can appear in source code wherever a type specifier is permitted in C—for example. checks whether the receiver is an instance of a particular class: if ( [anObject isMemberOfClass:someClass] ) . The set of classes for which isKindOfClass: returns YES is the same set to which the receiver can be statically typed. At runtime. Classes 2010-12-08 | © 2010 Apple Inc. it doesn’t defeat dynamic binding or alter the dynamic determination of a receiver’s class at runtime..
which means mainly information about what instances of the class are like. In the following example. Class rectClass = [Rectangle class]. As these examples show. like all other objects. be typed id. In source code. receive messages. a class definition can include methods intended specifically for the class object—class methods as opposed to instance methods. it’s not an instance itself. . The class object has access to all the information about the class. and are the agents for producing instances at runtime. It has no instance variables of its own and it can’t perform methods intended for instances of the class. Elsewhere. much of it about instances of the class: ● ● ● ● The name of the class and its superclass A template describing a set of instance variables The declarations of method names and their return and parameter types The method implementations This information is compiled and recorded in data structures made available to the runtime system. A class object inherits class methods from the classes above it in the hierarchy. you need to ask an instance or the class to return the class id. All Rights Reserved. the class object is represented by the class name. Using this type name for a class is equivalent to using the class name to statically type an instance. All class objects are of type Class. Classes. class objects can. 28 Classes 2010-12-08 | © 2010 Apple Inc. However. just as instances inherit instance methods. to represent the class. and inherit methods from other classes. id rectClass = [Rectangle class]. and Messaging Class Objects A class definition contains various kinds of information. Although a class object keeps the prototype of a class instance. However. the class name stands for the class object only as the receiver in a message expression. They’re special only in that they’re created by the compiler.CHAPTER 1 Objects. It’s able to produce new instances according to the plan put forward in the class definition. The compiler creates just one object. Both respond to a class message: id aClass = [anObject class]. But class objects can also be more specifically typed to the Class data type: Class aClass = [anObject class]. lack data structures (instance variables) of their own other than those built from the class definition. a class object. the Rectangle class returns the class version number using a method inherited from the NSObject class: int versionNumber = [Rectangle version]. Class objects are thus full-fledged objects that can be dynamically typed.
benefits for design. and Messaging Note: The compiler also builds a metaclass object for each class. Initialization methods often take parameters to allow particular values to be passed and have keywords to label the parameters (initWithPosition:size:. the metaclass object is used only internally by the runtime system. or one like it. to customize an object with a class. perhaps in response to user actions. But while you can send messages to instances and to the class object. that is. The inheritance hierarchy in Figure 1-3 shows some of those provided by AppKit. Every class object has at least one method (like alloc) that enables it to produce new objects. an NSMatrix object can be customized with a particular kind of NSCell object. All Rights Reserved.CHAPTER 1 Objects. but there are many different kinds. Classes 2010-12-08 | © 2010 Apple Inc. But what kind of objects should they be? Each matrix displays just one kind of NSCell. This code tells the Rectangle class to create a new rectangle instance and assign it to the myRectangle variable: id myRectangle. Classes. it generally needs to be more completely initialized. That’s the function of an init method. Creating Instances A principal function of a class object is to create new instances. and every instance has at least one method (like init) that prepares it for use. It describes the class object just as the class object describes instances of the class. Initialization typically follows immediately after allocation: myRectangle = [[Rectangle alloc] init]. In AppKit. where the class belongs to an open-ended set. for example. It’s possible. When it grows. for example. would be necessary before myRectangle could receive any of the messages that were illustrated in previous examples in this chapter. except the isa variable that connects the new instance to its class. 29 . All inherit from the generic NSCell class. The visible matrix that an NSMatrix object draws on the screen can grow and shrink at runtime. myRectangle = [Rectangle alloc]. It’s a choice that has intended. and sometimes surprising. the matrix needs to be able to produce new objects to fill the new slots that are added. but every initialization method begins with “init” . For an object to be useful. The alloc method dynamically allocates memory for the new object’s instance variables and initializes them all to 0—all. Customization with Class Objects It’s not just a whim of the Objective-C language that classes are treated as objects. The alloc method returns a new instance and that instance performs an init method to set its initial state. It can do this when the matrix is first initialized and later when new cells are needed. This line of code. for example. An NSMatrix object can take responsibility for creating the individual objects that represent its cells. is a method that might initialize a new Rectangle instance).
you’d also have to define a new kind of NSMatrix. read. even types that haven’t been invented yet. you can specify instance variables. The simplest way to do this is to declare a variable in the class implementation file: int MCLSGlobalVariable. NSTextFieldCell objects to display fields where the user can enter and edit text. This kind of customization would be difficult if classes weren’t objects that could be passed in messages and assigned to variables. should they be NSButtonCell objects to display a bank of buttons or switches. But this solution would require users of the NSMatrix class to do work that ought to be done in the NSMatrix class itself. you must define an external variable of some sort. a class object has no access to the instance variables of any instances. Because they would be implementing the methods. each with a different kind of cell. and Messaging Figure 1-3 The inheritance hierarchy for NSCell NSObject NSCell NSBrowserCell NSButtonCell NSMenuCell NSActionCell NSTextFieldCell NSSliderCell NSFormCell When a matrix creates NSCell objects. with a class object. it could become cluttered with NSMatrix subclasses. Variables and Class Objects When you define a new class. The NSMatrix object uses the class object to produce new cells when it’s first initialized and whenever it’s resized to contain more cells. There is. and it unnecessarily proliferates the number of classes. A better solution. Every time you invented a new kind of NSCell. Moreover. The NSMatrix class also defines a setCellClass: method that passes the class object for the kind of NSCell object an NSMatrix should use to fill empty slots: [myMatrix setCellClass:[NSButtonCell class]]. 30 Classes 2010-12-08 | © 2010 Apple Inc. For all the instances of a class to share data. Classes. users could make certain that the objects they created were of the right type. and the solution the NSMatrix class adopts. programmers on different projects would be writing virtually identical code to do the same job. . Every instance of the class can maintain its own copy of the variables you declare—each object controls its own data. Moreover. it can’t initialize. or alter them. Because an application might need more than one kind of matrix. Only internal data structures. are provided for the class. no class variable counterpart to an instance variable. is to allow NSMatrix instances to be initialized with a kind of NSCell—that is. All Rights Reserved. however. One solution to this problem would be to define the NSMatrix class as abstract and require everyone who uses it to declare a subclass and implement the methods that produce new cells.CHAPTER 1 Objects. or some other kind of NSCell? The NSMatrix object must allow for any kind of cell. initialized from the class definition. all to make up for the failure of NSMatrix to do it.
This saves the step of allocating and initializing an instance. because class B doesn’t implement initialize. @implementation MyClass + (MyClass *)sharedInstance { // check for existence of shared instance // create if necessary return MCLSSharedInstance. class A should ensure that its initialization logic is performed only once. or directly manipulated by. it can approach being a complete and versatile object in its own right. Although programs don’t allocate class objects. an initialize message sent to a class that doesn’t implement the initialize method is forwarded to the superclass. and class B inherits from class A but does not implement the initialize method. Objective-C does provide a way for programs to initialize them. Therefore. you don’t need to write an initialize method to respond to the message. you can declare a variable to be static.CHAPTER 1 Objects. All Rights Reserved. you can put all the object’s state into static variables and use only class methods. A class object can be used to coordinate the instances it creates. static MyClass *MCLSSharedInstance. static variables cannot be inherited by. Classes. In the case when you need only one object of a particular class. the initialize method is a good place to set their initial values. assume class A implements the initialize method. and for the appropriate class.) This pattern is commonly used to define shared instances of a class (such as singletons. If a class makes use of static or global variables. you may need to initialize it just as you would an instance. see “Creating a Singleton Instance” in Cocoa Fundamentals Guide). even though the superclass has already received the initialize message. the initialize method could set up the array and even allocate one or two default instances to have them ready. Declaring a variable static limits its scope to just the class—and to just the part of the class that’s implemented in the file. Just before class B is to receive its first message. subclasses. class A’s initialize is executed instead. 31 . but the limited scope of static variables better serves the purpose of encapsulating data into separate objects. dispense instances from lists of objects already created. and Messaging @implementation MyClass // implementation continues In a more sophisticated implementation. } // implementation continues Static variables help give the class object more functionality than just that of a factory producing instances. Note: It is also possible to use external variables that are not declared static. and provide class methods to manage it. This sequence gives the class a chance to set up its runtime environment before it’s used. For example. The runtime system sends an initialize message to every class object before the class receives any other messages and after its superclass has received the initialize message. If no initialization is required. Classes 2010-12-08 | © 2010 Apple Inc. Because of inheritance. But. For example. or manage other processes essential to the application. (Thus unlike instance variables. Initializing a Class Object If you want to use a class object for anything besides allocating instances. if a class maintains an array of instances. the runtime system sends initialize to it.
classes and instances alike. class objects can’t be. . This example passes the Rectangle class as a parameter in an isKindOfClass: message: 32 Classes 2010-12-08 | © 2010 Apple Inc. Static typing enables the compiler to do better type checking and makes source code more self-documenting. Therefore. class names can be used in only two very different contexts. in a class’s implementation of the initialize method. Both class objects and instances should be able to introspect about their abilities and to report their place in the inheritance hierarchy. This usage was illustrated in several of the earlier examples. Classes. because they aren’t members of a class. See “Enabling Static Behavior” (page 95) for details. Listing 1-3 Implementation of the initialize method + (void)initialize { if (self == [ThisClass class]) { // Perform initialization here. So that NSObject: ● The class name can be used as a type name for a kind of object.CHAPTER 1 Objects. For more on this peculiar ability of class objects to perform root instance methods. Here anObject is statically typed to be a pointer to a Rectangle object. When a class object receives a message that it can’t respond to with a class method. For example: Rectangle *anObject.. All Rights Reserved. Class Names in Source Code In source code. you must ask the class object to reveal its id (by sending it a class message). use the template in Listing 1-3 when implementing the initialize method. and only if there’s no class method that can do the job. } } Note: Remember that the runtime system sends initialize to each class individually. It’s the province of the NSObject class to provide this interface. The only instance methods that a class object can perform are those defined in the root class. and Messaging To avoid performing initialization logic more than once. the class name refers to the class object.. . the runtime system determines whether there’s a root instance method that can respond. Methods of the Root Class All objects. you must not send the initialize message to its superclass. need an interface to the runtime system. but rather belong to the Class data type. Only instances can be statically typed. ● As the receiver in a message expression. see NSObject Class Reference. In any other context. The class name can stand for the class object only as a message receiver. The compiler expects it to have the data structure of a Rectangle instance and to have the instance methods defined and inherited by the Rectangle class.
It would have been illegal to simply use the name “Rectangle” as the parameter.. In a dynamically-created subclass... key-value observing and Core Data do this—see Key-Value Observing Programming Guide and Core Data Programming Guide respectively). The class name can only be a receiver. This function returns nil if the string it’s passed is not a valid class name... the following inequalities pertain for dynamic subclasses: [object class] != object_getClass(object) != *((Class*)object) You should therefore test two classes for equality as follows: if ([objectA class] == [objectB class]) { //. Class names are the only names with global visibility in Objective-C. Put in terms of API. you should therefore compare the values returned by the class method rather than those returned by lower-level functions. A class and a global variable can’t have the same name. Classes 2010-12-08 | © 2010 Apple Inc.. if ( [anObject isKindOfClass:NSClassFromString(className)] ) . 33 .. There are several features in the Cocoa frameworks that dynamically and transparently subclass existing classes to extend their functionality (for example. to get the correct class. It is important. though. the class method is typically overridden such that the subclass masquerades as the class it replaces. Class names exist in the same namespace as global variables and function names.CHAPTER 1 Objects. If you don’t know the class name at compile time but have it as a string at runtime. . When testing for class equality. Testing Class Equality You can test two class objects for equality using a direct pointer comparison. Classes. you can use NSClassFromString to return the class object: NSString *className.. and Messaging if ( [anObject isKindOfClass:[Rectangle class]] ) . All Rights Reserved.
and Messaging 34 Classes 2010-12-08 | © 2010 Apple Inc.CHAPTER 1 Objects. Classes. All Rights Reserved. .
Class Interface The declaration of a class interface begins with the compiler directive @interface and ends with the directive @end. Keeping class interfaces separate better reflects their status as independent entities. once you’ve declared its interface—you can freely alter its implementation without affecting any other part of the application. class interface and implementation are usually in two different files.h extension typical of header files. Categories can compartmentalize a class definition or extend an existing one. it’s customary to have a separate interface file for each class. A single file can declare or implement more than one class. (All Objective-C directives to the compiler begin with “@” .m extension.) @interface ClassName : ItsSuperclass { instance variable declarations } method declarations Source Files 2010-12-08 | © 2010 Apple Inc. indicating that it contains Objective-C source code. classes are defined in two parts: ● ● An interface that declares the methods and instance variables of the class and names its superclass An implementation that actually defines the class (contains the code that implements its methods) Each of these parts is typically in its own file. however. Because it’s included in other source files. Nevertheless.m. a class definition spans several files through the use of a feature called a category. the name of the interface file usually has the . In Objective-C. Once you’ve determined how an object interacts with other elements in your program—that is. 35 . The interface file must be made available to anyone who uses the class. Categories are described in “Categories and Extensions” (page 81). the Rectangle class would be declared in Rectangle. The interface file can be assigned any other extension. An object is a self-contained entity that can be viewed from the outside almost as a black box.h and defined in Rectangle.CHAPTER 2 Defining a Class Much of object-oriented programming consists of writing the code for new objects—defining new classes. For example. All Rights Reserved. Separating an object’s interface from its implementation fits well with the design of object-oriented programs. Sometimes. if not also a separate implementation file. Interface and implementation files typically are named after the class. The name of the implementation file has the . Source Files Although the compiler doesn’t require it.
36 Class Interface 2010-12-08 | © 2010 Apple Inc.CHAPTER 2 Defining a Class @end The first line of the declaration presents the new class name and links it to its superclass. braces enclose declarations of instance variables. Parameters break the name apart in the declaration.(float)radius. When there’s more than one parameter... . The names of methods that can be used by class objects. the parameters are declared within the method name after the colons. The alloc method illustrated earlier returns id. just as in a message. instance methods. just as a function would: . as discussed under “Inheritance” (page 23). Methods for the class are declared next. the new class is declared as a root class. Circle has a radius method that could match a radius instance variable. If the colon and superclass name are omitted.(void)setWidth:(float)width height:(float)height. NSColor *fillColor. the data structures that are part of each instance of the class. If a return or parameter type isn’t explicitly declared. . For example: . are marked with a minus sign: . Methods that take a variable number of parameters declare them using a comma and ellipsis points. BOOL filled. you can define a class method and an instance method with the same name. especially if the method returns the value in the variable. Here’s a partial list of instance variables that might be declared in the Rectangle class: float width. float height. Although it’s not a common practice.. Method return types are declared using the standard C syntax for casting one type to another: . Parameter types are declared in the same way: . class methods. Following the first part of the class declaration.(void)display. which is more common.makeGroup:group. The methods that instances of a class can use. it’s assumed to be the default type for methods and messages—an id. A method can also have the same name as an instance variable. after the braces enclosing instance variables and before the end of the class declaration. All Rights Reserved.(void)setRadius:(float)aRadius. are preceded by a plus sign: + alloc. For example. a rival to the NSObject class. The superclass defines the position of the new class in the inheritance hierarchy.
To reflect the fact that a class definition builds on the definitions of inherited classes. 37 . and parameters.h" This directive is identical to #include. Because declarations like this simply use the class name as a type and don’t depend on any details of the class interface (its methods and instance variables). All Rights Reserved. an interface file begins by importing the interface for its superclass: #import "ItsSuperclass. return values. except that it makes sure that the same file is never included more than once. it must import them explicitly or declare them with the @class directive: @class Rectangle.CHAPTER 2 Defining a Class Importing the Interface The interface file must be included in any source module that depends on the class interface—that includes any module that creates an instance of the class.(void)setPrimaryColor:(NSColor *)aColor. Referring to Other Classes An interface file declares a class and. This directive simply informs the compiler that “Rectangle” and “Circle” are class names. If the interface mentions classes not in this hierarchy. implicitly contains declarations for all inherited classes. the interface files for all inherited classes. For example. by importing its superclass. When a source module imports a class interface. However. sends a message to invoke a method declared for the class. Note that if there is a precomp—a precompiled header—that supports the superclass. you may prefer to import the precomp instead. Circle. or mentions an instance variable declared in the class. this declaration . It’s therefore preferred and is used in place of #include in code examples throughout Objective-C–based documentation. It doesn’t import their interface files. when the interface to a class is actually used (instances created. it gets interfaces for the entire inheritance hierarchy that the class is built upon. the @class directive gives the compiler sufficient forewarning of what to expect. mentions the NSColor class. An interface file mentions class names when it statically types instance variables. from NSObject on down through its superclass. The interface is usually included with the #import directive: #import "Rectangle. indirectly. Class Interface 2010-12-08 | © 2010 Apple Inc.h" @interface ClassName : ItsSuperclass { instance variable declarations } method declarations @end This convention means that every interface file includes.
Every method that can be used outside the class definition is declared in the interface file. if one class declares a statically typed instance variable of another class. . For example. ● ● Class Implementation The definition of a class is structured very much like its declaration. Although instance variables are most naturally viewed as a matter of the implementation of a class rather than its interface. As a programmer. This declaration is necessary because the compiler must be aware of the structure of an object where it’s used. The Role of the Interface The purpose of the interface file is to declare the new class to other source modules (and to other programmers). Rectangle. it avoids potential problems that may come with importing files that import still other files. Being simple. the interface file lets other modules know what messages can be sent to the class object and instances of the class. the class interface must be imported. and the corresponding implementation file imports their interfaces (since it needs to create instances of those classes or send them messages). For example. It begins with the @implementation directive and ends with the @end directive: @implementation ClassName : ItsSuperclass { instance variable declarations } method definitions @end However. It contains information they need to work with the class (programmers might also appreciate a little documentation). they must nevertheless be declared in the interface file. ● The interface file tells users how the class is connected into the inheritance hierarchy and what other classes—inherited or simply referred to somewhere in the class—are needed. The @class directive minimizes the amount of code seen by the compiler and linker.CHAPTER 2 Defining a Class messages sent). and tells programmers what variables subclasses inherit. Typically. an interface file uses @class to declare classes. it can safely omit: ● ● The name of the superclass The declarations of instance variables 38 Class Implementation 2010-12-08 | © 2010 Apple Inc. methods that are internal to the class implementation can be omitted. and their two interface files import each other.h. you can generally ignore the instance variables of the classes you use. neither class may compile correctly. not just where it’s defined. every implementation file must import its own interface.m imports Rectangle. All Rights Reserved. The interface file also lets the compiler know what instance variables an object contains. and is therefore the simplest way to give a forward declaration of a class name. Because the implementation doesn’t need to repeat any of the declarations it imports. except when defining a subclass. through its list of method declarations. Finally. however.
It can refer to them simply by name. You don’t need either of the structure operators (. All Rights Reserved. . the exact nature of the structure is hidden.getGroup:group. } . } .. For example: + (id)alloc { .(BOOL)isFilled { . { va_list ap. va_start(ap... } Methods that take a variable number of parameters handle them just as a function would: #import <stdarg. within a pair of braces. group). this method definition refers to the receiver’s filled instance variable: . 39 .. yet the instance variable falls within its scope. This simplification of method syntax is a significant shorthand in the writing of Objective-C code.... the definition of an instance method has all the instance variables of the object within its scope. . } Referring to Instance Variables By default. Class Implementation 2010-12-08 | © 2010 Apple Inc.. .. For example. Before the braces..CHAPTER 2 Defining a Class Importing the interface file simplifies the implementation and makes it mainly devoted to method definitions: #import "ClassName.(void)setFilled:(BOOL)flag { filled = flag.. Although the compiler creates the equivalent of C structures to store instance variables.h> . but without the semicolon.. like C functions. } Neither the receiving object nor its filled instance variable is declared as a parameter to this method.(void)setFilled:(BOOL)flag { .h" @implementation ClassName method definitions @end Methods for a class are defined. ... or ->) to refer to an object’s data. they’re declared in the same manner as in the interface file.
(BOOL)isFilled { return filled. not in its internal data structures. as in the following example: . instance variables are more a matter of the way a class is implemented than of the way it’s used. the object’s type must be made explicit to the compiler through static typing. In referring to the instance variable of a statically typed object. } But this need not be the case. int gender. a Sibling method can set them directly: .makeIdenticalTwin { if ( !twin ) { twin = [[Sibling alloc] init]. even though the methods it declares remain the same. and some instance variables might store information that an object is unwilling to reveal. Some methods might return information not stored in instance variables. } As long as the instance variables of the statically typed object are within the scope of the class (as they are here because twin is typed to the same class). } return twin. Often there’s a one-to-one correspondence between a method and an instance variable. it also lets you explicitly set the scope at four levels. struct features *appearance. the compiler limits the scope of instance variables—that is. All Rights Reserved. these changes won’t really affect its interface. for example. } The Scope of Instance Variables Although they’re declared in the class interface. As a class is revised from time to time. twin->gender = gender. the choice of instance variables may change. 40 Class Implementation 2010-12-08 | © 2010 Apple Inc. twin->appearance = appearance. Each level is marked by a compiler directive: Directive @private Meaning The instance variable is accessible only within the class that declares it. as an instance variable: @interface Sibling : NSObject { Sibling *twin. Suppose. An object’s interface lies in its methods. But to provide flexibility. As long as messages are the vehicle for interacting with instances of the class. the structure pointer operator (->) is used. twin.CHAPTER 2 Defining a Class When the instance variable belongs to an object that’s not the receiver. that the Sibling class declares a statically typed object. limits their visibility within the program. To enforce the ability of an object to hide its data. .
the age and evaluation instance variables are private. Using the modern runtime. but acts like @private outside. All instance variables without an explicit scope directive have @protected scope. Figure 2-1 illustrates the levels of scoping. name. This scope is most useful for instance variables in framework classes. 41 . and wage are protected. Figure 2-1 The scope of instance variables (@package scope not shown) The class that declares the instance variable @private @protected A class that inherits the instance variable @public Unrelated code A scoping directive applies to all the instance variables listed after it. @interface Worker : NSObject { char *name. In the following example. an @package instance variable has @public scope inside the executable image that implements the class. Any code outside the class implementation’s image that tries to use the instance variable gets a link error.CHAPTER 2 Defining a Class Directive Meaning @protected The instance variable is accessible within the class that declares it and within classes that inherit it. All Rights Reserved. @private int age. where @private may be too restrictive but @protected or @public too permissive. @protected Class Implementation 2010-12-08 | © 2010 Apple Inc. and boss is public. The @package scope for Objective-C instance variables is analogous to private_extern for C variables and functions. @public @package The instance variable is accessible everywhere. up to the next directive or the end of the list. job. char *evaluation.
. if a subclass accesses an inherited instance variable and alters its value. all unmarked instance variables (like name above) are @protected. no matter how they’re marked. 42 Class Implementation 2010-12-08 | © 2010 Apple Inc. For example: Worker *ceo = [[Worker alloc] init].CHAPTER 2 Defining a Class id job. ceo->boss = nil. the instance variables would be of no use whatsoever. In later versions. can refer to it in a method definition: . the class that declares the variable is tied to that part of its implementation. if a class couldn’t access its own instance variables. ● To limit an instance variable’s scope to just the class that declares it. However. if they exist. All Rights Reserved. float wage. Moreover. Public instance variables should therefore be avoided except in extraordinary cases. It makes sense for classes to have their entire data structures within their scope. Normally. All instance variables that a class declares. job = newPosition. It runs counter to a fundamental principle of object-oriented programming—the encapsulation of data within objects where it’s protected from view and inadvertent error. such as the Worker class shown above. a class that declares a job instance variable. The ability to refer to an instance variable is usually inherited along with the variable. For example. } Obviously. Note that the object must be statically typed. Instance variables marked @private are only available to subclasses by calling public accessor methods. Marking instance variables @public defeats the ability of an object to hide its data. marking a variable @public makes it generally available. a class also has access to the instance variables it inherits. return old. } By default. to get information stored in an instance variable.promoteTo:newPosition { id old = job. it can’t eliminate the variable or alter the role it plays without inadvertently breaking the subclass. there are reasons why you might want to restrict inheriting classes from directly accessing an instance variable: ● Once a subclass accesses an inherited instance variable. especially if you think of a class definition as merely an elaboration of the classes it inherits from. The promoteTo: method illustrated earlier could just as well have been defined in any class that inherits the job instance variable from the Worker class. are within the scope of the class definition. However. Normally. @public id boss. other objects must send a message requesting it. it may inadvertently introduce bugs in the class that declares the variable. a public instance variable can be accessed anywhere as if it were a field in a C structure. At the other extreme. you must mark it @private. even outside of class definitions that inherit or declare the variable. especially if the variable is involved in class-internal dependencies.
the compiler substitutes another messaging routine for the objc_msgSend function. super is a term that substitutes for self only as the receiver in a message expression.reposition { .. self and super both refer to the object receiving a reposition message..reposition { . All Rights Reserved. 43 . Suppose. for example.. . to the superclass of the class sending the message to super—rather than to the class of the object receiving the message..CHAPTER 2 Defining a Class Messages to self and super Objective-C provides two terms that can be used within a method definition to refer to the object that performs the method—self and super. ● super starts the search for the method implementation in a very different place. whatever object that may happen to be. just as the names of instance variables can be. it would begin with the class of the object receiving the reposition message. In the example above. The reposition method could read either: . } or: . All it needs to do is send a setOrigin:: message to the same object that the reposition message itself was sent to.. The substitute routine looks directly to the superclass of the defining class—that is. It begins in the superclass of the class that defines the method where super appears. As receivers. however. . you can refer to that object as either self or super. The two terms are quite different. Wherever super receives a message. In the example above. It can invoke the setOrigin:: method to make the change.. Messages to self and super 2010-12-08 | © 2010 Apple Inc.. starting in the dispatch table of the receiving object’s class. that you define a reposition method that needs to change the coordinates of whatever object it acts on. [self setOrigin:someX :someY]. [super setOrigin:someX :someY].. the two terms differ principally in how they affect the messaging process: ● self searches for the method implementation in the usual manner. self is one of the hidden parameters that the messaging routine passes to every method. When you’re writing the reposition code. } Here. it’s a local variable that can be used freely within a method implementation. it would begin with the superclass of the class where reposition is defined.
Mid defines an ambitious method called makeLastingPeace. 44 Messages to self and super 2010-12-08 | © 2010 Apple Inc. makeLastingPeace sends a negotiate message to the same Low object. The messaging routine finds the version of negotiate defined in Low. which each class uses for its own purpose. In addition. Figure 2-2 The hierarchy of High. All three classes define a method called negotiate. the superclass of Mid is High.. that we create an object belonging to a class called Low. The superclass of Low is Mid. which itself employs the negotiate method. . Mid.CHAPTER 2 Defining a Class An Example: Using self and super The difference between self and super becomes clear when using a hierarchy of three classes. .makeLastingPeace { [self negotiate]. the class of self. and Low superclass High – negotiate superclass Mid – negotiate – makeLastingPeace superclass Low – negotiate Suppose that the implementation of makeLastingPeace (in the Mid class) uses self to indicate the object to send the negotiate message to: . All Rights Reserved. } When a message is sent to a Low object to perform the makeLastingPeace method. The classes and those methods are illustrated in Figure 2-2. for example.. Suppose.
} the messaging routine finds the version of negotiate defined in High. Not being able to reach the Mid version of negotiate. each class in the inheritance hierarchy can implement a method that does part of the job and passes the message on to super for the rest.CHAPTER 2 Defining a Class However.. The designer of Low didn’t want Low objects to perform the inherited method. Here. if the implementation of makeLastingPeace instead uses super as the receiver. super provides a way to bypass a method that overrides another method. Messages to self and super 2010-12-08 | © 2010 Apple Inc.negotiate { . . } For some tasks. 45 . because Mid is where makeLastingPeace is defined.. It ignores the class (Low) of the object that received the makeLastingPeace message and skips to the superclass of Mid. but it would take a direct message to a Mid instance to do so. ● The Mid version of negotiate could still be used. As this example illustrates. it sends an init message to super to have the classes it inherits from initialize their instance variables.(id)init { self = [super init].. Each init method has responsibility for initializing the instance variables defined in its class. But before doing so. may seem like a flaw. is designed to work like this..makeLastingPeace { [super negotiate]. return [super negotiate]. intentionally skipped over the Mid version of negotiate (and over any versions that might be defined in classes like Low that inherit from Mid) to perform the version defined in the High class. Using super Messages to super allow method implementations to be distributed over more than one class. Neither implementation finds the Mid version of negotiate. The init method. You can override an existing method to modify or add to it and still incorporate the original method in the modification: . Each version of init follows this procedure. The designer of the second implementation of makeLastingPeace wanted to use the High version of negotiate and no other. All Rights Reserved. but under the circumstances it’s intentional: ● The author of the Low class intentionally overrode the Mid version of negotiate so that instances of Low (and its subclasses) would invoke the redefined version of the method instead. so classes initialize their instance variables in the order of inheritance: . the use of super enabled makeLastingPeace to bypass the Mid version of negotiate that redefined the High version of that method. The author of the Mid method makeLastingPeace. as just described. . which initializes a newly allocated instance. in sending the negotiate message to super (as shown in the second implementation).
Class methods are often concerned not with the class object. self and super both refer to the receiving object—the object that gets a message telling it to perform the method. . many class methods combine allocation and initialization of an instance. and the rectangleOfColor: message is received by a subclass. return [newInstance autorelease]. it’s often better to send alloc to self. But that would be an error.. This way. self refers to the instance. the instance returned is the same type as the subclass (for example. they are described in more detail in “Allocating and Initializing Objects” (page 49). just as in an instance method. For example. There’s a tendency to do just that in definitions of class methods. often setting up instance variable values at the same time. every class method that creates an instance must allocate storage for the new object and initialize its isa variable to the class structure. If another class overrides these methods (a rare case). } In fact. It’s also possible to concentrate core functionality in one method defined in a superclass and have subclasses incorporate the method through messages to super. // EXCELLENT [newInstance setColor:color]. For example. return [newInstance autorelease]. } } Initializer methods have some additional constraints.CHAPTER 2 Defining a Class if (self) { .. if the class is subclassed. All Rights Reserved. + (id)rectangleOfColor:(NSColor *)color { id newInstance = [[self alloc] init]. but inside a class method. In such a method. // GOOD [newInstance setColor:color]. but with instances of the class. Redefining self super is simply a flag to the compiler telling it where to begin searching for the method to perform. } To avoid confusion. it’s used only as the receiver of a message. Allocation is typically left to the alloc and allocWithZone: methods defined in the NSObject class. Inside an instance method. the array method of NSArray is inherited by NSMutableArray). // BAD [self setColor:color]. self refers to the class object. it might be tempting to send messages to the newly allocated instance and to call the instance self. rather than sending the alloc message to the class in a class method. it’s usually better to use a variable other than self to refer to an instance inside a class method: + (id)rectangleOfColor:(NSColor *)color { id newInstance = [[Rectangle alloc] init]. 46 Messages to self and super 2010-12-08 | © 2010 Apple Inc. even assigned a new value. return [self autorelease]. it can still get the basic functionality by sending a message to super. This is an example of what not to do: + (Rectangle *)rectangleOfColor:(NSColor *) color { self = [[Rectangle alloc] init]. But self is a variable name that can be used in any number of ways.
CHAPTER 2 Defining a Class } See “Allocating and Initializing Objects” (page 49) for more information about object allocation. Messages to self and super 2010-12-08 | © 2010 Apple Inc. All Rights Reserved. 47 .
.CHAPTER 2 Defining a Class 48 Messages to self and super 2010-12-08 | © 2010 Apple Inc. All Rights Reserved.
.CHAPTER 3 Allocating and Initializing Objects Allocating and Initializing Objects It takes two steps to create an object using Objective-C. They don’t need to be overridden and modified in subclasses. method normally initializes the instance variables of the receiver and then returns it. labels for the parameters follow the “init” prefix. This initialization is the responsibility of class-specific instance methods that. Each step is accomplished by a separate method but typically in a single line of code: id anObject = [[Rectangle alloc] init]. by convention. It’s the responsibility of the method to return an object that can be used without error. an object needs to be more specifically initialized before it can be safely used. For example. Separating allocation from initialization gives you control over each step so that each can be modified independently of the other. the method name is just those four letters. 49 . All other instance variables are set to 0. it takes parameters. Every class that declares instance variables must provide an init. NSObject declares the method mainly to establish the naming convention described earlier.. Allocating and Initializing Objects 2010-12-08 | © 2010 Apple Inc. memory for new objects is allocated using class methods defined in the NSObject class. The Returned Object An init. method to initialize them. These methods allocate enough memory to hold all the instance variables for an object belonging to the receiving class.. However. Usually. If . because isa is initialized when memory for an object is allocated. All Rights Reserved. NSObject defines two principal methods for this purpose. init. The alloc and allocWithZone: methods initialize a newly allocated object’s isa instance variable so that it points to the object’s class (the class object). begin with the abbreviation “init” If the method takes no parameters. alloc and allocWithZone:. The following sections look first at allocation and then at initialization and discuss how they are controlled and modified. You must: ● ● Dynamically allocate memory for the new object Initialize the newly allocated memory to appropriate values An object isn’t fully functional until both steps have been completed. all the init method of NSObject does is return self. an NSView object can be initialized with an initWithFrame: method. In Objective-C.. The NSObject class declares the isa variable and defines an init method.
. For example. an initFromFile: method might get the data it needs from a file passed as a parameter. In these other cases.CHAPTER 3 Allocating and Initializing Objects However. All Rights Reserved. In Objective-C.. since it ignores the return of init... not just that returned by alloc or allocWithZone:. If the filename it’s passed doesn’t correspond to an actual file. Implementing an Initializer When a new object is created. or you want to pass values as parameters to the initializer. it might be impossible for an init. and the name is already being used by another object. this may be all you require when an object is initialized. [anObject someOtherMessage]. it won’t be able to complete the initialization.. then you should check the return value before proceeding: id anObject = [[SomeClass alloc] init]. In such a case. When asked to assign a name to a new instance. In some situations. method to do what it’s asked to do. Instead. . initWithName: might refuse to assign the same name to two objects. the name of a custom initializer method begins with init.. it might free the newly allocated instance and return the other object—thus ensuring the uniqueness of the name while at the same time providing what was asked for. [anObject someOtherMessage]. if ( anObject ) [anObject someOtherMessage]. all bits of memory (except for isa)—and hence the values for all its instance variables—are set to 0. you need to write a custom initializer. the init. In a few cases. If there can be no more than one object per name. method might return an object other than the newly allocated receiver. If there’s a chance that the init.. method could free the receiver and return nil. in many others. The following code is very dangerous. to safely initialize an object. it’s important that programs use the value returned by the initialization method. an instance with the requested name. in some cases. For example. custom initializers are subject to more constraints and conventions than are most other methods. you should combine allocation and initialization messages in one line of code. if a class keeps a list of named objects. indicating that the requested object can’t be created. id anObject = [[SomeClass alloc] init].. else . it might provide an initWithName: method to initialize new instances. id anObject = [SomeClass alloc].. [anObject init]. or even return nil.. Because an init. method might return nil (see “Handling Initialization Failure” (page 52)). you want to provide other default values for an object’s instance variables. Constraints and Conventions There are several constraints and conventions that apply to initializer methods that do not apply to other methods: ● By convention. this responsibility can mean returning a different object than the receiver. 50 Implementing an Initializer 2010-12-08 | © 2010 Apple Inc.
that represents the time when the object was created: . a full explanation of this issue is given in “Coordinating Classes” (page 53). you must return self unless the initializer fails. in which case you return nil. it must invoke the superclass’s designated initializer. } (The reason for using the if (self) pattern is discussed in “Handling Initialization Failure” (page 52). (See also. depending on context of invocation.(id)init { // Assign self to value returned by super's designated initializer // Designated initializer for NSObject is init self = [super init]. ● ● At the end of the initializer. In brief. The return type should be id because id gives an indication that the class is purposely not considered—that the class is unspecified and subject to change.) ● In the implementation of a custom initializer. When sent to an instance of NSMutableString (a subclass of NSString). you typically do so using direct assignment rather than using an accessor method. creationDate. the message returns an instance of NSMutableString. the singleton example given in “Combining Allocation and Initialization” (page 57). For example. or another of its own initializers that ultimately invokes the designated initializer. All Rights Reserved.CHAPTER 3 Allocating and Initializing Objects Examples from the Foundation framework include initWithFormat:. not NSString. Designated initializers are described in “The Designated Initializer” (page 55). it should invoke its own class’s designated initializer. } return self. 51 . though. the designated initializer is init. The following example illustrates the implementation of a custom initializer for a class that inherits from NSObject and has an instance variable.) Implementing an Initializer 2010-12-08 | © 2010 Apple Inc. ● The return type of an initializer method should be id. you must ultimately invoke a designated initializer. if you are implementing a new designated initializer. initWithObjects:. If you set the value of an instance variable. By default (such as with NSObject). Failed initializers are discussed in more detail in “Handling Initialization Failure” (page 52). ● You should assign self to the value returned by the initializer because the initializer could return an object different from the one returned by the original receiver. if (self) { creationDate = [[NSDate alloc] init]. NSString provides the method initWithFormat:. and initWithObjectsAndKeys:. If you are implementing any other initializer. Direct assignment avoids the possibility of triggering unwanted side effects in the accessors. however.
You must make sure that dealloc methods are safe in the presence of partially initialized objects. There are two main consequences of this policy: ● Any object (whether your own class. a subclass. For example.(id)initWithImage:(NSImage *)anImage { // Find the size for the new instance from the image NSSize size = anImage.width. or an external caller) that receives nil from an initializer method should be able to deal with it.size. but set nonessential instance variables to arbitrary values or allow them to have the null values set by default.CHAPTER 3 Allocating and Initializing Objects An initializer doesn’t need to provide a parameter for each variable. NSRect frame = NSMakeRect(0. you should call the release method on self and return nil. } This example doesn’t show what to do if there are any problems during initialization. It shows that you can do work before invoking the super class’s designated initializer. if (self) { image = [anImage retain].(id)init { self = [super init]. } return self.0. you must undo any connections. if a class requires its instances to have a name and a data source. You should simply clean up any references you had set up that are not dealt with in dealloc and return nil.height). size. 0. you should not also call release.0. Handling Initialization Failure In general. If you get nil back from an invocation of the superclass’s initializer. ● Note: You should call the release method on self only at the point of failure. In the unlikely case that the caller has established any external references to the object before the call. the class inherits from NSView. and setDimensions: to modify default values after the initialization phase had been completed. if (self) { creationDate = [[NSDate alloc] init]. In this case. } 52 Implementing an Initializer 2010-12-08 | © 2010 Apple Inc. . setFriend:. size. It could then rely on methods like setEnabled:. These steps are typically handled by the pattern of performing initialization within a block dependent on a test of the return value of the superclass’s initializer—as seen in previous examples: . if there is a problem during an initialization method. // Assign self to value returned by super's designated initializer // Designated initializer for NSView is initWithFrame: self = [super initWithFrame:frame]. The next example illustrates the implementation of a custom initializer that takes a single parameter. } return self. it might provide an initWithName:fromURL: method. . how to handle such problems is discussed in the next section. All Rights Reserved.
} The next example illustrates best practice where. } Implementing an Initializer 2010-12-08 | © 2010 Apple Inc.size. return nil. return nil. 0. NSRect frame = NSMakeRect(0. All Rights Reserved. } // Find the size for the new instance from the image NSSize size = anImage. // Assign self to value returned by super's designated initializer // Designated initializer for NSView is initWithFrame: self = [super initWithFrame:frame]. if (self) { name = [string copy].(id)initWithName:(NSString *)string { self = [super init]. if (data == nil) { // In this case the error object is created in the NSData initializer [self release]. Inherited instance variables are initialized by sending a message to super to perform an initialization method defined somewhere farther up the inheritance hierarchy: . there is a possibility of returning meaningful information in the form of an NSError object returned by reference: .(id)initWithImage:(NSImage *)anImage { if (anImage == nil) { [self release].. Coordinating Classes The init. } // implementation continues. size.. in the case of a problem.(id)initWithURL:(NSURL *)aURL error:(NSError **)errorPtr { self = [super init]. if (self) { NSData *data = [[NSData alloc] initWithContentsOfURL:aURL options:NSUncachedRead error:errorPtr].. see Error Handling Programming Guide.0. } return self. 53 .0.height). if (self) { image = [anImage retain]. methods a class defines typically initialize only those variables declared in that class. You should typically not use exceptions to signify errors of this sort—for more information.CHAPTER 3 Allocating and Initializing Objects The following example builds on that shown in “Constraints and Conventions” (page 50) to show how to handle an inappropriate value passed as the parameter: .width.. size.
Figure 3-2 includes the B version of init.CHAPTER 3 Allocating and Initializing Objects return self. and a Shape object before it’s initialized as a Rectangle object. Because it comes first. if class A defines an init method and its subclass B defines an initWithName: method. For example. } The message to super chains together initialization methods in all inherited classes. B must also make sure that an init message successfully initializes B instances. a Rectangle object must be initialized as an NSObject. All Rights Reserved. it ensures that superclass variables are initialized before those declared in subclasses. For example. The easiest way to do that is to replace the inherited init method with a version that invokes initWithName:: . 54 Implementing an Initializer 2010-12-08 | © 2010 Apple Inc. . a Graphic object. invoke the inherited method. in turn. as shown in Figure 3-1. as shown earlier. } The initWithName: method would.
a subclass of B. It’s also the method that does most of the work. For example.CHAPTER 3 Allocating and Initializing Objects Figure 3-2 Covering an inherited initialization method – init Class A – init Class B – initWithName: Covering inherited initialization methods makes the class you define more portable to other applications. which you can do just by covering the B class’s initWithName: method with a version that invokes initWithName:fromFile:. implements an initWithName:fromFile: method. } For an instance of the C class. someone else may use it to produce incorrectly initialized instances of your class. . It’s a Cocoa convention that the designated initializer is always the method that allows the most freedom to determine the character of a new instance (usually this is the one with the most parameters. class C. the inherited init method invokes this new version of initWithName:. The Designated Initializer In the example given in “Coordinating Classes” (page 53). initWithName: would be the designated initializer for its class (class B). you have to make sure that the inherited init and initWithName: methods of class B also work for instances of C. All Rights Reserved. It’s important to know the designated initializer when defining a subclass.initWithName:(char *)string { return [self initWithName:string fromFile:NULL]. The Designated Initializer 2010-12-08 | © 2010 Apple Inc. The designated initializer is the method in each class that guarantees inherited instance variables are initialized (by sending a message to super to perform an inherited method). In addition to this method. The relationship between these methods is shown in Figure 3-3. 55 . which invokes initWithName:fromFile:. If you leave an inherited method uncovered. and the one that other initialization methods in the same class invoke. but not always).
Designated initializers are chained to each other through messages to super. invoke the designated initializer in a superclass. for two reasons: ● Circularity would result (init invokes C’s initWithName:. and C are linked. through a message to super. which invokes initWithName:fromFile:. Figure 3-4 shows how all the initialization methods in classes A. The initWithName:fromFile: method. It won’t be able to take advantage of the initialization code in B’s version of initWithName:.initWithName:(char *)string fromFile:(char *)pathname { self = [super initWithName:string].. All Rights Reserved. But which of B’s methods should it invoke. while other initialization methods are chained to designated initializers through messages to self. 56 The Designated Initializer 2010-12-08 | © 2010 Apple Inc.. Messages to self are shown on the left and messages to super are shown on the right. initWithName:fromFile: must invoke initWithName:: . . init or initWithName:? It can’t invoke init. B. } General principle: The designated initializer in a class must. being the designated initializer for the C class. if (self) { . ● Therefore. which invokes init.
CHAPTER 3
Allocating and Initializing Objects
Figure 3-4
The initialization chain
– init Class A
– init Class B – initWithName:
Class C
– initWithName: – initWithName:fromFile:
57
CHAPTER 3
Allocating and Initializing Objects
+ (id)arrayWithObject:(id)anObject; + (id)arrayWithObjects:(id)firstObj, ...;). a parameter. in “The Returned Object” (page 49), determines a single shared instance:
+ (Soloist *)soloist { static Soloist *instance = nil; if ( instance == nil ) { instance = [[self alloc] init]; } return instance; }
Notice that in this case the return type is Soloist *. Because this method returns a singleton share instance, strong typing is appropriate—there is no expectation that this method will be overridden.
58
Combining Allocation and Initialization
CHAPTER 4
Protocols
Protocols declare methods that can be implemented by any class. Protocols are useful in at least three situations:
● ● ●; - (void)mouseDragged:(NSEvent *)theEvent; - (void)mouseUp:(NSEvent *)theEvent;.
Declaring Interfaces for Others to Implement
59
you can look at its interface declaration (and the interface declarations of the classes it inherits from) to find what messages it responds to.. you can’t import the interface file of the class that implements it. If you develop the class of the sender and the class of the receiver as part of the same project (or if someone else has supplied you with the receiver and its interface file). You provide an assistant instance variable to record the outlet for these messages and define a companion method to set the instance variable. you can’t know what kind of object might register itself as the assistant. 60 Methods for Others to Implement 2010-12-08 | © 2010 Apple Inc. if ( [assistant respondsToSelector:@selector(helpOut:)] ) { [assistant helpOut:self]. } Because.(BOOL)doWork { . an object might be willing to notify other objects of its actions so that they can take whatever collateral measures might be required. } return NO. a check is made to be sure that the receiver implements a method that can respond: . at the time you write this code. you can only declare a protocol for the helpOut: method.CHAPTER 4 Protocols Methods for Others to Implement If you know the class of an object. A protocol serves this purpose. an object might delegate responsibility for a certain operation to another object. this communication is easily coordinated. For example. } Then. The sender simply imports the interface file of the receiver. Communication works both ways.setAssistant:anObject { assistant = anObject. . Suppose. if you develop an object that sends messages to objects that aren’t yet defined—objects that you’re leaving for others to implement—you won’t have the receiver’s interface file. The imported file declares the method selectors the sender uses in the messages it sends. objects send messages as well as receive them. It informs the compiler about methods the class uses and also informs other implementors of the methods they need to define to have their objects work with yours. However. These declarations advertise the messages it can receive. whenever a message is to be sent to the assistant. or it may on occasion simply need to ask another object for information. for example. All Rights Reserved. that you develop an object that asks for the assistance of another object by sending it helpOut: and other messages. return YES. In some cases. Protocols provide a way for it to also advertise the messages it sends.. This method lets other objects register themselves as potential recipients of your object’s messages: . You need another way to declare the methods you use in messages but don’t implement.
Note: Even though the supplier of an anonymous object doesn’t reveal its class. at least not one the supplier is willing to reveal. all you need to know is what messages you can send (the protocol) and where to send them (the receiver). those classes are often grouped under an abstract class that declares the methods they have in common. especially when only one object of its kind is needed. Instead. Each subclass can reimplement the methods in its own way. 61 .CHAPTER 4 Protocols Declaring Interfaces for Anonymous Objects A protocol can be used to declare the methods of an anonymous object. there would be no way to declare an interface to an object without identifying its class. A class message returns the anonymous object’s class. Without a protocol. and internal logic. the supplier must provide a ready-made instance. Nonhierarchical Similarities If more than one class implements a set of methods. the information in the protocol is sufficient. Declaring Interfaces for Anonymous Objects 2010-12-08 | © 2010 Apple Inc. The object returned by the method is an object without a class identity. users have no way of creating instances of the class. Typically. An anonymous object may represent a service or handle a limited set of functions. a method in another class returns a usable object: id formatter = [receiver formattingService].) Objects are not anonymous to their developers. but the inheritance hierarchy and the common declaration in the abstract class capture the essential similarity between the subclasses. An application that publishes one of its objects as a potential receiver of remote messages must also publish a protocol declaring the methods the object will use to respond to those messages. the supplier must be willing to identify at least some of the messages that it can respond to. ● You can send Objective-C messages to remote objects—objects in other applications. (“Remote Messaging” in the Objective-C Runtime Programming Guide. The sending application doesn’t need to know the class of the object or use the class in its own design. As an outsider. the object itself reveals it at runtime. of course. For example. The messages are identified by associating the object with a list of methods declared in a protocol. an object of unknown class. It doesn’t have to disclose anything else about the object. classes. but they are anonymous when the developer supplies them to someone else. Lacking the name and class interface. All Rights Reserved. However. there’s usually little point in discovering this extra information. consider the following situations: ● Someone who supplies a framework or a suite of objects for others to use can include objects that are not identified by a class name or an interface file.) Each application has its own structure. Protocols make anonymous objects possible. (Objects that play a fundamental role in defining an application’s architecture and objects that you must initialize before using are not good candidates for anonymity. For it to be of any use at all. discusses this possibility in more detail. But you don’t need to know how another application works or what its components are to communicate with it. All it needs is the protocol.
rather than by their class.initFromXMLRepresentation:(NSXMLElement *)XMLElement. @end Unlike class names. In this case. just that it implemented the methods. These methods could be grouped into a protocol and the similarity between implementing classes accounted for by noting that they all conform to the same protocol. For example. Alternatively. This limited similarity may not justify a hierarchical relationship. .(NSXMLElement *)XMLRepresentation. Formal protocols are supported by the language and the runtime system. You can use @optional and @required to partition your protocol into sections as you see fit. the NSMatrix object wouldn’t care what class a cell object belonged to.(NSXMLElement *)XMLRepresentation. 62 Formal Protocols 2010-12-08 | © 2010 Apple Inc. protocol names don’t have global visibility. the NSMatrix object could require objects representing cells to have methods that can respond to a particular set of messages (a type based on protocol). Classes that are unrelated in most respects might nevertheless need to implement some similar methods. Declaring a Protocol You declare formal protocols with the @protocol directive: @protocol ProtocolName method declarations @end For example. Objects can be typed by this similarity (the protocols they conform to).initFromXMLRepresentation:(NSXMLElement *)xmlString.CHAPTER 4 Protocols However. All Rights Reserved. and objects can introspect at runtime to report whether or not they conform to a protocol. Formal Protocols The Objective-C language provides a way to formally declare a list of methods (including declared properties) as a protocol. Corresponding to the @optional modal keyword. If you do not specify any keyword. The matrix could require each of these objects to be a kind of NSCell (a type based on class) and rely on the fact that all objects that inherit from the NSCell class have the methods needed to respond to NSMatrix messages. you could declare an XML representation protocol like this: @protocol MyXMLSupport . For example. . the compiler can check for types based on protocols. the default is @required. Optional Protocol Methods Protocol methods can be marked as optional using the @optional keyword. there is a @required keyword to formally denote the semantics of the default behavior. you might want to add support for creating XML representations of objects in your application and for initializing objects from an XML representation: . For example. . sometimes it’s not possible to group common methods in an abstract class. They live in their own namespace. an NSMatrix instance must communicate with the objects that represent its cells.
CHAPTER 4
Protocols
@protocol MyProtocol - (void)requiredMethod; @optional - (void)anOptionalMethod; - (void)anotherOptionalMethod; @required - (void)anotherRequiredMethod; @end
Note: In Mac OS X v10.5, protocols cannot include optional declared properties. This constraint is removed in Mac OS X v10.6 and later.
Informal Protocols Mac OS X v10.5 and later) it is typically better to use a formal protocol with optional methods.
Informal Protocols
63
CHAPTER 4
Protocols::
● ●; names in the protocol list are separated by commas.
@interface Formatter : NSObject < Formatting, Prettifying >.
64
Protocol Objects
CHAPTER 4
Protocols:
@interface Formatter : NSObject < Formatting, Prettifying > .
if ( ! [receiver conformsToProtocol:@protocol(MyXMLSupport)] ) { // Object does not conform to MyXMLSupport protocol // If you are expecting receiver to implement methods declared in the // MyXMLSupport protocol, this is probably an error }
:
- (id <Formatting>)formattingService; id <MyXMLSupport> anObject;
Conforming to a Protocol
65
need to mention only the Paging protocol to test for conformance to Formatting as well. Only instances can be statically typed to a protocol. For example. Protocols can’t be used to type class objects. The two types can be combined in a single declaration: Formatter <Formatting> *anObject. In each case.CHAPTER 4 Protocols Just as static typing permits the compiler to test for a type based on the class hierarchy. (However. For example. the declaration id <Formatting> anObject. Type declarations such as id <Paging> someObject. and conformsToProtocol: messages such as if ( [anotherObject conformsToProtocol:@protocol(Paging)] ) . both classes and instances respond to a conformsToProtocol: message. 66 Protocols Within Protocols 2010-12-08 | © 2010 Apple Inc. or because they converge on a common set of methods.. the type groups similar objects—either because they share a common inheritance.). All Rights Reserved. if Formatter is an abstract class. if the Paging protocol incorporates the Formatting protocol @protocol Paging < Formatting > any object that conforms to the Paging protocol also conforms to Formatting. at runtime. The compiler can make sure only objects that conform to the protocol are assigned to the type. the declaration Formatter *anObject. .. regardless of their positions in the class hierarchy. just as only instances can be statically typed to a class. this syntax permits the compiler to test for a type based on conformance to a protocol. groups all objects that conform to the Formatting protocol into a type. Similarly.
it must implement the required methods the protocol declares. as mentioned earlier. including those declared in the incorporated Formatting protocol. @end In such a situation.h" @protocol B . @protocol A Referring to Other Protocols 2010-12-08 | © 2010 Apple Inc. To break this recursive cycle. you occasionally find yourself writing code that looks like this: #import "B. it must conform to any protocols the adopted protocol incorporates.CHAPTER 4 Protocols When a class adopts a protocol. All Rights Reserved. circularity results and neither file will compile correctly. for example. It adopts the Formatting protocol along with Paging. simply by implementing the methods declared in the protocol. Pager inherits conformance to the Formatting protocol from Formatter. If an incorporated protocol incorporates still other protocols. Referring to Other Protocols When working on complex applications. you must use the @protocol directive to make a forward reference to the needed protocol instead of importing the interface file where the protocol is defined: @protocol B. If Pager is a subclass of NSObject as shown here: @interface Pager : NSObject < Paging > it must implement all the Paging methods. On the other hand. the class must also conform to them. but not those declared in Formatting. In addition. A class can conform to an incorporated protocol using either of these techniques: ● ● Implementing the methods the protocol declares Inheriting from a class that adopts the protocol and implements the methods Suppose.h" @protocol A . @end where protocol B is declared like this: #import "A. 67 . Note that a class can conform to a protocol without formally adopting it. if Pager is a subclass of Formatter (a class that independently adopts the Formatting protocol) as shown here: @interface Pager : Formatter < Paging > it must implement all the methods declared in the Paging protocol proper. that the Pager class adopts the Paging protocol.foo:(id <B>)anObject.bar:(id <A>)anObject.
@end Note that using the @protocol directive in this manner simply informs the compiler that B is a protocol to be defined later. It doesn’t import the interface file where protocol B is defined.foo:(id <B>)anObject. .CHAPTER 4 Protocols . 68 Referring to Other Protocols 2010-12-08 | © 2010 Apple Inc. All Rights Reserved.
explicit specification of how the accessor methods behave.CHAPTER 5 Declared Properties The Objective-C declared properties feature provides a simple way to declare and implement an object’s accessor methods. aspects of the property that may be important to consumers of the API are left obscured—such as whether the accessor methods are thread-safe or whether new values are copied when set. Overview There are two aspects to this language feature: the syntactic elements you use to specify and optionally synthesize declared properties. 69 . You typically access an object’s properties (in the sense of its attributes and relationships) through a pair of accessor (getter/setter) methods. and a related syntactic element that is described in “Dot Syntax” (page 19). Properties are represented syntactically as identifiers and are scoped. Although using accessor methods has significant advantages. according to the specification you provide in the declaration. Moreover. ● Property Declaration and Implementation There are two parts to a declared property. its declaration and its implementation. The compiler can synthesize accessor methods for you. By using accessor methods. so the compiler can detect use of undeclared properties. This means you have less code to write and maintain. you adhere to the principle of encapsulation (see “Mechanisms Of Abstraction” in Object-Oriented Programming with Objective-C). All Rights Reserved. writing accessor methods is nevertheless a tedious process—particularly if you have to write code to support both garbage-collected and reference-counted environments. You can exercise tight control of the behavior of the getter/setter pair and the underlying state management while clients of the API remain insulated from the implementation changes. Declared properties address the problems with standard accessor methods by providing the following features: ● ● The property declaration provides a clear. Overview 2010-12-08 | © 2010 Apple Inc.
@property can appear anywhere in the method declaration list found in the @interface block of a class. They are both optional and can appear with any other attribute (except for readonly in the case of setter=). however. For property declarations that use a comma delimited list of variable names. If you use the @synthesize directive to tell the compiler to create the accessor methods. Listing 5-1 Declaring a simple property @interface MyClass : NSObject { float value. Listing 5-1 illustrates the declaration of a simple property.CHAPTER 5 Declared Properties Property Declaration A property declaration begins with the keyword @property. @end You can think of a property declaration as being equivalent to declaring two accessor methods. the code it generates matches the specification given by the keywords. you should ensure that it matches the specification (for example. . is equivalent to: . the property attributes apply to all of the named properties. } @property float value. If you implement the accessor methods yourself. each property has a type specification and a name. provides additional information about how the accessor methods are implemented (as described in “Property Declaration Attributes” (page 70)). properties are scoped to their enclosing interface declaration. . setFoo:. The @property directive declares a property. Like any other Objective-C type. A property declaration. Accessor Method Names The default names for the getter and setter methods associated with a property are propertyName and setPropertyName: respectively—for example.]). 70 Property Declaration and Implementation 2010-12-08 | © 2010 Apple Inc. An optional parenthesized set of attributes provides additional details about the storage semantics and other behaviors of the property—see “Property Declaration Attributes” (page 70) for possible values. attribute2. if you specify copy you must make sure that you do copy the input value in the setter method). given a property “foo” the accessors would be foo and . All Rights Reserved. @property(attributes) type name... The following attributes allow you to specify custom names instead. Property Declaration Attributes You can decorate a property with attributes by using the form @property(attribute [.(void)setValue:(float)newValue.(float)value. Like methods. @property can also appear in the declaration of a protocol or category. . Thus @property float value.
assign Specifies that the setter uses simple assignment. or (in a reference-counted environment) for objects you don’t own. All Rights Reserved. only a getter method is required in the @implementation block. In Mac OS X v10. 71 . this attribute is valid only for Objective-C object types (so you cannot specify retain for Core Foundation objects—see “Core Foundation” (page 77)). if you attempt to assign a value using the dot syntax. readonly Indicates that the property is read-only. If you specify that a property is readonly and also specify a setter with setter=. Both a getter and setter method are required in the @implementation block. only the getter method is synthesized. The getter must return a type matching the property’s type and take no parameters. Writability These attributes specify whether or not a property has an associated set accessor.) The previous value is sent a release message. Setter Semantics These attributes specify the semantics of a set accessor.6. retain Specifies that retain should be invoked on the object upon assignment.6 and later. (The default is assign. retain and assign are effectively the same in a garbage-collected environment. You typically use this attribute for scalar types such as NSInteger and CGRect. you get a compiler error. Moreover.CHAPTER 5 Declared Properties getter=getterName Specifies the name of the get accessor for the property. Property Declaration and Implementation 2010-12-08 | © 2010 Apple Inc. If you use the @synthesize directive in the implementation block. They are mutually exclusive. If you specify readonly. They are mutually exclusive. This attribute is the default. If you use the @synthesize directive in the implementation block. the getter and setter methods are synthesized. Typically you should specify accessor method names that are key-value coding compliant (see Key-Value Coding Programming Guide)—a common reason for using the getter decorator is to adhere to the isPropertyName convention for Boolean values. you can use the __attribute__ keyword to specify that a Core Foundation property should be treated like an Objective-C object for memory management: @property(retain) __attribute__((NSObject)) CFDictionaryRef myDictionary. you get a compiler warning. setter=setterName Specifies the name of the set accessor for the property. The setter method must take a single parameter of a type matching the property’s type and must return void. Prior to Mac OS X v10. This attribute is the default. readwrite Indicates that the property should be treated as read/write. such as delegates.
(The default is assign. for object properties you must explicitly specify one of assign.) The previous value is sent a release message. return result. The copy is made by invoking the copy method.. For further discussion. 72 Property Declaration and Implementation 2010-12-08 | © 2010 Apple Inc. see “Copy” (page 75).CHAPTER 5 Declared Properties copy Specifies that a copy of the object should be used for assignment. you don't get a warning if you use the default (that is. then in a reference-counted environment. Different constraints apply depending on whether or not you use garbage collection: ● If you do not use garbage collection. to preserve encapsulation you often want to make a private copy of the object. If you specify nonatomic. Markup and Deprecation Properties support the full range of C-style decorators. .. ● If you use garbage collection. retain. however. retain. Properties are atomic by default so that synthesized accessors provide robust access to properties in a multithreaded environment—that is. or copy) unless the property's type is a class that conforms to NSCopying. you need to understand Cocoa memory management policy (see Memory Management Programming Guide).) nonatomic Specifies that accessors are nonatomic. If you specify retain or copy and do not specify nonatomic. All Rights Reserved. see “Performance and Threading” (page 79). The default is usually what you want. which must implement the NSCopying protocol. (This constraint encourages you to think about what memory management behavior you want and to type the behavior explicitly. Atomicity You can use this attribute to specify that accessor methods are not atomic.)). For more details. if the property type can be copied. a synthesized accessor for an object property simply returns the value directly. accessors are atomic.) To decide which you should choose. Properties can be deprecated and support __attribute__ style markup: @property CGFloat x AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4. or copy—otherwise you get a compiler warning. a synthesized get accessor for an object property uses a lock and retains and autoreleases the returned value—the implementation will be similar to the following: [_internal lock]. By default. (There is no keyword to denote atomic. This attribute is valid only for object types. // lock using an object-level lock id result = [[value retain] autorelease]. the value returned from the getter or set via the setter is always fully retrieved or set regardless of what other threads are executing concurrently. if you don’t specify any of assign. @property CGFloat y __attribute__((. [_internal unlock].
} @property(copy. 73 . If you use garbage collection. IBOutlet is not. you can use the storage modifiers __weak and __strong in a property’s declaration: @property (nonatomic. age = yearsOld. All Rights Reserved. Note that neither is required for any given @property declaration. Listing 5-2 Using @synthesize @interface MyClass : NSObject { NSString *value. @end @implementation MyClass @synthesize value. lastName. you must provide a getter and setter (or just a getter in the case of a readonly property) method implementation for that property. @end You can use the form property=ivar to indicate that a particular instance variable should be used for the property.CHAPTER 5 Declared Properties If you want to specify that a property is an Interface Builder outlet. Whether or not you specify the name of the instance variable. But again. lastName. the compiler generates a warning. readwrite) NSString *value. If you do not. and age should be synthesized and that the property age is represented by the instance variable yearsOld. the @synthesize directive can use an instance variable only from the current class. not a superclass. There are differences in the behavior of accessor synthesis that depend on the runtime (see also “Runtime Difference” (page 80)): Property Declaration and Implementation 2010-12-08 | © 2010 Apple Inc. Other aspects of the synthesized methods are determined by the optional attributes (see “Property Declaration Attributes” (page 70)). Important: If you do not specify either @synthesize or @dynamic for a particular property. a formal part of the list of attributes. for example: @synthesize firstName. retain) __weak Link *parent. Property Implementation Directives You can use the @synthesize and @dynamic directives in @implementation blocks to trigger specific compiler actions. storage modifiers are not a formal part of the list of attributes. you can use the IBOutlet identifier: @property (nonatomic. retain) IBOutlet NSButton *myButton. though. This specifies that the accessor methods for firstName. @synthesize You use the @synthesize directive to tell the compiler that it should synthesize the setter and/or getter methods for a property if you do not supply them within the @implementation block.
the compiler would generate a warning. Core Foundation data type. retain) NSString *value. or “plain old data” (POD) type (see C++ Language Note: POD Types). @end @implementation MyClass @dynamic value. Listing 5-3 Using @dynamic with NSManagedObject @interface MyClass : NSManagedObject { } @property(nonatomic. If you just declared the property without providing any implementation. For constraints on using Core Foundation types. it is used—otherwise. You therefore typically declare properties for the attributes and relationships. however. the Core Data framework generates accessor methods for these as necessary. instance variables must already be declared in the @interface block of the current class. ● @dynamic You use the @dynamic keyword to tell the compiler that you will fulfill the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution. and if its type is compatible with the property’s type. you get a compiler error. The example shown in Listing 5-3 illustrates using @dynamic with a subclass of NSManagedObject. @end NSManagedObject is provided by the Core Data framework. Using @dynamic suppresses the warning. .CHAPTER 5 Declared Properties ● For the legacy runtimes. If an instance variable of the same name already exists. instance variables are synthesized as needed. however. it is used. see “Core Foundation” (page 77). at runtime. but you don’t have to implement the accessor methods yourself and shouldn’t ask the compiler to do so. You should use it only if you know that the methods will be available at runtime. A managed object class has a corresponding schema that defines attributes and relationships for the class. If an instance variable of the same name as the property exists. 74 Using Properties 2010-12-08 | © 2010 Apple Inc. It suppresses the warnings that the compiler would otherwise generate if it can’t find suitable implementations. Using Properties Supported Types You can declare a property for any Objective-C class. For the modern runtimes (see “Runtime Versions and Platforms” in Objective-C Runtime Programming Guide). All Rights Reserved.
All Rights Reserved. Copying is useful for attributes such as string objects where there is a possibility that the new value passed in a setter may be mutable (for example. // public header file @interface MyObject : NSObject { NSString *language. copy) NSString *string. copy) NSString *language. If you declare a property in one class as readonly. but (with the exception of readonly versus readwrite) you must repeat its attributes in whole in the subclasses. the fact that the property was redeclared prior to any @synthesize statement causes the setter to be synthesized. 75 . you specify that a value is copied during assignment. in a protocol. } } Using Properties 2010-12-08 | © 2010 Apple Inc. @end // private implementation file @interface MyObject () @property (readwrite. you can redeclare it as readwrite in a class extension (see “Extensions” (page 83)). The following example shows using a class extension to provide a property that is declared as read-only in the public header but is redeclared privately as read/write. if you declare a property as follows: @property (nonatomic. The same holds true for a property declared in a category or protocol—while the property may be redeclared in a category or protocol. or in a subclass (see “Subclassing with Properties” (page 79)). and NSDictionary are all examples) and a property that has a public API that is readonly but a private readwrite implementation internal to the class. } @property (readonly. For example. NSArray. @end Copy If you use the copy declaration attribute. @end @implementation MyObject @synthesize language. an instance of NSMutableString) and you want to ensure that your object has its own private immutable copy.CHAPTER 5 Declared Properties Property Redeclaration You can redeclare a property in a subclass. the property’s attributes must be repeated in whole. then the synthesized setter method is similar to the following: -(void)setString:(NSString *)newString { if (string != newString) { [string release]. copy) NSString *language. the synthesized method uses the copy method. In the case of a class extension redeclaration. If you synthesize the corresponding accessor. string = [newString copy]. The ability to redeclare a read-only property as read/write enables two common implementation patterns: a mutable subclass of an immutable class (NSString.
All Rights Reserved. it may present a problem if the attribute is a collection such as an array or a set. there is no direct interaction between property declaration and the dealloc method—properties are not automatically released for you. myArray = [newArray mutableCopy]. when you synthesize a property. Declared properties do. but the copy method returns an immutable version of the collection. take the place of accessor method declarations. however. as illustrated in this example: . along with the @synthesize directive.CHAPTER 5 Declared Properties Although this pattern works well for strings. @end @implementation MyClass @synthesize myArray.(void)dealloc { [self setProperty:nil]. [super dealloc]. . Typically you want such collections to be mutable. } If you are using the modern runtime and synthesizing the instance variable. and those marked assign are not released. so you must invoke the accessor method: . } @property (nonatomic. } 76 Using Properties 2010-12-08 | © 2010 Apple Inc. however. the compiler creates accessor methods as needed. you have to provide your own implementation of the setter method. provide a useful way to cross-check the implementation of your dealloc method: you can look for all the property declarations in your header file and make sure that object properties not marked assign are released. as illustrated in the following example. [super dealloc]. you cannot access the instance variable directly. Note: Typically in a dealloc method you should release object instance variables directly (rather than invoking a set accessor and passing nil as the parameter). } } @end dealloc Declared properties. However.(void)setMyArray:(NSMutableArray *)newArray { if (myArray != newArray) { [myArray release]. copy) NSMutableArray *myArray. .(void)dealloc { [property release]. @interface MyClass : NSObject { NSMutableArray *myArray. In this situation.
but this is the default value. name is synthesized and uses instance variable synthesis (recall that instance variable synthesis is not supported using the legacy runtime—see “Property Implementation Directives” (page 73) and “Runtime Difference” (page 80)). the synthesized set accessor simply assigns the new value to the instance variable (the new value is not retained and the old value is not released).. it requires only a getter) with a specified name (nameAndAgeAsString). but the synthesized setter method triggers a write barrier. @end then in a reference-counted environment. 77 . then the accessors are synthesized appropriately—the image in this example is not retained by CFRetain. @property CGImageRef myImage. All Rights Reserved. ● ● creationTimestamp and next are synthesized but use existing instance variables with different names. MyClass adopts the Link protocol. Using Properties 2010-12-08 | © 2010 Apple Inc. If. ... so it implicitly also declares the property next. Example: Declaring Properties and Synthesizing Accessors The example in Listing 5-4 illustrates the use of properties in several different ways: ● ● The Link protocol declares a property. } @property(readwrite) CGImageRef myImage. you should not synthesize the methods but rather implement them yourself. __strong CGImageRef myImage. prior to Mac OS X v10.6 you cannot specify the retain attribute for non-object types.CHAPTER 5 Declared Properties Core Foundation As noted in “Property Declaration Attributes” (page 70). @end @implementation MyClass @synthesize myImage. MyClass also declares several other properties. next. if the image variable is declared __strong: . you declare a property whose type is a CFType and synthesize the accessors as illustrated in the following example: @interface MyClass : NSObject { CGImageRef myImage. In a garbage collected environment. Simple assignment is typically incorrect for Core Foundation objects. nameAndAge does not have a dynamic directive.. it is supported using a direct method implementation (since it is read-only. ● ● gratuitousFloat has a dynamic directive—it is supported using direct method implementations. therefore.
name. @synthesize next = nextLink.CHAPTER 5 Declared Properties Listing 5-4 Declaring properties for a class @protocol Link @property id <Link> next. } . // in modern runtimes. @end @interface MyClass : NSObject <Link> { NSTimeInterval intervalSinceReferenceDate. . CGFloat gratuitousFloat. @property(readonly.(CGFloat)gratuitousFloat { return gratuitousFloat. @dynamic gratuitousFloat. All Rights Reserved. @property CGFloat gratuitousFloat. } . // Synthesizing 'name' is an error in legacy runtimes.(void)setGratuitousFloat:(CGFloat)aValue { gratuitousFloat = aValue. @end @implementation MyClass @synthesize creationTimestamp = intervalSinceReferenceDate.(NSString *)nameAndAgeAsString { return [NSString stringWithFormat:@"%@ (%fs)". // This directive is not strictly necessary. 78 Using Properties 2010-12-08 | © 2010 Apple Inc. @property(copy) NSString *name. . } . [NSDate timeIntervalSinceReferenceDate] intervalSinceReferenceDate]. } @property(readonly) NSTimeInterval creationTimestamp.(id)init { self = [super init]. // Uses instance variable "nextLink" for storage.(void)dealloc { [nextLink release]. } . id <Link> nextLink. getter=nameAndAgeAsString) NSString *nameAndAge. } return self. [self name]. the instance variable is synthesized. if (self) { intervalSinceReferenceDate = [NSDate timeIntervalSinceReferenceDate].
as illustrated below in a possible implementation: // assign property = newValue. the fact that you declared a property has no effect on the method’s efficiency or thread safety. 79 . If you use a synthesized accessor. assign. For example. All Rights Reserved. } @end Performance and Threading If you supply your own accessor method implementation. The declaration attributes that affect performance and threading are retain. you could define a class MyInteger with a readonly property.(void)setValue:(NSInteger)newX { value = newX. [super dealloc]. @end @implementation MyInteger @synthesize value. which redefines the property to make it writable: @interface MyMutableInteger : MyInteger @property(readwrite) NSInteger value. the method implementation generated by the compiler depends on the specification you supply in the property declaration. } @end Subclassing with Properties You can override a readonly property to make it writable.CHAPTER 5 Declared Properties [name release]. } @property(readonly) NSInteger value. copy. value: @interface MyInteger : NSObject { NSInteger value. and nonatomic. @end @implementation MyMutableInteger @dynamic value. MyMutableInteger. The first three of these affect only the implementation of the assignment part of the set method. @end You could then implement a subclass. . // retain if (property != newValue) { Subclassing with Properties 2010-12-08 | © 2010 Apple Inc.
see Threading Programming Guide. For example. In a garbage-collected environment. guaranteeing atomicity may have a significant negative impact on performance. if you do not provide an instance variable. } The effect of the nonatomic attribute depends on the environment. most synthesized methods are atomic without incurring this overhead. guaranteeing atomic behavior requires the use of a lock. float otherName. @synthesize noDeclaredIvar. Runtime Difference In general the behavior of properties is identical on both modern and legacy runtimes (see “Runtime Versions and Platforms” in Objective-C Runtime Programming Guide). With the modern runtime. synthesized accessors are atomic. @property float noDeclaredIvar. @property float differentName. . @end the compiler for the legacy runtime would generate an error at @synthesize noDeclaredIvar.CHAPTER 5 Declared Properties [property release]. For more about multithreading. } // copy if (property != newValue) { [property release]. whereas the compiler for the modern runtime would add an instance variable to represent noDeclaredIvar. All Rights Reserved. moreover a returned object is retained and autoreleased. Although “atomic” means that access to the property is thread-safe. given the following class declaration and implementation: @interface MyClass : NSObject { float sameName. simply making all the properties in your class atomic does not mean that your class or more generally your object graph is “thread-safe”—thread safety cannot be expressed at the level of individual accessor methods. For @synthesize to work in the legacy runtime. In a reference-counted environment. as illustrated in “Atomicity” (page 72). It is important to understand that the goal of the atomic implementation is to provide robust accessors—it does not guarantee correctness of your code. } @property float sameName. @synthesize differentName=otherName. If such accessors are invoked frequently. the compiler adds one for you. There is one key difference: the modern runtime supports instance variable synthesis whereas the legacy runtime does not. @end @implementation MyClass @synthesize sameName. 80 Runtime Difference 2010-12-08 | © 2010 Apple Inc. you must either provide an instance variable with the same name and compatible type of the property or specify another existing instance variable in the @synthesize statement. property = [newValue retain]. By default. property = [newValue copy].
but allow additional required APIs to be declared for a class in locations other than within the primary class @interface block. The declaration of a category interface looks very much like a class interface declaration—except the category name is listed within parentheses after the class name and the superclass isn’t mentioned. You cannot. just like other methods. there’s no difference.m) might therefore look like this: #import "ClassName+CategoryName. (This matters only for statically typed objects because static typing is the only way the compiler can know an object’s class. you can also distribute the implementation of your own classes among several files. not a new class. A common naming convention is that the base filename of the category is the name of the class the category extends followed by “+” followed by the name of the category. Unless its methods don’t access any instance variables of the class. are not included in the NSArray type. The methods the category adds to the class are inherited by all the class’s subclasses. however. the category must import the interface file for the class it extends: #import "ClassName. imports its own interface. however.CHAPTER 6 Categories and Extensions A category allows you to add methods to an existing class—even to one for which you do not have the source.h" @implementation ClassName ( CategoryName ) // method definitions @end Adding Methods to Classes 2010-12-08 | © 2010 Apple Inc. All Rights Reserved. Using categories. A category implementation (in a file named ClassName+CategoryName. At runtime.) Category methods can do anything that methods defined in the class proper can do. as usual. Methods added to the NSArray class in a subclass. Adding Methods to Classes You can add methods to a class by declaring them in an interface file under a category name and defining them in an implementation file under the same name. use a category to add additional instance variables to a class. methods added to the NSArray class in a category are included as methods the compiler expects an NSArray instance to have in its repertoire. The category name indicates that the methods are additions to a class declared elsewhere. 81 . For example. Class extensions are similar. The methods the category adds become part of the class type. Categories are a powerful feature that allows you to extend the functionality of existing classes without subclassing.h" @interface ClassName ( CategoryName ) // method declarations @end The implementation.
but each category name must be different. There are several significant shortcomings to using a category to override methods: 82 How You Can Use Categories 2010-12-08 | © 2010 Apple Inc.CHAPTER 6 Categories and Extensions Note that a category can’t declare additional instance variables for the class. Similar methods defined in different classes can be kept together in the same source file. ● To distribute the implementation of a new class into multiple source files For example. The added methods are inherited by subclasses and are indistinguishable at runtime from the original methods of the class. it includes only methods. Can help improve locality of reference for commonly used methods. as discussed under “Declaring Interfaces for Others to Implement” (page 59). How You Can Use Categories There are several ways in which you can use categories: ● To extend classes defined by other implementors For example. even ones declared @private. or even methods declared in the class interface. As in the case of a subclass. and each should declare and define a different set of methods. That includes all instance variables declared by the class. When used like this. categories can benefit the development process in a number of ways—they: ● Provide a simple way of grouping related methods. you could add categories to NSArray and other Cocoa classes. through a category you can add methods to the class directly. . For example. ● As an alternative to a subclass Rather than define a subclass to extend an existing class. There’s no limit to the number of categories that you can add to a class. without having to maintain different versions of the same source code. Although the Objective-C language currently allows you to use a category to override methods the class inherits. A category is not a substitute for a subclass. Enable you to configure a class differently for separate applications. all instance variables within the scope of the class are also within the scope of the category. Let you achieve some of the benefits of incremental compilation for a very large class. you can add methods to the classes defined in the Cocoa frameworks. ● ● ● ● ● To declare informal protocols See “Informal Protocols ” (page 63). All Rights Reserved. you are strongly discouraged from doing so. you could group the methods of a large class into several categories and put each category in its own file. Simplify the management of a large class when several developers contribute to the class definition. However. you don’t need source code for the class you’re extending.
● ● The very presence of some category methods may cause behavior changes across all frameworks. but it can also be quite dangerous. Methods added to NSObject become available to all classes that are linked to your code. if you override the windowWillClose: delegate method in a category on NSObject. All Rights Reserved. class objects can perform only class methods. They define an interface to the runtime system that all objects inherit. you may not know all the consequences of what you’re doing. 83 . For example.CHAPTER 6 Categories and Extensions ● When a category overrides an inherited method. Categories of the Root Class A category can add methods to any class. Categories of the Root Class 2010-12-08 | © 2010 Apple Inc. This issue is of particular significance because many of the Cocoa classes are implemented using categories. Normally. Class objects can perform instance methods defined in the root class. Adding methods to the root class with a category can be useful at times. if a category overrides a method that exists in the category's class. except that the methods they declare must be implemented in the main @implementation block for the corresponding class. invoke the inherited implementation via a message to super. including the root class. For example. Categories you add on a framework class may cause mysterious changes in behavior and lead to crashes. inheritance gives them a wide scope. Extensions Class extensions are like anonymous categories. Although it may seem that the modifications the category makes are well understood and of limited impact. Moreover. A category cannot reliably override methods declared in another category of the same class. You may be making unintended changes to unseen classes in your application. However. the method in the category can. A framework-defined method you try to override may itself have been implemented in a category. In addition. See NSObject Class Reference for more information on class access to root instance methods. and so which implementation takes precedence is not defined. as usual. all window delegates in your program then respond using the category method. But instance methods defined in the root class are a special case. who are unaware of your changes. within the body of the method. Class objects are full-fledged objects and need to share the same interface. others working on your application. the behavior of all your instances of NSWindow may change. there are two other considerations to keep in mind when implementing methods for the root class: ● ● Messages to super are invalid (there is no superclass of NSObject). won’t understand what they’re doing. This feature means that you need to take into account the possibility that an instance method you define in a category of the NSObject class might be performed not only by instances but by class objects as well. there is no way to invoke the original implementation. self might mean a class object as well as an instance.
as illustrated in the following example: @interface MyObject : NSObject { NSNumber *number.(void)setNumber:(NSNumber *)newNumber { number = newNumber. } @end Notice that in this case: ● No name is given in the parentheses in the second @interface block.(NSNumber *)number { return number.(void)setNumber:(NSNumber *)newNumber. This works. @end @implementation MyObject . Class extensions allow you to declare additional required methods for a class in locations other than within the primary class @interface block.(NSNumber *)number.CHAPTER 6 Categories and Extensions It is common for a class to have a publicly declared API and to then have additional methods declared privately for use solely by the class or the framework within which the class resides. the following declarations and implementation compile without error. 84 Extensions 2010-12-08 | © 2010 Apple Inc. @end @interface MyObject (Setter) . even though the setNumber: method has no implementation: @interface MyObject : NSObject { NSNumber *number. @end @interface MyObject () . } . } .(void)setNumber:(NSNumber *)newNumber. } . but the compiler cannot verify that all declared methods are implemented. would generate an error. @end @implementation MyObject .(NSNumber *)number. . however. You can declare such methods in a category (or in more than one category) in a private header file or implementation file as mentioned above. For example.(NSNumber *)number { return number. } @end Invoking setNumber: at runtime. All Rights Reserved.
the compiler emits a warning that it cannot find a method definition for setNumber:. 85 . All Rights Reserved. If this is not the case. Extensions 2010-12-08 | © 2010 Apple Inc.CHAPTER 6 Categories and Extensions ● The implementation of the setNumber: method appears within the main @implementation block for the class. The implementation of the setNumber: method must appear within the main @implementation block for the class (you cannot implement it in a category).
CHAPTER 6 Categories and Extensions 86 Extensions 2010-12-08 | © 2010 Apple Inc. All Rights Reserved. .
Associative references are available only in iOS and in Mac OS X v10. Listing 7-1 Establishing an association between an array and a string static char overviewKey. The key for each association must be unique. Adding Storage Outside a Class Definition Using associative references. or if for binary-compatibility reasons you cannot alter the layout of the object.CHAPTER 7 Associative References You use associative references to simulate the addition of object instance variables to an existing class. and an association policy constant. The policy specifies whether the associated object is assigned. you can add storage to an object without modifying the class declaration. the key and the association policy merit further discussion. An association can also ensure that the associated object remains valid for at least the lifetime of the source object (without the possibility of introducing uncollectible cycles in a garbage-collected environment). @"First three numbers"]. retained. This may be useful if you do not have access to the source code for the class. and whether the association is be made atomically or non-atomically. ● The key is a void pointer. NSArray *array = [[NSArray alloc] initWithObjects:@"One". Creating Associations You use the Objective-C runtime function objc_setAssociatedObject to make an association between one object and another. All Rights Reserved. The function takes four parameters: the source object. A typical pattern is to use a static variable. nil]. Adding Storage Outside a Class Definition 2010-12-08 | © 2010 Apple Inc. 87 . // For the purposes of illustration. each using a different key. Of these. so for any object you can add as many associations as you want. Associations are based on a key. You specify the policy for the relationship using a constant (see objc_AssociationPolicy and Associative Object Behaviors). @"Three". a key. @"Two". ● Listing 7-1 shows how you can establish an association between an array and a string. or copied.6 and later. the value. This pattern is similar to that of the attributes of a declared property (see “Property Declaration Attributes” (page 70)). use initWithFormat: to ensure // the string can be deallocated NSString *overview = [[NSString alloc] initWithFormat:@"%@".
To break all associations for an object. &overviewKey. nil. Continuing the example shown in Listing 7-1 (page 87). for example. All Rights Reserved. the string overview is still valid because the OBJC_ASSOCIATION_RETAIN policy specifies that the array retains the associated object. overview. overview is released and so in this case also deallocated. passing nil as the value. Retrieving Associated Objects You retrieve an associated object using the Objective-C runtime function objc_getAssociatedObject. &overviewKey). If you try to. you can call objc_removeAssociatedObjects. #import <Foundation/Foundation. . // (2) overview invalid At point 1. Given that the associated object is being set to nil. OBJC_ASSOCIATION_ASSIGN).” Complete Example The following program combines code from the preceding sections. you generate a runtime exception.h> #import <objc/runtime. the policy isn’t actually important. you typically call objc_setAssociatedObject. log the value of overview. you could break the association between the array and the string overview using the following line of code: objc_setAssociatedObject(array. OBJC_ASSOCIATION_RETAIN ).CHAPTER 7 Associative References objc_setAssociatedObject ( array. Breaking Associations To break an association. you could retrieve the overview from the array using the following line of code: NSString *associatedObject = (NSString *)objc_getAssociatedObject(array. Continuing the example shown in Listing 7-1 (page 87). Use this function only if you need to restore an object to “pristine condition. When the array is deallocated. [overview release].h> 88 Retrieving Associated Objects 2010-12-08 | © 2010 Apple Inc. &overviewKey. however (at point 2). however. // (1) overview valid [array release]. you are discouraged from using this function because it breaks all associations for all clients. In general.
89 . nil. OBJC_ASSOCIATION_ASSIGN ). OBJC_ASSOCIATION_RETAIN ). NSString *associatedObject = (NSString *) objc_getAssociatedObject (array. NSArray *array = [[NSArray alloc] initWithObjects:@ "One". All Rights Reserved. associatedObject). overview. &overviewKey. @"Three". &overviewKey). [overview release]. return 0.CHAPTER 7 Associative References int main (int argc. objc_setAssociatedObject ( array. @"First three numbers"]. @"Two". // For the purposes of illustration. &overviewKey. static char overviewKey. NSLog(@"associatedObject: %@". [array release]. } Complete Example 2010-12-08 | © 2010 Apple Inc. [pool drain]. const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]. objc_setAssociatedObject ( array. use initWithFormat: to ensure // we get a deallocatable string NSString *overview = [[NSString alloc] initWithFormat:@"%@". nil].
CHAPTER 7 Associative References 90 Complete Example 2010-12-08 | © 2010 Apple Inc. . All Rights Reserved.
If the loop is terminated early. and NSManagedObjectModel enumerates its entities. There are several advantages to using fast enumeration: ● ● ● The enumeration is considerably more efficient than. The syntax is concise. expression yields an object that conforms to the NSFastEnumeration protocol (see “Adopting Fast Enumeration” (page 91)). using NSEnumerator directly. Adopting Fast Enumeration Any class whose instances provide access to a collection of other objects can adopt the NSFastEnumeration protocol. Enumeration is “safe”—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration. NSDictionary enumerates its keys. for example. The iterating variable is set to nil when the loop ends by exhausting the source pool of objects. NSDictionary. for ( existingItem in expression ) { statements } In both cases. an exception is raised. For other classes. It should be obvious that in the cases of NSArray and NSSet the enumeration is over their contents. and the code defined by statements is executed. 91 . All Rights Reserved. as does NSEnumerator. Because mutation of the object during iteration is forbidden. and NSSet—adopt this protocol. the iterating variable is left pointing to the last iteration item.. NSDictionary and the Core Data class NSManagedObjectModel provide support for fast enumeration. the corresponding documentation should make clear what property is iterated over—for example. The for…in Syntax The syntax for fast enumeration is defined as follows: for ( Type newVariable in expression ) { statements } or Type existingItem. you can perform multiple enumerations concurrently. The for…in Syntax 2010-12-08 | © 2010 Apple Inc.
@"sex". element). @"Four". } In other respects. as illustrated in this example: NSArray *array = [NSArray arrayWithObjects: @"One". @"five". @"six". for (key in dictionary) { NSLog(@"English: %@. You can use break to interrupt the iteration. index++. so simply counting iterations gives you the proper index into the collection if you need it. NSArray *array = /* assume this exists */. Latin: %@". @"Two". nil]. for (NSString *element in array) { NSLog(@"element: %@". @"Three". // next = "Two" For collections or enumerators that have a well-defined order—such as an NSArray or an NSEnumerator instance derived from an array—the enumeration proceeds in that order. @"four". nil]. NSString *key. . @"Three". index. for (NSString *element in enumerator) { if ([element isEqualToString:@"Three"]) { break. key. } } NSString *next = [enumerator nextObject]. for (id element in array) { NSLog(@"Element at index %u is: %@". @"Four". element). NSUInteger index = 0. the feature behaves like a standard for loop. @"quinque". you can use a nested conditional statement: NSArray *array = /* assume this exists */. } NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"quattuor". All Rights Reserved. } You can also use NSEnumerator objects with fast enumeration. [dictionary objectForKey:key]). and if you want to skip elements. nil].CHAPTER 8 Fast Enumeration Using Fast Enumeration The following code example illustrates using fast enumeration with NSArray and NSDictionary objects. NSEnumerator *enumerator = [array reverseObjectEnumerator]. @"Two". NSArray *array = [NSArray arrayWithObjects: @"One". for (id element in array) { if (/* some test for element */) { // statements that apply only to elements passing test } } 92 Using Fast Enumeration 2010-12-08 | © 2010 Apple Inc.
index. } } Using Fast Enumeration 2010-12-08 | © 2010 Apple Inc. you could do so as shown in this example: NSArray *array = /* assume this exists */. 93 .CHAPTER 8 Fast Enumeration If you want to skip the first element and then process no more than five further elements. } if (++index >= 6) { break. NSUInteger index = 0. All Rights Reserved. for (id element in array) { if (index != 0) { NSLog(@"Element at index %u is: %@". element).
All Rights Reserved.CHAPTER 8 Fast Enumeration 94 Using Fast Enumeration 2010-12-08 | © 2010 Apple Inc. .
Static Typing If a pointer to a class name is used in place of id in an object declaration such as Rectangle *thisObject. Objective-C allows objects to be statically typed with a class name rather than generically typed as id. As many decisions about them as possible are pushed from compile time to runtime: ● ● The memory for objects is dynamically allocated at runtime by class methods that create new instances. In source code (at compile time). Default Dynamic Behavior 2010-12-08 | © 2010 Apple Inc. including ways to temporarily overcome its inherent dynamism. In the example above. Default Dynamic Behavior By design. The exact class of an id variable (and therefore its particular methods and data structure) isn’t determined until the program runs. as described in “Dynamic Binding” (page 19). To permit better compile-time type checking. A runtime procedure matches the method selector in the message to a method implementation that “belongs to” the receiver. All Rights Reserved. In particular. typically incurring an insignificant amount of overhead compared to actual work performed. but there’s a price to pay. ● These features give object-oriented programs a great deal of flexibility and power. 95 . Note: Messages are somewhat slower than function calls. Objects are dynamically typed. the compiler can’t check the exact types (classes) of id variables. and to make code more self-documenting.CHAPTER 9 Enabling Static Behavior This chapter explains how static typing works and discusses some other features of Objective-C. Objective-C objects are dynamic entities. any object variable can be of type id no matter what the object’s class is. Objective-C also lets you turn off some of its object-oriented features in order to shift operations from runtime back to compile time. the compiler restricts the value of the declared variable to be either an instance of the class named in the declaration or an instance of a class that inherits from the named class. Messages and methods are dynamically bound. The exceptionally rare case where bypassing the dynamism of Objective-C might be warranted can be proven by use of analysis tools like Shark or Instruments. thisObject can be only a Rectangle object of some kind.
Statically typed objects are dynamically allocated by the same class methods that create instances of type id. static typing opens up possibilities that are absent for objects typed id: ● ● In certain situations. Messages sent to statically typed objects are dynamically bound. performs the version of the method defined in the Square class. By giving the compiler more information about an object. The third is covered in “Defining a Class” (page 35). When a statically typed object is assigned to a statically typed variable. the compiler makes sure the types are compatible. A display message sent to the thisObject object: [thisObject display]. aRect = [[Rectangle alloc] init]. aShape = aRect. it affects only the amount of information given to the compiler about the object and the amount of information available to those reading the source code. The exact type of a statically typed receiver is still determined at runtime as part of the messaging process. The following example illustrates this: Shape *aShape. It can free objects from the restriction that identically named methods must have identical return and parameter types. the compiler can make sure the receiver can respond. . Type Checking With the additional information provided by static typing.CHAPTER 9 Enabling Static Behavior Statically typed objects have the same internal data structures as objects declared to be of type id. the class of the variable receiving the assignment. just as messages to objects typed id are. Static typing also doesn’t affect how the object is treated at runtime. Rectangle *aRect. not the one in its Rectangle superclass. or inherits from. not just those of a Rectangle object: Rectangle *thisObject = [[Square alloc] init]. A warning is issued if they’re not. It permits you to use the structure pointer operator to directly access an object’s instance variables. ● The first two possibilities are discussed in the sections that follow. ● An assignment can be made without warning. The type doesn’t affect the object. 96 Type Checking 2010-12-08 | © 2010 Apple Inc. provided the class of the object being assigned is identical to. the compiler can deliver better type-checking services in two situations: ● When a message is sent to a statically typed receiver. All Rights Reserved. If Square is a subclass of Rectangle. A warning is issued if the receiver doesn’t have access to the method named in the message. it allows for compile-time type checking. the following code would still produce an object with all the instance variables of a Square object.
can be statically typed as NSObject. This constraint is imposed by the compiler to allow dynamic binding. For example. (For reference. or an id object to a statically typed object. A statically typed object can be freely assigned to an id object. Return and Parameter Types 2010-12-08 | © 2010 Apple Inc. see Figure 1-2 (page 25). the compiler doesn’t ensure that a compatible object is returned to a statically typed variable. if you statically type a Rectangle instance as Shape as shown here: Shape *myRectangle = [[Rectangle alloc] init]. When it prepares information on method return and parameter types for the runtime system. can’t be known at compile time. However. The following code is error-prone. Therefore. the compiler treats it as a Shape instance. the compiler understands the class of a statically typed object only from the class name in the type designation. if you send it a message to perform a method that the Shape class knows about such as [myRectangle display]. which shows the class hierarchy including Shape and Rectangle.) There’s no check when the expression on either side of the assignment operator is of type id. the message is freed from the restrictions on its return and parameter types. aRect = [[Shape alloc] init]. and it does its type checking accordingly.CHAPTER 9 Enabling Static Behavior Here aRect can be assigned to aShape because a rectangle is a kind of shape—the Rectangle class inherits from Shape. for example. the compiler must treat all methods with the same name alike. Because the class of a message receiver (and therefore class-specific details about the method it’s asked to perform). methods in different classes that have the same selector (the same name) must also share the same return and parameter types. not in Shape. not every shape is a rectangle. the compiler generates a warning. All Rights Reserved. BOOL solid = [myRectangle isFilled]. Return and Parameter Types In general. However. However. if the roles of the two variables are reversed and aShape is assigned to aRect. The compiler has access to class-specific information about the methods. All instances. The isFilled method is defined in the Rectangle class. Static Typing to an Inherited Class An instance can be statically typed to its own class or to any class that it inherits from. the class of the receiver is known by the compiler. but is allowed nonetheless: Rectangle *aRect. Typing an instance to an inherited class can therefore result in discrepancies between what the compiler thinks would happen at runtime and what actually happens. 97 . it creates just one method description for each method selector. the compiler complains. when a message is sent to a statically typed object. However. Because methods like alloc and init return objects of type id. If you send the object a message to perform a Rectangle method.
the compiler thinks that its worry method returns a double. but it can do so reliably only if the methods are declared in different branches of the class hierarchy.(double)worry. the compiler thinks that worry returns an int. All Rights Reserved. and if an instance is typed to the Middle class.CHAPTER 9 Enabling Static Behavior the compiler doesn’t complain. Static typing can free identically named methods from the restriction that they must have identical return and parameter types. even though Rectangle overrides the method. . Errors result if a Middle instance is typed to the Upper class: The compiler informs the runtime system that a worry message sent to the object returns a double. If an instance is statically typed to the Upper class. 98 Static Typing to an Inherited Class 2010-12-08 | © 2010 Apple Inc. but at runtime it actually returns an int and generates an error. suppose that the Upper class declares a worry method that returns a double as shown here: .(int)worry. and the Middle subclass of Upper overrides the method and declares a new return type: . Similarly. the Rectangle version of the method is performed. At runtime.
it’s futile to assign them arbitrarily. Methods and Selectors For efficiency. though. It’s most efficient to assign values to SEL variables at compile time with the @selector() directive. setWidthHeight = @selector(setWidth:height:). You must let the system assign SEL identifiers to methods. All Rights Reserved. rather than to the full method name. All methods with the same name have the same selector. to distinguish them from other data. The runtime system makes sure each identifier is unique: No two selectors are the same. Here. The @selector() directive lets you refer to the compiled selector. Methods and Selectors 2010-12-08 | © 2010 Apple Inc. It also. method = NSStringFromSelector(setWidthHeight). you may need to convert a character string to a selector at runtime. Instead. and all methods with the same name have the same selector. Valid selectors are never 0. SEL and @selector Compiled selectors are assigned to a special type. the compiler writes each method name into a table. the selector for setWidth:height: is assigned to the setWidthHeight variable: SEL setWidthHeight. in some cases. Compiled selectors are of type SEL. It can be used to refer simply to the name of a method when it’s used in a source-code message to an object. full ASCII names are not used as method selectors in compiled code. SEL. You can use a selector to invoke a method on an object—this provides the basis for the implementation of the target-action design pattern in Cocoa. You can do this with the NSSelectorFromString function: setWidthHeight = NSSelectorFromString(aBuffer). 99 . selector has two meanings. then pairs the name with a unique identifier that represents the method at runtime. refers to the unique identifier that replaces the name when the source code is compiled. However. The NSStringFromSelector function returns a method name for a selector: NSString *method.CHAPTER 10 Selectors In Objective-C. Conversion in the opposite direction is also possible.
and performSelector:withObject:withObject: methods. has the same selector as display methods defined in other classes. A class method and an instance method with the same name are assigned the same selector. it lets you send the same message to receivers belonging to different classes. All three methods map directly into the messaging function. take SEL identifiers as their initial parameters. Varying the Message at Runtime The performSelector:. for example. If there were one selector per method implementation. These methods make it possible to vary a message at runtime. For example. the receiver (helper) is chosen at runtime (by the fictitious getTheReceiver function). . This is essential for polymorphism and dynamic binding. [friend performSelector:@selector(gossipAbout:) withObject:aNeighbor]. defined in the NSObject protocol. because of their separate domains. [helper performSelector:request]. It discovers the return type of a method. Variable names can be used in both halves of a message expression: id helper = getTheReceiver(). dynamic binding requires all implementations of identically named methods to have the same return type and the same parameter types. 100 Varying the Message at Runtime 2010-12-08 | © 2010 Apple Inc. is equivalent to: [friend gossipAbout:aNeighbor]. and the data types of its parameters.) Although identically named class methods and instance methods are represented by the same selector. SEL request = getTheSelector(). so it treats all methods with the same selector alike. Method Return and Parameter Types The messaging routine has access to method implementations only through selectors. and the method the receiver is asked to perform (request) is also determined at runtime (by the equally fictitious getTheSelector function). However. there’s no confusion between the two. they can have different parameter types and return types. A class could define a display class method in addition to a display instance method. (Statically typed receivers are an exception to this rule because the compiler can learn about the method implementation from the class type. just as it’s possible to vary the object that receives the message.CHAPTER 10 Selectors Methods and Selectors Compiled selectors identify method names. except for messages sent to statically typed receivers. All Rights Reserved. a message would be no different from a function call. from the selector. The display method for one class. not method implementations. In this example. Therefore. performSelector:withObject:.
The Target-Action Design Pattern 2010-12-08 | © 2010 Apple Inc. In software. but with directions on what message to send and who to send it to.CHAPTER 10 Selectors Note: performSelector: and its companion methods return an object of type id. NSControl objects are graphical devices that can be used to give instructions to an application. Constrained messaging would make it difficult for any object to respond to more than one button cell. a label. Accordingly. it should be cast to the proper type. But because messaging occurs at runtime. They interpret events coming from hardware devices such as the keyboard and mouse and translate them into application-specific instructions. switches. Each time you rearranged the user interface. (However. [myButtonCell setAction:@selector(reapTheWind:)]. the NSButtonCell class defines an object that you can assign to an NSMatrix instance and initialize with a size. casting doesn’t work for all types. If the method that’s performed returns a different type. menu items. Instead of simply implementing a mechanism for translating user actions into action messages. To do this. a picture. Avoiding Messaging Errors If an object receives a message to perform a method that isn’t in its repertoire. text fields. 101 . dials. knobs. Most resemble real-world control devices such as buttons. a size. and a keyboard shortcut. the method should return a pointer or a type compatible with a pointer. If Objective-C didn’t allow the message to be varied. you would also have to reimplement the method that responds to the action message. an NSButtonCell object must be initialized not just with an image. a button labeled “Find” would translate a mouse click into an instruction for the application to start searching for something. the error often isn’t evident until the program executes. the id of the control device sending the message. the button cell sends the message using the NSObject protocol method performSelector:withObject:. There would either have to be one target for each button. these devices stand between the application and the user. an NSButtonCell instance can be initialized for an action message (the method selector it should use in the message it sends) and a target (the object that should receive the message). or the target object would have to discover which button the message came from and act accordingly. For example. When the user clicks the button (or uses the keyboard shortcut). and the like. For example. AppKit makes good use of the ability to vary both the receiver and the message at runtime. All Rights Reserved. a font. [myButtonCell setTarget:anObject]. When the user clicks the corresponding button. button cells and other controls would have to constrain the content of the message. It’s the same sort of error as calling a nonexistent function. An absence of dynamic messaging would create an unnecessary complication that Objective-C happily avoids. and a label. the NSButtonCell object sends a message instructing the application to do something. the name of the method would be frozen in the NSButtonCell source code.) The Target-Action Design Pattern In its treatment of user-interface controls. an error results. AppKit defines a template for creating control devices and defines a few off-the-shelf devices of its own. all NSButtonCell objects would have to send the same message. All action messages take a single parameter.
"%s can’t be placed\n".0]. [NSStringFromClass([anObject class]) UTF8String]). tests whether a receiver can respond to a message. defined in the NSObject class. For example. the compiler performs this test for you. from the caller’s perspective. The respondsToSelector: method. In that case. See “Message Forwarding” in Objective-C Runtime Programming Guide for more information. As you write your programs. Note: An object can also arrange to have messages it receives forwarded to other objects if it doesn’t respond to them directly itself. All Rights Reserved. . even though it handles the message indirectly by forwarding it to another object. 102 Avoiding Messaging Errors 2010-12-08 | © 2010 Apple Inc. you can make sure that the receiver is able to respond. if the message selector or the class of the receiver varies. else fprintf(stderr. However. if you write code that sends a message to an object represented by a variable that others can set. the object appears to handle the message directly. It takes the method selector as a parameter and returns whether the receiver has access to a method matching the selector: if ( [anObject respondsToSelector:@selector(setOrigin::)] ) [anObject setOrigin:0.0 :0. If the receiver is statically typed. you should make sure the receiver implements a method that can respond to the message. The respondsToSelector: runtime test is especially important when you send messages to objects that you don’t have control over at compile time. it may be necessary to postpone this test until runtime.CHAPTER 10 Selectors It’s relatively easy to avoid this error when the message selector is constant and the class of the receiving object is known.
You can have multiple @catch{} blocks to catch different types of exception. A @catch{} block contains exception-handling logic for exceptions thrown in a @try{} block.CHAPTER 11 Exception Handling The Objective-C language has an exception-handling syntax similar to that of Java and C++. All Rights Reserved.3 and later. Enabling Exception-Handling Using GNU Compiler Collection (GCC) version 3. @catch. This chapter provides a summary of exception syntax and handling. @try { [cup fill].) Exception Handling An exception is a special condition that interrupts the normal flow of program execution. You typically use an NSException object. } Enabling Exception-Handling 2010-12-08 | © 2010 Apple Inc. for more details. and attempting to access a collection element out of bounds. To turn on support for these features. you can add robust error-handling to your programs. ● ● This example depicts a simple exception-handling algorithm: Cup *cup = [[Cup alloc] init]. (For a code example.3 and later. @throw. use the -fobjc-exceptions switch of the GNU Compiler Collection (GCC) version 3. There are a variety of reasons why an exception may be generated (exceptions are typically said to be raised or thrown). Objective-C provides language-level support for exception handling. underflow or overflow. see Exception Programming Topics. calling undefined instructions (such as attempting to invoke an unimplemented method). but you are not required to. NSError. by hardware as well as software. and @finally: ● ● Code that can potentially throw an exception is enclosed in a @try{} block. which is essentially an Objective-C object. By using this syntax with the NSException. A @finally{} block contains code that must be executed whether an exception is thrown or not. (Note that this switch renders the application runnable only in Mac OS X v10. Examples include arithmetical errors such as division by zero.3 and later because runtime support for exception handling and synchronization is not present in earlier versions of the software. 103 .) You use the @throw directive to throw an exception. or custom classes. see “Catching Different Types of Exception” (page 104). Objective-C exception support involves four compiler directives: @try.
as shown in Listing 11-1.. Listing 11-1 An exception handler @try { . NSException *exception = [NSException exceptionWithName: @"HotTeaException" reason: @"The tea is too hot" 104 Catching Different Types of Exception 2010-12-08 | © 2010 Apple Inc. } Catching Different Types of Exception To catch an exception thrown in a @try{} block. [exception name]. [exception reason]). whether exceptions were thrown or not. The @catch{} blocks should be ordered from most-specific to least-specific. Throwing Exceptions To throw an exception. } @finally { [cup release]. .CHAPTER 11 Exception Handling @catch (NSException *exception) { NSLog(@"main: Caught %@: %@"... That way you can tailor the processing of exceptions as groups.. All Rights Reserved. use one or more @catch{}blocks following the @try{} block. .. } @catch (id ue) { . } @catch (NSException *ne) { // 2 // Perform processing necessary at this level... 2. such as the exception name and the reason it was thrown. 3. Catches the most specific exception type. } The following list describes the numbered code lines: 1. } @catch (CustomException *ce) { // 1 . Performs any clean-up processing that must always be performed.. } @finally { // 3 // Perform processing necessary whether an exception occurred or not. you must instantiate an object with the appropriate information.. Catches a more general exception type. ..
but you can implement your own if you so desire. Exceptions are resource-intensive in Objective-C. you might throw an exception to signal that a routine could not execute normally—such as when a file is missing or data could not be parsed correctly. or simply to signify errors. All Rights Reserved. you can rethrow the caught exception using the @throw directive without providing an argument. For example. The NSException class provides methods that help in exception processing. see Error Handling Programming Guide. Throwing Exceptions 2010-12-08 | © 2010 Apple Inc. You should not use exceptions for general flow-control.CHAPTER 11 Exception Handling userInfo: nil]. 105 . Important: In many environments. Inside a @catch{} block. You can also subclass NSException to implement specialized types of exceptions. @throw exception. use of exceptions is fairly commonplace. such as file-system exceptions or communications exceptions. For more information. and provide information about the problem in an error object. You can throw any Objective-C object as an exception object. Instead you should use the return value of a method or function to indicate that an error has occurred. You are not limited to throwing NSException objects. Leaving out the argument in this case can help make your code more readable.
All Rights Reserved.CHAPTER 11 Exception Handling 106 Throwing Exceptions 2010-12-08 | © 2010 Apple Inc. .
All Rights Reserved. . . 107 2010-12-08 | © 2010 Apple Inc. It’s safest to create all the mutual exclusion objects before the application becomes multithreaded. which are explained in this chapter and in “Exception Handling” (page 103). Therefore. // Get the semaphore. The @synchronized() directive takes as its only argument any Objective-C object. a situation that can cause serious problems in a program. } } Listing 12-2 shows a general approach.3 and later because runtime support for exception handling and synchronization is not present in earlier versions of the software. Other threads are blocked until the thread exits the protected code—that is. Objective-C supports multithreading in applications. Before executing a critical process. Note: Using either of these features in a program renders the application runnable only in Mac OS X v10. It allows a thread to lock a section of code to prevent its use by other threads. use the -fobjc-exceptions switch of the GNU Compiler Collection (GCC) version 3. In the latter case. To turn on support for these features. Listing 12-1 shows code that uses self as the mutex to synchronize access to the instance methods of the current object. to avoid race conditions. the code obtains a semaphore from the Account class and uses it to lock the critical section. Listing 12-1 Locking a method using self . To protect sections of code from being executed by more than one thread at a time. The Account class could create the semaphore in its initialize method.. You can take a similar approach to synchronize the class methods of the associated class. using the class object instead of self.(void)criticalMethod { @synchronized(self) { // Critical code. of course. including self.CHAPTER 12 Threading Objective-C provides support for thread synchronization and exception handling. only one thread at a time is allowed to execute a class method because there is only one class object that is shared by all callers. The @synchronized()directive locks a section of code for use by a single thread. when execution continues past the last statement in the @synchronized() block. two threads can try to modify the same object at the same time. You should use separate semaphores to protect different critical sections of a program.. Objective-C provides the @synchronized() directive. This object is known as a mutual exclusion semaphore or mutex. Listing 12-2 Locking a method using a custom semaphore Account *account = [Account accountFromString:[accountField stringValue]].3 and later.
the Objective-C runtime catches the exception. 108 2010-12-08 | © 2010 Apple Inc. All Rights Reserved. @synchronized(accountSemaphore) { // Critical code. and rethrows the exception to the next exception handler.. that is. . every @synchronized() block is exited normally or through an exception. .CHAPTER 12 Threading id accountSemaphore = [Account semaphore]. A thread can use a single semaphore several times in a recursive manner. When code in an @synchronized() block throws an exception. releases the semaphore (so that the protected code can be executed by other threads).. } The Objective-C synchronization feature supports recursive and reentrant code. other threads are blocked from using it until the thread releases all the locks obtained with it.
" Corrected minor typographical errors. Updated to show the revised initialization pattern. Date 2010-12-08 2010-07-13 2009-10-19 2009-08-12 2009-05-06 2009-02-04 2008-11-19 2008-10-15 2008-07-08 2008-06-09 Notes Edited for content and clarity. . Updated description of categories. Significant reorganization. Corrected typographical errors. Clarified use of the static specifier for global variables used by a class. Updated article on Mixing Objective-C and C++. Corrected minor errors. Clarified the discussion of sending messages to nil.REVISION HISTORY Document Revision History This table describes the changes to The Objective-C Programming Language. Added discussion of associative references. Corrected minor typographical errors. Moved the discussion of memory management to "Memory Management Programming Guide for Cocoa. Provided an example of fast enumeration for dictionaries and enhanced the description of properties. particularly in the "Properties" chapter. Corrected typographical errors.. Corrected minor typographical errors. Corrected minor errors. Extended the discussion of properties to include mutable objects. All Rights Reserved. Made several minor bug fixes and clarifications. Clarified the description of Code Listing 3-3. Added references to documents describing new features in Objective-C 2.
Changed the font of function result in class_getInstanceMethod and class_getClassMethod.mm" extension to signal Objective-C++ to compiler. Corrected the grammar for the protocol-declaration-list declaration in “External Declarations” . 2004-02-02 2003-09-16 2003-08-14 Corrected typos in “An exception handler” . Added examples of thread synchronization approaches to “Synchronizing Thread Execution” . Corrected definition of method_getArgumentInfo. Added exception and synchronization grammar. Documented the language support for concatenating constant strings in “Compiler Directives” . Added exception and synchronization grammar to “Grammar” . . Corrected definition of id. Corrected typo in language grammar specification and modified a code example. 2005-04-08 2004-08-31 Removed function and data structure reference.3 and later in “Exception Handling and Thread Synchronization” . Moved “Memory Management” before “Retaining Objects” . Moved function and data structure reference to Objective-C Runtime Reference. Documented the Objective-C exception and synchronization support available in Mac OS X version 10. noted use of ". Clarified example in “Using C++ and Objective-C instances as instance variables” . Made technical corrections and minor editorial changes. All Rights Reserved. Corrected definition of the term conform in the glossary. Renamed from Inside Mac OS X: The Objective-C Programming Language to The Objective-C Programming Language. Clarified when the initialize method is called and provided a template for its implementation in “Initializing a Class Object” .REVISION HISTORY Document Revision History Date 2005-10-04 Notes Clarified effect of sending messages to nil. 110 2010-12-08 | © 2010 Apple Inc. Corrected the descriptions for the Ivar structure and the objc_ivar_list structure. Replaced conformsTo: with conformsToProtocol: throughout document.
2002-05-01 111 2010-12-08 | © 2010 Apple Inc. . and archaic tone. passive voice. Added runtime library reference material. Fixed a bug in the Objective-C language grammar’s description of instance variable declarations. Renamed from Object Oriented Programming and the Objective-C Language to Inside Mac OS X: The Objective-C Programming Language. All Rights Reserved. which allows C++ constructs to be called from Objective-C classes. Added an index.REVISION HISTORY Document Revision History Date 2003-01-01 Notes Documented the language support for declaring constant strings. Fixed several typographical errors. Mac OS X 10. Updated grammar and section names throughout the book to reduce ambiguities.1 introduces a compiler for Objective-C++. and vice versa. Restructured some sections to improve cohesiveness.
All Rights Reserved. .REVISION HISTORY Document Revision History 112 2010-12-08 | © 2010 Apple Inc.
Categories can be used to split a class definition into parts or to add methods to an existing class. . AppKit Sometimes called Application Kit. Programs don’t use instances of an abstract class. All Rights Reserved. class object In the Objective-C language. Cocoa An advanced object-oriented development platform in Mac OS X. Thus. Protocols are adopted by listing their names between angle brackets in a class or category declaration. Through messages to self. abstract superclass Same as abstract class. Cocoa is a set of frameworks whose primary programming interfaces are in Objective-C.. designated initializer The init. Each class defines or inherits its own designated initializer. Class objects are created by the compiler. As the receiver in a message expression. class In the Objective-C language. class method In the Objective-C language. adopt In the Objective-C language. a prototype for a particular kind of object. without waiting for the application that receives the message to respond. other init. The interface to an anonymous object is published through a protocol declaration. A class definition declares instance variables and defines methods for all members of the class. conform In the Objective-C language. a class is said to conform to a protocol if it (or a superclass) implements the methods declared in the protocol. Compare synchronous message. asynchronous message A remote message that returns immediately. and are therefore not in sync. delegate An object that acts on behalf of another object. a class object is represented by the class name... methods in the same class directly or 113 2010-12-08 | © 2010 Apple Inc. lack instance variables.Glossary abstract class A class that’s defined solely so that other classes can inherit from it. a set of method definitions that is segregated from the rest of the class definition. an instance that conforms to a protocol can perform any of the instance methods declared in the protocol. AppKit provides a basic program structure for applications that draw on the screen and respond to events. The sending application and the receiving application act independently. anonymous object An object of unknown class. an object that represents a class and knows how to create new instances of the class. they use only instances of its subclasses. Decisions made at compile time are constrained by the amount and kind of information encoded in source files. a class is said to adopt a protocol if it declares that it implements all the methods in the protocol. See also class object. a method that can operate on class objects rather than instances of the class. and can’t be statically typed.. A Cocoa framework that implements an application's user interface. An instance conforms to a protocol if its class does. but otherwise behave like all other objects. category In the Objective-C language. compile time The time when source code is compiled. Objects that have the same types of instance variables and have access to the same methods belong to the same class. method that has primary responsibility for initializing new instances of a class.
dynamic typing Discovering the class of an object at runtime rather than at compile time. instance variable In the Objective-C language. among others. through a message to super. and functions together with localized strings. Classes can adopt formal protocols. invokes the designated initializer of its superclass. The language gives explicit support to formal protocols. framework A way to package a logically related set of classes. but not to informal ones. It sets up the corresponding objects for you and makes it easy for you to establish connections between these objects and your own code where needed. Every class (except root classes such as NSObject) has a superclass. It allows the implementation to be updated or changed without impacting the users of the interface. a protocol that’s declared with the @protocol directive. instead of when it launches. inheritance hierarchy In object-oriented programming. finding the method implementation to invoke in response to the message—at runtime. formal protocol In the Objective-C language. and public-method prototypes. the general type for any kind of object regardless of class. online documentation. any variable that’s part of the internal data structure of an instance. which includes its superclass name. rather than at compile time. a protocol declared as a category. factory object Same as class object. instance In the Objective-C language. usually as a category of the NSObject class. interface The part of an Objective-C class specification that declares its public interface. especially user activity on the keyboard and mouse. objects can respond at runtime when asked if they conform to a formal protocol. protocols. dispatch table The Objective-C runtime table that contains entries that associate method selectors with the class-specific addresses of the methods they identify. Instances are created at runtime according to the specification in the class definition. Through its superclass. dynamic binding Binding a method to a message—that is. . implementation The part of an Objective-C class specification that defines public methods (those declared in the class’s interface) as well as private methods (those not declared in the class’s interface). informal protocol In the Objective-C language. 114 2010-12-08 | © 2010 Apple Inc. each class inherits from those above it in the hierarchy. inheritance In object-oriented programming. an object that belongs to (is a member of ) a particular class. and other pertinent files. distributed objects An architecture that facilitates communication between objects in different address spaces.GLOSSARY indirectly invoke the designated initializer. Interface Builder A tool that lets you graphically specify your application’s user interface. instance method In the Objective-C language. instances variables. id In the Objective-C language. id is defined as a pointer to an object data structure. Instance variables are declared in a class definition and become part of all objects that are members of or inherit from the class. and instances can be typed by the formal protocols they conform to. any method that can be used by an instance of a class rather than by the class object. and the designated initializer. factory Same as class object. and any class may have an unlimited number of subclasses. Cocoa provides the Foundation framework and the AppKit framework. All Rights Reserved. dynamic allocation A technique used in C-based languages where the operating system provides memory to a running application as it needs it. It can be used for both class objects and instances of a class. the ability of a superclass to pass its characteristics (methods and instance variables) on to its subclasses. the hierarchy of classes that’s defined by the arrangement of superclasses and subclasses. encapsulation A programming technique that hides the implementation of an operation from its users behind an abstract interface. event The direct or indirect report of external activity.
object A programming unit that groups together a data structure (instance variables) and the operations (methods) that can use or affect that data. subclass In the Objective-C language. such as C. message expression In object-oriented programming. outlet An instance variable that points to another object. informal protocol. a class that’s one step above another class in the inheritance hierarchy. nil In the Objective-C language.GLOSSARY link time The time when files compiled from different source modules are linked into a single program. Decisions made by the linker are constrained by the compiled code and ultimately by the information contained in source code. procedural programming language A language. the class through which a subclass inherits methods and instance variables. an object id with a value of 0. Compiled selectors are of type SEL. polymorphism In object-oriented programming. remote object An object in another application. one that’s a potential receiver for a remote message. namespace A logical subdivision of a program within which all names must be unique. selector In the Objective-C language. 115 2010-12-08 | © 2010 Apple Inc. Similarly. message In object-oriented programming. Objects are the principal building blocks of object-oriented programs. in Objective-C. the object that is sent a message. All Rights Reserved. or the unique identifier that replaces the name when the source code is compiled. An object used to synchronize thread execution. static typing In the Objective-C language. the method selector (name) and accompanying parameters that tell the receiving object in a message expression what to do. a procedure that can be executed by an object. reference counting A memory-management technique in which each entity that claims ownership of an object increments the object’s reference count and later decrements it. the object is deallocated. runtime The time after a program is launched and while it’s running. the name of a method when it’s used in a source-code message to an object. This technique allows one instance of an object to be safely shared among several other objects. Occasionally used more generally to mean any class that inherits from another class. In the Objective-C language. protocol In the Objective-C language. Outlet instance variables are a way for an object to keep track of the other objects to which it may need to send messages. message expressions are enclosed within square brackets and consist of a receiver followed by a message (method selector and parameters). . and the instance variables of a class are in their own namespace. each in its own way. by typing it as a pointer to a class. remote message A message sent from one application to an object in another application. the instance methods of a class are in a unique namespace for the class. See also formal protocol. mutex Short for mutual exclusion semaphore. the ability of different objects to respond. superclass In the Objective-C language. the declaration of a group of methods not associated with any particular class. For example. an expression that sends a message to an object. Symbols in one namespace do not conflict with identically named symbols in another namespace. method In object-oriented programming. to the same message. Decisions made at runtime can be influenced by choices the user makes. When the object’s reference count reaches zero. the class methods of a class are in their own namespace. giving the compiler information about what kind of object an instance is. Also used as a verb to mean the process of defining a subclass of another class. that organizes a program as a set of procedures that have definite beginnings and ends. any class that’s one step below another class in the inheritance hierarchy. receiver In object-oriented programming.
. Because the application that sends the message waits for an acknowledgment or return information from the receiving application. All Rights Reserved. Compare asynchronous message. the two applications are kept in sync. 116 2010-12-08 | © 2010 Apple Inc.GLOSSARY synchronous message A remote message that doesn’t return until the receiving application finishes responding to the message.
|
https://www.scribd.com/doc/61203062/ObjC
|
CC-MAIN-2017-51
|
refinedweb
| 33,006
| 52.05
|
i Have wriiten a code in "c" and it works fine for bluetooth connection with my cell but the OBEX_REQUEST_PUT does not work.I am not able track what the issue is.Below is the program plz tell me if i'm missing something,
typedef struct client_context {
int serverdone;
int clientdone;
char *get_name; /* Name of last get-request */
int arg; /* error code */
int opcode;
char *rsp; /* response storage place */
uint32_t con_id; /* connection ide */
void *private;
} client_context_t;
void obex_event(obex_t *handle, obex_object_t *object, int mode, int event, int obex_cmd, int obex_rsp)
{
}
int get_filesize(const char *filename)
{
struct stat stats;
stat(filename, &stats);
return (int) stats.st_size;
}
uint8_t *easy_readfile(const char *filename, int *file_size)
{
int actual;
int fd;
uint8_t *buf;
fd = open(filename);
if (fd == -1) {
return NULL;
}
int file_size1 = get_filesize(filename);
printf("name=%s, size=%d\n", filename, file_size1);
if (!(buf = malloc(file_size1))) {
return NULL;
}
actual = read(fd, buf, file_size1);
if(buf == NULL)
printf("read file is null\n");
close(fd);
*file_size = actual;
printf("*******");
printf("buf :%d\n",*buf);
return buf;
}
void syncwait(obex_t *handle)
{
client_context_t *gt;
int ret;
gt = OBEX_GetUserData(handle);
while(!gt->clientdone) {
//printf("syncwait()\n");
ret = OBEX_HandleInput(handle, 10);
if(ret < 0) {
printf("Error while doing OBEX_HandleInput()\n");
break;
}
if(ret == 0) {
/* If running cable. We get no link-errors, so cancel on timeout */
printf("Timeout waiting for data. Aborting\n");
OBEX_CancelRequest(handle, 0);
break;
}
}
gt->clientdone =1 ;
}
void put_client(obex_t *handle)
{
obex_object_t *object;
char lname[100];//="2.png";
char rname[100];//="2.png";
unsigned int rname_size;
obex_headerdata_t hd;
uint8_t *buf;
int file_size;
printf("PUT file (local, remote)> ");
scanf("%s %s", lname, rname);
buf = easy_readfile(lname, &file_size);
if(buf == NULL)
return;
printf("Going to send %d bytes\n", file_size);
/* Build object */
object = OBEX_ObjectNew(handle, OBEX_CMD_PUT);
uint8_t *ucname;
int ucname_len;
ucname_len = strlen(rname)*2 + 2;
ucname = malloc(ucname_len);
int err=0;
hd.bq4 = ConnectionID;
OBEX_ObjectAddHeader(handle, object, OBEX_HDR_CONNECTION, hd, 4, 0);
rname_size = OBEX_CharToUnicode(ucname, rname,ucname_len);
hd.bq4 = file_size;
OBEX_ObjectAddHeader(handle, object, OBEX_HDR_LENGTH, hd, sizeof(uint32_t), 0);
hd.bs = (uint8_t *) ucname;
OBEX_ObjectAddHeader(handle, object, OBEX_HDR_NAME, hd, ucname_len, 0);
hd.bs = buf;
OBEX_ObjectAddHeader(handle, object, OBEX_HDR_BODY, hd, file_size, OBEX_FL_STREAM_START);
if((err=OBEX_Request(handle, object)) < 0)
printf("Error sending =%d\n",err);
syncwait(handle);
}
int main (int argc, char *argv[])
{
char* pcMacddr="xx:xx:xx:xx:xx:xx";
char* pcChannel;
uint8_t channel=9;
obex_t *handle;
if(! (handle = OBEX_Init(OBEX_TRANS_BLUETOOTH, obex_event, 0)))
{
printf("Error initializing callbac event\n");
}
client_context_t *gt;
gt = malloc(sizeof(client_context_t));
memset(gt, 0, sizeof(client_context_t));
OBEX_SetUserData(handle, gt);
bdaddr_t *dst;
str2ba(pcMacddr, &dst);
if(BtOBEX_TransportConnect (handle ,BDADDR_ANY ,& dst, channel)<0)
{
printf("Error connecting client\n");
getchar();
return 0;
}
int err=0;
obex_object_t *oo;
oo = OBEX_ObjectNew(handle, OBEX_CMD_CONNECT);
obex_headerdata_t hd;
obex_object_t *object;
err = OBEX_Request(handle, oo);
syncwait(handle);
if(err < 0)
{
printf("Obex Request failed\n");
getchar();
return 0;
}
printf("Started a new request\n");
gt = OBEX_GetUserData(handle);
put_client(handle);
return 0;
}
I think i'm missing some thing plz lemme know ,
Please be more specific. This is too much code to read jff. You might want to compare to and examine each part.
If you want a quick result try some scripting language and ObexFTP.
I have gone thru this code .But during BtOBEX_TransportConnect request , the request comes to the cell phone (bluetooth device) and after connection in the obex_event i get 0X43(OBEX_RSP_FORBIDDEN) obex_rsp for OBEX_CMD_CONNECT.Can you tell me the reason why this happens?
I see. You need to setup the connection properly. Send a connect with the proper UUID. This is FBS for most mobiles. In some cases it's the PCSOFTWARE UUID or maybe the S45 UUID for older Siemens mobiles.
When yu send the obex frame for connect, the fone answer, yu should find 0xCB, and then the UUID is 0xCB 0xxx 0xxx 0xxx 0xxx, for me and my too phone i have one with 0xCB 0x00 0x00 0x00 0x00 and other 0xCB 0x00 0x00 0x00 0x01, 5 Bytes.
Also i don't know and never use openobex to write a client, if openobex can't give yu this response from the phone yu can use jobexftp (from me) at SF.net and then yu can see the hex frame of obex response.
Eric, you are talking about the Connection ID. Like you write you can not use the header 0xCB in CONNECT and that's where the error happens. Connection ID is mostly optional and will error with 0xD3, Service Unavailable.
If suppling the appropriate UUID and handling Connection IDs is too much trouble, have a look at the ObexFTP API. On the other hand if you want to explore OBEX and learn something try OpenOBEX itself. jobexftp is very early in develpment and a bit unstable I guess.
Now i have got it working but the file transferred have size zero always.I think the problem is with the header.The file name i receive is same as i input .And one more thing i don't get the call bac event called after Obex put request.Can u plz tell if thr is anything wrong with the code below,
struct stat stats;
stat(filename, &stats);
int file_size = stats.st_size;
int fd = open(filename,O_RDONLY);
uint8_t *buf= malloc(file_size);
int actual = read(fd, buf, file_size1);
strcpy(rname,"MyFile");
uint8_t *ucname;
int ucname_len;
ucname_len = strlen(rname)*2 + 2;
ucname = malloc(ucname_len);
rname_size = OBEX_CharToUnicode(ucname, rname,ucname_len);
hd.bs = (uint8_t *) ucname;
OBEX_ObjectAddHeader(handle, object, OBEX_HDR_NAME, hd, ucname_len, 0);
hd.bq4 = actual ;
OBEX_ObjectAddHeader(handle, object, OBEX_HDR_LENGTH, hd, sizeof(uint32_t), 0);
hd.bs = buf;
OBEX_ObjectAddHeader(handle, object, OBEX_HDR_BODY, hd,actual ,0);
OBEX_Request(handle, object)
Yu are complety right zany about UUID and Id, sorry.
also i spoke about jobexftp only for test and debug, i never think about publicity or to replace openobex stuff because this one is more like "Yoda" for me and i never plane to do a staff bigest and great as yu, i haven't got enouth knoeldge for this.
For K750I and M341i/342 jobexftp seems to work corectly.
|
http://sourceforge.net/p/openobex/discussion/27860/thread/b7f07330
|
CC-MAIN-2015-11
|
refinedweb
| 989
| 52.39
|
map the name to the ip address, you have a client service installed on your machine (a lot of new routers actually have this installed now) and it checks periodically and remaps your external ip address to your domain name. That way you can just type in your domain name and you'll alway point to your external IP address.
HTH
jocasio
Experts Exchange Solution brought to you by
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial
DNS obviously translates a domain name (computer.company.com) into an IP address (1.2.3.4), and reverse DNS does the opposite function, translating the IP address back to a name, using the "in-addr.arpa" namespace (e.g., 4.3.2.1.in-addr-arpa => computer.company.com). As long as your IP never changes, this works rather well with static DNS tables that remain fixed.
Dynamic DNS tries to address issues where the IP address of a computer is not fixed. If your computer gets it's IP address dynamically, such as via DHCP, it may not receive the same IP address every time the DHCP lease is obtained or renewed. In a typical Windows server environment, the DHCP and DNS services are integrated on the server and combine to provide DDNS. When a computer obtains an IP address, the DNS tables are updated with the computer name pointing to the newly assigned IP address. When the lease expires, the DNS entry is removed. This isn't just a Windows thing anymore, ISC's bind and dhcpd can provide DDNS as well.
This is relatively easy to do within an organization, and since the organization controls the names, IP addresses, and DNS/DHCP services, DDNS can be used to provide both forward and reverse DNS for the clients of the DHCP server.
The other type of dynamic DNS such as jocasio123 mentions is more common when you do not control the domain name, IP address, DNS, and/or DHCP service. If you want to have your own web server, for example "", without having all of the underlying IP/DNS/DHCP control, there are several providers that can provide a form of "dynamic" DNS for you. In the example above, you can't pick your own full domain name, just the hostname part. You would get a hostname from the DDNS provider and end up with a server name like "". Whenever your computer starts up and gets an IP from whatever source (typically your ISP's DHCP service), your computer then "registers" with your DDNS provider to link your current IP address with the name you registered. The advantage here is that you only need to do business with the DDNS provider for the name.
You can also get a "complete" name from other providers. Here, you register your own "myname.com" domain name with one of the various domain registries, then register this name with one of the DDNS providers. When you register "myname.com" you specify the DDNS provider's DNS servers in your registration, so that lookups for "myname.com" use the DDNS provider. Your computer registers it's IP address after getting a DHCP lease the same as above, but now you have a full name () instead of just a hostname (). To get this full name, you must now do business with your internet registry provider (to keep the myname.com registered) AND your DDNS provider (to keep the DNS service active).
Note that in both cases that you will typically NOT get reverse DNS, since your ISP still controls your IP namespace (and delegation of the in-addr.arpa section of your IP address).
|
https://www.experts-exchange.com/questions/22072060/What-is-DDNS.html
|
CC-MAIN-2018-34
|
refinedweb
| 630
| 70.63
|
fluidControl — Sends MIDI note on, note off, and other messages to a SoundFont preset.
The fluid opcodes provide a simple Csound opcode wrapper around Peter Hanappe's Fluidsynth SoundFont2 synthesizer. This implementation accepts any MIDI note on, note off, controller, pitch bend, or program change message at k-rate. Maximum polyphony is 4096 simultaneously sounding voices. Any number of SoundFonts may be loaded and played simultaneously.
kstatus -- MIDI channel message status byte: 128 for note off, 144 for note on, 176 for control change, 192 for program change, or 224 for pitch bend.
kchannel -- MIDI channel number to which the Fluidsynth program is assigned: from 0 to 255. MIDI channels numbered 16 or higher are virtual channels.
kdata1 -- For note on, MIDI key number: from 0 (lowest) to 127 (highest), where 60 is middle C. For continuous controller messages, controller number.
kdata2 -- For note on, MIDI key velocity: from 0 (no sound) to 127 (loudest). For continous controller messages, controller value.
Invoke fluidControl in instrument definitions that actually play notes and send control messages. Each instrument definition must consistently use one MIDI channel that was assigned to a Fluidsynth program using fluidLoad.
In this implementation, SoundFont effects such as chorus or reverb are used if and only if they are defaults for the preset. There is no means of turning such effects on or off, or of changing their parameters, from Csound.
Here is a more complex example of the fluidsynth opcodes written by Istvan Varga. It uses the file fluidcomplex.csd.
<CsoundSynthesizer> <CsOptions> ; Select audio/midi flags here according to platform ;Load external midi file from manual/examples -odac -T -F Anna.mid;;;realtime audio I/O and midifile in ;-iadc ;;;uncomment -iadc if realtime audio input is needed too ; For Non-realtime ouput leave only the line below: ; -o fluidcomplex.wav -W ;;; for file output any platform </CsOptions> <CsInstruments> sr = 44100 ksmps = 32 nchnls = 2 0dbfs = 1 ; Example by Istvan Varga ; disable triggering of instruments by MIDI events ichn = 1 lp1: massign ichn, 0 loop_le ichn, 1, 16, lp1 pgmassign 0, 0 ; initialize FluidSynth gifld fluidEngine gisf2 fluidLoad "sf_GMbank.sf2", gifld, 1 ; k-rate version of fluidProgramSelect opcode fluidProgramSelect_k, 0, kkkkk keng, kchn, ksf2, kbnk, kpre xin igoto skipInit doInit: fluidProgramSelect i(keng), i(kchn), i(ksf2), i(kbnk), i(kpre) reinit doInit rireturn skipInit: endop instr 1 ; initialize channels kchn init 1 if (kchn == 1) then lp2: fluidControl gifld, 192, kchn - 1, 0, 0 fluidControl gifld, 176, kchn - 1, 7, 100 fluidControl gifld, 176, kchn - 1, 10, 64 loop_le kchn, 1, 16, lp2 endif ; send any MIDI events received to FluidSynth nxt: kst, kch, kd1, kd2 midiin if (kst != 0) then if (kst != 192) then fluidControl gifld, kst, kch - 1, kd1, kd2 else fluidProgramSelect_k gifld, kch - 1, gisf2, 0, kd1 endif kgoto nxt endif ; get audio output from FluidSynth ivol init 3 ;a bit louder aL, aR fluidOut gifld outs aL*ivol, aR*ivol endin </CsInstruments> <CsScore> i 1 0 3600 e </CsScore> </CsoundSynthesizer>
fluidEngine, fluidNote, fluidLoad
More information on soundfonts in the Floss Manuals:
Other information on soundfonts on Wikipedia:
|
http://www.csounds.com/manual/html/fluidControl.html
|
CC-MAIN-2015-48
|
refinedweb
| 514
| 50.57
|
I have remote server on CentOS via ssh and I have one
test mongo database on port 27017.
I would like to run another databases on the same port or maybe on another port to use two databases in my application at the same time.
You can run multiple databases on one instance of mongod, there is no need to start up more than one instance if all you need is another database.
You cannot run more than one process on the same port, therefore you cant run another mongod on 27017. You could start up another instance on a different port though, but I'm not sure why you would want to unless you're trying to create a replicaset.
I am running multiple mongodb databases using graphQL on one connection. This should give you some idea:
connection:
import {MongoClient} from 'mongodb'; import assert from 'assert'; import graphqlHTTP from 'express-graphql'; const server_url = 'mongodb://localhost:27017/contest_server'; const client_url = 'mongodb://localhost:27017/contest_client'; // Establish connection to serverPool module.exports = (app, PORT, ncSchema) => { MongoClient.connect(server_url, (serverErr, serverPool) => { assert.equal(null, serverErr); MongoClient.connect(client_url, (clientErr, clientPool) => { assert.equal(null, serverErr); app.use('/graphql', graphqlHTTP({ schema: ncSchema, context: { serverPool, clientPool }, graphiql: true })); app.listen(PORT, () => { console.log(`Server is listening on port ${PORT}`) }); serverPool.collection("votes").count((err, count) => { console.log(count); }); clientPool.collection("counts").count((err, count) => { console.log(count); }); }); }); };
|
http://www.dlxedu.com/askdetail/3/6516bdd18c414ccb5df9ff61cce39b10.html
|
CC-MAIN-2018-39
|
refinedweb
| 231
| 50.63
|
Almost all tools have parameters, and you set their values on the tool dialog box or within a script. When the tool is executed, the parameter values are sent to your tool's source code. Your tool reads these values and proceeds with its work.
To learn more about parameters, see Understanding script tool parameters.
Script tool parameters can be set when creating a new script tool. You can also add, delete, and modify script tool parameters from a tool's Properties dialog box. To access script tool properties, right-click the tool, click Properties, and click the Parameters tab.
To add a new parameter, click the first empty cell under the Label column and type the name of the parameter. This is the name that will be displayed on the tool dialog box and can contain spaces. Under the Name column, a default parameter name will be created based on the Label but can be changed if needed. The parameter name is needed for Python syntax and will be validated (including removal of spaces).
After entering the display name of the parameter, choose a data type for the parameter by clicking in the Data Type cell as shown below.
If you need to create a parameter that will accept multiple values, check the Multi values check box. If you need to create a composite data type, that is, a parameter that accepts different data types, you can check multiple data types.
Each parameter has additional properties you can set as shown earlier and described below.
Type
There are three choices for Type:
- A Required parameter requires an input value from the user. The tool cannot be executed until the user supplies a value.
- An Optional parameter does not require a value from the user.
- A Derived parameter is only for output parameters (see Direction below). A derived output parameter does not show on the tool dialog box.
There are five uses for a derived output parameter as follows:
- The output is the same as the input, such as Calculate Field. Calculate Field changes the values of a particular field on the input table—it doesn't create a new table or modify the schema of the input. Other examples of tools whose output is the same as the input can be found in the Editing toolbox.
- The tool modifies the schema of the input, such as Add Field. Add Field adds a field to the input table—it doesn't create a new output table.
- The tool creates output using information in other parameters, such as the Create Feature Class tool. With the Create Feature Class tool, you specify the workspace and the name of the new feature class, and the feature class is created for you.
- The tool outputs a scalar value as opposed to a dataset. Get Count, for example, outputs a long integer (the number of records). Whenever a tool outputs a scalar value, the output is Derived.
- The tool will create data in a known location. For example, you may have a script that updates an existing table in a known workspace. The user doesn't need to provide this table on the dialog box or in scripting.
Note:
If your script tool has derived output, you need to set the value of the derived output parameter in your script using the SetParameterAsText or SetParameter function.
Output values instead of data
The examples above show outputting derived datasets. Some tools, however, output values instead of datasets, such as the Get Count tool, which outputs a Long data type containing the number of rows in a table. Outputting values instead of datasets is common. You may have scripts of your own that perform analysis on several related datasets and output nothing more than a couple of numbers, or a pass/fail Boolean value.
Output parameters containing value data types (such as Long or Boolean) are always Derived rather than Required.
Direction
This property defines whether the parameter is an input to the tool or an output of the tool.
If the parameter type is Derived, the parameter direction will be automatically set to Output.
All script tools should have output parameters so they can be used in ModelBuilder. The fundamental idea of ModelBuilder is to connect the output of tools to inputs of other tools, and if your script tool doesn't have an output parameter, it isn't very useful in ModelBuilder. The output might be a dataset that is entered in a parameter value, a derived output where the location and or name is determined within the script, or a derived value that is calculated or determined. At the very least, you can output a Boolean containing true if the tool completed successfully, and false otherwise.
Category
Parameters can be grouped into different categories to minimize the size of the tool dialog box or to group related parameters that will be infrequently used. You can enter either a new category name or choose from a list if you have set a category for other parameters. Several ArcGIS Network Analyst extension tools use categories as shown below.
Categories are always shown after noncategorized parameters. Do not put required parameters into categories, as they are hidden from view on the tool dialog box.
Multivalue
If you want a parameter to be able to handle a list of values rather than just one value, set the MultiValue property to Yes.
An example of a multivalue control is illustrated below.
Multivalues can be accessed as lists when using the arcpy.GetParameter() function and iterated over using a for loop. Otherwise, multivalues can be accessed as a semicolon-delimited string using arcpy.GetParameterAsText(). To break apart a delimited string, use the Python split() method as shown in the code example below.
import arcpy road_types = arcpy.GetParameterAsText(0) road_list = road_types.split(";") # Process each road type for road_type in road_list: # road_type contains an individual road type string (ex: "Interstates") arcpy.AddMessage("Processing: {}".format(road_type))
Default
The default value will be the contents of the parameter when the script's tool dialog box is opened. It is also the value that will be used if a # is entered for the parameter in scripting. If you don't specify a value for the Default property, the parameter value will be blank when the script's dialog box is opened. If you specify a value for this property, the Environment property will become disabled. To enable the Environment property, clear the Default property.
Schema
When the input parameter data type is a Feature Set or Record Set, you must specify the location of a schema that defines the fields and geometry type of the features to be entered. A schema is either a feature class, table, or layer file (.lyrx).
The Feature Set and Record Set data types allow interactive input of data. A Feature Set allows the user of your script to interactively create features by clicking on the map. The Record Set allows your user to interactively create rows in a table grid.
Environment
You can set the default value for a parameter to the value of an environment setting by right-clicking the appropriate cell under Environment and choosing the name of the environment setting.
Filter
If you want only certain values or dataset types to be entered for a parameter, you can specify a filter. Click the appropriate cell under Filter and choose the appropriate filter type from the drop-down list. A dialog box opens and you specify the values for the filter. There are six types of filters, and the type of filter you can choose depends on the data type of the parameter.
Usually, there is only one filter type you can choose. Only Long and Double have two choices: Value List and Range.
You can also set filters programmatically with Python by customizing a script tool's ToolValidator class.
Areal Units
The areal units filter defines the permissible unit types: Square Inches, Square Feet, Square Yards, Acres, Square Miles, Square Millimeters, Square Centimeters, Square Decimeters, Square Meters, Ares, Hectares, Square Kilometers, and Unknown.
Feature Type
For this filter, choose one or more filter values. Input feature classes will be checked against the filter values. For example, if you select only Point as the filter value, the user can only enter point feature classes as the parameter value.
A feature type filter defines the permissible feature class types: Point, Multipoint, Polygon, Polyline, Annotation, and Dimension. More than one value can be supplied to the filter.
Field
The field filter defines the permissible field types: Short, Long, Float, Double, Text, Date, OID, Geometry, Blob, Raster, GUID, GlobalID, and XML. More than one value can be supplied to the filter.
File
The file filter contains a list of file suffixes that a file may have, such as txt (simple text file) and csv (comma-separated values). You can supply any text for a suffix—it doesn't have to be a suffix that ArcGIS recognizes. The suffix can be of any length and does not include the dot. Multiple suffixes are separated by a semi-colon delimiter.
Linear Units
The linear units filter defines the permissible unit types: Inches, Points, Feet, Yards, Miles, Nautical Miles, Millimeters, Centimeters, Meters, Kilometers, Decimal Degrees, Decimeters, Degrees, and Unknown. More than one value can be supplied to the filter.
Range
A Long or Double parameter can have a Range filter. Range filters have two values: minimum and maximum. The range is inclusive, meaning the minimum and maximum are valid choices.
Time Units
The time units filter defines the permissible unit types: Milliseconds, Seconds, Minutes, Hours, Days, Weeks, Months, Years, Decades, Centuries, and Unknown. More than one value can be supplied to the filter.
Value List
The Value List filter is very useful for providing a set of keywords. Many tools have a predefined set of keywords, such as the Field Type parameter found in Add Field or the JoinAttributes parameter of many of the tools in the Overlay toolset.
A Value List filter can be used for Long and Double data types. For these types, you enter the allowable numeric values.
If you want the user to be able to choose more than one of the values, set the Multivalue property to Yes.
A Value List can be used for Boolean data types. For Boolean data types, the Value List contains two values: true and false. The true value is always the first value in the list. These values are used in the command line for specifying the value. See, for example, Add Field and the {NULLABLE | NON_NULLABLE} keywords used for the IsNullable property.
Workspace
The workspace filter specifies the types of input workspaces that are permissible. The three values are as follows:
- File System—A system folder used to store shapefiles, coverages, INFO tables, and grids
- Local Database—A personal or file geodatabase
- Remote Database—An enterprise database connection
More than one value can be supplied.
Dependency
The Dependency property has the following two purposes:
- For a derived output parameter, Dependency is set to the input parameter that will be modified by the tool. For more information on derived data and Dependency, see the discussion of the Type property above.
- For input parameters, Dependency contains the name of other parameters used by the data type. For example, for an input field data type, Dependency is set to the name of the table parameter containing the fields.
You can only set Dependency for certain input parameters as shown in the table below.
Symbology
If the output of your tool is a feature set, raster, TIN, or layer, you can specify the location of a layer file (.lyrx) in the Symbology property. When your tool is run and output is added to display, it will be drawn using the symbology defined in the symbology layer file.
Caution:
The layer file is read each time the tool is run. If the layer file cannot be found (because it was moved or deleted), default symbology will be used.
|
http://pro.arcgis.com/en/pro-app/arcpy/geoprocessing_and_python/setting-script-tool-parameters.htm
|
CC-MAIN-2019-09
|
refinedweb
| 2,002
| 54.52
|
Written By Lancelot Rossert,
Edited By Mae Semakula-Buuza, Lewis Fogden
Thu 10 May 2018, in category Data science
I see you’re ready for the next part of the "Your First Machine Learning Pipeline" series – part II! If you’re new to this series, you can begin by following along to the first blog post, "Your First Machine Learning Pipeline – Part I", where we outlined the various uses of the sci-kit learn package. In this blog post, we will focus on the ease and advantages of using feature selection to optimise predictions for your model.
First things first, we need to define what feature selection is. When building a Machine Learning (ML) model, it’s trained on features (also known as variables or predictors) - these are usually the columns in your training set. Similar to when you’re picking ingredients for making pancakes or any other delicious dessert, some ingredients are more important than others. Fact. This is why we use feature elimination, the removal of a subset of detrimental features from the initial ones, to obtain a better feature set. Optimisation of the feature set can vastly improve the prediction power of the model, hence why it is a key aspect of any ML project.
There are many ways of going about feature elimination - the most intuitive (but least efficient) one uses heuristic arguments, which essentially uses domain knowledge, and iterative manual analysis to remove features. This approach is time-consuming, making it unrealistic to use on larger feature sets. Furthermore, the importance of each feature is not always known so using manual elimination may not be viable.
As explained before, each feature has a degree of importance associated to it, subsequently impacting the prediction power of the model. Therefore, it is important to rank which features are most valuable when building a model. One example of a popular feature selection method is gini importance, commonly used with Random Forest models. Unfortunately, issues typically arise with feature selection when using a Random Forest model; one particular issue is that Random Forest models are more inclined to choose variables with more categories, inducing biased variable selection.
Recursive Feature Elimination (RFE) helps resolve some of the issues commonly faced during feature elimination. RFE is a ML algorithm that is typically used on small samples to improve classfication performance. It differs from alternative feature elimination algorithms by disregarding insignificant features, resulting in better predictions.
Some of the benefits of using RFE include:
So... we now know about the advantages of using RFE, but how exactly does it work? The following step-by-step guide shows you how RFE works (in theory)::
Figure 1. Accuracy vs. the number of features in the feature set (1-30).
Figure 1 shows the relationship between accuracy against increasing feature numbers in the feature set, ranging from 1-30. The highest model accuracy for the lowest model complexity was achieved using 9 features, indicating that this could be an optimal feature set.
This graph was generated using the Sci-KitLearn RFECV algorithm, which can be reproduced by following the step-by-step code guide in the later part of this post.
After running RFE, it is common that several feature sets will have similarly high accuracy scores. Furthermore, there are also times where some larger feature set has a slightly higher accuracy score than a smaller set. When this scenario occurs, it is best practice to utilise the feature set with the least number of features as the accuracy difference is negligible. Not only will the model benefit by having a faster runtime, it can also help prevent over-fitting of the model.
The more complicated our model is (e.g. the more features it has), the higher the chance of over-fitting our model. In simple terms, this means that our model becomes so streamlined in optimising the test set it is being tested on that it will only produce accurate results on this test set. If we were to train this over-fitting model on a new dataset and compare it to a model which does not suffer from over-fitting, our results would not be as accurate. This is the reason why simpler models tend to be preferred. We call this the Principle of Parsimony.
Similar to other ML algorithms, implementation of the RFE algorithm follows the same 4 steps (
instantiate,
fit,
score and
predict) that were discussed in the part I of this blog series.
As with most ML algorithms, RFE has a ready built algorithm within Python's sci-Kit Learn package.
from sklearn.feature_selection import RFECV
Before we can instantiate the RFE class, we must first create an instance of the model class to pass as a variable into our RFE.
sgdc = SGDClassifier() rfe = RFECV(sgdc)
Next comes the fitting the instance of the class – this also happens to be the most computationally intensive and expensive step of the overall process.
rfe = rfe.fit(X=clean.train_x, y=clean.train_y)
The model is fitted on a training dataset made up of a feature set (without a response). This is denoted as
X in the Sci-Kit Learn documentation and the response variable is denoted as
y. Note that there is a slight difference compared to when we first fitted the model as the RFECV fit is not done in-place.
Now that our data has been fitted to the model, there are several useful attributes of RFE than we can call. The one we shall focus on is the
support_ attribute. This gives us a boolean array (a mask) of which features to keep. To put this simply, it tells us which feature set will optimise our scoring metric.
Run RFE on the same data set but instead of using the SGDClassifier, use the Random Forest model.
Hint: Import the Random Forest model’s estimated class from its associated module.
Do you end up with the same optimal feature set? If not, what are some reasons that might have happened?
RFE enables us to generate an improved feature set and as a result, the prediction power of the model improves. It is possible to automate the feature selection process to improve our ML pipeline. We shall briefly outline how this can be done below.
Start by importing the following model classes (classifiers):
SGDClassifier,
RandomForestClassifier and
LogisticRegression.
from sklearn.linear_model import SGDClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression
We can then define a function to run RFE optimisation, taking into account the model class and the appropriate training and testing dataset:
def rfe_optimisation(model_class, x_train, y_train, x_test, y_test): model_instance = model_class() rfe = RFECV(model_instance) rfe = rfe.fit(X=train_x, y=train_y) return rfe.support_
We can then call this function to retrieve our feature masks for our imported estimators.
estimators = [SGDClassifier, RandomForestClassifier, LogisticRegression] feature_mask_dict = {} for estimator in estimators: feature_mask = rfe_optimisation( estimator, clean.train_x, clean.train_y, clean.test_x, clean.test_y) feature_mask_dict[estimator.__name__] = feature_mask
We have now successfully automated the RFE process, and can use each estimator's respective ideal features when making use of that estimator. We could then either make the models generated from these estimators compete, selecting the best of them, or stack them to make use of them all.
Create some additional features in your training dataset and run RFE on the new training set.
Hint: It might be useful to create new features using the python package, pandas.
Not to worry if you’re still a bit lost about what kind of features you want to create. Why not try creating:
Now compare the feature sets. Are the newly generated features kept in the final set? If so, did they improve your overall accuracy score?
Prior to reading this blog post, you were probably able to fit a ML model onto a training dataset. Now, you have officially levelled up (well done!) and are able to optimise your feature set using RFE, thus optimising the accuracy of your ML model.
In case you were wondering if there were other means of improving your feature set, the creation (not the elimination) of new features is always an option. Some examples include: - The time elapsed (difference) between two date columns e.g. start and end dates - The average of two float columns which are related - The range between two float columns that are related
As you can see, there are endless ways of going about feature selection, so it is your responsibility to determine the most effective feature selection method to improve the predictive power of the model.
Stay tuned for the next part of this blog series, "Your First Machine Learning Pipeline - Part III", where we will learn how to analyse the results generated from our ML algorithms.
|
http://blog.keyrus.co.uk/ml_pipeline_part_2.html
|
CC-MAIN-2018-51
|
refinedweb
| 1,454
| 52.49
|
I namespace::clean that is causing the problem.
I've managed to narrow it down to this minimal test case, but I haven't had any luck in figuring out why this is occuring...
package Test1;
use namespace::clean;
sub foo { if } # Yes, this is an intentional syntax error
1;
[download]
I'm simply running this code from the command line like so:
% perl -Ilib -MTest1 -e1
[download]
If you remove the call to 'use namespace::clean', this is the output (which is what I would expect)
syntax error at lib/Test1.pm line 2, near "if }"
Compilation failed in require.
BEGIN failed--compilation aborted.
[download]
However, when using namespace::clean, the output becomes:
Unknown error
Compilation failed in require.
BEGIN failed--compilation aborted.
[download]
Obviously this makes it very difficult to find bugs when it isn't even reporting which file the error was in when loading up hundreds of modules for a very large application. I realize namespace::clean is doing some pretty heavy magic, but I'd hate to give it up considering how tremendously useful it is.
Update:
Reported it to RT (43362). I also forked it on github and added a testcase ().
use Foo();
no Foo; # unimport
[download]
Which is a pretty clear indication that you have no idea what it does. Being able to import all the handy utility methods I need from whatever libraries I like without having all those imported functions appear as methods on the object is extremely useful.
5.10 broke just about any code written prior that looks into a package's namespace. That seems likely to be part of the problem here.
For the sake of saving memory, 5.10 causes code that expects (as has always been the case) for package symbol tables to only contain 'globs' to die with the fatal error "Not a glob reference at". This even broke the 5.10 debugger.
I think this optimization was included too cavalierly and it should become optional (an environment variable makes for an easy control mechanism) for 5.10
|
http://www.perlmonks.org/index.pl?node_id=744169
|
CC-MAIN-2014-23
|
refinedweb
| 343
| 62.58
|
Zopfli module for python
Project description
USAGE
pyzopfli is a straight forward wrapper around zopfli’s ZlibCompress method.
from zopfli.zlib import compress from zlib import decompress s = 'Hello World' print decompress(compress(s))
pyzopfli also wraps GzipCompress, but the API point does not try to mimic the gzip module.
from zopfli.gzip import compress from StringIO import StringIO from gzip import GzipFile print GzipFile(fileobj=StringIO(compress("Hello World!"))).read()
Both zopfli.zlib.compress and zopfli.gzip.compress support the following keyword arguments. All values should be integers; boolean parmaters are treated as expected, 0 and >0 as false and true.
- verbose dumps zopfli debugging data to stderr
- numiterations Maximum amount of times to rerun forward and backward pass to optimize LZ77 compression cost. Good values: 10, 15 for small files, 5 for files over several MB in size or it will be too slow.
- blocksplitting If true, splits the data in multiple deflate blocks with optimal choice for the block boundaries. Block splitting gives better compression. Default: true (1).
- blocksplittinglast If true, chooses the optimal block split points only after doing the iterative LZ77 compression. If false, chooses the block split points first, then does iterative LZ77 on each individual block. Depending on the file, either first or last gives the best compression. Default: false (0).
- blocksplittingmax Maximum amount of blocks to split into (0 for unlimited, but this can give extreme results that hurt compression on some files). Default value: 15.
TODO
- Stop reading the entire file into memory and support streaming
- Monkey patch zlib and gzip so code with an overly tight binding can be easily modified to use zopfli.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/zopfli/
|
CC-MAIN-2019-30
|
refinedweb
| 301
| 57.67
|
Hi, I was wondering if there was some simple free script (PHP or something) that would help me with making an incentive site. I plan on making a small incentive site, basically the user fills out a few email/zip submit type offers, and gets a freebie in return (havent decided what yet... but something that can be sent by email, like an ebook, voucher for some site, PLR website templates, etc) All I want it to do very simple: 1- User goes to main page, enters his email address (no registration or membership required), for example [email protected] 2- Script takes the email address, and adds it to the CPA tracking link code on the offers page, i.e hxxp://cpacompany.com/tracking12345blahblah/[email protected] so that I know the user has completed the offers and send him his gift. I think a script like that was shared here (or maybe it was somewhere else, dont remember) some time ago, and forgot what its called. Can someone please point me to the right direction on where to find this script?
|
https://www.blackhatworld.com/seo/question-about-freebie-incentive-script.28631/
|
CC-MAIN-2017-47
|
refinedweb
| 181
| 58.76
|
John Keeping <j...@keeping.me.uk> writes: > On Fri, Jul 05, 2013 at 10:20:11AM -0700, Junio C Hamano wrote: >> "brian m. carlson" <sand...@crustytoothpaste.net> writes: >> >> > You've covered the STARTTLS case, but not the SSL one right above it. >> > Someone using smtps on port 465 will still see the warning. You can >> > pass SSL_verify_mode to Net::SMTP::SSL->new just like you pass it to >> > start_SSL. >> >> OK, will a fix-up look like this on top of 1/2 and 2/2? > > According to IO::Socket::SSL [1], if neither SSL_ca_file nor SSL_ca_path > is specified then builtin defaults will be used, so I wonder if we > should pass SSL_VERIFY_PEER regardless (possibly with a switch for > SSL_VERIFY_NONE if people really need that). > > [1]
Advertising
Interesting. That frees us from saying "we assume /etc/ssl/cacerts is the default location, and let the users override it". To help those "I do not want verification because I know my server does not present valid certificate, I know my server is internal and trustable, and I do not bother to fix it" people, we can let them specify an empty string (or any non-directory) as the CACertPath, and structure the code like so? if (defined $smtp_ssl_cert_path && -d $smtp_ssl_cert_path) { return (SSL_verify_mode => SSL_VERIFY_PEER, SSL_ca_path => $smtp_ssl_cert_path); } elsif (defined $smtp_ssl_cert_path) { return (SSL_verify_mode => SSL_VERIFY_NONE); } else { return (SSL_verify_mode => SSL_VERIFY_PEER); } -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at
|
https://www.mail-archive.com/git@vger.kernel.org/msg31446.html
|
CC-MAIN-2016-50
|
refinedweb
| 248
| 52.39
|
Some time ago we ran into strange behaviour of MongoDB’s GridFS which caused me creating a Bug Ticket for the MongoDB Java driver.
Today I found the link to the bug ticket in my browser bookmarks. The ticket isn’t solved at the current time so I thought it would be worth a short blog post in case someone else runs into this problem.
Let’s look at the following simplified Java service:
public class GridFsService { private GridFS gridFs; public void connect(String mongoDbHost, String databaseName) throws UnknownHostException { DB db = Mongo.connect(new DBAddress(mongoDbHost, databaseName)); this.gridFs = new GridFS(db, "myBucket"); } public void removeGridFsFile(String id) { GridFSDBFile file = this.gridFs.findOne(new ObjectId(id)); this.gridFs.remove(file); } // .. other methods to create and update files }
This service uses the MongoDB Java driver to create, update and remove files from GridFS. However, there is a serious flaw in the removeGridFsFile() method. Guess what happens if an invalid id is passed to removeGridFsFile(). gridFs.findOne() returns null for non existent ids. So null is passed to gridFs.remove() which then removes all files in the current bucket.
Fixing this is easy. Just add a null check or use another GridFS remove() method that takes an ObjectId instead of a GridFsDBFile:
public void removeGridFsFile(String id) { this.gridFs.remove(new ObjectId(id)); }
Using this way everything works fine if an invalid id is passed to removeGridFsFile() (no file is removed). To make sure this won’t happen again I tested what happens if null is passed to any of the three different remove() methods:
gridFs.remove((String)null); // nothing happens gridFs.remove((ObjectId)null); // nothing happens gridFs.remove((DBObject)null); // all files from bucket are removed
I don’t know if this is intended behaviour. The Javadoc comment for gridFs.remove(DBObject query) tells me that it removes all files matching the given query. However, if it is intended I think it should be clearly stated in the javadoc comment that passing null removes all files in the bucket.
Thanks for the tips. GridFS is a very useful abstraction on top of MongodB.
|
http://www.javacodegeeks.com/2013/11/mongodb-gridfs-remove-method-deletes-all-files-in-bucket.html/comment-page-1/
|
CC-MAIN-2014-35
|
refinedweb
| 352
| 58.69
|
The objective of this post is to explain how to set a HTTP webserver on a ESP8266 and how to make some requests to it using a web browser.
Introduction
The objective of this post is to explain how to set an HTTP webserver on a ESP8266 and how to make some requests to it using a web browser.
We assume the use of the ESP8266 libraries for the Arduino IDE. You can check here how to configure the Arduino IDE to support the ESP8266.. Naturally, this class has some methods available that will help us setting up a server and handle incoming HTTP requests without needing to worry about low level implementation details. You can check the implementation of the library here.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
Next, we declare a global object variable from the previously mentioned class, so we will be able to access it in our functions.
As argument for the constructor of this class, we will pass the port where the server will be listening to. Since 80 is the default port for HTTP [1], we will use this value, so we will not need to specify it in the URL when accessing to our ESP8266 server using a browser.
ESP8266WebServer server(80);
Since we need to pre-configure our HTTP server before actually running it, we will do most of the coding in the setup function.
First of all, we open a serial connection for debugging.
Serial.begin(115200);
Then, we will need to connect to the WiFi network, as shown with the code below. If you need a detailed explanation on how to connect to a WiFi network with the ESP8266, check here.
WiFi.begin(“Network name”, “Password”);
while (WiFi.status() != WL_CONNECTED) { //Wait for connection
delay(500);
Serial.println(“Waiting to connect…”);
}
Since we are not going to do any domain name resolution, we need to know the IP where the ESP8266 is listening to incoming requests, which will be the local IP assigned in the WiFi network.
To get this value, we just call the localIP method on the WiFi global variable and then print it to the serial port, so we will know which URL to call on our web browser.
Serial.println(WiFi.localIP());
Then, we will start to specify which code to execute when an HTTP request is performed to each path. To do so, we call the on method on our previously declared server global object.
The more elegant method consists on defining a handling function somewhere in our code and passing it to the on function, alongside the URL that will trigger the execution of that function. This is exemplified below.
server.on(“/”, handleRootPath);
So, the code mentioned bellow indicates that when an HTTP request is received on the root (“/”) path, it will trigger the execution of the handleRootPath function. Note that we don’t specify the IP or port where the ESP8266 is listening, but only the path of the URL from that point onward.
For the sake of simplicity, let’s assume that our handleRootPath only answers with the text “Hello World” to the incoming HTTP request. So, to define an answer to a request, we call the send method on our server object.
Although the method can be called with a different set of arguments, its simplest form consists on receiving the HTTP response code, the content type and the content. Check the code below.
void handleRootPath() {
server.send(200, “text/plain”, “Hello world”);
}
In this case, we are sending the code 200, which corresponds to the “OK” response [2]. Then, we are specifying the content type as “text/plain“, since we are only responding with a simple “Hello world”, and finally the actual response text.
Naturally, this function needs to be declared outside the setup function.
We can also specify the handling function when calling the on method. In this case, we don’t need to declare a separate function and we can do everything in the setup function, as demonstrated bellow.
server.on(“/other”, [](){
server.send(200, “text/plain”, “Other URL”);
});
In this case, if we receive an HTTP request in the path “/other”, we will answer with a “Other URL” sentence.
Now, to start our server, we call the begin method on the server object. This is the last line of code we need to include in our setup function.
server.begin();
Finally, to handle the actual incoming of HTTP requests, we need to call the handleClient method on the server object, on the main loop function.
void loop() {
server.handleClient();
}
The complete code can be seen bellow.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server(80);
void setup() {
Serial.begin(115200);
WiFi.begin(“Network name”, “Password”); //Connect to the WiFi network
while (WiFi.status() != WL_CONNECTED) { //Wait for connection
delay(500);
Serial.println(“Waiting to connect…”);
}
Serial.print(“IP address: “);
Serial.println(WiFi.localIP()); //Print the local IP
server.on(“/other”, [](){ //Define the handling function for the path
server.send(200, “text/plain”, “Other URL”);
});
server.on(“/”, handleRootPath); //Associate the handler function to the path
server.begin(); //Start the server
Serial.println(“Server listening”);
}
void loop() {
server.handleClient(); //Handling of incoming requests
}
void handleRootPath() { //Handler for the rooth path
server.send(200, “text/plain”, “Hello world”);
}
Testing the code
To test the code we just need to open our browser and make an HTTP request to the IP of the ESP8266, on a path we defined early. The format is shown bellow:
Since, as stated before, we are listening on the 80 port, the browser will assume it by default, so we don’t need to specify it:
So, we substitute the serverIP by the IP printed on the serial console, and we make a request as shown in figure 1.
Figure 1 – HTTP request via browser on the root path (Google Chrome).
In this case, only the IP is shown because the browser removed the “/” from the root path. Also, the http:// was removed by the browser. Although some browsers perform the request when we only specify the IP, others assume that we want to search something in a search engine. So, the safest way is to always specify the http:// before the IP.
The example from figure 2 shows a request on the path “/other” that we also defined.
Figure 2 – HTTP request via browser on the “/other” path (Firefox).
Finally, note that if we specify a path not defined, the ESP will return a message indicating that the resource was not found, as we can see in figure 3, where we sent an HTTP request to the path “/notdefined”.
Figure 3 – HTTP request via browser on a path not defined.
Important: The IP that will be printed by the ESP8266 will be its private IP on the network. It won’t be possible for a client outside the network to contact it on that IP (and thus, the URL will not work). In order for a client
References
[1]
[2]
Technical details
ESP8266 libraries: v2.3.0
Pingback: ESP8266 HTTP server: Serving HTML, Javascript and CSS | techtutorialsx
Pingback: ESP8266 Webserver: Getting query parameters | techtutorialsx
Pingback: ESP8266 Webserver: Receiving GET requests from Python | techtutorialsx
Pingback: ESP8266 Webserver: Controlling a LED through WiFi | techtutorialsx
Pingback: ESP8266 Webserver: Resolving an address with mDNS | techtutorialsx
Have you considered the Watchdog on the Esp8266? I have several of these things but they always seem to halt. (Daily) I wonder if you’ve figured out how to employ the watchdog so they reboot themselves. Thanks for the content!
LikeLiked by 2 people
Hi! I haven’t yet played with the watchdog, but from what I’ve seen in the API there are some functions to enable / disable it:
If I find out how to make it work, I will make a post explaining it.
Thanks for the feedback 🙂
LikeLiked by 2 people
Hi again! I’ve been playing a little bit with the watchdogs of the ESP8266 and shared the results here:
As it seems, the ESP has 2 watchdogs: a software one and a hardware one. The ESP libraries for the Arduino IDE give us some control on the software watchdog. For the hardware watchdog, I haven’t found any way to control it.
Nevertheless, both the hardware and software watchdogs are enabled by default, so it’s strange that they don’t reset your devices when they halt. Do you have any error log that you can share in the github page of the libraries? It’s probably the best way to try to find the root cause and solve it.
LikeLiked by 1 person
Thanks for looking! That’s funny, it definitely locks up on me for hours, until I reset the device. I’ll see about posting it somewhere. The device I built simply lets my kids see their BTC balance, on an oled, all running on a esp8266 feather. So it’s just making http calls… and it locks up daily.
LikeLiked by 2 people
You’re welcome 🙂 It sounds a very cool project!
Well, I remember that once I had some problems while doing socket communication with a Java program. My program seemed to hang but in reality the sockets were being left half opened, so I wasn’t able to do any more connections after a certain point. Is that a possible case for your program or is it really crashing/locking at a deeper level?
I also have once experienced problems when doing many HTTP requests in a row, without a delay between them. It also caused some malfunctions.
Other things that you can try to solve the problem:
– Making sure you have the latest version of the ESP libraries.
– Changing the type of ESP board if you only tested in the same model. The problem you are experiencing may be a hardware issue. You have some different models at eBay, from the NodeMCU to the ESP01.
Hope it helps, if you are able to solve the issue please share with us.
LikeLiked by 2 people
Humm that ESP seems ereally nice . . .
LikeLiked by 1 person
It’s a very powerful device and very easy to use with the Arduino IDE. I really recommend it.
LikeLiked by 1 person
how cqn it communicate with the ide? meaning is it not another brand?
LikeLiked by 1 person
You can check here how to configure the Arduino IDE to support the ESP8266:
Think as Arduino not only as an hardware platform but also as a software platform. The Arduino IDE already supports multiple Arduino boards, which are implemented with different microcontrollers.
So, the question is being able to translate the Arduino language to the language that a specific microcontroller knows, being it integrated in an Arduino board or not. This project achieves that for the ESP8266:
Pingback: ESP8266 Webserver: Accessing the body of a HTTP request | techtutorialsx
Pingback: ESP8266: Setting an access point | techtutorialsx
I encountered a strange phenomenon. When I started this described program; my ESP8266 first connected to the IP-address: 192-168.4.2 which is NOT the default range of my WiFiNetwork (192.168.2.xxx). And when I reset this chip then it founds a good adres: 192.168.2.4
And I found in my Wifi Networklist that this chip pronounce itsself as “ESP_863074”. And in LookatLAN (a Windowsprogram thats pinning the arrea) I found this chip on this 2 IP-adresses. Also it is accessible on this both addresses.
LikeLiked by 1 person
Hi! That’s really a strange behavior, never happened to me yet, or at least I haven’t noticed. Does it happen to any other devices on your network or just the ESP8266?
I think it may be related to the router, since its the router that assigns the IP to the device on the network. But is just a guess.
Let us know if you discover the cause 🙂
Pingback: ESP8266: Adding Swagger UI to REST API | techtutorialsx
To associate an IP to a domain, download the library DNSServer.h. Then,
…
dnsServer.start(DNS_PORT, “”, my_IP);
See more,
sketches/examples —- DNSServer —– DNSServer (sketch)
LikeLiked by 1 person
Thanks for sharing!
|
https://techtutorialsx.com/2016/10/03/esp8266-setting-a-simple-http-webserver/
|
CC-MAIN-2017-26
|
refinedweb
| 2,022
| 63.39
|
This is GCC Bugzilla
This is GCC Bugzilla
Version 2.20+
View Bug Activity
|
Format For Printing
|
Clone This Bug
Compiling the following code:
#include <vector>
std::vector<int> *factory()
{
std::vector<int> *p = new std::vector<int>;
p->reserve(10);
return p;
}
with -Wall -O -fno-exceptions yields the following error in gcc-4.0.0
and gcc-4.0-20050602:
.../include/c++/4.0.0/bits/vector.tcc: In member function 'void std::vector<_Tp,
_Alloc>::reserve(size_t) [with _Tp = int, _Alloc = std::allocator<int>]':
.../include/c++/4.0.0/bits/vector.tcc:78: warning: control may reach end of
non-void function 'typename _Alloc::pointer std::vector<_Tp,
_Alloc>::_M_allocate_and_copy(size_t, _ForwardIterator, _ForwardIterator) [with
_ForwardIterator = int*, _Tp = int, _Alloc = std::allocator<int>]' being inlined
The warning comes from a catch/rethrow block deep in the bowels of stl
which (because of -fno-exceptions) evaluates to if(false).
This is a false positive warning, which would be fine except
for shops whose policy is to always compile with -Werror -Wall;
there, the warning is fatal. And because this problem is not
confined to just one user source file, it's hard to work around.
This problem does not occur in gcc-3.4.3 nor in recent gcc-4.1 snapshots.
cf. discussion here:
And I already filed this way back, see PR 19699 which I am closing this bug as
a dup.
See comment #2 in that PR from RTH:
There is zero chance that this will be fixed for 4.0. That's exactly why Ian
implemented the minimalistic check that he did in solving PR19583 and related.
You may retartget this pr to fixing the silliness in libstdc++, if you want.
*** This bug has been marked as a duplicate of 19699 ***
> You may retartget this pr to fixing the silliness in libstdc++, if you want.
And the "silliness" would be? Personally, I'm finding quite a bit of silliness
in this remark, to tell you the truth and indeed, mainline is ok, probably the
current compiler judges that "silliness" not so silly, after all.
When -fno-exceptions, the catch becomes simply an 'if (false)' and I don't see
why the implementors of v3 have necessarily to care about the branch not
returning.
(In reply to comment #2)
> > You may retartget this pr to fixing the silliness in libstdc++, if you.
(In reply to comment .
I disagree. libstdc++ can do exactly what everybody else does in such cases:
add a dummy (unreachable) "return __result" at the end, after both try
and catch blocks.
This will be a hack, no doubt, a pragmatic one. I don't think that emitting
false positive diagnostic that the user does not control is a good thing.
I have been working in a verification (research) department for 10 years,
and I can assure you that false positives, which can't be turned off,
are worse than no diagnostic at all. Such diagnostics *will* turn
customers/users away from your tool, or at best "just" ignore diagnostics.
I have used a (bought) tool that gave a false positive every 500 lines of
code. For 500 KLOC it would give 1K false positive. Now, try to find out a
single true bug out of the noise of 1000 false positives. I can tell you that
the tool was dropped very fast.
We write tools used for verification and testing. Our customers are more likely
to be willing to live with uncovered events, than to get false positives. Think
of millions of tests/events that cause even 0.1% of false positive. These may
overshadow hundreds of real bugs.
Same with gcc, if something as central as vector.reserve() give false positive
diagnostics then the sheer volume of warnings will render either the warning
or reserve() unusable.
I suggest to reopen PR19699 against libstdc++ (or maybe open a new one)
I concur with the last post -- a dummy return at the end would solve
the problem and seems like an acceptable solution for a release
branch.
W.
Note Mark has said in the past (and in a private mail which was supposed to be
a public one too) that
warnings cannot cause this to be a rejects valid.
It sure as hell is for those shops that require -Werror.
But ok, I'll be happy if it's fixed for 4.0.2.
(In reply to comment #6)
> Note Mark has said in the past (and in a private mail which was supposed to be
a public one too) that
> warnings cannot cause this to be a rejects valid.
For the same reason, PR 21183 should be reopened or merged with this PR:
> When compiling a C++ program with -Wall, I get the following compiler warning
>
>/usr/local/bin/../lib/gcc/i686-pc-linux-gnu/4.0.0/../../../../include/c++/4.0.0/bits/stl_uninitialized.h:113:
>warning: control may reach end of non-void function '_ForwardIterator
> std::__uninitialized_copy_aux(_InputIterator, _InputIterator,
...
> The problem seems to be in __uninitialized_copy_aux() in stl_uninitialized.h
>
> The catch statement block beginning on line 89 merely exits the routine without
> actually returning a value.
(In reply to comment #7)
> It sure as hell is for those shops that require -Werror.
>
> But ok, I'll be happy if it's fixed for 4.0.2.
I think that your argument (as phrased) does not hold.
Maybe you meant "It sure as hell is for those shops that require -Werror,
in this particular instance".
(Pardon my language, I just quoted the original ;-)
Consider:
1. 1: int main()
2: {
3: int a;
4: never_return(); // the halting problem
5: return a; // Uninitialized variable?
6: }
This is perfectly valid code and well defined, yet -Wall -Werror
will reject it. No compiler will ever be able to determine if
line 5 is ever reached.
2. 1: int main()
2: {
3: int a;
4: if(foo())
5: a= bar();
6: if(foo())
7: return a; // Uninitialized variable?
8: return 0;
9: }
Again, no compiler will be able to prove that a nontrivial foo() does
not change over time (unless declared const/pure/whatever).
And as a result, -Wall -Werror will reject valid code.
In both examples, the user has a simple work-around, initialize 'a'.
Adding initialization will make the code more stable, as foo() is
no longer constrained to be const/pure (forgive me for not remembering if
it is called pure or const).
In contrast (as mentioned in comment #4), this PR and PR 21183 do not
give the user the tools to shut this specific diagnostic instance up.
This is a compiler bug. If they don't fix it in 4.0.x, then we'll have to work
around it in libstdc++ 4.0 sources only.
People have suggested a patch to add a dummy return. If that's posted, it seems
to be perfectly acceptable to me. I suggest that be posted...
-benjamin
OK, I'm testing a patch now.
Created an attachment (id=9071) [edit]
proposed workaround
I have a patch for the compiler here:
which will fix this problem.
That's certainly prettier than my header changes.
I'll give it a shot. Thanks!
Fixed by:
2005-07-08 Geoffrey Keating <geoffk@apple.com>
* tree-inline.c (expand_call_inline): Prevent 'may reach end'
warning in system headers.
*** Bug 24498 has been marked as a duplicate of this bug. ***
|
http://gcc.gnu.org/bugzilla/show_bug.cgi%3Fid=21951
|
crawl-002
|
refinedweb
| 1,228
| 64.3
|
If you have been programming in Python (in object oriented way of course) for some time, I'm sure you have come across methods that have
self as their first parameter. It may seem odd, especially to programmers coming from other languages, that this is done explicitly every single time we define a method. As The Zen of Python goes, "Explicit is better than implicit".
So, why do we need to do this? Let's take a simple example to begin with. We have a
Point class which defines a method
distance to calculate the distance from origin.
class Point(object): def __init__(self,x = 0,y = 0): self.x = x self.y = y def distance(self): """Find distance from origin""" return (self.x**2 + self.y**2) ** 0.5
Let us now instantiate this class and find the distance.
>>> p1 = Point(6,8) >>> p1.distance() 10.0
In the above example,
__init__() defines three parameters but we just passed two (6 and 8). Similarly
distance() requires one but zero arguments were passed. Why is Python not complaining about this argument number mismatch?
Let me first clarify that
Point.distance and
p1.distance in the above example are a bit different.
>>> type(Point.distance) <class 'function'> >>> type(p1.distance) <class 'method'>
We can see that the first one is a function and second, a method. A peculiar thing about methods (in Python) is that the object itself is passed on as the first argument to the corresponding function. In the case of the above example, the method call
p1.distance() is actually equivalent to
Point.distance(p1). Generally, when we call a method with some arguments, the corresponding class function is called by placing the method's object before the first argument. So, anything like
obj.meth(args) becomes
Class.meth(obj, args). The calling process is automatic while the receiving process is not (its explicit).
This is the reason the first parameter of a function in class must be the object itself. Writing this parameter as
self is merely a convention. It is not a keyword and has no special meaning in Python. We could use other names (like
this) but I strongly suggest you not to. Using names other than
self is frowned upon by most developers and degrades the readability of the code ("Readability counts").
By now you are clear that the object (instance) itself is passed along as the first argument, automatically. This implicit behavior can be avoided by making a method, static. Consider the following simple example.
class A(object): @staticmethod def stat_meth(): print("Look no self was passed")
Here,
@staticmethod is a function decorator which makes
stat_meth() static. Let us instantiate this class and call the method.
>>> a = A() >>> a.stat_meth() Look no self was passed
From the above example, we are clear that the implicit behavior of passing the object as the first argument was avoided using static method. All in all, static methods behave like our plain old functions.
>>> type(A.stat_meth) <class 'function'> >>> type(a.stat_meth) <class 'function'>
The explicit
self is not unique to Python. This idea was borrowed from Modula-3. Following is a use case where it becomes helpful.
There is no explicit variable declaration in Python. They spring into action on the first assignment. The use of
self makes it easier to distinguish between instance attributes (and methods) from local variables. In, the first example self.x is an instance attribute whereas x is a local variable. They are not the same and lie in different namespaces.
Many have proposed to make self a keyword in Python, like
this in C++ and Java. This would eliminate the redundant use of explicit
self from the formal parameter list in methods. While this idea seems promising, it's not going to happen. At least not in the near future. The main reason is backward compatibility. Here is a blog from the creator of Python himself explaining why the explicit self has to stay.
One important conclusion that can be drawn from the information so far is that,
__init__() is not a constructor. Many na?ve Python programmers get confused with it since
__init__() gets called when we create an object. A closer inspection will reveal that the first parameter in
__init__() is the object itself (object already exists). The function
__init__() is called immediately after the object is created and is used to initialize it.
Technically speaking, constructor is a method which creates the object itself. In Python, this method is
__new__(). A common signature of this method is
__new__(cls, *args, **kwargs)
When
__new__() is called, the class itself is passed as the first argument automatically. This is what the cls in above signature is for. Again, like self, cls is just a naming convention. Furthermore, *args and **kwargs are used to take arbitary number of arguments during method calls in Python.
Some important things to remember when implementing __new__() are:
__new__()is always called before
__init__().
__new__(). Not mandatory, but thats the whole point.
Let's take a look at an example to be crystal clear.
class Point(object): def __new__(cls,*args,**kwargs): print("From new") print(cls) print(args) print(kwargs) # create our object and return it obj = super().__new__(cls) return obj def __init__(self,x = 0,y = 0): print("From init") self.x = x self.y = y
Now, let's now instantiate it.
>>> p2 = Point(3,4) From new <class '__main__.Point'> (3, 4) {} From init
This example illustrates that
__new__() is called before
__init__(). We can also see that the parameter cls in
__new__() is the class itself (
Point). Finally, the object is created by calling the
__new__() method on object base class. In Python,
object is the base class from which all other classes are derived. In the above example, we have done this using
super().
You might have seen
__init__() very often but the use of
__new__() is rare. This is because most of the time you don't need to override it. Generally,
__init__() is used to initialize a newly created object while
__new__() is used to control the way an object is created. We can also use
__new__() to initialize attributes of an object, but logically it should be inside
__init__(). One practical use of
__new__() however, could be to restrict the number of objects created from a class.
Suppose we wanted a class
SqPoint for creating instances to represent the four vertices of a square. We can inherit from our previous class
Point (first example in this article) and use
__new__() to implement this restriction. Here is an example to restrict a class to have only four instances.
class SqPoint(Point): MAX_Inst = 4 Inst_created = 0 def __new__(cls,*args,**kwargs): if (cls.Inst_created >= cls.MAX_Inst): raise ValueError("Cannot create more objects") cls.Inst_created += 1 return super().__new__(cls)
A sample run.
>>> p1 = SqPoint(0,0) >>> p2 = SqPoint(1,0) >>> p3 = SqPoint(1,1) >>> p4 = SqPoint(0,1) >>> >>> p5 = SqPoint(2,2) Traceback (most recent call last): ... ValueError: Cannot create more objects
|
https://www.programiz.com/article/python-self-why
|
CC-MAIN-2018-30
|
refinedweb
| 1,174
| 67.96
|
sofine 0 those data sets with one command line, REST or Python call? Wouldn’t it be great if each data retrieval script you wrote was a reusable plugin that you could combine with any other to retrieve one combined data set over a set of keys?
You need a “glue API.”
This is the problem sofine solves. It’s a small enough problem that you could solve it yourself. But sofine is minimal to deploy and write plugins for, and has already solved in an optimally flexible way the design decisions you would have to solve on your own if you did so.
Features
- Do (almost) no more work than if you wrote a, such as the example above, can themselves be composed in larger piped expressions.
For fun, here is an example of features 4 and 5, combining a sofine pipeline with the fantastic JSON query tool jq for further filtering.
echo '{"AAPL":{}}' | python sofine/runner.py '--SF-s ystockquotelib --SF-g example | --SF-s google_search_results --SF-g example' | jq 'map(recurse(.SOME_KEY) | {SOME_OTHER_KEY}' TODO sofine/runner.py '--SF-s ystockquotelib --SF-g example | --SF-s google_search_results --SF-g example'
REST-fully:
$ python JSON objects of data to string keys. So here, we have the key “AAPL,” with all the attributes retrieved from Yahoo! Finance and the Google Search API combined in a JSON object associated with the key. Notice that the keys in the attribute data set are namespaced so multiple calls can’t overwrite data from each other.
{ "AAPL": { "example::google_search_results:" }, ... ... ], "example::ystockquotelib::avg_daily_volume": "59390100", "example::ystockquotelib::book_value": "20.193", "example::ystockquotelib::change": "+1.349", "example::ystockquotelib::dividend_per_share": "1.7771", "example::ystockquotelib::dividend_yield": "1.82", "example::ystockquotelib::earnings_per_share": "6.20", "example::ystockquotelib::ebitda": "59.128B", "example::ystockquotelib::fifty_day_moving_avg": "93.8151", "example::ystockquotelib::fifty_two_week_high": "99.24", "example::ystockquotelib::fifty_two_week_low": "63.8886", "example::ystockquotelib::market_cap": "592.9B", "example::ystockquotelib::price": "99.02", "example::ystockquotelib::price_book_ratio": "4.84", "example::ystockquotelib::price_earnings_growth_ratio": "1.26", "example::ystockquotelib::price_earnings_ratio": "15.75", "example::ystockquotelib::price_sales_ratio": "3.28", "example::ystockquotelib::short_ratio": "1.70", "example::ystockquotelib::stock_exchange": "\"NasdaqNM\"", "example::ystockquotelib::two_hundred_day_moving_avg": "82.8458", "example::ystockquotelib::volume": "55317688" } }
Getting sofine
git clone git@github.com:marksweiss/sofine.git cd <CLONED DIRECTORY> python setup.py
Then, create a plugin directory and assign its path to an environment variable SOFINE_PLUGIN_PATH. You probably want to add it to your shell configuration file:
export SOFINE_PLUGIN_PATH=<MY PATH>
How Plugins Work and How to Write Them
All plugins inherit from a base class which must match the module name of the plugin module, that is the name you would use in an import statement. group must match the name of the subdirectory of your plugin directory where the plugin is deployed. sofine uses name and group to load and run your plugin, so they have to be there and they have to be correct.
schema and adds_keys are optional. They allow users of your plugin to introspect your plugin. schema is a list of strings that tells a client of your plugin the set of possible attribute keys that your plugin returns for each key it recieves. For example, if your plugin takes stock tickers as keys and looks up their price, its schema declaration might look like this:
self.schema = ['quote'].
Plugins also have three methods.]
The third method is get_schema. You will rarely need to implement this. Any plugin that knows the set of attributes it can return for a key doesn’t need to implement get_schema and can rely on the default. So, for example, a call to an API that returns a know JSON or XML object, a scraper that builds a known object of attributes, or a call to a relational or NoSql data store with a known set of possible fields – all of these can rely on the default get_schema. Note that get_schema returns the set of attribute keys you define in self.schema namespace qualified with the plugin group and name. For example, if our stock quote plugin mentioned above is named get_quotes and it is in the trading group, the return value of get_schema would be ["trading::get_quotes::quote"].
Finally, the last line of your plugin should assign the module-scope variable plugin to the name of your plugin class. For example:
plugin = GoogleSearchResults: ret = {'results' : ret['responseData']['results']} else: ret = {'results' : []} return ret
Now, here are the 10 additional lines of code you need to make your plugin run in sofine.
from sofine.plugins import plugin_base as plugin_base class GoogleSearchResults(plugin_base.PluginBase): def __init__(self): self.name = 'google_search_results' self.group = 'example' self.schema = ['results'] self.adds_keys = False def get_data(self, keys, args): return {k : query_google_search(k) for k in keys} plugin = GoogleSearchResults
Now write a unit test for get_data, which you can even leave in the same plugin subdirectory as the plugin, and you are done., depending on the call, the plugin action.
There are four actions, which correspond to the three methods get_data, parse_args and get_schema, while adds_keys returns the value of the the plugin’s self.adds_keys.
get_data parse_args get:
TODO: Actual installer and correct path to call sofine python to retrieve sofine/runner.py '--SF-s ystockquotelib --SF-g example --SF-a adds_keys'
REST:
curl -X POST -d '{}' --header "Content-Type:application/json"
Python:
data_source = 'ystockquotelib' data_source_group = 'example' schema = runner.adds_keys(data_source, data_source retults JSON objects that it returns for each key passed to it. Because this is nested data, the more interesting attributes are one level down in the data returned, so this helper is useful in this particular case. This is an example of the value of the flexibility of putting additional attributes or functions in your module as needed and accessing them in Python directly. it like any other source code repo, and include unit tests for plugins anywhere in the plugin directory if you want..
- All attribute keys are namespaced with the prefix of the plugin group and plugin name and then the attribute key name, guaranteeing they are!
Developer documentation is here:
- Author: Mark S. Weiss
- Keywords: glueAPI data pipelines scraper webAPI
- License: MIT
- Categories
- Package Index Owner: marksweiss
- DOAP record: sofine-0.1.xml
|
https://pypi.python.org/pypi/sofine/0.1
|
CC-MAIN-2018-13
|
refinedweb
| 1,021
| 58.18
|
.D. Willems310 Points
what am i doing wrong? error code is: Does your GetVideoGames doesn't have any parameters
""" public VideoGame GetVideoGames(int id){
VideoGame gamee = null; foreach(var game in _videoGames){ if(game.Id == id) gamee = game; break; } return gamee; }
"""
using Treehouse.Models; namespace Treehouse.Data { public class VideoGamesRepository { // TODO Add GetVideoGames method // TODO Add GetVideoGame method } }; public VideoGame GetVideoGames(int id){ VideoGame gamee = null; foreach(var game in _videoGames){ if(game.Id == id) gamee = game; break; } return gamee; } } } + ")"; } } } }
2 Answers
Allan Clark10,810 Points
You are a little ahead of yourself. The first challenge asks you to create a GetVideoGames method that accepts no parameter and returns the private field. What you have is trying to answer the second challenge. So the first challenge should look like this.
public VideoGame[] GetVideoGames() { return _videoGames; }
As for the second challenge you are pretty close. Make sure you adjust the name of the method, it should be GetVideoGame (singular bc we are returning only one). My suggestion would be to just remove the 'break' from the loop entirely. It is generally considered good practice to avoid keywords such as break, continue, and goto that manually manipulate the execution flow of the code. This is because it can lead to unforeseen and hard to diagnose bugs in your code. As written the method will go into the foreach loop, check the id of the first element of the array and then break out of the loop, never getting the chance to check the other elements.
Simply removing the break line will fix this issue and will pass the second challenge, but since there are use cases where breaking would make sense this is what the code would need to look like: (Note: this would only be used if you are searching through a very large array probably ~10k+, and at that point there are other optimizations that would be needed as well)
public VideoGame GetVideoGame(int id){ VideoGame gotGame = null; foreach(var game in _videoGames) if(game.Id == id) { gotGame = game; break; } return gotGame; }
Let me know if you have any more questions, and keep up the great work! Happy Coding!! :)
|
https://teamtreehouse.com/community/what-am-i-doing-wrong-error-code-is-does-your-getvideogames-doesnt-have-any-parameters
|
CC-MAIN-2022-27
|
refinedweb
| 359
| 67.89
|
public class PoliceOfficer
{
String officerName;
double badgeNumber;
ParkedCar carInfo;
ParkingMeter meter;
double timeParked;
double timePurchased;
public class PoliceOfficer
{
String officerName;
double badgeNumber;
ParkedCar carInfo;
ParkingMeter meter;
double timeParked;
double timePurchased;
It was the getPassFail method but I figured it out I forgot to call the Exam1.setInfo() method in the main method so the variables I was trying to return were never set. Thanks
I'm writing this program that is a drivers license test . the main method allows the user to input 20 answers and it creates an array of those answers then it is suppose to make that a new instance...
I have a drivers license test program where in the main method the user inputs the answers then in a separate class there needs to be a method to see if the user passed a method to tell how many were...
that was it thanks
it does compile the only issue I'm having is that my correctCount doesn't count up it stays at 0 so the return is always false
I have to tell if someone passed a drivers test or not. for some reason in the class the
correctCount isn't adding when it should so I am always having a return of false and I cant figure out why....
because it is set to 0 inside the SaveDistinctNumber method doesn't increment until it is inside the for loop in the SaveDistinctNumber method that's why i was talking about returning count to the...
that's what count does so in my method to save the numbers count is set to 0 . the user enters a number and that is saved into array 1 wether it is a number the user already entered or not then i...
I have count declared at 0 at the top of my main method I must have missed that when I was copying it. All Im trying to be able to do is print out array2 up until the element where nothing else was...
im trying to create a for loop in the main method after all the elements have been saved that looks like this but im not getting any output because in the main method count is still equal to 0.
...
sorry didn't know how to do that but so far I've figured out that the issue was the breaks in the if statements ending the for loops cause my count to not count and that I had ...
I have to make an array of 10 numbers then copy that array into a new array without the duplicates. I got it to the point where it will weed out dups but for some reason after I determine that a...
|
http://www.javaprogrammingforums.com/search.php?s=da2efccee14cf07f2b083c8988c57b1a&searchid=1419697
|
CC-MAIN-2015-11
|
refinedweb
| 456
| 68.54
|
In this video we will learn about creating components and Vue files. We will create a real example of the component that renders the list of users.
In previous video we talked about file structure in Vue project. In this video I want to talk about Vue components and how to render data inside them. So the first question is what is component as all? It's a entity inside Vue which have template, some javascript business logic and some css inside. The idea is that everything inside Vue is a component. Let's say you have an application with users list topbar, sidebar and pagination. We can for each feature create a component. One component for topbar, one for users list, one for pagination and so on. And then all our components are isolated, business logic and styles which are related to that specific feature is stored inside of that component. And actually all components are looking together as a tree. So the root component is App.vue then you render some components inside it and inside every next component we can render more and more components.
Now let's try to create a component and that we can check how it's all look like. Let's say that we need to create a users list page. As we already so in previous video we write all our route components inside views folder. So let's create there UsersList.vue. As you can see all filenames of components are written with capital letter.
The first thing that we want to do is write at least something in our template. Inside component we use template tag for this.
<template> <div>Users list</div> </template>
Now we need to define our component. We are doing it in script section.
<script> export default { name: "UsersList", }; </script>
So here we simply exporting an object with name property. And actually our new component is completely ready. But to see it in browser we need to bind a route with our component. For this let's jump in router/index.js
import UsersList from '../views/UsersList.vue' const routes = [ ..., { path: "/users", name: "users", component: UsersList, } ]
We need to add here new object with path, name and component. Path is our route, component is what we just created and name property we will discuss later when we will learn router deeper.
Now when we jump in /users we can see that our new component is rendered there. So it is a route component because we rendered it inside route.
So we successfully created our component and rendered there markup. But normally we want to write there some properties and business logic. As this is a users list we want to render a list of users inside our component.
The first question is how can we render some javascript inside our template. For this we can use double brackets and just write some javascript inside
<div>Users list {{ 1 + 1 }}</div>
so Vue will evaluate what is inside the brackets and render the result. It is called string interpolation. But it's a bad practice to write javascript code directly in template. Normally we just want to write there variables. So let's create a variable to render.
To define variables inside component we have specific property data.
data() { return { foo: "Foo", }; },
The most important point here is that data is not an object. It's a function where we are returning an object. So here we created a property foo and we can now use it inside our template.
Now we can render it in double brackets now. As you can see in browser our property is now rendered inside the template.
Now we can do the same with users. Let's create an array of users and render them inside the template.
data() { return { users: [ { id: "1", name: "User 1", age: 20, }, { id: "2", name: "User 2", age: 25, }, { id: "3", name: "User 3", age: 30, }, ], }; },
So this is just a javascript array of objects.
<div> <div v-{{ user.name }}</div> </div>
So here is a lot to cover. First of all we used special attribute inside div. This is how we render loops in Vue. as a value in v-for attribute we are giving user in users. Users here is our variable from data. And user is the local variable inside this div while we are going through the loop. This is why we can render name of the user inside.
Also the important thing is to add key property inside our div. We must do it every time when we are using v-for loop. Key property should be unique so Vue can render loops correctly for us. As you can see there is a special color symbol because key. We are using it there when we want to pass properties inside. As you can see user.id is a property so we need to put colon to this attribute in order to render it.
As you can see in browser, we successfully rendered the list of users inside our page.
In this video we created our new component and rendered the array of users inside it. And it's completely fine it you can't grasp all this syntax of Vue now because you will see it again and again in next videos.
If "Vue for beginners" is too easy for you go check my advanced course about Vue which is going 10 course and where we are creating together the application from empty folder to fully finished application.
|
https://monsterlessons-academy.com/posts/components-and-vue-files
|
CC-MAIN-2022-40
|
refinedweb
| 929
| 75.3
|
During my busy week, I occasionally come across some really useful or just plain interesting programming links. Instead of hoarding them all to my brain only, I aggregated the links into a post for your reading pleasure.
- Jason Diamond's Anthem.NET just went 1.0. This is an awesome AJAX library that is completely free. In my opinion, this is the best of its kind since it includes AJAX-ready server controls plus it is open source (C#). Try it and see for yourself.
- For developers who would like to play with add-ons in IE 7, Peter Bromberg discusses ways to work with the FeedManagerClass.
- MSDN TV is running an episode that covers ways to add blog capabilities to applications through the use of My.Blogs and VB 2005. My.Blogs is an extension of the My namespace, which Ars' own C.J. Anderson covered last week.
- The Daily Dose of Excel blog has an interesting post covering the deterioration of Microsoft's MVP program. The blog argues that newly admitted MVPs lack quality, experience, knowledge, and skillfulness.
- Many people have been wondering about IE 7 Beta 2 Preview's CSS features. On Thursday, the IEBlog covered Microsoft's objectives pertaining to CSS in IE 7. And yes, it does discuss the move toward CSS compliance.
- While this may be old news to some (because it is old news), I figured I'd throw it out anyway. Here is a registry modification that allows you to have guidelines in your Visual Studio IDE. Very cool indeed.
- The January Visual Basic 9.0 Language Integrated Query (LINQ) CTP is now available for download from Microsoft's Future Versions site. Hello Orcas!
- Lori Pearce answers the question of why the Windows SDK is so big. She says, "because old APIs never die, we just add new ones."
- Blogger James Van Dyne of Lomohut has an intriguing post about why the Microsoft platform is "dead" to him. While I don't know who he is, he does make some interesting points to talk about on Monday morning around the water cooler. You know, just in case the Super Bowl is called off.
You must login or create an account to comment.
|
https://arstechnica.com/information-technology/2006/02/2762/
|
CC-MAIN-2018-30
|
refinedweb
| 370
| 67.04
|
Board index » comp.lang.pop
All times are UTC
CONTENTS - (Use <ENTER> g to access required sections)
-- Question (A) - what is constrained to have a given type? -- Question(B) What grammar does a type-expression denote? -- (i) Do we separate type-names and variable-names? -- (ii) How do type-names relate to datakey, dataword and defstruct? -- (iii) Should type-name-space be flat? -- Should dynamic locals have a local type?
There are really two questions we have to address when we say
declare x:Type;
(A) what is the entity -x- which is constrained to have the given -Type-? (B) what is the grammar denoted by -Type-?
Question (A) - what is constrained to have a given type? -------------------------------------------------------- It is clear that the type should be attached to a -permanent identifier- rather than to the word. Currently this is not done. If it were done, I think that sections would be handled correctly. Relying on the standard section mechanism, this would work with declarations separated from section bodies if preferred (I think this is a good idea, as discussed later).
section mary; declare joe:Int->Int, annie:Word -> Number; endsection
section mary => joe annie;
define joe(x); lvars x; x+2 enddefine; .... endsection;
The current mechanism for lexicals, which maintains an association between word and type, mirrors the mechanism the VM is described as using, and would seem to be adequate. All that is needed is to extend the mechanism for file-local lexicals.
However, as the system stands, there is no direct way of constraining the types of lexicals. Experience with the system is indicating that, while much can be done by type-inference, especially with a functional style of writing POP-11, it is necessary to be able to put type-constraints on lexicals. Because I am not enthusiastic about mandating in-line type constraints of the style:
define fred(x); lvars is_ok:Boolean = false; enddefine
I would advocate some kind of way of referring to specific lexicals, e.g.
declare fred.is_ok:Boolean;
Question(B) What grammar does a type-expression denote? ------------------------------------------------------- Strategically the questions here are:
(i) Do we separate type-name-space from variable-name-space? (ii) How do type-names relate to the built-in dynamic type mechanisms of POP-11, i.e. key-cells and their associated datawords? (iii) Does type-name-space have structure related to variable-name-space, is it flat, or does it have some other structure?
The decisions taken for the current type-checker are (i) YES, we do have separated name-spaces and (ii) NO, type-name-space is flat.
(i) Do we separate type-names and variable-names? --------------------------------------------------- As far as (i) goes, let me say that I am in favour of keeping a separate name-space for mapping type-names to type-grammars. If we consider precedents, it is clear that mainstream LISP is -wrong- in having separate name-spaces for functions and other object. That is because it prevents LISP being a proper functional language. Taking the lambda-calculus as model it is quite clear that LISP has it wrong. And this makes writing higher order functions rather more difficult, since special operators have to be used to obtain function-objects from function-names.
But in the same lambda-calculus model, types are distinct from values. While I would aim to make type-grammars be user-manipulable objects of POP-11, I nevertheless believe that the advantages of a separate namespace outweigh the advantages of a uniform one, largely because, while users should be -encouraged- to write higher order functions frequently, the manipulation of type-grammars will be something of a specialist activity. Having separate name-spaces facilitates the use of accepted and/or convenient notation (at least in an ASCII world) of T1*T2, T1+T2 for product and union of types, whereas with a flat namespace T1*T2 would potentially mean ordinary multiplication.
(ii) How do type-names relate to datakey, dataword and defstruct? -------------------------------------------------------------------- To discuss (ii): first let us observe that the built-in dynamic type system based on key-cells has to be the foundation on which any type-checker is constructed. The -dataword- is convenient, but secondary, since it is not necessarily unique, and does not provide access to the attributes of the class. Secondly, let us observe that the primitive type of objects having a given key, is -inadequate- as a descriptive mechanism for many important POP operations. A number can have any one of a variety of keys, some procedures operate both on words and strings. Lists are best considered as an abstract data-type, built out of objects which are either pairs or nil, but with additional constraints.
Bearing this in mind, I have introduced capitalised type-names which are (mostly) bound to grammars specifying which primitive types are to be unioned to make up the capitalised type. Thus Integer denotes the type of all monologs of objects that have -integer_key- and -biginteger_key- as their datakey. This is a useful type because it is closed under +,- and *.
This does of course create problems in relating to defstruct, as well as to the datakey names. defstruct focusses on a much narrower set of types than the type-checker, since most of the types to which the latter refers are simply "full" to defstruct. Moreover, most of the types referred to in defstruct have very restricted closure properties, so that type-inference is of limited use.
Thus the clash between the conventions I have adopted and -defstruct- is minimal, since defstruct is talking about different things. The near-clashes are: PChar = integer or termin int = integer of natural wordsize Int = POP-11 integer (say 32 bits) (say 30 bits) pint = POP-11 integer full = Any POPLOG item. Top = any POPLOG item except a stack-mark
With the data-word/data-key naming conventions we have:
Clash? Existing POP-11 Current Type Checker
Y integer = POP-11 integer Int = POP-11 integer Y integer_key Y isinteger N biginteger = POP-11 long integer N isbiginteger N biginteger_key Y isintegral Integer = short and long integers
N isnumber Number = anything with a numeric dataword (integer,....complex)
N boolean_key Boolean = true or false N isboolean N false False
(iii) Should type-name-space be flat? --------------------------------------- The arguments for having a structured name space are much the same as those for having any name-space be structured, namely that stucture supports modularity.
There is an argument however that types should be uniform across a large program, in the same way, say, that uniform standards should apply across a large engineering project. E.g. in an electronic system, there will be many dispositions of individual integrated circuits, but only a limited number of -types- of circuit. If a new type of circuit is needed for the project, quite likely its designation will be standardised across the project.
For the moment, therefore, I propose to keep a flat name-space for types.
Should dynamic locals have a local type? ---------------------------------------- What should be done with dlocal variables is more problematic. I am inclined to say that:
define fred(x); x+1 enddefine
define joe(x); subscrs(1,x) enddefine
should -not- be type-correct, on the grounds that is -is- the same x in both cases.
---------------------------
(2) Conventions for type variables -----------------------------------
This is quite a complex issue, as I realise from talking to Haskellers. I would like to defer discussion until I have hoisted aboard all they have to say. Suffice it to say that it looks as though we should regard -List- as a function on grammars in the same way as Hd and Tl are, and say e.g. List(Int)
My "All" would seem to be related to capital Lambda in the second order lambda-calculus. There is scope for getting the type-system right and powerful, although one has to be careful not to require it to be too powerful and so impossible to make efficient.
As a result of these discussions, I incline towards regarding List as a function from types to types in the same way as Hd. With care one might arrive at a precise characterisation of dynamic lists as:
List = All a; Pair(Hd(a),Tl(a)) + Pair(^true, Unit->a) + Nil
Pair = All a,b; <pair_key>(a,b)
More Later. The a's and b's above would be monologs. One might have 3rd order types, m and p for monolog and polylog:
All a:m, b:p; ....
Robin.
1. Type Checking POP-11
2. forwarding message from Steve Leach re Running Pop-11
3. Pop-11 XML tools by Steve Leach
4. POP-11 types
5. Type Checking - Steve's comments
6. Type checking in POP (Oops)
7. A POP-11 Book Available via FTP
8. calling prolog from pop-11
9. Pop-11 Procedures for encoding and decoding BASE64 files (mimencode)
10. Development of Pop-11 for Windows
11. GSL interface: another Pop-11 development task?
12. vectors in pop-11
|
http://computer-programming-forum.com/35-comp.lang.pop/bd53a36a01089217.htm
|
CC-MAIN-2021-17
|
refinedweb
| 1,493
| 62.78
|
Getting started with h2o4gpu
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
(best viewed on original website)
Over the last year, my focus has been diverted from exploring analytics, new packages and blogging, to completing my dissertation. With the dissertation now complete and only final edits remaining, I had some spare time to spend on projects that I have been curating throughout the year. One such project that has been in the back of my mind for the last couple of months concern itself with with faster, scalable machine learning. This is where
h2o comes in. We have been using
h2o in production over the last year with great results. But as the data has grown, so has our need for faster turnaround in the estimation of the models. Currently, 96 core, 750GB RAM machines are not doing the job (Or perhaps I am just impatient). I have a limited amount of time and would like to spend it evaluating the model’s business value, not waiting 12 hours for it to train. This has lead me to two very promising and exciting alternatives:
- Multi Node h2o clusters
- h2o4gpu
Although the multi node h2o cluster approach is something to behold, I wanted to start working with GPUs1!
The rest of this post goes through the pain and suffering of getting to the point where you can train models using the
h2o4gpu package in
R. It hopefully serves as a resource for users (and future me) who just want to skip the fuss and run a
h2o model on a GPU. All of the following setup commands and tests are done on a
p2.xlarge machine from amazon. It goes for around $0.38 per hour if you go for a spot request and comes with 12GB of GPU memory, 4 cores and 61GB RAM. I also use Louis Aslett’s amazing AMI as a starting point – ami-09aea2adb48655672.
The steps for getting this to work is (tldr):
- Start
p2.xlargemachine with 100GB HDD
- Create virtual environment for python
- Install h2o4gpu into environment
- Install
Rpackage
- Do AI
Getting started with h2o4gpu
If you are not familiar with the
h2o open source machine learning toolkit, I highly recommend having a look at their website and some of the previous blogs I wrote on how amazing their machine learning suite is – Part I, Part II, Part III.
Apart from the usual
h2o api, the team has also been working on
h2o4gpu:
H.
Continuing with their vignette, further down it states:
The Python package is a prerequisite for the R package. So first, follow the instructions here to install the h2o4gpu Python package (either at the system level or in a Python virtual envivonment)
And this is where the wheels came off… I decided to install the packages at a system level, which according the the vignette:
… if you installed the h2o4gpu Python package into the main Python installation on your machine…
setting your virtual environment using
reticulate::use_virtualenv("/home/ledell/venv/h2o4gpu") is not necessary. Which for the life of me I could not get working due to a couple of frustrations:
- Python2.7 is still default python on ubuntu
- Installing reticulate will most likely install miniconda and keep looking there
This eventually led me to go the
venv route, which worked! If you are like me and didnt know how/why python prefers virtual environments, you can read up here. The first thing to do is install the necessary package:
sudo apt install python3-venv python3-pip sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2 sudo update-alternatives --config python
From here we follow the steps as per the
h2o4gpu vignette. First we must make some adjustments in our
.bashrc:
export CUDA_HOME=/usr/local/cuda export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CUDA_HOME/lib64/:$CUDA_HOME/lib/:$CUDA_HOME/extras/CUPTI/lib64
Install OpenBlas dev environment:
sudo apt-get install libopenblas-dev pbzip2
We are building the h2o4gpu R package, so it is necessary to install the following dependencies:
sudo apt-get -y install libcurl4-openssl-dev libssl-dev libxml2-dev
Once the installation is done, we need to create and activate the virtual environment:
python3 -m venv h2o4gpu source h2o4gpu/bin/activate
Next we can download and install the Python wheel file for CUDA:
python -m pip install h2o4gpu
My understanding of wheels are that they resemble the notion of the
tidyverse – a collection of packages and dependencies, working together to bring you a service – in my case h2o4gpu2.
Now we can test whether it works!
import h2o4gpu import numpy as np X = np.array([[1.,1.], [1.,4.], [1.,0.]]) model = h2o4gpu.KMeans(n_clusters=2,random_state=1234).fit(X) model.cluster_centers_ # >>> import h2o4gpu # >>> import numpy as np # >>> # >>> X = np.array([[1.,1.], [1.,4.], [1.,0.]]) # >>> model = h2o4gpu.KMeans(n_clusters=2,random_state=1234).fit(X) # >>> model.cluster_centers_ # array([[1. , 0.5], # [1. , 4. ]]) # >>>
Back to R
Hopefully all worked, which means you are now well on your way to running models in
R on the gpu. Using the AMI discussed above, you can log into the server with:
- username: rstudio
The instance id is available on your EC2 dashboard:
After changing to darkmode you should have the classic AMI screen (restart your session the first time you log in, otherwise packages struggle to install):
To install the development version of the h2o4gpu R package, you can install directly from GitHub as follows:
# install.packages("devtools", Ncpus = 4) # install.packages("Metrics", Ncpus = 4) library(devtools) devtools::install_github("h2oai/h2o4gpu", subdir = "src/interface_r")
Higgs example
To illustrate the package, I will now use the
h2o4gpu package to distinguish between signal “1” and background “0”, so this is a binary classification problem. Do note.
First, set up the libraries and the VERY important use of the virtual environment:
library(tidyverse) library(h2o4gpu) library(reticulate) use_virtualenv("/home/ubuntu/h2o4gpu/", required = T) py_config()
Next, lets load up the example data from Erin LeDell3:
# Setup dataset train <- read.csv("") test <- read.csv("")
If you feel like experimenting with the full dataset (11mil observations), you can download it using
data.table::fread. Just be aware that you will also need to install
R.utils as well:
# install.packages('data.table') # install.packages('R.utils') higgs <- data.table::fread("", verbose = TRUE, nThread = 4) test_index <- sample_frac(tibble(index = 1:nrow(higgs)), 0.7) train <- higgs[test_index$index,] test <- higgs[-test_index$index,]
Create train & test sets (column 1 is the response):
x_train <- train[, -1] y_train <- unlist(train[, 1]) x_test <- test[, -1] y_test <- unlist(test[, 1])
The final step is to estimate the models, predict on unseen test data and compare the different models. The models are estimated in a two-step fashion: initialize and then fit. This is more common in Python, and they borrow that paradigm in the package.
model_gbc <- h2o4gpu.gradient_boosting_classifier(n_estimators = 10) %>% fit(x_train, y_train) model_rfc <- h2o4gpu.random_forest_classifier(n_estimators = 10) %>% fit(x_train, y_train) pred_gbc <- model_gbc %>% predict(x_test, type = "prob") pred_rfc <- model_rfc %>% predict(x_test, type = "prob") Metrics::auc(actual = y_test, predicted = pred_gbc[, 2]) Metrics::auc(actual = y_test, predicted = pred_rfc[, 2])
If all went well, your model will be estimated with the GPU. It is quite difficult to tell if the process is working as should if you do not have some kind of monitoring tool. I always use
htop for process monitoring, so I found a tool called nvtop. I could only get the older build one as I am not using ubuntu 19.04, which in all honesty sucks. I loved how the picture look:
BUT, instead I got this:
Conclusion
In all honesty, I have been itching to play with GPUs to estimate my models, now I realise the itch was just poison ivy. The setup was frustrating and took me a day to figure out. The interface of the
h2o4gpu package is not the same as the CPU
h2o variant and I am sceptical about the API doing what it says it is doing – the AUC of the Random Forest and GBM was the same! Which is either a crazy concidence or something is wrong. The last thing that irritated me was the lack of documentation on how to go from training to production using the
h2o4gpu package – one of the advantages of using the
h2o package is its excellent documentation and its focus on being ‘production ready’.
Despite all of this, I can say, the idea is promising and I’ll be watching the package closely. It is still in its infancy, so one cannot be too judgemental4. Training on ~7.7 million observations with 28 variables only took around a minute which is astonishingly fast. The idea was that I would go on the benchmark the
h2o4gpu and
h2o package in terms of speed and accuracy, but given my scepticism around the output of the model, I might put that off for another day.
Also, seeing that Colin Fey is coming to SatRday 2020 Johannesburg, I think Ill be better off spending time learning
golem, than benchmarking tools likely to change in the future.
- Because if you not doing machine learning on GPUs these days, apparently you cannot claim to be a Data Scientist ^
- I might also be wrong, but the code worked and I trudged forward ^
- ^
- Plus, lets be honest, this stuff ain’t easy and I can certainly not.
|
https://www.r-bloggers.com/getting-started-with-h2o4gpu/
|
CC-MAIN-2020-40
|
refinedweb
| 1,560
| 57.61
|
I am having a problem with validating phone numbers. In our system we have two phone numbers which you can store. The problem I am having is that these are optional fields. So I want it to validate the phone number IF and only IF the user has tried to enter a phone number in there. If not it can be left as blank.
I am using the Phone attribute and have set a MaxLength. I have tried to set a MinLength to 0 but that doesn't work.
[Phone] [MaxLength(24)] [MinLength(0)] public string PhoneNum1 { get { return phoneNum1; } set { if (phoneNum1 != value) { phoneNum1 = value; RaisePropertyChanged("PhoneNum1"); } } }
Additionally, we have a checkbox which if ticked the user would have to add at least one of the phone numbers. I haven't attempted this yet so I am technically not asking for that solution but it would be great if any solutions would bare this in mind.
Here is the WPF which I am using. I am using ValidatesOnDataErrors and NotifyOnValidationError
<TextBox Margin="0,10,0,0" Grid.
You can implement your
OptionalPhoneAttribute based on the original
PhoneAttribute:
public sealed class OptionalPhoneAttribute : ValidationAttribute { public override bool IsValid(object value) { var phone = new PhoneAttribute(); //return true when the value is null or empty //return original IsValid value only when value is not null or empty return (value == null || string.IsNullOrEmpty(Convert.ToString(value)) || phone.IsValid(value)); } }
Then you can just use this new attribute instead:
[OptionalPhone] [MaxLength(24)] public string PhoneNum1 { get { return phoneNum1; } set { if (phoneNum1 != value) { phoneNum1 = value; RaisePropertyChanged("PhoneNum1"); } } }
|
http://databasefaq.com/index.php/answer/397/c-wpf-idataerrorinfo-validate-a-field-only-if-it-is-populated
|
CC-MAIN-2018-39
|
refinedweb
| 261
| 55.03
|
What is NumPy?
NumPy is a scientific library that provides multidimensional array object with fast routines on it. NumPy is short for Numerical Python.
When we talk about NumPy often we refer to the powerful ndarray, which is the multidimensional array (N-dimensional array).
A few comparisons between Python lists and ndarray.
Examples showing the difference: Fixed after creation
The Numpy is imported by default imported by import numpy as np. To create a ndarray, you can use the array call as defined below.
import numpy as np data = np.array([[1, 2, 3], [1, 2, 3]]) print(data)
Which will create an 2 dimensional array object with 2 times 3 elements.
[[1 2 3] [1 2 3]]
That will be a fixed sized ndarray. You cannot add new dimensions or elements to the the single arrays.
A Python list is a more flexible.
my_list = [] my_list.append(2) my_list.append(4) my_list.remove(2) print(my_list)
Which demonstrates the flexibility and power of Python lists. It is simple to add and remove elements. The above code will result in the following output.
[4]
Examples showing the difference: One type
The type of a ndarray is stored in dtype. Interesting thing is that each element must have the same type.
import numpy as np data = np.random.randn(2, 3) print(data) print(data.dtype)
It will result in a random ndarray of type float64.
[[-0.85925182 -0.89247774 -2.40920842] [ 0.84647869 0.27631307 -0.80772023]] float64
An interesting way to demonstrate that only one type can be present in an ndarray, is by trying to create it with a mixture of ints and floats.
import numpy as np data = np.array([[1.0, 2, 3], [1, 2, 3]]) print(data) print(data.dtype)
As the first element is of type float they are all cast to float64.
[[1. 2. 3.] [1. 2. 3.]] float64
While the following list is valid.
my_list = [1.0, 2, 3] print(my_list)
Where the first element will be float the second and third element are ints.
[1.0, 2, 3]
Examples showing the difference: No loops needed
Many operations can be made directly on the ndarray.
import numpy as np data = np.random.randn(2, 3) print(data) print(data*10) print(data + data)
Which will result in the following output.
[[ 1.18303358 -2.20017954 0.46294824] [-0.56508587 0.0990272 -1.8431866 ]] [[ 11.83033584 -22.00179538 4.62948243] [ -5.65085867 0.990272 -18.43186601]] [[ 2.36606717 -4.40035908 0.92589649] [-1.13017173 0.1980544 -3.6863732 ]]
Expected right? But easy to multiply and add out of the box.
Similar of the Python list would be.
my_list = [1, 2, 3] for i in range(len(my_list)): my_list[i] *= 10 for i in range(len(my_list)): my_list[i] += my_list[i]
And it is not even the same, as you write it directly to the old elements.
Another way to compare differences
It might at first glance seem like ndarrays are inflexible with all the restrictions comparing the Python lists. Yes, that is true, but the benefit is the speed.
import time import numpy as np my_arr = np.arange(1000000) my_list = list(range(1000000)) start = time.time() for _ in range(10): my_arr2 = my_arr * 2 end = time.time() print(end - start) start = time.time() for _ in range(10): my_list2 = [x * 2 for x in my_list] end = time.time() print(end - start)
Which resulted in.
0.03456306457519531 0.9373760223388672
The advantage is that ndarrays are 10-100 times faster than Python lists, which makes a considerable impact on scientific calculations.
|
https://www.learnpythonwithrune.org/quick-numpy-tutorial/
|
CC-MAIN-2021-25
|
refinedweb
| 594
| 75.91
|
SYNOPSIS
#include <ixp_srvutil.h>
void ixp_srv_readbuf(Ixp9Req *req, char *buf, uint len);
void ixp_srv_writebuf(Ixp9Req *req, char **buf, uint *len, uint max);
DESCRIPTION
Utility functions for handling TRead and TWrite requests for files backed by in-memory buffers. For both functions, buf points to a buffer and len specifies the length of the buffer. In the case of ixp_srv_writebuf, these values add a level of pointer indirection, and updates the values if they change.
If max has a value other than 0, ixp_srv_writebuf will truncate any writes to that point in the buffer. Otherwise, *buf is assumed to be malloc(3) allocated, and is reallocated to fit the new data as necessary. The buffer is is always left nul-terminated.
BUGS
ixp_srv_writebuf always truncates its buffer to the end of the most recent write.
|
https://manpages.org/ixp_srv_readbuf/3
|
CC-MAIN-2022-21
|
refinedweb
| 134
| 55.24
|
Hey Guys really need to learn - Java Beginners
Hey Guys really need to learn Im a java beginner and i want to know...? Someone can help me.. Thank you so much. Hi Friend,
There are lot... the following code to input three integers from the command prompt.
import
should be stored vend_id in the place of vend_name...so please write the code and send me...
Thanks once again...for sending scjp link...Thanks Hi,
Thanks ur sending url is correct..And fullfill
Thanks - Java Beginners
should be stored vend_id in the place of vend_name...so please write the code and send me...
Thanks once again...for sending scjp link Hi friend...Thanks Hi,
Thanks ur sending url is correct..And fullfill
Reply Me - Struts
Reply Me Hi Friends,
Please write the code using form element...because i got error in textbox null value Hi Soniya
Would you... to provide a better solution for you..
Thanks
Struts Code - Struts
But it is not appending..
Can any one help me.
Thanks in Advance...Struts Code Hi
I executed "select * from example" query... using struts . I am placing two links Update and Delete beside each record .
Now I
Please help need quick!!! Thanks
Please help need quick!!! Thanks hey i keep getting stupid compile... simulation program of sorts here is my code:
RentforthBoatRace.java
public...();
^
6 errors
any help would be appreciated guys. Thanks so
Struts - Struts
Struts hi,
I am new in struts concept.so, please explain example login application in struts web based application with source code .
what are needed the jar file and to run in struts application ?
please kindly
Reply Me - Struts
Reply Me Hi Friends,
I am new in struts please help me... visit for more information.
Thanks... file,connection file....etc please let me know its very urgent
Hi Friend,
Is backward redirection possible in struts.If so plz explain me
Answer me ASAP, Thanks, very important
Answer me ASAP, Thanks, very important Sir, how to fix this problem in mysql
i have an error of "Too many connections" message from Mysql server,, ASAP please...Thanks in Advance
struts code - Struts
://
Thanks...struts code In STRUTS FRAMEWORK
we have a login form with fields
USERNAME:
In this admin
can login and also narmal uses can log
Struts Code - Struts
://
Thanks...Struts Code How to add token , and encript token and how decript token in struts. Hi friend,
Using the Token methods
The methods we
struts code - Struts
struts code Hi all,
i am writing one simple application using struts framework. In this application i thought to bring the different menus of my... help me
Achor tag. Struts2 code - Struts
) in Struts? Please help me. I am waiting for the answer.
Regards,
Sandeep .../struts/struts2/struts-2-tags.shtml
Thanks
use this i don't know...
please tell me what is the use of this ....and also solve my previous problem....
Thanks
Hello Ragini
MVC... jsp file and one java file
Thanks
Rajanikant Hi friend,
MVC : M
Thanks - Java Beginners
Thanks Hi,
thanks
This is good ok this is write code but i... either same page or other page.
once again thanks
hai frnd..
all data means...?wat do u mean by that?
that code will display all
thanks - Java Beginners
thanks Sir , i am very glad that u r helping me a lot in all... to understood...can u please check it and tell me..becoz
it says that any two... it to me .....thank you vary much
Pls review my code - Struts
Pls review my code Hello friends,
this is my code in struts action... the submit it shows me blank page.
can anybody solve my problem its urgent.
help me.
thanks in advance
public class AleAction extends Action {
public
Thanks - Java Beginners
Thanks Hi Rajnikant,
Thanks for reply.....
I am not try for previous problem becoz i m busy other work...
please tell me what is the advantage of interface and what is the use of interface...
Thanks
How to code in struts for 3 Failed Login attempts - Struts
How to code in struts for 3 Failed Login attempts Hi,
I require help.
I am doing one application in struts where i have to incorporate.../struts-login-form.shtml
Thanks.3) action code for file upload
action or let me how the upload request is post to struts action.
Thanks
... in struts action or let me how the upload request is post to struts action.
Thanks...Struts(1.3) action code for file upload Hi All,
I want to upload
struts
struts i have one textbox for date field.when i selected date from datecalendar then the corresponding date will appear in textbox.i want code for this in struts.plz help
Need help in completing a complex program; Thanks a lot for your help
Need help in completing a complex program; Thanks a lot for your help ... no output. So please help me with this too.
And also, I am using Runtime function to call the batch file into the Java code. Is there any other way to call first example - Struts
require and input data type is int.
can you give me an example code... the version of struts is used struts1/struts 2.
Thanks
Hi!
I am using struts 2 for work.
Thanks. Hi friend,
Please visit file uploading - Struts
Struts file uploading Hi all,
My application I am uploading files using Struts FormFile.
Below is the code.
NewDocumentForm... when required.
I could not use the Struts API FormFile since
Code in IDE - Struts
Code in IDE In a project using struts how to get the contact no from user which should accept only '-' or '+' in IDE environment using struts... enters like for example(s.divya.kumar)It should show an error..pl do help
java - Struts
java i want to display a list through struts what code i writen in action, class , struts config.xml and jsp please tell me
thnks for solving my...-tag.shtml
Thanks
Thanks for fast reply - Java Beginners
Thanks for fast reply Thanks for response
I am already use html for data grid but i m noot understood how to connect to the data base, and how...://
and this is the database connectivity code Hi,
I am new to struts.Please send the sample code for login and registration sample code with backend as mysql database.Please send the code immediately.
Please its urgent.
Regards,
Valarmathi Hi Friend
Hello - Struts
to going with connect database using oracle10g in struts please write the code and send me its very urgent
only connect to the database code
Hi...://
Thanks
Amardeep
Struts - Struts
://
Thanks...Struts Is Action class is thread safe in struts? if yes, how it is thread safe? if no, how to make it thread safe? Please give me with good
struts - Struts
/struts/
Thanks...struts hi,
what is meant by struts-config.xml and wht are the tags...
2. wht is the difference b/w the web.xml and struts-config.xml
3.
Help me
the code
java.lang.NullPointerException...)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
here is code
login.jsp
<html>
<body... a clear resolution to this vexing issue? Thanks in advance. Hi Friend source code to solve the problem.
Mention the technology you have used
Help me
the code , i am
using login.html ,login .jsp,login.java and web.xml code...)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
// here is code login.jsp
<...;/html>
and web.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<
code for login fom - Struts
code for login fom we have a login form with fields
USERNAME:
PASSWORD...? Hi Friend,
Specify the technology.
Thanks
struts - Struts
struts Hi,
I need the example programs for shopping cart using struts with my sql.
Please send the examples code as soon as possible.
please...
Hope that it will be helpful for you.
Thanks
Tell me - Struts
Struts tutorial to learn from beginning Tell me, how can i learn the struts from beginning
Struts - Struts
.
Thanks in advance Hi friend,
Please give full details with source code to solve the problem.
For read more information on Struts visit...Struts Hello
I have 2 java pages and 2 jsp pages in struts
Struts + HTML:Button not workin - Struts
Struts + HTML:Button not workin Hi,
I am new to struts. So pls bare with me if my question is fundamental.
I am trying to add 2 Submit buttons... is called.
JSP code
--------
Actionclass
java - Struts
java Hi,
I want full code for login & new registration page in struts 2
please let me know as soon as possible.
thanks,. Hi...
Thanks
Tell me - Struts
Directory Structure for Struts Tell me the Directory Structure for Struts
Error - Struts
. If you can please send me a small Struts application developed using eclips.
My... the line of code :
Thanks...Error Hi,
I downloaded the roseindia first struts example
code problem - Struts
code problem hi friends i have 1 doubt regarding how to write the code of opensheet in action class i have done it as
the action class code...();
System.out.println(conn);
//Code to generate new sheet i.e login time IS NULL
exception - Struts
in struts I am getting the exception
javax.servlet.jsp.JspException: Cannot...:
can anybody help me
regards,
Sorna
Hi friend,
Here is running code, read for more information.
Struts - Struts
Struts Dear Sir ,
I am very new in Struts and want... provide the that examples zip.
Thanks and regards
Sanjeev. Hi friend... and specify the type.
5
6
Zip Code needs to between
struts - Struts
of a struts application Hi friend,
Code to help in solving the problem :
In the below code having two submit button's its values...://
Thanks
Struts - Struts
://
Thanks... in struts 1.1
What changes should I make for this?also write struts-config.xml and jsp code.
Code is shown below
Struts - Struts
Struts hi
can anyone tell me how can i implement session tracking in struts?
please it,s urgent........... session tracking? you mean session management?
we can maintain using class HttpSession.
the code follows
/Password is incurrect
Retry click here!
please revert me. Hi friend,
Check your code having error :
struts-config.xml
In Action...:
Submit
struts
Struts Validation - Struts
Struts Validation Hi friends.....will any one guide me to use the struts validator...
Hi Friend,
Please visit the following links:
http
Java - Struts
Java Hi,
Can any send the code for insert,select,update in database using Frontcontroller in Struts.Plse help me.
Many Thanks
Raghavendra....
Thanks
Reply - Struts
Reply
Thanks For Nice responce Technologies::--JSP
please write the code and send me....when click "add new button" then get the null value...?
thanks.
java - Struts
config
/WEB-INF/struts-config.xml
1
action
*.do
Thanks...!
struts-config.xml...="add";
}
}
please give me correct answer .
Hi friend
j2ee - Struts
in to form2 with in a listbox. pls help me. Hi bhaskar,
You have to write database related code in the form itself in which the list box is present.
Thanks
Sreenivas...;
// End of variables declaration
}
Thanks
java - Struts
to mark selected one of the option of object. So can u plz send me any code... code to solve the problem.
Thanks
multiboxes - Struts
onclick event is coded in javascript)...
Can u please give me a solution either in javascript code or in struts bean. Hi friend,
Code to solve
example on struts - Struts
example on struts i need an example on Struts, any example.
Please help me out. Hi friend,
For more information,Tutorials and Examples on Struts visit to :
Thanks
For Loop - Struts
Java code in the JSP.
In my application I am using List is sending to jsp... Containing 2 records.
In jsp need to dsiplay as two columns.
Pls help me.
How to use the For loop in JSP.
Thanks,
Rajesh. Hi Rajesh,
i
Struts2 - Struts
me code and explain in detail.
I am sending you a link. This link will help.../struts/struts2/struts2uitags/autocompleter-example.shtml
Thanks. hi i checked the link that you sent, and tried the same code, but looks like it dint
please help me.
please help me. Please send me a code of template in opencms and its procedure.so i can implement the code.
Thanks
trinath
pls review my code - Struts
pls review my code Hello friends,
This is the code in struts. when i click on the submit button.
It is showing the blank page. Pls respond soon its urgent.
Thanks in advance.
public class LOGINAction extends Action
login application - Struts
login application Can anyone give me complete code of user login application using struts and database? Hello,
Here is good example... it at
Thanks
Tapestry - Struts
respond me fast
thanks Hi friend,
Code to help in solving... Tapestry4.1 as frontend, could anyone guide me, is der any inbuild tapestry...;
}
//end of copied code
do this for me plzz - Java Interview Questions
do this for me plzz Given the no of days and start day of a month... not have to write code to take input from the console Hi friend... GregorianCalendar(yy, mm, 1);
System.out.println("Su Mo Tu We Th Fr Sa"); //can change
Tell me - Struts
Directory Structure with example program Execution Tell me the Directory Structure with example program Execution
|
http://www.roseindia.net/tutorialhelp/comment/11805
|
CC-MAIN-2015-06
|
refinedweb
| 2,216
| 77.33
|
This article was written by Harshit Sharma.
Successful detection and classification of traffic signs is one of the important problem to be solved if we want self driving cars. Idea is to make automobiles smart enough so as to achieve least human interaction for successful automation. Swift rise in dominance of deep learning over classical machine learning methods which is complemented by advancement in GPU (Graphics Processing Unit) has been astonishing in fields related to image recognition, NLP, self-driving cars etc.
The chart only goes to 2015 and 2016 NIPS had over 6,000 attendees. Chart displays surge in interest in deep learning and related techniques.
Deep learning is a class of machine learning technique where artificial neural network uses multiple hidden layers. Lot of credit goes to David Hubel and Torsten Wiesel, two famous neurophysiologists, who showed how neurons in the visual cortex work. Their work determined how neurons with similar functions are organized into columns, tiny computational machines that relay information to a higher region of the brain, where visual image is progressively formed.
In layman’s term brain combines low level features such as basic shapes, curves and builds more complex shapes out of it. A deep convolutional neural network is similar. It first identifies low level features and then learns to recognize and combines these features to learn more complicated patterns. These different levels of features come from different layers of the network.
Tensorflowis used to implement deep conv net for traffic sign classification. RELU was used for activation to introduce non linearity and drop out of varying percentages was used to avoid overfitting at different stages. It was hard to believe that simple deep net was able to achieve high accuracy on the training data. Following is the architecture used for traffic sign classification.
def deepnn_model(x,train=True):
# Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
x = tf.nn.conv2d(x, layer1_weight, strides=[1, 1, 1, 1], padding='VALID')
x = tf.nn.bias_add(x, layer1_bias)
x = tf.nn.relu(x)
x = tf.nn.max_pool(x,ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1],padding='SAME')
if(train):
x = tf.nn.dropout(x, dropout1)
x = tf.nn.conv2d(x, layer2_weight, strides=[1, 1, 1, 1], padding='VALID')
x = tf.nn.bias_add(x, layer2_bias)
x = tf.nn.relu(x)
conv2 = tf.nn.max_pool(x,ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1],padding='SAME')
if(train):
conv2 = tf.nn.dropout(conv2, dropout2)
fc0 = flatten(conv2)
fc1 = tf.add(tf.matmul(fc0, flat_weight),bias_flat)
fc1 = tf.nn.relu(fc1)
if(train):
fc1 = tf.nn.dropout(fc1, dropout3)
fc1 = tf.add(tf.matmul(fc1, flat_weight2),bias_flat2)
fc1 = tf.nn.relu(fc1)
if(train):
fc1 = tf.nn.dropout(fc1, dropout4)
fc1 = tf.add(tf.matmul(fc1, flat_weight3),bias_flat3)
logits = tf.nn.relu(fc1)
return logits
My aim was to achieve 90 percent accuracy to start with simple architecture and I was surprised to see it close to 94 percent in the first run. Further adding more layers and complexity into the model complemented by data augmentation can achieve accuracy as high as 98 percent.
To read the full original article click here. For more deep learning related articles on DSC click here.
DSC Resources
Popular Articles
Views: 2380
Comment
© 2020 Data Science Central ®
Badges | Report an Issue | Privacy Policy | Terms of Service
You need to be a member of Data Science Central to add comments!
Join Data Science Central
|
https://www.datasciencecentral.com/profiles/blogs/identifying-traffic-signs-with-deep-learning
|
CC-MAIN-2020-34
|
refinedweb
| 583
| 51.04
|
12 September 2012 11:30 [Source: ICIS news]
LONDON (ICIS)--European chemical stocks rose on Wednesday, in line with financial markets, after ?xml:namespace>
German citizens and lawmakers had brought forward a case calling for the court to block the ESM, stating the mechanism would commit the country to potentially unlimited funding of the weakest eurozone economies.
The maximum lending capacity of the ESM, which is expected to go into effect in October, is €500bn ($641m) and
At 10:12 GMT, the
At the same time, the Dow Jones Euro Stoxx Chemicals index was up by 0.98%, as shares in many of
Chemical producer BASF’s shares had risen by 1.10%, while fellow Germany-based chemical company Bayer’s shares were trading up by 1.34%.
Switzerland-based company Clariant’s shares were trading up by 1.97% from the previous close, French specialty chemical group Arkema’s shares were trading 2.70% higher from the previous close, while Norway-based fertilizer producer Yara International’s shares were trading up by 0.81% on the previous
|
http://www.icis.com/Articles/2012/09/12/9594709/europe-chemical-stocks-show-gains-on-germany-court-bailout.html
|
CC-MAIN-2014-52
|
refinedweb
| 178
| 53.41
|
Ticket #5764 (reopened defect)
Arrow and other keys not working when starting with VBoxSDL => Fixed in SVN
Description (last modified by frank) (diff)
Host: Ubuntu 9.10 32bit i386
Guest: Windows XP SP3 32bit i386
VirtualBox: 3.1
After upgrading the Host OS (from Ubuntu 8.04) the arrow keys, Home, End, Insert, PgUp, PgDwn, and / on the numeric keypad no longer work when starting the virtual machine with VBoxSDL.
The upgrade was an export VBox virtual machine, format hard drive, clean install new OS and then import the vbox Virtual machine.
I use the following command to start VirtualBox:
/usr/bin/gksudo -u fred 'VBoxSDL --startvm freds_VM --nofstoggle --termacpi'
After the upgrade mentioned above, the keyboard keys stopped working (sometimes the Start menu will open, other times it's like a right mouse click is pressed.)
If I start Virtual box like this:
/usr/bin/gksudo -u fred VBoxManage startvm freds_VM
all keys work as expected and as they always have, no matter which of these two methods I use to start the VM.
So this appears to be specific to VBoxSDL.
Attachments
Change History
comment:1 Changed 5 years ago by frank
I'm quite sure your problems are gone when you append the --evdevkeymap switch to your VBoxSDL parameters.
comment:2 Changed 5 years ago by mpefra
- Status changed from closed to reopened
- Resolution worksforme deleted
comment:3 Changed 5 years ago by frank
That option does exist in VBox 3.1.6. What happens if you start your VM with
VBoxSDL --evdevkeymap --startvm VM_NAME
(replace VM_NAME with the name of a VM)?
comment:4 Changed 5 years ago by mpefra
It displays the usage message :
PS C:\Program Files\Sun\VirtualBox> & 'C:\Program Files\Sun\VirtualBox\VBoxSDL.exe' --evdevkeymap --startvm Debian Sun VirtualBox SDL GUI version 3.1.6 (C) 2005-2010 Sun Microsystems, Inc. All rights reserved. Error: unrecognized switch '--evdevkeymap' Usage: --startvm <uuid|name> Virtual machine to start, either UUID or name --hda <file> Set temporary first hard disk to file --fda <file> Set temporary first floppy disk to file .....
comment:6 Changed 5 years ago by frank
Hmm, looks like this is a Windows host. The --evdevkeymap switch is only available for Linux hosts. Yours must be another issue then.
comment:7 Changed 5 years ago by mpefra
Yes it is a windows host (as mentionned in my first message). Do I have to create to create a new ticket?
comment:8 Changed 5 years ago by dreif
Hi,
I have a the same problem with VirtualBox 3.2.0 (ubuntu 10.4 host + ubuntu 9.10 guest). '--evdevkeymap' helps but the new command "VBoxManage --startvm uuid --type sdl" does not allows to pass this option.
I would use the VBoxSDL command, but since this release, VBoxSDL does not set the title attribute of the X windows anymore (tested with xlsclients command line util), which is a MUST in my integration setup. Actually I am stuck.
Regards, Frederic
comment:9 Changed 5 years ago by frank
- Summary changed from Arrow and other keys not working when starting with VBoxSDL to Arrow and other keys not working when starting with VBoxSDL => Fixed in SVN
This will be fixed in the next maintenance release. VBoxSDL will inherit the keyboard handling from the Qt GUI.
comment:10 Changed 5 years ago by frank
- Status changed from reopened to closed
- Resolution set to fixed
comment:11 Changed 5 years ago by rbhkamal
- Status changed from closed to reopened
- Resolution fixed deleted
Did the fix go into the OSE? I'm still having the same exact problem with VirtualBox 3.2.12 OSE and 3.2.8 OSE (both self compiled)
Windows 7 32bit Guest: All operating systems have the problem
There are other strange issues with keyboard mapping, one user complained about the "\" key mapping to the "]" key... still investigating.
I tried to launch the same VM using VirtualBox.exe and the problem was NOT there, so there must be something wrong with vboxsdl.exe.
I also noticed that the first "UP Arrow" key works and prints "[[A" but the second and on print "8"
comment:12 Changed 5 years ago by rbhkamal
Sorry, the first up arrow key press prints the following:
^[[A
Then it starts printing the following:
8
VirtualBox is running on Windows 7 32bit
Guest machine is a debian linux 2.6 with Xorg 7.4
comment:13 Changed 5 years ago by lsbz
Below patch against 3.2.12 seems to work for Windows hosts.
--- VBoxSDL-org.cpp 2010-12-01 18:09:24 +0100 +++ VBoxSDL.cpp 2010-12-29 23:50:35 +0100 @@ -2919,7 +2919,7 @@
return (gfAbsoluteMouseHost && gfAbsoluteMouseGuest);
}
/
- Fallback keycode conversion using SDL symbols. *
@@ -3392,7 +3392,7 @@
RTPrintf("scancode=%#x -> %#x\n", ev->keysym.scancode, keycode);
#endif
-#elif RT_OS_OS2
keycode = Keyevent2KeycodeFallback(ev);
#endif /* RT_OS_DARWIN */
return keycode;
Changed 5 years ago by lsbz
- attachment VBoxSDL.cpp.cursorkeys.diff
added
Vbox SDL frontend cursor keys patch
comment:14 Changed 5 years ago by rbhkamal
Verified that the fix works for the arrow keys. I tested on Windows 7 64bit with Linux 2.4 guest.
I know this is not the place to ask questions, but do you think this would fix the cases were the "\" key maps to the "]" key?
Thanks, RK
comment:15 Changed 5 years ago by lsbz
@rbhkamal:
Backslash '\' works OK on my keyboard in Win7 host and Fedora 14 guest. Maybe this is caused by a keyboard mapping in the guest?!
About the patch: it converts the SDL internal key codes back to "raw" key input for the guest. The source file has it prepared, but did not have it connected for Windows hosts.
|
https://www.virtualbox.org/ticket/5764
|
CC-MAIN-2015-35
|
refinedweb
| 948
| 70.73
|
Implementation Of DFS Using Adjacency Matrix
Introduction
This blog will discuss the implementation of DFS using an adjacency matrix. Before jumping on the approach, let’s first understand the Adjacency matrix,
The Adjacency matrix is a simple integral matrix of size ‘V * V’, where ‘V’ represents the number of vertices in the graph. Basically, it is the representation of the graph in matrix form where the index of row and column represents the vertex, and the value at index [row][column] in adjacency matrix states whether there exists an edge between the two vertices same as the value of row and column.
In this problem, we need to print all the vertices while traversing the whole graph using the DFS algorithm.
For Example:
Graph as Matrix: 0 1 1 0 1 0 0 1 0 1 1 0 0 0 1 1 0 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 0
Output:
Explanation:
In this above-given graph, we can see that there are no disconnected components in the graph, and while starting from 0, we shift to 1, then after checking the adjacency matrix each time, we shift to 2, then we shift to 3. Now while checking for 3, we got to know that all the vertices that are directly connected to 3 are already visited, so we backtracked to vertex 2, now we’ll check for other connected edges with 2. In this, we shift to 5 and check for the vertices connected with 5, and we, therefore, shift to 4. Now at 4, we again found the same that no vertex is left not visited that are directly connected to 4. So we again backtracked to 5, now we again found the same and backtracked to 2, and got to know that 6 is still left, so we visit 6. In this way, we traversed the whole graph using DFS.
Approach
This approach considers traversing the complete graph using the Depth First Search algorithm, in which we use recursive calls to complete the task. In this implementation, we need to create an array of integers globally that will keep track of all the visited vertices, and we need to implement an adjacency matrix that will represent the edge between two vertices. In this implementation, we need to make an iteration using the ‘for’ loop, which will call the ‘get_Result’ function for all the components of the graph, whether it’s a disconnected or connected graph. If in the iteration, if the value at index ‘i’ in the ‘visited’ vector, then it means that it is the disconnected component and needs to be traversed.
Steps of algorithm
Step 1. In the ‘main()’ function, initialize an adjacency matrix ‘adj’ with zero of size ‘V * V’, where this ‘V’ is the number of vertices in the graph.
Step 2. Store all the edges data in two arrays, ‘a’ and ‘b’, where vertices on ‘ith’ index of both ‘a’ and ‘b’ represent an edge between both the vertices, and mark the element at index same as the pair of vertices as 1, representing that an edge exists between these two vertices.
Step 3. Print the adjacency matrix.
Step 4. Initialize a global array of integers ‘visited’ to keep track of already visited vertex with zero, representing that the vertex is not visited.
Step 5. Make an iteration using the ‘for’ loop to cover the disconnected component of the graph. If the value at ‘ith’ index of ‘visited’ vector is 0, representing that the vertex is not visited, then make a call to ‘get_result()’ function, passing 4 parameters:- first one is the number of vertices ‘V’, the second one is the adjacency matrix ‘adj’, and third is the vertex ‘i’ from which we need to traverse.
Step 6. In the ‘get_result()’ function, print the vertex ‘x’ received along with marking it as visited in the ‘visited’ array, and then make an iteration using ‘for’ loop using a variable ‘i’ to check all the edges, in this, if the value of ‘i’ is equal to ‘x’ then we need to continue, and if the edge exists between the ‘x’ vertex and ‘ith’ vertex and the ‘ith’ vertex is still not visited, then make a recursive call to ‘get_result()’ function, passing ‘i’ as the vertex to be traversed.
Note:- Initialize the size of the global ‘visited’ array according to the number of vertices in the graph.
Implementation in C
#include <stdio.h> // Array to keep the track of all the visited vertices int visited[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; void get_result(int v, int adj[][v], int x) { // print the current vertex printf("%d, ", x); // Mark the current vertex as visited visited[x] = 1; for(int i = 0; i < v; i++) { if(i == x) { continue; } // If there exists an edge between both the vertices and the other vertex is still not visited if(adj[x][i] && !visited[i]) { get_result(v, adj, i); } } return; } int main() { // V represents the number of vertices in the graph and e represents the number of edges in the graph int v = 10 , e = 11; // Adjacency matrix int adj[v][v]; for(int i = 0 ; i < v ; i++) { for(int j = 0 ; j < v; j++) { adj[i][j] = 0; } } // Describes edge between both the vertices of a and b array int a[] = {0, 0, 0, 1, 1, 2, 2, 2, 4, 7, 9}; int b[] = {1, 2, 4, 2, 3, 3, 5, 6, 5, 9, 8}; // Mark the edge in the adjacency matrix for(int i = 0 ; i < e ; i++) { adj[a[i]][b[i]] = 1; adj[b[i]][a[i]] = 1; } printf("Adjacency matrix of the above mentioned graph is as follows:- \n"); for(int i = 0; i < v ; i++) { for(int j = 0 ; j < v; j++) { printf("%d ", adj[i][j]); } printf("\n"); } printf("\n"); printf("DFS using an adjacency matrix of the above graph gives following order:- "); printf("\n"); // Check for all the disconnected components for(int i = 0 ; i < v ; i++) { if(!visited[i]) { get_result(v, adj, i); } } }
Input:
Output:
Adjacency matrix of the above mentioned graph is as follows:- 0 1 1 0 1 0 0 0 0 0 1 0 1 1 0 0 0 0 0 0 1 1 0 1 0 1 1 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 DFS using an adjacency matrix of the above graph gives following order:- 0, 1, 2, 3, 5, 4, 6, 7, 9, 8,
Complexity Analysis
Time Complexity for DFS using an adjacency matrix: O(V ^ 2)
Incall to ‘getResult()’, we are checking the whole adjacency matrix in the iterations, and the size of the adjacency matrix is ‘V ^ 2’, therefore, the overall time complexity is O(V * 2), where ‘V’ is the number of the vertices.
Space Complexity for DFS using an adjacency matrix: O(V ^ 2)
As we are implementing DFS using adjacency matrix of size ‘V ^ 2’, where ‘V’ is the number of vertices, therefore, the overall space complexity will be O(V ^ 2).
Frequently Asked Questions
- What is the DFS traversal?
The DFS refers to Depth First Search. In this type of traversal, we use recursion to traverse the graph. We start from a node in this traversal and go as far as possible before backtracking.
- Why are the alternates of the adjacency matrix?
We can use Adjacency List to store the edges. In the adjacency list, we store the vertices directly connected to the ‘ith’ vertex in the ‘ith’ vertex list.
- What is the computational time of the implementation of DFS using the adjacency list?
The computational time of the implementation of DFS using the adjacency list is ‘V + E’, where this ‘V’ is the number of vertices and ‘E’ is the number of edges.
Conclusion
In this article, we discussed the implementation of DFS using an adjacency matrix and the approach to solve this problem programmatically.
If you think that this blog helped you share it with your friends!. Refer to the DSA C++ course for more information.
Until then, all the best for your future endeavors, and Keep Coding.
|
https://www.codingninjas.com/codestudio/library/implementation-of-dfs-using-adjacency-matrix
|
CC-MAIN-2022-27
|
refinedweb
| 1,438
| 53.99
|
Opened 9 years ago
Closed 9 years ago
#706 closed enhancement (wontfix)
rename of django-admin.py?
Description
I would like to step thru django-admin.py in an IDE debugger. (Eclipse and Pydev).
To do so I have attempted to run django-admin.py as follows:
from django.bin import django-admin
django-admin.main()
# (pydev allows me to supply the parms)
but the - in django-admin.py gives me a syntax error on both statements. If i rename django-admin.py to django_admin.py (- to _), all is well.
Perhaps you would consider making this change.
(I am a python newbie...so please cut me some slack if I am missing something simple.)
thx,
gerry rodman
htp://
Attachments (0)
Change History (1)
comment:1 Changed 9 years ago by adrian
- Resolution set to wontfix
- Status changed from new to closed
If you want to access django-admin.py's functionality programatically, use the functions in django.core.management.
|
https://code.djangoproject.com/ticket/706
|
CC-MAIN-2014-23
|
refinedweb
| 160
| 63.25
|
Related
How To Build a Blog with Nest.js, MongoDB, and Vue.js
The author selected Software in the Public Interest Inc to receive a donation as part of the Write for DOnations program.
Introduction
Nest.js is a scalable, server-side JavaScript framework built with TypeScript that still preserves compatibility with JavaScript, which makes it an effective tool for building efficient and reliable back-end applications. It has a modular architecture that provides a mature, structural design pattern to the Node.js development world.
Vue.js is a front-end JavaScript framework for building user interfaces. It has a simple, yet very powerful API along with great performance. Vue.js is capable of powering the front-end layer and logic of any web application irrespective of the size. The ease of integrating it with other libraries or existing projects makes it a perfect choice for most modern web applications.
In this tutorial, you'll build a Nest.js application to get yourself familiar with its building blocks as well as the fundamental principles of building modern web applications. You'll approach this project by separating the application into two different sections: the frontend and the backend. Firstly, you'll concentrate on the RESTful back-end API built with Nest.js. You'll then focus on the frontend, which you will build with Vue.js. Both applications will run on different ports and will function as separate domains.
You'll build a blog application with which users can create and save a new post, view the saved posts on the homepage, and carry out other processes such as editing and deleting posts. Furthermore, you'll connect your application and persist its data with MongoDB, which is a schema-less NoSQL database that can receive and store JSON documents. This tutorial focuses on building your application in a development environment. For a production environment, you should also consider user authentication for your application.
Prerequisites
To complete this tutorial, you will need:
-.
- MongoDB installed on your machine. Follow the instructions here to download and install it for your choice of operating system. To successfully install MongoDB, you can either install it by using Homebrew on Mac or by downloading it from the MongoDB website.
- A basic understanding of TypeScript and JavaScript.
- A text editor installed, such as Visual Studio Code, Atom, or Sublime Text.
Note: This tutorial uses a macOS machine for development. If you're using another operating system, you may need to use
sudo for
npm commands throughout the tutorial.
Step 1 — Installing Nest.js and Other Dependencies
In this section, you will get started with Nest.js by installing the application and its required dependencies on your local machine. You can easily install Nest.js by either using the CLI that Nest.js provides, or, by installing the starter project from GitHub. For the purpose of this tutorial, you'll use the CLI to set up the application. To begin, run the following command from the terminal to have it installed globally on your machine:
You will see output similar to the following:
Output@nestjs/cli@5.8.0 added 220 packages from 163 contributors in 49.104s
To confirm your installation of the Nest CLI, run this command from your terminal:
- nest --version
You'll see output showing the current version installed on your machine:
Output5.8.0
You'll make use of the
nest command to manage your project and use it to generate relevant files — like the controller, modules, and providers.
To begin the project for this tutorial, use the
nest command to craft a new Nest.js project named
blog-backend by running the following command from your terminal:
- nest new blog-backend
Immediately after running the command,
nest will prompt you to provide some basic information like the
description,
version, and
author. Go ahead and provide the appropriate details. Hit
ENTER on your computer to proceed after responding to each prompt.
Next, you'll choose a package manager. For the purpose of this tutorial, select
npm and hit
ENTER to start installing Nest.js.
This will generate a new Nest.js project in a
blog-backend folder within your local development folder.
Next, navigate to the new project’s folder from your terminal:
- cd blog-backend
Run the following command to install other server dependencies:
You've installed
@nestjs/mongoose, which is a Nest.js dedicated package for an object modelling tool for MongoDB, and
mongoose, which is a package for Mongoose.
Now you'll start the application using the following command:
- npm run start
Now, if you navigate to from your favorite browser, you will see your application running.
You've successfully generated the project by leveraging the availability of the Nest CLI command. Afterward, you proceeded to run the application and accessed it on the default port
3000 on your local machine. In the next section, you'll take the application further by setting up the configuration for the database connection.
Step 2 — Configuring and Connecting with the Database
In this step, you'll configure and integrate MongoDB into your Nest.js application. You'll use MongoDB to store data for your application. MongoDB stores its data in documents as field : value pairs. To access this data structure, you'll use Mongoose, which is an object document modeling (ODM) that allows you to define schemas representing the types of data that a MongoDB database stores.
To start MongoDB, open a separate terminal window so that the application can keep running, and then execute the following command:
- sudo mongod
This will start the MongoDB service and run the database in the background of your machine.
Open the project
blog-backend in your text editor and navigate to
./src/app.module.ts. You can set up a connection to the database by including the installed
MongooseModule within the root
ApplicationModule. To achieve this, update the content in
app.module.ts with the following highlighted lines:
import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { MongooseModule } from '@nestjs/mongoose'; @Module({ imports: [ MongooseModule.forRoot('mongodb://localhost/nest-blog', { useNewUrlParser: true }), ], controllers: [AppController], providers: [AppService], }) export class AppModule { }
In this file, you use the
forRoot() method to supply the connection to the database. Save and close the file when you are finished editing.
With this in place, you have set up the database connection by using the Mongoose module for MongoDB. In the next section, you will create a database schema using the Mongoose library, a TypeScript interface, and a data transfer object (DTO) schema.
Step 3 — Creating a Database Schema, Interfaces, and DTO
In this step, you will create a schema, interface, and a data transfer object for your database using Mongoose. Mongoose helps to manage relationships between data and provides schema validation for data types..
interfaces: TypeScript interfaces are used for type-checking. It can be used to define the types of data that should be passed for an application.
data transfer object: This is an object that defines how data will be sent over the network and carries the data between processes.
To begin, go back to your terminal where the application is currently running and stop the process with
CTRL + C, then navigate to the
./src/ folder:
- cd ./src/
Then, create a directory named
blog, and a
schemas folder within that:
- mkdir -p blog/schemas
In the
schemas folder, create a new file called
blog.schema.ts and open it using your text editor. Then, add the following content:
import * as mongoose from 'mongoose'; export const BlogSchema = new mongoose.Schema({ title: String, description: String, body: String, author: String, date_posted: String })
Here, you have used Mongoose to define the type of data that you will store in the database. You've specified that all the fields will store and only accept string values. Save and close the file when you are finished editing.
Now, with the database schema determined, you can move on to creating the interfaces.
To begin, navigate back into the
blog folder:
- cd ~/blog-backend/src/blog/
Create a new folder named
interfaces and move into it:
- mkdir interfaces
In the
interfaces folder, create a new file called
post.interface.ts and open it using your text editor. Add the following content to define the types of data for a
import { Document } from 'mongoose'; export interface Post extends Document { readonly title: string; readonly description: string; readonly body: string; readonly author: string; readonly date_posted: string }
In this file, you have successfully defined the types of data for a
Post type as string values. Save and exit the file.
Since your application will carry out the functionality of posting data to the database, you will create a data transfer object that will define how data will be sent over the network.
To achieve this, create a folder
dto inside the
./src/blog folder. Within the newly created folder, create another file named
create-post.dto.ts
Navigate back into the
blog folder:
- cd ~/blog-backend/src/blog/
Then create a folder named
dto and move into it:
- mkdir dto
In the
dto folder, create a new file called
create-post.dto.ts and open it using your text editor to add the following content:
export class CreatePostDTO { readonly title: string; readonly description: string; readonly body: string; readonly author: string; readonly date_posted: string }
You've marked each of the individual properties in the
CreatePostDTO class to have a data type of
string and as
readonly to avoid unnecessary mutation. Save and exit the file when you are finished editing.
In this step, you have created a database schema for the database, an interface, and a data transfer object for the data your database will store. Next, you'll generate a module, controller, and service for your blog.
Step 4 — Creating the Module, Controller, and Service for the Blog
In this step, you're going to improve on the existing structure of the application by creating a module for your blog. This module will organize the file structure of your application. Next, you'll create a controller to handle routes and process HTTP requests from the client. To wrap things up, you'll set up a service to handle all the business logic that is too complex for the controller of the application to process.
Generating a Module
Similarly to the Angular front-end web framework, Nest.js uses a modular syntax. Nest.js applications have a modular design; it comes installed with a single root module, which is often sufficient for a small application. But when an application starts to grow, Nest.js recommends a multiple-module organization, splitting the code into related features.
A module in Nest.js is identified by the
@Module() decorator and takes in an object with properties such as
controllers and
providers. Each of these properties takes an array of
controllers and
providers respectively.
You will generate a new module for this blog application in order to keep the structure more organized. To begin, still in the
~/blog-backend folder, execute the following command:
- nest generate module blog
You will see output similar to the following:
OutputCREATE /src/blog/blog.module.ts UPDATE /src/app.module.ts
The command generated a new module named
blog.module.ts for the application and imported the newly created module into the root module for the application. This will allow Nest.js to be aware of another module besides the root module.
In this file, you will see the following code:
import { Module } from '@nestjs/common'; @Module({}) export class BlogModule {}
You will update this
BlogModule with the required properties later in the tutorial. Save and exit the file.
Generating a Service
A service, which can also be called a provider in Nest.js, was designed to remove logic from controllers, which are meant to only handle HTTP requests and redirect more complex tasks to services. Services are plain JavaScript classes with an
@Injectable() decorator on top of them. To generate a new service, run the following command from the terminal while you are still within the project directory:
- nest generate service blog
You will see output similar to the following:
OutputCREATE /src/blog/blog.service.spec.ts (445 bytes) CREATE /src/blog/blog.service.ts (88 bytes) UPDATE /src/blog/blog.module.ts (529 bytes)
The
nest command used here has created a
blog.service.spec.ts file, which you can use for testing. It has also created a new
blog.service.ts file, which will hold all the logic for this application and handle adding and retrieving documents to the MongoDB database. Also, it automatically imported the newly created service and added to blog.module.ts.
The service handles all the logic within the application, is responsible for interacting with the database, and returns the appropriate responses back to the controller. To accomplish this, open the
blog.service.ts file in your text editor and replace the contents with the following:
import { Injectable } from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { Post } from './interfaces/post.interface'; import { CreatePostDTO } from './dto/create-post.dto'; @Injectable() export class BlogService { constructor(@InjectModel('Post') private readonly postModel: Model<Post>) { } async getPosts(): Promise<Post[]> { const posts = await this.postModel.find().exec(); return posts; } async getPost(postID): Promise<Post> { const post = await this.postModel .findById(postID) .exec(); return post; } async addPost(createPostDTO: CreatePostDTO): Promise<Post> { const newPost = await this.postModel(createPostDTO); return newPost.save(); } async editPost(postID, createPostDTO: CreatePostDTO): Promise<Post> { const editedPost = await this.postModel .findByIdAndUpdate(postID, createPostDTO, { new: true }); return editedPost; } async deletePost(postID): Promise<any> { const deletedPost = await this.postModel .findByIdAndRemove(postID); return deletedPost; } }
In this file, you first imported the required module from
@nestjs/common,
mongoose, and
@nestjs/mongoose. You also imported an interface named
CreatePostDTO.
In the
constructor, you added
@InjectModel(
'
'
), which will inject the
Post model into this
BlogService class. You will now be able to use this injected model to retrieve all posts, fetch a single post, and carry out other database-related activities.
Next, you created the following methods:
getPosts(): to fetch all posts from the database.
getPost(): to retrieve a single post from the database.
addPost(): to add a new post.
editPost(): to update a single post.
deletePost(): to delete a particular post.
Save and exit the file when you are finished.
You have finished setting up and creating several methods that will handle proper interaction with the MongoDB database from the back-end API. Now, you will create the required routes that will handle HTTP calls from a front-end client.
Generating a Controller
In Nest. js, controllers are responsible for handling any incoming requests from the client side of an application and returning the appropriate response. Similarly to most other web frameworks, it is important for the application to listen for a request and respond to it.
To cater to all the HTTP requests for your blog application, you will leverage the
nest command to generate a new controller file. Ensure that you are still in the project directory,
blog-backend, and run the following command:
- nest generate controller blog
You will see output similar to:
OutputCREATE /src/blog/blog.controller.spec.ts (474 bytes) CREATE /src/blog/blog.controller.ts (97 bytes) UPDATE /src/blog/blog.module.ts (483 bytes)
The output indicates that this command created two new files within the
src/blog directory. They are
blog.controller.spec.ts and
blog.controller.ts. The former is a file that you can use to write automated testing for the newly created controller. The latter is the controller file itself. Controllers in Nest.js are TypeScript files decorated with
@Controller metadata. The command also imported the newly created controller and added to the blog module.
Next, open the
blog.controller.ts file with your text editor and update it with the following content:
import { Controller, Get, Res, HttpStatus, Param, NotFoundException, Post, Body, Query, Put, Delete } from '@nestjs/common'; import { BlogService } from './blog.service'; import { CreatePostDTO } from './dto/create-post.dto'; import { ValidateObjectId } from '../shared/pipes/validate-object-id.pipes'; @Controller('blog') export class BlogController { constructor(private blogService: BlogService) { } @Get('posts') async getPosts(@Res() res) { const posts = await this.blogService.getPosts(); return res.status(HttpStatus.OK).json(posts); } @Get('post/:postID') async getPost(@Res() res, @Param('postID', new ValidateObjectId()) postID) { const post = await this.blogService.getPost(postID); if (!post) throw new NotFoundException('Post does not exist!'); return res.status(HttpStatus.OK).json(post); } @Post('/post') async addPost(@Res() res, @Body() createPostDTO: CreatePostDTO) { const newPost = await this.blogService.addPost(createPostDTO); return res.status(HttpStatus.OK).json({ message: "Post has been submitted successfully!", post: newPost }) } }
In this file, you first imported the necessary modules to handle HTTP requests from
@nestjs/common module. Then, you imported three new modules which are:
BlogService,
CreatePostDTO, and
ValidateObjectId. After that, you injected the
BlogService into the controller via a constructor in order to gain access and make use of the functions that are already defined within the
BlogService file. This is a pattern regarded as dependency injection used in Nest.js to increase efficiency and enhance the modularity of the application.
Finally, you created the following asynchronous methods:
getPosts(): This method will carry out the functionality of receiving an HTTP GET request from the client to fetch all posts from the database and then return the appropriate response. It is decorated with a
@Get(
'
'
).
getPost(): This takes a
postIDas a parameter and fetches a single post from the database. In addition to the
postIDparameter passed to this method, you realized the addition of an extra method named
ValidateObjectId(). This method implements the
PipeTransforminterface from Nest.js. Its purpose is to validate and ensure that the
postIDparameter can be found in the database. You will define this method in the next section.
addPost(): This method will handle a POST HTTP request to add a new post to the database.
To be able to edit and delete a particular post, you will need to add two more methods to the
blog.controller.ts file. To do that, include the following
editPost() and
deletePost() methods directly after the
addPost() method you previously added to
blog.controller.ts:
... @Controller('blog') export class BlogController { ... @Put('/edit') async editPost( @Res() res, @Query('postID', new ValidateObjectId()) postID, @Body() createPostDTO: CreatePostDTO ) { const editedPost = await this.blogService.editPost(postID, createPostDTO); if (!editedPost) throw new NotFoundException('Post does not exist!'); return res.status(HttpStatus.OK).json({ message: 'Post has been successfully updated', post: editedPost }) } @Delete('/delete') async deletePost(@Res() res, @Query('postID', new ValidateObjectId()) postID) { const deletedPost = await this.blogService.deletePost(postID); if (!deletedPost) throw new NotFoundException('Post does not exist!'); return res.status(HttpStatus.OK).json({ message: 'Post has been deleted!', post: deletedPost }) } }
Here you have added:
editPost(): This method accepts a query parameter of
postIDand will carry out the functionality of updating a single post. It also made use of the
ValidateObjectIdmethod to provide proper validation for the post that you need to edit.
deletePost(): This method will accept a query parameter of
postIDand will delete a particular post from the database.
Similarly to the
BlogController, each of the asynchronous methods you have defined here has a metadata decorator and takes in a prefix that Nest.js uses as a routing mechanism. It controls which controller receives which requests and points to the methods that should process the request and return a response respectively.
For example, the
BlogController that you have created in this section has a prefix of
blog and a method named
getPosts() that takes in a prefix of
posts. This means that any GET request sent to an endpoint of
blog/posts (
http:localhost:3000/blog/posts) will be handled by the
getPosts()method. This example is similar to how other methods will handle HTTP requests.
Save and exit the file.
For the complete
blog.controller.ts file, visit the DO Community repository for this application.
In this section, you have created a module to keep the application more organized. You also created a service to handle the business logic for the application by interacting with the database and returning the appropriate response. Finally, you generated a controller and created the required methods to handle HTTP requests such as
GET,
PUT, and
DELETE from the client side. In the next step, you'll complete your back-end setup.
Step 5 — Creating an Extra Validation for Mongoose
You can identify each post in your blog application by a unique ID, also known as
PostID. This means that fetching a post will require you to pass this ID as a query parameter. To validate this
postID parameter and ensure that the post is available in the database, you need to create a reusable function that can be initialized from any method within the
BlogController.
To configure this, navigate to the
./src/blog folder:
- cd ./src/blog/
Then, create a new folder named
shared:
- mkdir -p shared/pipes
In the
pipes folder, using your text editor, create a new file called
validate-object-id.pipes.ts and open it. Add the following content to define the accepted
postID data:
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'; import * as mongoose from 'mongoose'; @Injectable() export class ValidateObjectId implements PipeTransform<string> { async transform(value: string, metadata: ArgumentMetadata) { const isValid = mongoose.Types.ObjectId.isValid(value); if (!isValid) throw new BadRequestException('Invalid ID!'); return value; } }
The
ValidateObjectId() class implements the
PipeTransform method from the
@nestjs/common module. It has a single method named
transform() that takes in value as a parameter —
postID in this case. With the method above, any HTTP request from the frontend of this application with a
postID that can’t be found in the database will be regarded as invalid. Save and close the file.
After creating both the service and controller, you need to set up the
Post model that is based on the
BlogSchema. This configuration could be set up within the root
ApplicationModule, but in this instance building the model in
BlogModule will maintain your application's organization. Open the
./src/blog/blog.module.ts and update it with the following highlighted lines:
import { Module } from '@nestjs/common'; import { BlogController } from './blog.controller'; import { BlogService } from './blog.service'; import { MongooseModule } from '@nestjs/mongoose'; import { BlogSchema } from './schemas/blog.schema'; @Module({ imports: [ MongooseModule.forFeature([{ name: 'Post', schema: BlogSchema }]) ], controllers: [BlogController], providers: [BlogService] }) export class BlogModule { }
This module uses the
MongooseModule.forFeature() method to define which models should be registered in the module. Without this, injecting the
PostModel within the
BlogService using
@injectModel() decorator wouldn't work. Save and close the file when you have finished adding the content.
In this step, you've created the complete backend RESTful API with Nest.js and integrated it with MongoDB. In the next section, you'll configure the server to allow HTTP requests from another server, because your frontend application will be running on a different port.
Step 6 — Enabling CORS
An HTTP request from one domain to another is often blocked by default, except when specified by the server to allow it. For your front-end application to make a request to the back-end server, you must enable Cross-origin resource sharing (CORS), which is a technique that allows requests for restricted resources on a web page.
In Nest.js to enable CORS, you need to add a single method to your
main.ts file. Open this file in your text editor, which is located at
./src/main.ts, and update it with the following highlighted content:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors(); await app.listen(3000); } bootstrap();
Save and exit the file.
Now that you have completed the back-end setup, you'll shift your focus to the frontend and use Vue.js to consume the APIs built so far.
Step 7 — Creating the Vue.js Frontend
In this section, you are going to create your front-end application with Vue.js. Vue CLI is a standard tool that allows you to quickly generate and install a new Vue.js project without much hassle.
To begin, you first need to install the Vue CLI globally on your machine. Open another terminal, and instead of working from the
blog-backend folder, navigate to your local project's development folder and run:
Once the installation process is complete, you'll make use of the
vue command to create a new Vue.js project:
- vue create blog-frontend
You'll see a short prompt after you've entered this command. Choose the
manually select features option, and then select the features you'll need for this project by pressing
SPACE on your computer to highlight multiple features. You'll select
Babel,
Router, and
Linter / Formatter.
For the next instructions, type
y to use history mode for a router; this will ensure that history mode is enabled within the router file, which will automatically generate for this project. In addition, select
ESLint with error prevention only to pick a linter/formatter configuration. Next, select
Lint on save for additional Lint features. Then select to save your configuration in a
dedicated config file for future projects. Type a name for your preset, like
vueconfig.
Vue.js will then start creating the application and all its required dependencies in a directory named
blog-frontend.
Once the installation process is complete, navigate inside the Vue.js application:
- cd blog-frontend
Then, start the development server with:
- npm run serve
Your application will be running on.
Since you'll be performing HTTP requests within this application, you'll need to install Axios, which is a promise-based HTTP client for the browser. You'll use Axios here to perform HTTP requests from the different components within the application. Stop the front-end application by hitting
CTRL + C from the terminal on your computer and then run the following command:
- npm install axios --save
Your front-end application will be making an API call to the back-end API on a particular domain from different components within the application. In order to ensure proper structure for this application, you can create a
helper file and define the server
baseURL.
To begin, from you terminal still within
blog-frontend, navigate to the
./src/ folder:
- cd ./src/
Create another folder named
utils:
- mkdir utils
In the
utils folder, using your text editor, create a new file called
helper.js and open it. Add the following content to define the
baseURL for the back-end Nest.js project:
export const server = { baseURL: '' }
By defining a
baseURL, you'll be able to call it from anywhere within you Vue.js component files. In the event that you need to change the URL, it will be an easier process to update the
baseURL in this file rather than across your application.
In this section, you installed the Vue CLI, a tool for creating a new Vue.js application. You used this tool to craft the
blog-frontend application. In addition, you ran the application and installed a library named Axios, which you will use whenever there is an HTTP call within the app. Next, you will create components for the application.
Step 8 — Creating Reusable Components
Now you're going to create reusable components for your application, which is the standard structure for Vue.js applications. The component system in Vue.js makes it possible for developers to build a single, independent unit of an interface that can have its own state, markup, and style. This makes it appropriate for components in Vue.js to be reusable.
Every Vue.js component contains three different sections:
<template>: contains the HTML contents
<script>: holds all the basic frontend logic and defines the functions
<style>: the stylesheet for each separate component
First, you'll start by creating a component to create a new post. To do that, create a new folder named
post within the
./src/components folder, which will house the necessary reusable components for posts. Then using your text editor, inside the newly created
post folder, create another file and name it
Create.vue. Open the new file and add the following code, which contains the necessary input fields for submitting a post:
<template> <div> <div class="col-md-12 form-wrapper"> <h2> Create Post </h2> <form id="create"> Create Post </button> </div> </form> </div> </div> </template>
This is the
<template> section of the
CreatePost component. It contains the HTML input elements required to create a new post. Each of the input fields has a
v-model directive as an input attribute. This is to ensure two-way data bindings on each of the form input to make it easy for Vue.js to obtain the user's input.
Next, add the
<script> section to the same file directly following the preceding content:
... <script> import axios from "axios"; import { server } from "../../utils/helper"; import router from "../../router"; export default { data() { return { title: "", description: "", body: "", author: "", date_posted: "" }; }, created() { this.date_posted = new Date().toLocaleDateString(); }, methods: { createPost() { let postData = { title: this.title, description: this.description, body: this.body, author: this.author, date_posted: this.date_posted }; this.__submitToServer(postData); }, __submitToServer(data) { axios.post(`${server.baseURL}/blog/post`, data).then(data => { router.push({ name: "home" }); }); } } }; </script>
Here you've added a method named
createPost() to create a new post and submit it to the server using Axios. Once a user creates a new post, the application will redirect back to the homepage where users can view the list of created posts.
You will configure vue-router to implement the redirection later in this tutorial.
Save and close the file when you are finished editing. For the complete
Create.vue file, visit the DO Community repository for this application.
Now, you need to create another component for editing a particular post. Navigate to
./src/components/post folder and create another file and name it
Edit.vue. Add the following code that contains the
<template> section to it:
<template> <div> <h4 class="text-center mt-20"> <small> <button class="btn btn-success" v-on: View All Posts </button> </small> </h4> <div class="col-md-12 form-wrapper"> <h2> Edit Post </h2> <form id="edit"> Edit Post </button> </div> </form> </div> </div> </template>
This template section holds similar content as the
CreatePost() component; the only difference is that it contains the details of the particular post that needs to be edited.
Next, add the
<script> section directly following the
</template> section in
Edit.vue:
... <script> import { server } from "../../utils/helper"; import axios from "axios"; import router from "../../router"; export default { data() { return { id: 0, post: {} }; }, created() { this.id = this.$route.params.id; this.getPost(); }, methods: { editPost() { let postData = { title: this.post.title, description: this.post.description, body: this.post.body, author: this.post.author, date_posted: this.post.date_posted }; axios .put(`${server.baseURL}/blog/edit?postID=${this.id}`, postData) .then(data => { router.push({ name: "home" }); }); }, getPost() { axios .get(`${server.baseURL}/blog/post/${this.id}`) .then(data => (this.post = data.data)); }, navigate() { router.go(-1); } } }; </script>
Here, you obtained the route parameter
id to identify a particular post. You then created a method named
getPost() to retrieve the details of this post from the database and updated the page with it. Finally, you created an
editPost() method to submit the edited post back to the back-end server with a PUT HTTP request.
Save and exit the file. For the complete
Edit.vue file, visit the DO Community repository for this application.
Now, you'll create a new component within the
./src/components/post folder and name it
Post.vue. This will allow you to view the details of a particular post from the homepage. Add the following content to
Post.vue:
<template> <div class="text-center"> <div class="col-sm-12"> <h4 style="margin-top: 30px;"><small><button class="btn btn-success" v-on: View All Posts </button></small></h4> <hr> <h2>{{ post.title }}</h2> <h5><span class="glyphicon glyphicon-time"></span> Post by {{post.author}}, {{post.date_posted}}.</h5> <p> {{ post.body }} </p> </div> </div> </template>
This code renders the details of a post that includes,
title,
author, and the post
body.
Now, directly following
</template>, add the following code to the file:
... <script> import { server } from "../../utils/helper"; import axios from "axios"; import router from "../../router"; export default { data() { return { id: 0, post: {} }; }, created() { this.id = this.$route.params.id; this.getPost(); }, methods: { getPost() { axios .get(`${server.baseURL}/blog/post/${this.id}`) .then(data => (this.post = data.data)); }, navigate() { router.go(-1); } } }; </script>
Similar to the
<script> section of the edit post component, you obtained the route parameter
id and used it to retrieve the details of a particular post.
Save and close the file when you are finished adding the content. For the complete
Post.vue file, visit the DO Community repository for this application.
Next, to display all the created posts to users, you will create a new component. If you navigate to the
views folder in
src/views, you will see a
Home.vue component — if this file is not present, use your text editor to create it, add the following code:
<template> <div> <div class="text-center"> <h1>Nest Blog Tutorial</h1> <p> This is the description of the blog built with Nest.js, Vue.js and MongoDB</p> <div v- <h2> No post found at the moment </h2> </div> </div> <div class="row"> <div class="col-md-4" v- <div class="card mb-4 shadow-sm"> <div class="card-body"> <h2 class="card-img-top">{{ post.title }}</h2> <p class="card-text">{{ post.body }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group" style="margin-bottom: 20px;"> <router-link :View Post </router-link> <router-link :Edit Post </router-link> <button class="btn btn-sm btn-outline-secondary" v-on:Delete Post</button> </div> </div> <div class="card-footer"> <small class="text-muted">Posted on: {{ post.date_posted}}</small><br/> <small class="text-muted">by: {{ post.author}}</small> </div> </div> </div> </div> </div> </div> </template>
Here, within the
<template> section, you used the
<router-link> to create a link for editing as well as for viewing a post by passing the
post._id as a query parameter. You also used the
v-if directive to conditionally render the post for users. If there is no post from the database, a user will only see this text: No post found at the moment.
Save and exit the file. For the complete
Home.vue file, visit the DO Community repository for this application.
Now, directly following the
</template> section in
Home.vue, add the following
</script> section:
... <script> // @ is an alias to /src import { server } from "@/utils/helper"; import axios from "axios"; export default { data() { return { posts: [] }; }, created() { this.fetchPosts(); }, methods: { fetchPosts() { axios .get(`${server.baseURL}/blog/posts`) .then(data => (this.posts = data.data)); }, deletePost(id) { axios.delete(`${server.baseURL}/blog/delete?postID=${id}`).then(data => { console.log(data); window.location.reload(); }); } } }; </script>
Within the
<script> section of this file, you created a method named
fetchPosts() to fetch all posts from the database, and you updated the page with the data returned from the server.
Now, you'll update the
App component of the front-end application in order to create links to the
Home and
Create components. Open
src/App.vue and update it with the following:
<template> <div id="app"> <div id="nav"> <router-linkHome</router-link> | <router-linkCreate</router-link> </div> <router-view/> </div> </template> <style> #app { font-family: "Avenir", Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; } #nav { padding: 30px; text-align: center; } #nav a { font-weight: bold; color: #2c3e50; } #nav a.router-link-exact-active { color: #42b983; } </style>
Apart from including the links to both
Home and
Create components, you also included the
<Style> section, which is the stylesheet for this component and holds the definition of styles for some of the elements on the page. Save and exit the file.
You have created all the required components for your application in this step. Next, you will configure the router file.
Step 9 — Setting Up Routing
After creating all the necessary reusable components, you can now properly configure the router file by updating its content with links to all the components you've created. This will ensure that all endpoints within the front-end application are mapped to a particular component for appropriate action. Navigate to
./src/router.js and replace its content with the following:
import Vue from 'vue' import Router from 'vue-router' import HomeComponent from '@/views/Home'; import EditComponent from '@/components/post/Edit'; import CreateComponent from '@/components/post/Create'; import PostComponent from '@/components/post/Post'; Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', redirect: { name: 'home' } }, { path: '/home', name: 'home', component: HomeComponent }, { path: '/create', name: 'Create', component: CreateComponent }, { path: '/edit/:id', name: 'Edit', component: EditComponent }, { path: '/post/:id', name: 'Post', component: PostComponent } ] });
You imported
Router from the
vue-router module and instantiated it by passing the
mode and
routes parameters. The default mode for
vue-router is a hash mode, which uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes. In order to make the hash unnecessary, you have used history mode here to achieve URL navigation without a page reload. Finally, within the
routes option, you specified the path for the endpoint — a name for the route and the component that should be rendered when the route is called within the application. Save and exit the file.
Now that you have set up routing to the application, you need to include the Bootstrap file to help with pre-built styling for the user interface of the application. To achieve that, open
./public/index.html file in your text editor and include the CDN file for Bootstrap by adding the following content to the file:
<!DOCTYPE html> <html lang="en"> <head> ... <link rel="stylesheet" href=""> <title>blog-frontend</title> </head> <body> ... </body> </html>
Save and exit the file, and then restart the application with
npm run serve for your
blog-frontend, if it is not currently running.
Note: Ensure that both the back-end server and the MongoDB instance are running as well. If otherwise, navigate to the
blog-backend from another terminal and run
npm run start. Also, start the MongoDB service by running
sudo mongod from a new terminal as well.
Navigate to your application at:. Now you can test your blog by creating and editing posts.
Click on Create on your application to see the Create Post screen, which relates to and renders the
CreateComponent file. Enter values into the input fields and click on the Create Post button to submit a post. Once you are done, the application will redirect you back to the homepage.
The homepage of the application renders the
HomeComponent. This component has a method that sends an HTTP call to fetch all posts from the database and displays them to users.
Clicking on the Edit Post button for a particular post will take you to an edit page where you can incorporate any changes and save your post.
In this section, you configured and set up routing for the application. With this in place, your blog application is ready.
Conclusion
In this tutorial, you have explored a new way of structuring a Node.js application by using Nest.js. You created a simple blog application using Nest.js to build the back-end RESTful API and used Vue.js to handle all the front-end logic. Furthermore, you also integrated MongoDB as a database for your Nest.js application.
To learn more about how to add authentication to your application, you can make use of Passport.js, a popular Node.js authentication library. You can learn about Passport.js integration in the Nest.js documentation.
You can find the complete source code for this project here on GitHub. For more information about Nest.js, you can visit the official documentation.
2 Comments
|
https://www.digitalocean.com/community/tutorials/how-to-build-a-blog-with-nest-js-mongodb-and-vue-js
|
CC-MAIN-2019-30
|
refinedweb
| 6,661
| 56.86
|
I built a default layout using the Layout Builder, to have one drawer on the right. It is defined as
<template> <q-layout <q-header elevated <q-toolbar> <q-toolbar-title> <q-avatar> <img src=""> </q-avatar> Title </q-toolbar-title> <q-btn dense flat round </q-toolbar> <q-tabs <q-route-tab <q-route-tab </q-tabs> </q-header> <q-drawer show-if-above </q-page-container> <q-footer elevated <q-toolbar> <q-toolbar-title> <q-avatar> <img src=""> </q-avatar> Title </q-toolbar-title> </q-toolbar> </q-footer> </q-layout> </template> <script> export default { name: 'App', data() { return { right: true } } } </script>
Despite not having defined a drawer on the left side, I still get an area on the left I do not know how to get rid of:
What should I do so that the central part starts directly on the left edge?
What are the styling options you applied on the q-page (displayed within router-view)?
It’s
justify-centerin the layout builder example but in your case, it looks like more
justify-end. You can set
justify-start. Does your q-page have a fixed position/width ?
@jraez thank you for your answer. I did not style anything - I used the default skeleton from the builder.
I pushed my code to in case it is easier to understand what went wrong.
Sorry for the quality of the code - I am just starting with Quasar and did not go too far yet.
EDIT: I just checked across all the sources, there is no
justify-anywhere.
@wpq eummm did you modify App.vue? You basically have 2 files with a q-layout and drawer, layouts/MainLayout.vue and App.vue
Both are being used. MainLayout.vue because it used in the router and App.vue because of index.template.html
MainLayout.vue contains the left drawer
App.vue contains the right drawer
this is the template of my App.vue
<template> <div id="q-app"> <router-view/> </div> </template>
nothing more
yes it is used. See:
src/router/routes.js
It is used because the default Quasar app is router enabled, and uses the MainLayout.
This is
routes.js(from the repo I mentioned earlier ()
import Main from "layouts/Main" import RenderMD from "components/RenderMD" const routes = [ { path: '/', component: Main, }, { path: '/one', component: RenderMD, props: { title: 'One', hello: true, filename: 'subdir/one.md' } }, { path: '/two', component: RenderMD, props: { title: 'Two', hello: true, filename: 'subdir/two.md' } }, // Always leave this as last one, // but you can also remove it { path: '*', component: () => import('pages/Error404.vue') } ] export default routes
Main.vueis almost empty:
<template> <div> This is the main page </div> </template> <script> export default { name: "Main" } </script> <style scoped> </style>
your git repo code does not run. Check it out and try…
You removed the
id="q-app"
|
https://forum.quasar-framework.org/topic/6434/how-to-remove-the-left-area-of-a-qlayout
|
CC-MAIN-2021-39
|
refinedweb
| 470
| 65.62
|
Contents
Abstract
While we generally try to avoid global state when possible, there nonetheless exist a number of situations where it is agreed to be the best approach. In Python, the standard way() tmp = yield foo resume():
def f2(): with warnings.catch_warnings(record=True) as w: for x in g(): yield x assert len(w) == 1 assert "xyzzy" in w[0].message
And notice that this last example isn't artificial at all -- if you squint, it turns out to be exactly how you write a test that an asyncio-using coroutine g correctly raises a warning. Similar issues arise for pretty much any use of warnings.catch_warnings, decimal.localcontext, or numpy.errstate in asyncio.
Interaction with PEP 492
PEP 492 added new asynchronous context managers, which are like regular context managers but instead of having regular methods __enter__ and __exit__ they have coroutine methods __aenter__ and __aexit__.
There are a few options for how to handle these:
Add __asuspend__ and __aresume__ coroutine methods.
One potential difficulty here is that this would add a complication to an already complicated part of the bytecode interpreter. Consider code like:
async def f(): async with MGR: await g() @types.coroutine def g(): yield 1
In 3.5, f gets desugared to something like:
@types.coroutine def f(): yield from MGR.__aenter__() try: yield from g() finally: yield from MGR.__aexit__()
With the addition of __asuspend__ / __aresume__, the yield from would have to replaced by something like:
for SUBVALUE in g(): yield from MGR.__asuspend__() yield SUBVALUE yield from MGR.__aresume__()
Notice that we've had to introduce a new temporary SUBVALUE to hold the value yielded from g() while we yield from MGR.__asuspend__(). Where does this temporary go? Currently yield from is a single bytecode that doesn't modify the stack while looping. Also, the above code isn't even complete, because it skips over the issue of how to direct send/throw calls to the right place at the right time...
Add plain __suspend__ and __resume__ methods.
Leave async context managers alone for now until we have more experience with them.
It isn't entirely clear what use cases even exist in which an async context manager would need to set coroutine-local-state (= like thread-local-state, but for a coroutine stack instead of an OS thread), and couldn't do so via coordination with the coroutine runner. So this draft tentatively goes with option (3) and punts on this question until later.
|
http://legacy.python.org/dev/peps/pep-0521/
|
CC-MAIN-2017-39
|
refinedweb
| 413
| 64.3
|
Update (Feb 2016): These instructions are now outdated.
The recommended way to install Jupyter (new name for IPython Notebook) is now using Anaconda.
The.
The problem is, you haven’t explained how to use easy_install.
What’s missing from step 2? Easy_install should be included with the Python distribution.
I also couldn’t initially use easy_install. Here are instructions for getting it:
Though I actually just dragged ez_setup.py into the command prompt and pressed enter and it worked ~shrugs~
easy_install is included in activepython
Thank you very much!
Very-very good guide
Hi, this was really helpful, but I can only run ipython and ipython notebook if I run the commands from an administrator terminal.
How odd. What kind of error do you get if you try to run IPython in a normal command line?
Just to share some experience: for one that does not work…please use ActivePython as mentioned in the article, rather than the normal Python downloaded from Python.org.
IPython notebook on Python 3.4 cannot print or download on Windows. See here
I wish I could help, but I don’t have any experience with Python 3.4 or with Python on Windows x64. Sorry.
Tried several versions. The 2.7.8.10 (x86) active python has easy_install built in. After installing the python, you can directly run easy_install under cmd.exe
steps 1-3 worked fine. However trying to run ipython notebook is step 5, I get an error that ipython is not recognized as an internal or external command.
Looks like ipython is not in the PATH. I think ActivePython should add the correct directory to the path (e.g. C:\Program Files (x86)\ActivePython 2.7.5\Scripts\) during installation.
However, maybe your command line doesn’t use the latest value of the PATH, for example if you opened it before installing ActivePython. Try opening a new command line window (as a normal user) and see if ipython is found now.
If not, you may have to log off and on again, and try again. If this still doesn’t work, then the directory I mentioned above is probably missing from the PATH, so you need to add it yourself.
I’ve install ipython through easy_install and I have not found iputhon folder in PATH
I follow Christian’s comment and problem was solved by adding to PATH
C:\Python27\Scripts
Thanks a lot for such a good step by step explanation! Everything started working after the very first try.
Richardt,
I have downloaded Anaconda and run the following script:
C:\Users\cjw_2>ipython notebook
C:\Python27\lib\site-packages\numpy\core\__init__.py:6: Warning: Numpy 64bit experimental build with
Mingw-w64 and OpenBlas.
from . import multiarray
2015-01-31 13:42:14.296 [NotebookApp] Using existing profile dir: u’C:\\Users\\cjw_2\\.ipython\\prof
ile_default’
2015-01-31 13:42:14.312 [NotebookApp] Using MathJax from CDN:
/MathJax.js
2015-01-31 13:42:14.344 [NotebookApp] Serving notebooks from local directory: C:\Users\cjw_2
2015-01-31 13:42:14.344 [NotebookApp] 0 active kernels
2015-01-31 13:42:14.359 [NotebookApp] The IPython Notebook is running at:
2015-01-31 13:42:14.359 [NotebookApp] Use Control-C to stop this server and shut down all kernels (t
wice to skip confirmation).
Do you have any advice?
Colin W.
That looks pretty normal to me, and it should have opened IPython notebook in your browser. If it didn’t, open in a tab, and you should be done.
[…] user (like me) you won’t have a good time, but using easy_install makes life way easier! This tutorial might also be helpful for windows users. If you’re on a Mac or some Linux Distro…. The […]
When I enter “ipython notebook”, I was told “UnicodeDecodeError:’utf8′ codec can’t decode byte 0xbb in position invtart byte”.
Please help me. I have been struggling in installing ipython for a whole way only to find I am not that smart.
This sounds like the same problem as this one:
Try this solution but with UnicodeDecodeError as noted in another answer:
easy_install ipython[all] does not work for me.
I install python x86 in C:\Program Files (x86)\ActivePython 2.7.8
Please help
Could you please be more specific? What error do you get? Could it be related to one of the other easy_install issues already discussed above?
Hi,
I am getting this below. Do I need to install ipywidgets?:
PS C:\Program Files (x86)\Python27> ipython notebook
[I 16:38:50.576 NotebookApp] Copying C:\Users\rafa\.ipython\nbextensions -> C:\Users\rafa\AppData\Roaming\jupyter\nbexte
nsions
[W 16:41:11.332 NotebookApp] ipywidgets package not installed. Widgets are unavailable.
[I 16:41:11.358 NotebookApp] Serving notebooks from local directory: C:\Program Files (x86)\Python27
[I 16:41:11.359 NotebookApp] 0 active kernels
[I 16:41:11.361 NotebookApp] The IPython Notebook is running at:
[I 16:41:11.361 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
It’s just a warning that you can ignore. IPython Notebook is running fine.
Microsoft Windows [Version 6.1.7600]
C:\Users\CBIT>cd\
C:\>cd Python27
C:\Python27>ipython notebook
[I 15:29:19.388 NotebookApp] Serving notebooks from local directory: C:\Python27
[I 15:29:19.388 NotebookApp] 0 active kernels
[I 15:29:19.388 NotebookApp] The IPython Notebook is running at:
t:8888/
[I 15:29:19.388 NotebookApp] Use Control-C to stop this server and shut down all
kernels (twice to skip confirmation).
[W 15:29:19.657 NotebookApp] 404 GET /static/components/bootstrap/fonts/glyphico
ns-halflings-regular.eot? (::1) 10.00ms referer=
i am getting this, and blank on the explorer, what’s the problem
Please don’t post comments as replies to unrelated comments.
It looks like a font belonging to Bootstrap wasn’t found (error 404). Look here for a fix:
If I try running easy_install ipython[all] I get:
Running gnureadline-6.3.3\setup.py -q bdist_egg –dist-dir c:\users\tomq\appdata\local\temp\easy_install-cyoflt\gnureadline-6.3.3\egg-dist-tmp-npzt0y
error: Setup script exited with Error: this module is not meant to work on Windows (try pyreadline instead)
I have activestate python 32 bit. I have tried manually installing pyreadline, but makes no difference.
Any ideas?
Well, “gnureadline” clearly seems to be the wrong package, and “pyreadline” should work, so I don’t know what the problem is.
You could try running “pip install ipython”, which is the currently recommended way to install IPython/Jupyter and all its dependencies, including readline (). Please let me know if that works.
By a process of just manually installing individual packages as it gave me errors about this that and the other not being found, I have finally got a running system.
pip install python does essentially the same thing, fails on gnureadline.
I’m glad it works now. I just don’t understand why it even attempts to install gnureadline on Windows. Are you perhaps using Cygwin or mingw?
No. Just plain windows.
I installed IPython using the directions above on WinXPSP, I already have Python 3.4.4 installed. When I run ipython notebook from a command line I see a new page in my browser but it doesn’t have the IPython control panel, it has 3 Tabs: Files, Running, Clusters, and when I click “New” to start a notebook “Notebooks” is disabled. Also on the Running tab no terminals or notebooks are running. I clicked on “Untitled.ipynb” to see if that would start a notebook, and it does, a new Tab opened in the browser, with what looks like the correct control panel, and a place to type code : In [ ]:, but I see “Kernel Error” in the browser and a bunch of errors in the CLI and then it terminates IPython. I’ll paste the beginning and end of the error listing from the command line. Any help will be much appreciated.
C:\python34>ipython notebook
[I 00:38:56.254 NotebookApp] Serving notebooks from local directory: C:\python34
[I 00:38:56.254 NotebookApp] 0 active kernels
[I 00:38:56.254 NotebookApp] The Jupyter Notebook is running at:
t:8888/
[I 00:38:56.254 NotebookApp] Use Control-C to stop this server and shut down all
kernels (twice to skip confirmation).
Assertion failed: Socket operation on non-socket (bundled\zeromq\src\select.cpp:
185)
Assertion failed: Socket operation on non-socket (bundled\zeromq\src\select.cpp:
185)
[E 00:39:18.737 NotebookApp] Unhandled error in API request
….
[E 00:39:18.784 NotebookApp] 500 POST /api/sessions (127.0.0.1) 3468.57ms refere
r=
C:\python34>Assertion failed: Socket operation on non-socket (bundled\zeromq\src
\select.cpp:185)
Assertion failed: Socket operation on non-socket (bundled\zeromq\src\signaler.cp
p:181)
The only thing I could find are these two things, but it doesn’t look like they’d solve your problem:
*
*
Thank you for your quick reply and for looking into this. I turned off the antivirus and firewall, uninstalled ipython, upgraded pip to the lastest version, installed the latest version of ipython[all], still seeing problems. I ran iptest and the lib section failed, I hope you don’ t mind me posting the results here:
Test group: lib
………………………S……..F……….S………………….
======================================================================
FAIL: testIPythonLexer (IPython.lib.tests.test_lexers.TestLexers)
———————————————————————-
Traceback (most recent call last):
File “c:\python34\lib\site-packages\IPython\lib\tests\test_lexers.py”, line 26, in testIPythonLexer
self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
nose.proxy.AssertionError: Lists differ: [(Tok[65 chars]), (Token.Name.Variable,
‘$HOME’), (Token.Text, ‘\n’)] != [(Tok[65 chars]), (Token.Text, ‘$’), (Token.Text, ‘HOME’), (Token.Text, ‘\n’)]
First differing element 3:
(Token.Name.Variable, ‘$HOME’)
(Token.Text, ‘$’)
Second list contains 1 additional elements.
First extra element 5:
(Token.Text, ‘\n’)
[(Token.Operator, ‘!’),
(Token.Name.Builtin, ‘echo’),
(Token.Text, ‘ ‘),
– (Token.Name.Variable, ‘$HOME’),
+ (Token.Text, ‘$’),
+ (Token.Text, ‘HOME’),
(Token.Text, ‘\n’)]
“””Fail immediately, with the given message.”””
>> raise self.failureException(“Lists differ: [(Tok[65 chars]), (Token.Name.Variable, ‘$HOME’), (Token.Text, ‘\\n’)] != [(Tok[65 chars]), (Token.Text, ‘$’), (Token.Text, ‘HOME’), (Token.Text, ‘\\n’)]\n\nFirst differing element 3:\n(Token.Name.Variable, ‘$HOME’)\n(Token.Text, ‘$’)\n\nSecond list contains 1 additional elements.\nFirst extra element 5:\n(Token.Text, ‘\\n’)\n\n [(Token.Operator, ‘!’),\n (Token.Name.Builtin, ‘echo’),\n (Token.Text, ‘ ‘),\n- (Token.Name.Variable, ‘$HOME’),\n+ (Token.Text, ‘$’),\n+ (Token.Text, ‘HOME’),\n (Token.Text, ‘\\n’)]”)
———————————————————————-
Ran 70 tests in 6.234s
FAILED (SKIP=2, failures=1)
I have no idea about this and again couldn’t find any solution about this.
If I had to guess, I would blame the unusual combination of Windows XP and the latest Jupyther/Python 3.4. Although Windows XP is officially supported by Python 3.4, the Jupyter developer perhaps may not have test Windows XP anymore.
One thing you could try is to install Anaconda (), which bundles everything you should need.
Hi Christian,
Thank you very much for writing such a great post! I’m in China now and wasn’t able to download Anaconda from its website. Your post helped me take a detour and solve my problem. Thank you!
Christian,
You deserve a round of applause for following up on so many problems with such great research. This page catapulted me forward in my quest to install IPython on Windows. Thanks for your time and effort here!
Ben
|
http://richardt.name/blog/setting-up-ipython-notebook-on-windows/
|
CC-MAIN-2019-22
|
refinedweb
| 1,933
| 69.38
|
A few months back the New York Times ran an article titled "At Chipotle, How Many Calories Do People Really Eat?" which took a look at the average amount of calories a typical order at Chipotle contained. They found that:
The typical order at Chipotle has about 1,070 calories. That’s more than half of the calories that most adults are supposed to eat in an entire day. The recommended range for most adults is between 1,600 and 2,400.
Very surprising, Chipotle isn't the healthiest place to eat. What was more interesting to me was the fact that the NYT released the data they used for the article on their Github page. The article states that "The data is based on about 3,000 meals in about 1,800 Grubhub orders from July to December 2012, almost all from two Chipotle restaurants: one in Washington, D.C., and another in East Lansing, Mich."
I had been meaning to mess around with this order file for a while but had forgotten about it. That was until today when today I saw Chipotle had announced it will be offering delivery in select cities through a SF based delivery startup.
After starting up a new IPython notebook I loaded the TSV file into a pandas dataframe and ran the .head() method to make sure everything looked okay.
import pandas as pd df = pd.read_table('/Users/danielforsyth/Desktop/orders.tsv') df.head()
The First thing I wanted to look at was what items were the most popular.
items = df.item_name.value_counts().plot(kind='bar')
You can see that the chicken bowl dominates all of the items but there's obviously way too much going on here. How about just the top ten most popular items.
items = df.item_name.value_counts()[:10].plot(kind='bar')
That's much easier to read and you can clearly see the chicken bowl and chicken burrito are the most popular items at the locations included in the data.
Next I wanted to look at the prices of the orders. This was a little trickier as the 'item price' column contained string values and multiple items could be part of one order. The first step was to strip the $ sign from the string and then convert it to a float. Then you can just group by the order_id and add the sum method on the end.
df['item_price'] = df['item_price'].str.replace('$','') df['item_price'] = df['item_price'].astype(float) orders = df.groupby('order_id').sum() orders.head() orders['item_price'].describe()
From this we are able to see that 1834 meals were ordered with a total of 4622 different items. The mean price of a meal is $18 with the minimum being right around $10 (Obligatory mention of the term fast casual). Someone was also able to rack up a $205 dollar bill.
The last type of information I was interested in finding was the variety of different meals people ordered. The 'choice description' column describes the item type. For example what kind of soda or what toppings on a burrito bowl.
descriptions = df.groupby(["item_name", "choice_description"])["order_id"].count().reset_index(name="count")
Using this new dataframe we can easily see the most popular versions of each menu item. For example the different kinds of the most ordered item, the chicken bowl.
descriptions = descriptions[descriptions['item_name'].str.contains("Chicken Bowl")] descriptions.sort(['count'], ascending=False)[:10]
There were actually 348 different varieties of chicken bowls ordered but I limited it to the top ten which you can see here.
How about the most popular drinks?
descriptions = descriptions[descriptions['item_name'].str.contains("Canned Soda")] descriptions.sort(['count'], ascending=False)
It was very interesting playing around with this dataset, I would be curious to see the results if something like this were to be done at a much larger scale, to see things such as ordering trends in different stores and areas of the country. I am sure this data is very useful to Chipotle to see what items are doing well on top of optimizing inventory control on a location to location basis.
If you have any questions, feedback, advice, or corrections please get in touch with me on Twitter or email me at danforsyth1@gmail.com.
|
http://www.danielforsyth.me/pandas-burritos-analyzing-chipotle-order-data-2/
|
CC-MAIN-2018-09
|
refinedweb
| 705
| 63.39
|
menu_driver(3) UNIX Programmer's Manual menu_driver(3)
menu_driver - command-processing loop of the menu system
#include <menu.h> int menu_driver(MENU *menu, int c);
Once a menu has been posted (displayed), you should funnel input events to it through menu_driver. This routine has three major input cases; either the input is a menu naviga- tion request, it's a printable ASCII character or it is the KEY_MOUSE special key associated with an mouse event. The menu driver requests MirOS BSD #10-current Printed 19.2.2012 1 menu_driver(3) UNIX Programmer's Manual menu_driver(3) win- dow (e.g. inside the menu display area or the decoration window) are handled. If you click above the display region of the menu, a REQ_SCR_ULINE is generated, if you doub- le tri- ple exe- cuted.. MirOS BSD #10-current Printed 19.2.2012 2 menu_driver(3) UNIX Programmer's Manual menu_driver(3)
menu_driver return one of the following error codes: E_OK The routine succeeded. E_SYSTEM_ERROR System error occurred (see errno). E_BAD_ARGUMENT Routine detected an incorrect or out-of-range argument.), menu(3).
The header file <menu.h> automatically includes the header files <curses.h>.
These routines emulate the System V menu library. They were not supported on Version 7 or BSD versions. The support for mouse events is ncurses specific..
|
http://mirbsd.mirsolutions.de/htman/sparc/man3/menu_driver.htm
|
crawl-003
|
refinedweb
| 218
| 59.19
|
Hi all,
I have a problem with download file. I would like to download file document that I have uploaded into one folder in CMSdesk. I use repeater webpart to show all documents that's in that folder based on Transformation.
I would like to click on "Download", it will download that file for me.
Note: allow all file extension(.docx,.pdf,.jpg...)
Could you please advise me on this. If you have another way to work with download, please share it. I have no idea to work on it anymore.
Hi,
You can use 'download' attribute for your links into transformation code.
Hi,
I have used it already. but I cannot get file's extension as ".pdf, .docx,...", I just get only ".aspx". So I would like to get "document.pdf" not "document.aspx".
That's why, I cannot download it correctly.
So how can I get the extension as "pdf or docx or gif...."?
Thank you,
Hi,
Have you created an attachment to a document or upload it into the content tree using the file page type?
You could also create use the media library, but it depends how you want link to this items and/or if you need document permission?
Greets,
David
If you use files from media library, you can show all fields from MediaFileInfo class type(CMS.MediaLibrary namespace) in your transformation. Example: <% Eval("FileName") %>, <% Eval("FileExtension") %> and etc, and you can add this fields to 'download' attribute
What you need to do is specify a download attribute inside an anchor tag like this
I am putting this code in quotes otherwise it will also appear as a download link.
Download Your Expense Report
You will be all set with download.
Thanks,
Chetan
You can configure files extensions in Settings -> URLs and SEO -> Files friendly URL extensions. But I'm not really sure this is your issue. So what actually happens when you click that link? Does it open PDF in new tab?
Hi,
Again, I used webpart "Repeater" to show all document in one folder based on its transformation. I used attribute "download" of HTML5, but it's just working on Chrome. How to make it support with all browser? or should I need to create custom webpart?
Please, sign in to be able to submit a new answer.
|
http://devnet.kentico.com/questions/download-file
|
CC-MAIN-2016-50
|
refinedweb
| 386
| 76.22
|
Some concepts in ScalaCollider are very similar to their SC-Lang counterparts, while others are not. Foremost, ScalaCollider's library is far more reduced than the standard class library of SC-Lang. However, in many cases this is compensated by similar offerings in Scala's standard library. As a rule of thumb, constructs that are available in Scala are the preferred way of doing things in ScalaCollider, so that there are little reinventions of the wheel. Secondly, the general idea of ScalaCollider is to be modular. Special topics should be handled by extension libraries. This is why, for example, ScalaCollider-Swing is a separate package. ScalaCollider is open for extensions, so if you wish to contribute some, please get in touch.
In the meantime, we try to give here an overview of solutions to common problems in SC-Lang, and how they can be solved with ScalaCollider and the standard Scala libraries.
UGensUGens
The UGens work pretty much the same as in SC-Lang. However note the following differences:
Some UGens have different default values. For example, in the BEQSuite, the frequency defaults are 1200 Hz in SC-Lang, while the default in ScalaCollider is 500 Hz (more the middle range). The changes have been made in a sensitive way, and mostly to have more regular or reasonable defaults. In some cases, default values have been omitted where clearly the user should be prompted to provide a value, and in other case additional default values have been added.
It is thus crucial that you work either with code completion that shows you the default values, or keep an eye on the Scala-Docs.
Not all shortcut methods are available on graph elements (
GEs). For instance,
rangeand
exprangeare not available and you need to work around these limitations:
SinOsc.ar.range(4, 8)becomes
SinOsc.ar.linlin(-1, 1, 4, 8)
The multiply-and-add slots have been omitted. These are synthetic slots which are actually not part of the UGens themselves, but produce additional
MulAddUGens. In SC-Lang, for example the oscillators provide
muland
addarguments. In ScalaCollider you would use the
maddmethod instead, or just a multiplication
*or addition
+, if only one of the two arguments is used:
// SC-Lang play { SinOsc.ar(800, SinOsc.ar(XLine.kr(1, 1000, 9), 0, 2pi), 0.25) }; play { SinOsc.ar(LFNoise0.ar(4, 400, 450 ), 0, 0.2) };
// ScalaCollider play { SinOsc.ar(800, SinOsc.ar(XLine.kr(1, 1000, 9)) * 2*math.Pi) * 0.25 } play { SinOsc.ar(LFNoise0.ar(4).madd(400, 450)) * 0.2 }
- Multi-channel expansion in ScalaCollider works similar to SC-Lang. However, instead of Arrays which can be written as literal
[ ... ]in SC-Lang, you typically use
Listor
Seqin Scala:
// sclang play { var f = LFSaw.kr(0.4, 0, 24, LFSaw.kr([8, 7.23], 0, 3, 80)).midicps; CombN.ar(SinOsc.ar(f, 0, 0.04), 0.2, 0.2, 4) }
// ScalaCollider play { val f = LFSaw.kr(0.4).madd(24, LFSaw.kr(Seq(8, 7.23)).madd(3, 80)).midicps CombN.ar(SinOsc.ar(f) * 0.04, 0.2, 0.2, 4) }
SynthsSynths
In Scala, a curly block
{ ... } is not automatically a function or even a thunk statement. However, a thunk argument may be provided by using curly braces. The Scala way of playing a synth graph with default envelope and output is thus
play { ... }, while in SC-Lang you can either use
{ ... }.play or
play { ... }
Routines and TasksRoutines and Tasks
Client-side scheduling mechanisms are currently not part of ScalaCollider, as there are many different ways to conceive them. We envision extra packages for this in the future, though. For now, different approaches have been discussed on the ScalaCollider mailing list.
Possibly interesting libraries:
Maths and OperatorsMaths and Operators
Numbers: In SC-Lang, the forward slash operator
/always produces floating-point division. In Scala, it only provides floating-point division when either operand is a floating-point number. Dividing two integers this way behaves like
divin SC-Lang:
4/3 // --> 1! this is like doing 4.div(3) in SC-Lang
4.0/3 // --> 1.3333
Operator precedence: In Scala infix notation the operators take precedence over the infixes (which is what you'd expect typically). For example, multiplication and divison have higher precedence than adding and subtracting. In SC-Lang operations are strictly carried out from left to right, though. Thus
3+4/5in SC-Lang translates to
(3+4)/5.0in Scala.
Some operators are different
Again, be careful with operator precedence:
2 pow 3 * 4 // --> 4096
2.pow(3) * 4 // --> 32
Random NumbersRandom Numbers
We have decided not to include extensive random functions in ScalaCollider. These might be going into an extra package some day. The reason is that we are planning something particular for the SoundProcesses project, and it would be unfortunate to have that collide with random numbers in the base package (ScalaCollider).
In UGens, though, you can just use scalar UGens instead of simple number operations. E.g. instead of
4.randyou can do
IRand(0,3), instead of
1.0.randyou can do
Rand(0,1). There are more, like
ExpRandetc.
the standard random number generator is
math.random, delivering doubles from 0.0 inclusive to 1.0 exclusive. You can also generate integers, e.g. through
util.Random.nextInt(4)(interval from 0 inclusive to 4 exclusive), or a boolean through
util.Random.nextBoolean. If you wish to control the seed, create a generator with
new util.Random(mySeed). For
exprandyou currently would need to write a helper function (e.g. call
math.randomand then
linexpon the result).
CollectionsCollections
The methods for operating on collections have different names than in sclang, but work similarly:
There are quite a few more operations with the Scala Collections, such as
drop,
dropWhile,
dropRight,
groupBy,
partition,
span,
splitAt. Also, for intense number crunching, you can use Parallel Collections. On the other hand, SC-Lang has some operations which are more typical in musical usage, e.g. random operations like
scramble. Often there are some simple ways to achieve the same in Scala, but the solutions might be less obvious, e.g.
(1..10).scramblebecomes
util.Random.shuffle(1 to 10)
SC-Lang defines arithmetics and all sorts of operations which are applied to the collections' elements directly on the collection type. In Scala you would use the
map operation instead. E.g.
// SC-Lang [1, 2, 3, 4] * 2
// ScalaCollider Seq(1, 2, 3, 4).map(_ * 2)
In SC-Lang all collections are usually mutable, at least for assignment. In Scala there is a clear division between mutable and immutable collections, and immutable collections should be used by default, unless there is a specific need for mutability, since immutable data structures are inherently thread-safe and avoid concurrency problems. In most cases they are as efficient as the mutable counter-parts. The following chart describes a possible set of rules to change SC-Lang collections into Scala collections. The classes in the chart do not have the equivalent functionality, instead they have enough functionality for what is usually needed in SC-Lang.
For more information see the Scala Collections Guide
General CaveatsGeneral Caveats
TODO...
Graphical User InterfacesGraphical User Interfaces
There are several options. On the desktop, you will most likely use scala-swing, or even better ScalaCollider-Swing which builds on top of scala-swing and adds more widgets. You could also go for the Standard Widget Toolkit (SWT).
On mobile platforms, you could also develop using the Android UI. If you love Qt, QtJambi for Scala might be for you.
Audio FilesAudio Files
ScalaCollider comes with an audio file library:
import de.sciss.synth.io.AudioFile val af = AudioFile.openRead("my-file.aif") val buf = af.buffer(4096) af.read(buffer) af.close() ...
See the project for more information.
MIDI (Musical Instrument Digital Interface)MIDI (Musical Instrument Digital Interface)
You can either use the
javax.sound.midi (Java MIDIMIDIScalaMIDI.
|
https://git.iem.at/sciss/ScalaCollider/-/wikis/Guide-for-converting-supercollider-code-to-scalacollider
|
CC-MAIN-2020-34
|
refinedweb
| 1,321
| 59.3
|
I find this aspect of learning new things in Swift and Xcode very puzzling.
I cannot seem to decipher the actual code I need to write from what I read in the Apple API documentation; In my specific case: the API Reference for 'PlaygroundSupport', and the actual code I need, which is:
import PlaygroundSupport
let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 375.0, height: 667.0))
PlaygroundPage.current.liveView = containerView
Reading API documentation is a lot like reading a math textbook: you need to understand every word you're reading, or else you might miss what you need. In this case, inspecting that documentation, you'd probably check out the
PlaygroundPage class, and you'd see the
liveView property described as "The active live view in the assistant timeline". If you're not sure what a "live view" is, or what "the assistant timeline" is, then some further searching might be required. If you are aware of those terms, however, you should instantly recognize this as the property you're looking for!
Keep browsing through the documentation and make sure you understand enough of each method or property to definitely rule it out or look into it further. It can be overwhelming at first, but as you read the Swift iBook, follow tutorials, and continue to read the documentation, you will find yourself understanding more and more of what it says.
|
https://codedump.io/share/vpHgPW9nnpBr/1/how-do-i-translate-apple-api-documentation-in-to-real-life-code
|
CC-MAIN-2017-30
|
refinedweb
| 236
| 59.33
|
Answered
I was shown that importing replit and using the clear() console works on other compilers (such as Repl). However, when I try this in Pycharm nothing happens.
import replit
replit.clear()
neither clears the console or gives an error.
The use case specifically calls for a cleared console, without the ability to scroll up (so repeating newlines will not work).
I am currently researching other ways to do this. But I am a bit surprised that a function that works just fine in other consoles won't work in Pycharm. Does anyone have a solution?
I'm trying to use keymap and pyautogui right now but it's not intuitive or working as yet.
Thanks in advance.
It seems to be a bug. I filed a ticket to our issue tracker about that, feel free to vote for it and comment.
Instead, you can use PyCharm's feature for clearing the console. Right-click inside the output area and choose Clear All:
I'm sorry for the inconvenience.
|
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360010648539-Clearing-the-Python-Console
|
CC-MAIN-2022-05
|
refinedweb
| 169
| 76.62
|
- Author:
- marinho
- Posted:
- November 16, 2007
- Language:
- Python
- Version:
- .96
- template json
- Score:
- 1 (after 1 ratings)
Explanation:
I think this shortcut can be util for who uses JSON many times and does not want to write same code everytime.
Setup:
Saves the snippet as
myproject/utils.py or add the code to some place in your project with same ends.
Use in a view:
from myproject.utils import render_to_json from django.contrib.admin.models import User def json_view(request): admin_user = User.objects.get(username='admin') return render_to_json( 'json/example.json', locals(), )
Update:
This code can be used as complement to too.
More like this
- CSV to JSON Fixture by briangershon 5 years, 10 months ago
- Breaking tests.py into multiple files by gsakkis 5 years, 3 months ago
- Format transition middleware by limodou 8 years, 4 months ago
- Custom model field to store dict object in database by rudyryk 5 years, 2 months ago
- JSONField by deadwisdom 7 years, 10 months ago
JSON doesn't necessarily mean no cache. Don't blindly copy-paste; think about if your data can be cached.
#
Please login first before commenting.
|
https://djangosnippets.org/snippets/468/
|
CC-MAIN-2015-27
|
refinedweb
| 188
| 66.54
|
3428/how-is-storage-space-handled-in-hyperledger-peer
Every transaction is not stored by every peer in a hyperledger fabric network. The channel feature of hyperledger v1.0.0 provides that a peer only stores and and can see the transactions pertaining to that channel.
Talking about the storage requirements, the ledger is ever growing, but each peer only stores the transactions that are executed in the peers channel. A peer can take part in more than one channel, and it will store transaction from those different channels.
The ordering service of hyperledger fabric stores transaction from same channel. Transacction data is only shared in the context of the channel, so only peers and orderer participate in the channel.
Since it is a private blockchain platform, ...READ MORE
Consensus is the key concept for validating ...READ MORE
The peers communicate among them through the ...READ MORE
The transactions in the network is ordered ...READ MORE
You can find the explaination about it ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
I know it is a bit late ...READ MORE
There can only be one block at ...READ MORE
OR
Already have an account? Sign in.
|
https://www.edureka.co/community/3428/how-is-storage-space-handled-in-hyperledger-peer
|
CC-MAIN-2020-16
|
refinedweb
| 215
| 60.21
|
Created on 2017-11-15 10:34 by xdegaye, last changed 2020-04-14 18:31 by miss-islington. This issue is now closed.
On Android API 24:
$ python -c "import pwd; print(pwd.getpwuid(0))"
pwd.struct_passwd(pw_name='root', pw_passwd='', pw_uid=0, pw_gid=0, pw_gecos=None, pw_dir='/', pw_shell='/system/bin/sh')
The pw_gecos member is None and the test_values test of pwd fails because it expects a string. The fix is either (1) to skip the pw_gecos check in test_values for Android or (2) to modify the sets() function in Modules/pwdmodule.c to set an empty string instead of None when the member of the passwd structure is a NULL pointer.
POSIX [1] does not specify what are the possible values of the members of the struct passwd. GNU libc states that pw_dir and pw_shell may be NULL pointers so it seems that sets() is broken in these two cases.
[1]
[2]
> self.assertIsInstance(e.pw_gecos, str)
This test is wrong: it's perfectly fine to get None here.
Python must not test the OS itself, but only test our own code: make sure that Python converts properly C types to nice Python types, so a string or None.
I propose to use something like:
def check_type(field):
self.assertTrue(field is None or isinstance(field, str), repr(field))
...
check_type(e.pw_gecos)
Hum, I changed my mind a little bit :-)
> (2) to modify the sets() function in Modules/pwdmodule.c to set an empty string instead of None when the member of the passwd structure is a NULL pointer.
I checked the doc: pwd doesn't mention None at all :-(
For practical reasons, maybe (2) is nicer option. It would avoid to have all existing code just for Android.
I'm not sure that it's very useful to distinguish NULL and an empty char* string.
> I'm not sure that it's very useful to distinguish NULL and an empty char* string.
I agree. An attribute of a ('pwd' Python module) password database entry corresponds to the field of a line in a 'passwd' text file. So it makes sense that when the field is empty in the text file, the corresponding attribute be an empty string and never None if it is not an integer (FWIW Android does not have a 'passwd' file).
Changing the title of the issue.
I disagree. This is an old API, a thin wrapper around standard POSIX API, and returning an empty string instead of None will make impossible to distinguish NULL from "".
It is easy to convert None in an empty string in Python: `value or ''`.
I would change the test to
if field is not None:
self.assertIsInstance(field, str)
or
self.assertIsInstance(field, (str, type(None)))
(I prefer the former variant).
Changing test_pwd does not correct the fact that the current implementation of the pwd module may break an existing Python application since this (old indeed) API states "The uid and gid items are integers, all others are strings".
> returning an empty string instead of None will make impossible to distinguish NULL from "".
AFAIK in the 50 years since the creation of the unix operating system, there has never been an implementation of pwd that states that a string field may be either an empty string or NULL. And it is doubtful that there will ever be one, since this would break all (all, not just the Python applications) existing applications using pwd.
On your second link it is documented explicitly that pw_dir and pw_shell might be NULL. And at least for pw_shell the behavior for NULL and "" are different.
> And at least for pw_shell the behavior for NULL and "" are different.
What is the difference between the two?
New changeset 96515e9f6785328c52ebc5d4ce60e0087a9adc2d by Zackery Spytz in branch 'master':
bpo-32033: Fix test_pwd failures on Android (GH-19502)
It's now fixed in master and backports to 3.7 and 3.8 will be merged as soon as the CI pass.
New changeset 1e1dbdf23f7a18f53a3257badc3541973831f2c4 by Miss Islington (bot) in branch '3.8':
bpo-32033: Fix test_pwd failures on Android (GH-19502)
New changeset 8821200d85657ef3bbec78dcb43694449c05e896 by Miss Islington (bot) in branch '3.7':
bpo-32033: Fix test_pwd failures on Android (GH-19502)
|
https://bugs.python.org/issue32033
|
CC-MAIN-2020-40
|
refinedweb
| 702
| 72.36
|
>> larger of x^y and y^x in C++
In this problem, we are given two numbers x and y. Our task is to find larger of x^y and y^x.
Problem Description: The problem is simple, we need to find weather x to the power y is greater than y to the power x.
Let’s take an example to understand the problem,
Input: x = 4, y = 5
Output: 1024
Explanation:
x^y = 4^5 = 1024
y^x = 5^4 = 625
Solution Approach
The solution to the problem is simple. We need to find the value of x^y and y^x and return the maximum of both.
There can be a more mathematically easy way to solve the problem, which is by taking log. So,
x^y = y*log(x).
These values are easy to calculate.
Program to illustrate the working of our solution,
Example
#include <bits/stdc++.h> using namespace std; int main() { double x = 3, y = 7; double ylogx = y * log(x); double xlogy = x * log(y); if(ylogx > xlogy) cout<<x<<"^"<<y; else if (ylogx < xlogy) cout<<y<<"^"<<x; else cout<<"None"; cout<<" has greater value"; return 0; }
Output
3^7 has greater value
- Related Questions & Answers
- Find maximum among x^(y^2) or y^(x^2) where x and y are given in C++
- Find number of pairs (x, y) in an array such that x^y > y^x in C++
- Count Distinct Non-Negative Integer Pairs (x, y) that Satisfy the Inequality x*x + y*y < n in C++
- Count Distinct Non-Negative Integer Pairs (x, y) that Satisfy the Inequality x*x + y*y < n in C++
- Find a distinct pair (x, y) in given range such that x divides y in C++
- Find x, y, z that satisfy 2/n = 1/x + 1/y + 1/z in C++
- Count of pairs (x, y) in an array such that x < y in C++
- Find x and y satisfying ax + by = n in C++
- Maximize the sum of X+Y elements by picking X and Y elements from 1st and 2nd array in C++
- Find the value of the function Y = (X^6 + X^2 + 9894845) % 981 in C++
- Check if a number can be expressed as x^y (x raised to power y) in C++
- Find value of y mod (2 raised to power x) in C++
- Different X and Y scales in zoomed inset in Matplotlib
- What is ternary operator (? X : Y) in C++?
- Write an iterative O(Log y) function for pow(x, y) in C++
Advertisements
|
https://www.tutorialspoint.com/find-larger-of-x-y-and-y-x-in-cplusplus
|
CC-MAIN-2022-33
|
refinedweb
| 428
| 56.12
|
How to really get the OAuth 2 token automatically
I wrote some code that gets an access token. When the code runs, a browser displays on the screen which contains the access token.
But when I try to get the access token and log it, a null string is being displayed. Also, I do not know if there is a way to force the browser to close using my code. Right now when I run this code, the browser window opens but I have to click on it to close it.
Could you please let me know what I am doing wrong ?
Groovy Code:
import com.eviware.soapui.impl.rest.actions.oauth.OltuOAuth2ClientFacade import com.eviware.soapui.support.editor.inspectors.auth.TokenType def project = context.getTestCase().getTestSuite().getProject(); def oAuthProfile = project.getAuthRepository().getEntry("IMAGEN_Profile"); def clientSecret = testRunner.testCase.testSuite.getPropertyValue("Client_Secret") def clientID = testRunner.testCase.testSuite.getPropertyValue("Client_ID") oAuthProfile.setClientSecret(clientSecret); oAuthProfile.setClientID(clientID); log.info("Client Secret:"+clientSecret) log.info("Client ID:"+clientID) // the following code for getting new access token def oAuthClientFacade = new OltuOAuth2ClientFacade(TokenType.ACCESS); oAuthClientFacade.requestAccessToken(oAuthProfile, true); def accessToken = oAuthProfile.getAccessToken() testRunner.testCase.testSuite.setPropertyValue("Auth_Code",accessToken) log.info("Access Token:"+accessToken)
Solved! Go to Solution.
I can't tell you what is wrong but I can post our script. :X Maybe it helps.
I didn't write it, so I can't answer any questions
We added this script as Event "SubmitListener.beforeSubmit
// def authProfileName = "PROFILE_NAME" if(!submit.getRequest().getAuthType().asBoolean()){ return // stop if the auth type is null, for example jdbc requests }else if(submit.getRequest().getActiveAuthProfile() == null){ return // stop if the auth profile is null }else if(authProfileName == submit.getRequest().getActiveAuthProfile().getName()){ // Set up variables def project = ModelSupport.getModelItemProject(context.getModelItem()) def authProfile = project.getAuthRepository().getEntry(authProfileName) def oldToken = authProfile.getAccessToken() def tokenType = TokenType.ACCESS // Create a facade object def oAuthFacade = new OltuOAuth2ClientFacade(tokenType) // Request an access token in headless mode oAuthFacade.requestAccessToken(authProfile, true, true) // Wait until the access token gets updated //while(oldToken == authProfile.getAccessToken()) {} //The sleep method can be used instead of a while loop //sleep(3000) for(int i = 0; i<=3000; i++){ if(oldToken != authProfile.getAccessToken()){ break } sleep(1) } // Post the info to the log //log.info("Set new token: " + authProfile.getAccessToken()) }
Cheers,
Cekay
Thank Cekay, that didn't work for me, I must be missing something. First of all, all of the if code that is associated with the submit. didn't work. When I commented that out, the token is still blank. Do you have any Java code on the OAuth 2 script for page 1 and page 2.
Cekay,
I've never worked with Event Handlers, so it is probably my problem. Can anybody guide me?
I'll try my best. There is not much to guide
- Click on "Events" in your SoapUI - It will open a new window
- Click on the green plus, to add a new event
- Choose "SubmitListener.beforeSubmit"
- Click OK and copy paste the script
- Change in line 6: PROFILE_NAME to the name of your auth-profile
- Save script via clicking OK
That is basically everything. Please find attached screenshot for more details ,
Run your testcase, where you need to get a token, and let the magic work for you 😉
I copied the script from my colleque, who is working on another project. All I did is to change the profile name so I think you don't have to change anything else. If this not working, you should show your error log.
Good Luck and have a nice weekend
I have a question, where does the token go? Where do I retrieve it to put into my "Authorization" part of the header. I see in the loop that it waits for a new token and then just ends...
Ah so that is the problem. Maybe we use the token in different ways. I don't have put it anywhere.
I have a testCase with a put rest request and use for the authorization my auth profile, which I used in the script.
It will generate the token for this profile. We don't have to send it via header.
When I start the testCase I will get a new token and it will be used directly.
See screenshot again please
So now we reached the end of my knowledge. If this is still not working for you, someone else has to help =/ Sorry
Here is the example and link to the event handlers article:...
Did my reply answer your question? Give Kudos or Accept it as a Solution to help others. ⬇️⬇️⬇️
Thanks @Nastya_Khovrina,
I've read this article about 40 times and get nothing from it. I'm lost in the Auth Manager, I can't get an access token unless I use "Authorization Code Grant" and it only gives it to me in a web browser that I can do nothing with. Are there any classes on OAuth 2 with ReadyAPI? Maybe that would be helpful. Like a course for dummies. I'm not a dummy, but don't deal with websites very often, mostly do background stuff in PowerShell, Ruby, VBA and such.
|
https://community.smartbear.com/t5/ReadyAPI-Questions/How-to-really-get-the-OAuth-2-token-automatically/m-p/184048?attachment-id=12846
|
CC-MAIN-2022-40
|
refinedweb
| 856
| 59.5
|
Develop and test in a WCF Service Library project while hosting your application in an ASP.NET project.
It's easy to test a service if you create it in a Windows Communication Foundation (WCF) Service Library -- just press F5 to bring up Visual Studio's Test Client. Testing isn't as easy if you create your service in an ASP.NET project -- you have to write your own test client. However, deploying a WCF service is much easier when you create it in an ASP.NET service (just deploy the ASP.NET project). Deploying isn't as easy if you create your service in a WCF Service Library, because you have to write your own host. But you can get the best of both worlds: develop and test in a WCF Service Library project while hosting your application in an ASP.NET project.
Start by creating a solution containing the WCF Service Library project that will hold your WCF service. When you've finished building and testing your service using the Test Client and are ready to host it in a Web site, add the ASP.NET project that will host your service to the solution. Give your ASP.NET project a reference to your WCF Service Library project. Then add a WCF Service to your ASP.NET project (if you want, to reduce the number of names you're managing, you can give the WCF Service in the ASP.NET project the same name as the service class in your WCF Service Library).
The next step is to get rid of what you don't need in your ASP.NET project. First, delete both of the C# or Visual Basic code files that were added with the service's svc file (i.e., the interface and the code behind file). Now double-click on the svc file to open it and, in the ServiceHost directive, delete the CodeBehind="…" attribute. Then open the project's Web.config file and delete the system.serviceModel element along with everything inside of it.
Now you can add what you need to your ASP.NET project. Open the app.config file in your WCF Service Library project and copy its system.serviceModel element (and everything in it). Then switch to your ASP.NET project's Web.config file, and paste the copied system.serviceModel element into the Web.config file where you deleted the old system.serviceModel element.
The last step is to change the svc file in your ASP.NET project to use your service class. In the svc file's ServiceHost directive, change the name in the Service attribute to the namespace and class name for your service in your WCF Service Library (i.e., if your WCF Service Library is called NorthwindManagement and your service class is called Customers, your Service attribute would be Service="NorthwindManagement.Customers").
And you're done: the service hosted in your ASP.NET project is now using the service you built in your Service Library. You can continue to test your Service Library project just by making the Service Library your solution's start project and pressing F5; you can deploy your service by deploying the ASP.NET
|
https://visualstudiomagazine.com/articles/2012/09/11/host-wcf-service-library-in-asp-net.aspx
|
CC-MAIN-2019-47
|
refinedweb
| 533
| 75.61
|
Python library for interacting with YouTrack via REST API supporting python3
Project description
Features modified
- Ported to python3
- Added
to_dictmethod on YouTrack objects
YouTrack REST API Client Library for Python
This is a Python client library that you can use to access the REST API for JetBrains YouTrack. Previously, this repository also included command-line tools for importing issues from other issue trackers. We have created a separate repository to store scripts that use this library.
The primary purpose of this library is to support migration to YouTrack, but you are welcome to build integrations with it as well. If you choose to work with this library, please be mindful of the following limitations:
- We don't provide any documentation for this library. You can either learn through trial and error or by dissecting the import scripts in the linked repository.
- This library references an older version of the YouTrack REST API. Many of the newer features in YouTrack are not supported.
We will continue to support this library with updates that are required to support issue import. Other issues that are not import related may be closed. Our intention is to eventually publish a fully-documented library that uses the latest version of the YouTrack REST API and is also compatible with Python 3.
Compatibility
This client library and the import scripts that use the library are compatible with Python 2.7+. Python 3 releases are not supported.
This library supports YouTrack Standalone versions 5.x and higher as well as the current version of YouTrack InCloud. The REST API is enabled by default in all YouTrack installations.
Getting Started
This package has been published to PyPI and can be installed with pip.
pip install youtrack
Authentication
To communicate with YouTrack, you need a connection.
- The preferred method is to use a permanent token for authentication requests. You can generate your own permanent tokens in your user profile. For instructions, refer to the YouTrack documentation.
- You can also authenticate using a login and password, however, these values are printed in plain text and expose your credentials in your client application.
from youtrack.connection import Connection as YouTrack # authentication request with permanent token yt = YouTrack('', token='perm:abcdefghijklmn') # versus authentication with username and password yt = YouTrack('', login='username', password='password')
This request requires that you specify the base URL of the target YouTrack server. For YouTrack InCloud instances, your base URL includes the trailing
/youtrack, as shown in the previous example.
Once you have established a connection, your credentials are cached for subsequent requests.
Supported Operations
Most of the operations that are supported by the YouTrack REST API are mapped to methods for the
Connection object. The Python client library, however, supports a simplified set of parameters. In some cases, like
createIssue, the Python method supports a custom set of request parameters.
To learn more about the YouTrack REST API, refer to the YouTrack documentation.
YouTrack Support
Your feedback is always appreciated.
- To report bugs and request updates, please create an issue.
- If you experience problems with an import script, please submit a support request.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/youtrack/0.1.52/
|
CC-MAIN-2020-16
|
refinedweb
| 542
| 55.64
|
CallCommandResponse
Since: BlackBerry 10.2
#include <bb/system/phone/CallCommandResponse>
To link against this class, add the following line to your .pro file: LIBS += -lbbsystem
Provides information about a call command response.
An instance of the CallCommandResponse class is provided through the Phone::callCommandResponseReceived() signal to deliver information to the client about the network response to a call command.
The call command response includes information such as the call command, response ID, call ID, and error.
You must specify the control_phone permission in your bar-descriptor.xml file.
Overview
Public Functions Index
Public Functions
Constructs an invalid CallCommandResponse object.
BlackBerry 10.2
Creates a copy of other.
BlackBerry 10.2
Destructor.
BlackBerry 10.2
QString
Returns the command that the response is for.
The call command.
BlackBerry 10.2
int
Returns the unique ID of the call that the response is for.
A non-negative ID of the call if the CallCommandResponse object is valid, or -1 if the object is invalid.
BlackBerry 10.2
QString
Returns the error code related to a command executed on a call.
The error returned when executing the call command, or an empty string if the command was executed successfully.
BlackBerry 10.2
CallCommandResponse &
Copies another CallCommandResponse to this object.
The CallCommandResponse instance.
BlackBerry 10.2
bool
Compares another CallCommandResponse to this object.
true if call id matches, false otherwise.
BlackBerry 10.2
int
Returns the command response ID that matches the ID used to send the call command.
The returned ID will match the ID used to send the call command.
The command ID.
BlackBerry 10.2
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
|
http://developer.blackberry.com/native/reference/cascades/bb__system__phone__callcommandresponse.html
|
CC-MAIN-2015-27
|
refinedweb
| 280
| 60.41
|
When debugging an executable opening a TFile with GDB (both 10.2 and 11.1) the debug session ends with a SIGTRAP and not much useful information for understanding the problem. This is a simple reproducer:
#include "TFile.h" int main(int argc, char** argv){ TFile *file = TFile::Open(argv[1]); return 0; }
When starting a debug session with no breakpoints I get:
$ gdb a.out GNU gdb (GDB) 10.2 Copyright (C) 2021 a.out... (gdb) r Starting program: /tmp/test/a.out [Thread debugging using libthread_db enabled] Using host libthread_db library "/usr/lib/libthread_db.so.1". [Detaching after vfork from child process 118892] Program terminated with signal SIGTRAP, Trace/breakpoint trap. The program no longer exists. (gdb)
The
Program terminated with signal SIGTRAP, Trace/breakpoint trap. mesage is found over many help threads on the web, but it is usually related to breakpoints, and I don’t have any in my test session.
I’m clueless so I’d need a bit of help with this. I can provide more info about my system and Root build configuration if needed.
Thanks in advance for any help
ROOT Version: 6.22.08
Platform: Archlinux, glibc 2.33
Compiler: GCC 11.1.0
|
https://root-forum.cern.ch/t/opening-a-tfile-crashes-gdb-session/47838
|
CC-MAIN-2022-27
|
refinedweb
| 203
| 69.99
|
ustat - get file system statistics
#include <sys/types.h> #include <ustat.h> int ustat(dev_t dev, struct ustat *buf);
The ustat() function returns information about a mounted file system. The dev argument is a device number identify- ing a device containing a mounted file system (see makedev(3C)). The buf argument is a pointer to a ustat structure that includes the following members: daddr_t f_tfree; /* Total free blocks */ ino_t f_tinode; /* Number of free inodes */ char f_fname[6]; /* Filsys name */ char f_fpack[6]; /* Filsys pack name */ The f_fname and f_fpack members may not contain significant information on all systems; in this case, these members will contain the null character as the first character.
Upon successful completion, 0 is returned. Otherwise, -1 is returned and errno is set to indicate the error.
The ustat() function will fail if: ECOMM The dev argument is on a remote machine and the link to that machine is no longer active. EFAULT The buf argument points to an illegal address. EINTR A signal was caught during the execution of the ustat() function. EINVAL The dev argument is not the device number of a device containing a mounted file system. ENOLINK The dev argument refers to a device on a remote machine and the link to that machine is no longer active. EOVERFLOW One of the values returned cannot be represented in the structure pointed to by buf.
The statvfs(2) function should be used in favor of ustat().
stat(2), statvfs(2), makedev(3C), lfcompile(5)
The NFS revision 2 protocol does not permit the number of free files to be provided to the client; therefore, when ustat() has completed on an NFS file system, f_tinode is always -1.
|
http://man.eitan.ac.il/cgi-bin/man.cgi?section=2&topic=ustat
|
CC-MAIN-2020-24
|
refinedweb
| 283
| 53.1
|
I have a simple Python module file
First.py
a = 50
b = [100,200,300]
Test.py
import First
First.a = 420
First.b[0] = 420
print (First.a)
Test.py
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (I
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import First
>>> dir(First)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'a', 'b']
>>> First.a
50
>>> First.b
[100, 200, 300]
Once the script
Test.pycompletes when I print the values inside the module , i find that the values have not changed.
If you executed
python Test.py, then fired up your interpreter interactively and checked the values, of course, modifications won't be visible. Python just loads
First.py when the
import is found, executing it and initializing
a and
b with the values in
First.py; previous executions won't affect this.
If you import
Test in your interactive interpreter and then import
First changes will be reflected:
Python 3.5.2 |Anaconda 4.2.0 (64-bit)| (default, Jul 2 2016, 17:53:06) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import Test 420 >>> import First >>> First.a 420 >>> First.b [420, 200, 300]
During the import of
Test,
First was loaded and executed, then its values modified. When you re-import python will just look in a table of imported modules (
sys.modules) and return it without executing its content (and re-initializing
a and
b)
|
https://codedump.io/share/E3wwqx3NoFFm/1/changing-values-inside-python-modules
|
CC-MAIN-2017-04
|
refinedweb
| 269
| 71.41
|
By Harshad Oak
Optimize your Java applications with Oracle JDeveloper 10g tools.
What if your Java IDE did more than just help you write code? What if it also gave you meaningful advice about how to actually improve it? What if you had a single, integrated environment that not only helped you optimize your Java applications, but also offered powerful built-in profiling, debugging, and optimization tools?
Oracle JDeveloper 10g does all that and more. It lets you develop, debug, deploy, check, and optimize your Java applications directly from within the IDE.
In this article, we'll look at the Java optimization tools that come with Oracle JDeveloper 10g and show how to use them to develop powerful, robust applications..
But development teams can't go through every line of code to optimize Java applications. Instead, they specify unambiguous guidelines and programming standards at a project's inception, and then monitor and modify code using optimization tools such as those provided with Oracle JDeveloper 10g.
Oracle JDeveloper 10g can help teams perform a variety of optimization tasks such as fixing coding errors, avoiding common performance pitfalls, and optimizing or eliminating resource-hungry code. Here's a brief look at the optimization tools integrated into Oracle JDeveloper 10g:
CodeCoach: Offers suggestions to help write better Java code
Code Audit: Checks code for adherence to programming standards
Code Metrics: Provides metrics about your code and identifies areas where it exceeds acceptable limits
Memory Profiler: Analyzes your application's memory usage
Execution Profiler: Helps you analyze your application's performance
Event Profiler: Helps you track specific application events
All of these tools are included within Oracle JDeveloper 10g; they don't require a separate download or installation.
Let's look at each tool in more depth. You'll start by creating a simple Java application, and then use it to show what these tools can do.
This application was developed using Oracle JDeveloper 10g (10.1.3) Developer Preview (J2EE Download), which you can download at oracle.com/technology/products/jdev. When you install this version, you can use either your existing Java SDK installation or the Java SDK that comes with the Oracle JDeveloper install. If you use the former, when you first launch Oracle JDeveloper it will ask you, "Do you want to install OJVM in this JDK to take advantage of the profilers, CodeCoach, and advanced debugging features?" Click Yes to enable the features described in this article.
Now, let's create a new workspace and project to manage your work. From the main menu choose File -> New.... In the New Gallery dialog box, select the Workspaces node (under Categories: General), select the Application item, and click OK . In the Create Application dialog box that follows, type OraMag as the Application Name and click the Options >> button to show extended options. Type oramag as the Application Package Prefix, and select Java Application [Java, Swing] as the Application Template. Click OK .
You should now have a new workspace named OraMag and a project named Client within that workspace. From the Applications Navigator window, right-click the Client project node, and select New . In the New Gallery dialog box, select the General node, then the Java class item, and then click OK . In the Create Java Class dialog box, enter OptimizationTrial for the class name and oramag.client for the package name. Click OK to generate the new OptimizationTrial class file.
Now replace the code in the class with the code shown in Listing 1. This test application simply outputs the current day, and then adds elements to two ArrayList objects. Once the code is in place, you'll use each tool to analyze and improve what you've written.
Code Listing 1: OptimizationTrial.java before first CodeCoach run
package oramag.client;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class OptimizationTrial {
public OptimizationTrial() {
}
static int count=99999;
public static void main(String[] args) throws IOException{
todaysDay();
demoArrayListOptimized(count);
demoArrayList(count);
}
public static void todaysDay() throws IOException{
Object today = fetchTodaysDay();
if (today instanceof String) {
System.out.println("The object 'today' is always a String. Check unnecessary");
}
System.out.println("Today is >>>" + today);
}
public static Object fetchTodaysDay() {
SimpleDateFormat sfInput = new SimpleDateFormat("EEEEEEEEE");
return sfInput.format(new Date());
}
public static void demoArrayList(int number) {
System.out.println("Unoptimized Run");
ArrayList ar= new ArrayList ();
//NOTE: Change number to zero to demonstrate codecoach and audit features
for(int i=0; i<0; i++) {
ar.add(new Integer(i));
}
}
public static void demoArrayListOptimized(int numberOpt) {
System.out.println("Optimized Run");
ArrayList ar= new ArrayList (numberOpt);
for(int i=0; i<numberOpt; i++) {
ar.add(new Integer(i));
}
}
}
CodeCoach helps you avoid well-known Java pitfalls and write better Java code. It highlights problems in your code that need to be fixed and provides other code-improvement suggestions. You can use it with any Java or J2EE project.
CodeCoach offers the following types of advice:
Class advice: Should a class be declared final or static?
Method advice: Should a method be declared final, private, or static?
Field advice: Is there an unused field, or should a field be declared final, local, private, or static?
Local variable advice: Is a local variable unused or should it be declared final?
Memory improvement advice: General advice related to the usage of ArrayList, BitSet, HashMap, Hashtable, StringBuffer, Vector , and WeakHashMap classes.
Configure CodeCoach from the main menu by choosing Tools->Preferences and then selecting the CodeCoach node. You can set the level of advice provided from 1-10, where 1 indicates only a few types of advice and 10 indicates all types of advice. You can also specify classes and packages to include or exclude during its operation.
To run CodeCoach from the main menu, choose Run->CodeCoach Client.jpr .
Try it now. First, from the main menu, choose Tools->Preferences , select the CodeCoach node, set the advice level slider to 10, and click OK . Then run CodeCoach on your Client.jpr project. The results are shown in Figure 1. CodeCoach provides 10 recommendations to improve your code, with the line number and the advice type shown for each recommendation. It finds a number of important code errors, including the unnecessary usage of instanceof and a listing of unused variables.
Another important CodeCoach suggestion is the "dead code" suggestion for demoArrayList() . Looking at the code, it's clear that you inadvertently wrote i < 0 instead of i < number when constructing the for loop. As a result, this dead code will never get executed. Dead code isn't always obvious even to human reviewers, so CodeCoach's ability to find this type of error is especially useful.
In many cases, you can have CodeCoach automatically fix the errors it finds by simply right-clicking on the error and selecting Apply Fix To Source . In other cases (such as with the dead code suggestion), you'll need to make the appropriate changes yourself. The updated code listing, which corrects all the problems found by CodeCoach, is shown in Listing 2.
Code Listing 2: OptimizationTrial.java after CodeCoach optimization
package oramag.client;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public final class OptimizationTrial {
public OptimizationTrial() {
}
private static final int count=99999;
public static void main(String[] args) throws IOException{
todaysDay();
demoArrayListOptimized(count);
demoArrayList(count);
}
private static void todaysDay() throws IOException{
Object today = fetchTodaysDay();
//if (today instanceof String) {
System.out.println("The object 'today' is always a String. Check unnecessary");
//}
System.out.println("Today is >>>" + today);
}
private static Object fetchTodaysDay() {
SimpleDateFormat sfInput = new SimpleDateFormat("EEEEEEEEE");
return sfInput.format(new Date());
}
private static void demoArrayList(int number) {
System.out.println("Unoptimized Run");
ArrayList ar= new ArrayList ();
//NOTE: Change number to zero to demonstrate codecoach and audit features
for(int i=0; i<number; i++) {
ar.add(new Integer(i));
}
}
private static void demoArrayListOptimized(int numberOpt) {
System.out.println("Optimized Run");
ArrayList ar= new ArrayList (numberOpt);
for(int i=0; i<numberOpt; i++) {
ar.add(new Integer(i));
}
}
}
Now run CodeCoach on this updated code in Listing 2. The new results are shown in Figure 2. In analyzing your use of the ArrayList object in demoArrayList() , CodeCoach determines that too many expansions of ArrayList are taking place. How did it find this problem? Compare the methods demoArrayList() and demoArrayListOptimized() in Listing 2. In demoArrayList() , you didn't state the initial size of the ArrayList , so it will initially be created with a small size but grow every time you add a new item beyond its current size. However, in the optimized method demoArrayListOptimized() , you specified the size of the ArrayList up front. Since it's clear from the code that you're adding 99,999 items to the ArrayList, the optimized method takes less time and memory than the unoptimized method. (We'll compare the performance of these two methods later in this article.)
You've seen how CodeCoach can help you write better code. Now let's look at how Code Audit can save you precious hours otherwise spent manually reviewing Java code.
While CodeCoach analyzes and suggests changes to code based on how it performs on execution, Code Audit performs a static audit of the code without needing to actually execute it. Code Audit can complement peer code review by allowing peer reviewers to focus on the business logic specific to that code, while Code Audit automates certain general, low-level review tasks. For example, Code Audit can find programmer errors such as missing Javadoc comments or nonadherence to naming conventions.
You can configure the level and type of audit performed by selecting an appropriate audit profile under the Tools-> Preferences menu. To do so, from the main menu select Tools->Preferences , expand the Audit node, and select Profiles . In addition to selecting a particular profile, you can specify individual rules to check for, such as missing Javadoc, nonadherence to naming standards, and improper exception handling.
You can run Code Audit on your code from Listing 1 from the main menu by choosing Run->Audit OptimizationTrail.java . In the dialog box that appears, select the All Rules profile, and click Run . The results are shown in Figure 3. Code Audit finds eight low-priority Javadoc violations and three medium-priority violations. In some cases, you can have Code Audit auto-fix these violations by right-clicking an item and selecting Apply... from the menu that appears. In other cases, you'll need to apply changes manually.
Let's look at Code Metrics, which is now integrated within the Code Audit user interface.
The Code Metrics tool performs a quantitative analysis of your code. You can use it to measure the following:
The depth of the inheritance tree (DIT): DIT refers to the level of the Java inheritance hierarchy in your code. In Listing 1, your class extends the java.lang.Object class, which is at the top of the Java hierarchy, so the DIT is 2.
Cyclomatic complexity (V(G)): This value provides a measure of the logical complexity of a program, and depicts the branching complexity of a class or method. A high V(G) value can raise a flag to help you find areas of significant complexity in your code.
Number of Statements (NOS): This attribute specifies the number of Java statements in a method, class, or other construct.
You run Code Metrics similarly to Code Audit. From the main menu, choose Run->Audit OptimizationTrial .java , and select All Metrics in the resulting dialog box. If you run Code Metrics with the code in Listing 1, you'll get the results shown in Figure 4. Since your code is pretty straightforward, all the values shown in Figure 4 are within acceptable limits.
Code Metrics can help you enforce coding rules that you specify across your development teams. For example, if you set a rule that no method in an application should be more than x number of lines and inheritance should never be more than y levels, you can easily check adherence using Code Metrics. These kinds of rules can help make sure that your developers maintain a certain level of code quality throughout the application.
You configure Code Metrics in the same way you configure Code Audit: from the main menu, choose Tools-> Preferences , expand the Audit node, and then choose Profiles . To set Code Metrics, select All Metrics in the dialog box and set the DIT, V(G), and NOS values as needed. With both Code Audit and Code Metrics, you can select the rules that the tool should check for, as well as create new profiles that capture your preferred selections.
Now let's look at some of the profiler tools in Oracle JDeveloper 10g that can help you better understand your code's performance.
Oracle JDeveloper 10g provides three profiling tools: Memory Profiler, Execution Profiler, and Event Profiler. We'll look at the first two profilers in this article. (Event Profiler comes with built-in events that it can track, and allows you to insert calls to the Profiler API in your code to track your own events. For information on Event Profiler, refer to the link in the Next Steps box at the end of this article.)
Profiling activities can overwhelm users with too much data and thus end up accomplishing very little. To get the best use out of profiling tools, then, it's important to not try to optimize every line of Java code in your application. In most cases, it's usually a small portion of code that takes the most time and consumes the most resources. So one worthwhile strategy is to optimize these code snippets.
One other note about profilers: the output may change based on your computer configuration. If you have a very fast computer that can execute our sample code in less than 0.5 seconds, Oracle JDeveloper 10g won't be able to generate accurate reports because the minimum update interval is 0.5 seconds for the Memory Profiler and 5 milliseconds for the Execution Profiler. This issue generally won't be a problem for complex, real-world applications that take a lot more time to execute than our simple example.
The Oracle JDeveloper 10g Memory Profiler provides a visual analysis of your application's memory usage. It offers many memory-related details, such as the number of instances created and the size of your Java objects. It also captures snapshots at specified durations to let you see how memory consumption changes over the life of the application. You can also configure the Memory Profiler to monitor classes from only specific packages, to help focus your analysis. These capabilities are essential to help you tune performance, optimize memory usage, and make sure that unnecessary objects don't bog down the system by consuming too much memory.
Let's start from the main menu by choosing Tools->Preferences, expanding the Profiler node, and selecting Memory . Change the Update Interval to 0.5 seconds, and click OK . Note that Oracle JDeveloper 10g gives you an option to take samples manually in addition to auto-sampling.
Next, load the code from Listing 2, and comment out the line demoArrayListOptimized(count) ; in the main method. Now run the Memory Profiler from the main menu by choosing Run-> Memory Profile Client.jpr . The output will be similar to what's shown in Figure 5. As you can see, the Memory Profiler gives detailed information such as the number of instances in the heap, their current size in the heap, the number of instances allocated after the last sample was taken, and the size of these instances. You can sort your data based on any of the columns in the list, or you can save the report to an HTML file.
Since our application spends most of its time adding integers to an ArrayList , you'll see that the numbers for java.lang.Integer will top the list.
Now, uncomment the line demoArrayListOptimized(count); and comment the call to the method demoArrayList(count); on the very next line. Then, run the Memory Profiler again. You'll see a significant drop in the total current size in the heap, primarily because of a drop in the size of java.lang.Object[] .
You can also use the Memory Profiler to check if a particular coding approach is memory-intensive or if instances of a certain class are taking up too much memory. The Count field can tell you if too many instances of your custom classes or data objects are still hanging around after they've been used.
READ about Event Profiler
DOWNLOAD Oracle JDeveloper 10g
For the last stop of our tour, let's look at the Execution Profiler.
The Execution Profiler is used to time your application. It shows how much time the application spends in each method, giving you valuable information to help you determine which ones you should optimize.
You can run the Execution Profiler from the main menu by choosing Run->Execution Profile Client.jpr . The results show how long each method took, as well as the methods called from that method and how long those methods took. So the next time you think a particular flow in your application seems unacceptably slow, try monitoring it with the Execution Profiler and then optimize the methods that are the most sluggish.
Let's do the same experiment we did with Memory Profiler. First, load the code in Listing 1, then comment out the call to the method demoArrayListOptimized() .When you run the Execution Profiler (by choosing Run->Execution Profile Client.jpr) , you'll get output similar to that shown in Figure 6. Then uncomment demoArrayListOptimized() , comment out demoArrayList() , and run the Execution Profiler again. Note the drop in total execution time, and also note that the method demoArrayListOptimized() takes a lot less time than the unoptimized method demoArrayList() .
We've looked at a number of Oracle JDeveloper 10g tools that give you valuable data that can help you improve the quality of your Java code and develop top-performing applications. I recommend you learn how to use these tools and incorporate code optimization activities early in your project lifecycles. As we all know, when schedules get very tight, code reviews and optimization tasks are often the first casualties in the development process.
Send us your comments
|
http://www.oracle.com/technetwork/issue-archive/2005/05-sep/o55opt-084977.html
|
CC-MAIN-2013-48
|
refinedweb
| 3,059
| 55.13
|
Ably Debugging Tales Part 1 — An Elixir Erlang Mystery | Ably Blog: Data in Motion
Part 1 — Debugging in Elixir Erlang
I enjoy debugging, and I enjoy reading tales of debugging. They’re like miniature detective stories — the mystery, the investigation, and (hopefully!) the resolution. So we (the Ably engineering team) decided to start sharing some of our own debugging adventures. Here’s the first. This particular story deals with a misbehaving Elixir application.
The opening of the rabbit hole was small, as it often is. Something that just doesn’t quite work as expected.
$ curl -v < HTTP/1.1 500 Internal Server Error * Server Cowboy is not blacklisted < server: Cowboy
Getting an unknown path was returning a 500 (internal server error), not a 404 (not found) error. But only in production (or in this case, staging). Not on my local machine, not in ci.
This shouldn’t happen as I have a ‘catch-all’ handler in the webserver I’m using that serves a nice 404. Which definitely works — it works locally, it has tests, and at least up until now, it’s worked in production.
First things first: check the logfile… which is empty. Which is strange, since anything which causes a 500 should print an error log or a crash trace. In Elixir/Erlang, if something happens that you didn’t anticipate or can’t handle locally, you ‘let it crash’: the ‘process’ (an erlang term for a green thread) handling that particular task dies, and if needed, is restarted in a known good state by its supervisor. When this happens you get a crash report in the logs.
So this is odd. I do the same thing a few more times, and suddenly:
=INFO REPORT==== application: logger exited: shutdown type: permanent =ERROR REPORT==== Error in process <0.438.0> with exit value: {[{reason,undef}, {mfa,{'Elixir.AppName.Web.CatchAll',handle,2}}, {stacktrace, [{'Elixir.Inspect.List',inspect, [[], #{'__struct__' => 'Elixir.Inspect.Opts', width => 80, ...}], []}, {'Elixir.Kernel',inspect,2,[{file,"lib/kernel.ex"},{line,1566}]}, {'Elixir.AppName.Web.CatchAll',handle,2, [{file,"lib/web/catch_all.ex"},{line,11}]}, ...
Aha.
application: logger, exited: shutdown: the logger has crashed. Which at least explains why I wasn't seeing anything in the logs: the logger application must be responsible for flushing stdout; without that the logs were building up in the stdout buffer.
So now we can find out the reason for the crash. The module it crashed in my 404 handler. But the reason doesn’t seem to make much sense. It’s saying that
inspect is undefined, at least when called with one argument, an empty list. (More precisely
Inspect.List.inspect/2; the second argument is just the default options).
This is part of the Elixir standard library, and is used to pretty-print data structures for debugging. How could it be undefined?
Here’s the line it crashed on:
Logger.warn "Unknown path: #{:cowboy_req.path(request) |> elem(0)}, params: #{:cowboy_req.qs_vals(request) |> elem(0) |> inspect}"
In this particular case there were no
qs_vals (querystring parameters). So the logic it crashed on reduces to
inspect([]) - as expected, it's just inspecting an empty list.
But
inspect definitely does work. On that same instance that was having the issue, I log some data when the application starts using
inspect, and that works fine.
Admittedly none of that data involves lists.
So I add something to app startup to just inspect and log an empty list to see what happens. And the bug disappears. Everything works fine.
I take that away again, and it starts happening again. (Sometimes, at least; it doesn’t happen on every deploy)
So at this stage it seems like this is only ever happening if the very first call to
inspect for some datatype is done from a webserver request handler process, instead of just on app startup. Which meant I could work around the problem by doing the following
Logger.debug "Some data structures: #{inspect {%{}, [], MapSet.new, 0.1, 1..2, ~r//, :a, <<1>>}}"
on app startup — inspecting and logging a simple example of every datatype I can think of — so that the first call to
inspect with an array happens immediately, instead of in a web server request handler.
This is crazy. Let’s dig a bit deeper.
In the Erlang ecosystem you can directly query whether a function with a given signature (module, function name, and arity trio) is available using
:erlang.function_exported\3, e.g.
:erlang.function_exported(Elixir.Inspect.List, :inspect, 2). That returned
false at the times when the bug happened.
And yet the
Elixir.Inspect.List.beam file, the physical file containing the compiled code for inspect, is present and correct in the slug - I downloaded the slug and checked - and as far as I could tell it seemed to have been compiled correctly.
In Erlang when running in interactive mode (which we were doing), modules are loaded on-demand as needed from the
.beam files. You can use
Code.ensure_loaded? to make sure a given module is loaded. (Note that this is not true if you're running a 'release', e.g. built using Distillery or the new Mix release feature of Elixir 1.9, which run in 'embedded mode', where all modules are preloaded up front).
When we ran
Code.ensure_loaded?(Elixir.Inspect.List) in the request handler before inspecting the list, sometimes it would return true and sometimes false. If it successfully loaded the code, subsequent
function_exported(Elixir.Inspect.List, :inspect, 2) calls would return
true, and
inspect calls would work correctly. If not,
function_exported(Elixir.Inspect.List, :inspect, 2) calls would continue to return
false, and all subsequent
inspect calls would fail (or if done by the logger, crash it).
And to be clear, this isn’t just between builds, it’s between deploys of a single build — the same slug, the same compiled artifacts.
Eventually, with assistance from José Valim and the rest of the always-wonderful Elixir community, we figured out that the code being first run from a webserver request handler was a red herring. The reason that made a difference was just because if it ran on app startup, it was running earlier.
Which led to the answer!
(spoiler: it was our fault)
First, a bit of background on how we deploy.
Our CI server compiles a slug, with everything needed to run the app, which we then copy to where where it’s needed and mount it with OverlayFS. That’s a kind of filesysem that means that when the application tries to write something to the slug, it doesn’t change the actual slug, but instead writes the changes to a separate ‘upper’ layer, that’s then overlayed on top of the lower, slug layer to produce the virtual filesystem that the application sees.
This upper directory is in
/tmp, in a directory unique to each docker container instance. This means multiple independent docker containers can share the same underlying slug at the same time, can be redeployed and start from a clean slate with no residual state, and so on.
Normally this all just works.
But. We had a maintenance script that ran shortly after a deploy completes, that among other things was cleaning up up any files in
/tmp with a last-modified time of older than 2 day ago:
if File.exists?('/tmp') logger.info 'Cleaning up temp files older than 2 days' warn 'Could not delete old temp files' unless system( 'sudo find /tmp -type f -mtime +2 -exec rm -f {} \;' ) end
Since the things in /tmp are these ‘upper directories’, this cleanup script didn’t change the actual slug. So whenever I downloaded and checked that, it was all correct. But it did mark files as ‘deleted’ in overlayfs, so they were hidden from the docker container.
The result was that any BEAM files that had not yet been loaded by the Erlang VM at the time the cleanup script ran were being marked as deleted, and so became inaccessible.
So the problem only showed up with inspect because it happened that every other file and protocol was being loaded and exercised earlier on, on app startup or by successful requests — but, as it happens, not
Inspect.List.
The fix: move the OverlayFS upper directories out of
/tmp.
def slug_volume(slug_path) # use an overlayfs mount so that the container cannot change files in the # underlying slug directory - tmp = Dir.mktmpdir("slug-") - run "sudo mount -t overlayfs \ - -o lowerdir=#{slug_path},upperdir=#{tmp} overlayfs #{tmp}" + FileUtils.mkdir_p "/slugs/mnt" + mnt = Dir.mktmpdir("slug-", "/slugs/mnt") + run "sudo mount -t overlayfs \ + -o lowerdir=#{slug_path},upperdir=#{mnt} overlayfs #{mnt}" { - host: tmp, + host: mnt, guest: "/app" } end
Ably Realtime provides a globally distributed, high-performance data stream network. It allows users to stream data anywhere, between any device, with mission-critical reliability.
Originally published at on July 30, 2019.
|
https://medium.com/ably-realtime/ably-debugging-tales-part-1-an-elixir-erlang-mystery-ably-blog-data-in-motion-d279a18a2eb
|
CC-MAIN-2020-40
|
refinedweb
| 1,478
| 64.81
|
From: Reece Dunn (msclrhd_at_[hidden])
Date: 2004-05-07 13:36:56
John Nagle wrote:
>Reece Dunn wrote:
>>John Nagle wrote:
>>
>>>Reece Dunn wrote:
>>>
>>>>There is currently a static-sized array in the Boost library that allows
>>>>you to operate on arrays of fixed size. I was wondering if something
>>>>similar exists for strings, in particular, providing buffer-overflow
>>>>safe string operations.
>>>>
>>>>I have an nstring< std::size_t n > string class that provides size-safe
>>>>copying and comparison, allowing for you to do things like:
>
>OK, thanks. First bug reports:
>
>1. Compile problems under VC++ 6:
> No include brings in "std::size_t".
Fixed.
>2. VC++ 6.x complains about references to a zero-sized array for
> [edit]: copy( const char( & s )[ m ] )
I have disabled these for VC6 since they are causing problems with the
compiler, even with Thorsten Ottersen's workaround :(.
>3. "copy" function does not place a trailing null in the string.
>[snip]
> Note that "strlen" returns a count that does NOT contain the null.
I have added this facility as a template parameter (bool null_terminate).
The logic behind this is when you do not specifically need a null-terminated
string, e.g.:
struct JPEGHeader
{
// ...
boost::string::char_string< 4 > magic;
// ...
} hdr;
if( hdr.magic != "JPEG" ) error( "invalid format" );
but also to allow it if you need that security.
> All the operations should guarantee that the string remains null
>terminated. A constructor should be provided, but all it has to
>do is put a null in the first character position.
I have already provided such a constructor :).
> As for the naming issue, the important thing for retrofit work
>is that it should be possible to write a "using" statement that makes
>"strcopy", "sprintf", for char_string etc. valid without prefixes, and
>doesn't break anything else. You should be able to include something
>("safe_strings.hpp"?) that does as much as possible to fix old code.
I have moved the char_string class into char_string.hpp and started work on
providing safe versions of ::strXXX. It is not possible to use the same
names (strlen, etc.) for the char_string versions :( as can be seen in the
example below.
#include <iostream>
#include <cstring>
namespace boost { namespace string
{
using ::strcpy;
inline char * strcpy( char * d, const char * s, size_t n )
{
return( ::strncpy( d, s, n ));
}
}}
int main()
{
char str[ 100 ];
using boost::string::strcpy;
::strcpy( str, "Meine Welt!" );
std::cout << str << '\n';
::strcpy( str, "1234567890", 5 ); // error
std::cout << str << '\n';
return( 0 );
}
Because of this, I have decided to use the c prefix (e.g. cstrlen). This
seems the best solution, but if the c prefix is problematic, let me know and
I'll change it.
>This is a good start, and not hard to fix. I look forward to the
>next round.
I have included this round as attachments, but will place the next version
in the boost sandbox. It has the signature:
template< size_t n, bool null_terminate = true, typename CharT = char,
class StringPolicy = std::char_traits< CharT > >
class boost::string::char_string;
and is the initial move towards a basic_string-like interface. How about the
name fixed_string?
|
https://lists.boost.org/Archives/boost/2004/05/65191.php
|
CC-MAIN-2021-49
|
refinedweb
| 514
| 73.07
|
One.
In case you need a quick answer and don’t have time to read through the entire article, here’s a small TL;DR:
-.
- Watchers: These are allowing you a peek into the reactivity system. We’re offered some hooks with which to observe any properties that are stored by Vue. If we want to add a bit of functionality each time something changes, or respond to a particular change, we could watch a property and apply some logic. This means that the name of the watcher has to match what we’re trying to observe.
If any of this sounds confusing, don’t worry! We’ll dive in further below and hopefully address any confusion. If you’re familiar with vanilla JavaScript already, methods may be pretty obvious to you, aside from one or two caveats. It might then behoove you (I love that phrase) to skip to the Computed and Watchers sections.
MethodsMethods
Methods are likely something you’re going to use a lot while working with Vue. They’re aptly named as, in essence, we’re hanging a function off of an object. They’re incredibly useful for connecting functionality to directives for events, or even just creating a small bit of logic to be reused like any other function. You can call a method within another method, for example. You can also call a method inside a lifecycle hook. They’re very versatile.
Here’s a simple demo to demonstrate:
See the Pen Slim example of methods by Sarah Drasner (@sdras) on CodePen.
<code class="language-css"><div id="app"> <button @Try Me</button> <p>{{ message }}</p> </div>
new Vue({ el: '#app', data() { return { message: null } }, methods: { tryme() { this.message = Date() } } })
We could have also executed the logic in the directive itself like
<button @Try Me</button>, which works very well for this small example. However, as the complexity of our application grows, it’s more common to do as we see above to break it out to keep it legible. There’s also a limit to the logic that Vue will allow you to express in a directive—for instance, expressions are allowed but statements are not.
You may notice that we’re be able to access this method within that component or Vue instance, and we can call any piece of our data here, in this case,
this.message. You don’t have to call a method like you’d call a function within a directive. For example,
@click=”methodName()” is unnecessary. You can reference it with
@click=”methodName”, unless you need to pass a parameter, such as
@click=”methodName(param)”.
Using directives to call methods is also nice because we have some existing modifiers. One such example that’s very useful is
.prevent, which will keep a submit event from reloading the page, used like this:
<form v-on:submit.</form>
There are many more, here are just a few.
ComputedComputed
Computed properties are very valuable for manipulating data that already exists. Anytime you’re building something where you need to sort through a large group of data and you don’t want to rerun those calculations on every keystroke, think about using a computed value.
Some good candidates include, but are not limited to:
- Updating a large amount of information while a user is typing, such as filtering a list
- Gathering information from your Vuex store
- Form validation
- Data visualizations that change depending on what the user needs to see
Computed properties are a vital part of Vue to understand..
Computed properties aren’t used like methods, though at first, they might look similar- you’re stating some logic in a function and returning- but the name of that function becomes a property that you’d then use in your application like
data.
If we needed to filter this big list of names of heroes based on what the user was typing, here’s how we would do it. We’re keeping this really simple so you can get the base concepts down. Originally our list would output in our template using
names, which we store in
data:
new Vue({ el: '#app', data() { return { names: [ 'Evan You', 'John Lindquist', 'Jen Looper', 'Miriam Suzanne', ... ] } } })
<div id="app"> <h1>Heroes</h1> <ul> <li v- {{ name }} </li> </ul> </div>
Now let’s create a filter for those names. We’ll start by creating an input with
v-model that will originally be an empty string, but we’ll eventually use to match and filter through our list. We’ll call this property
findName and you can see it referenced both on the input and in the
data.
<label for="filtername">Find your hero:</label> <input v-
data() { return { findName: '', names: [ 'Evan You', 'John Lindquist', ... ] } }
Now, we can create the computed property that will filter all of the names based on what the user has typed into the input, so anything in our
findName property. You’ll note that I’m using regex here to make sure that mismatched capitalization doesn’t matter, as users will typically not capitalize as they type.
computed: { filteredNames() { let filter = new RegExp(this.findName, 'i') return this.names.filter(el => el.match(filter)) } }
And now we’ll update what we’re using in the template to output from this:
<ul> <li v- {{ name }} </li> </ul>
…to this:
<ul> <li v- {{ name }} </li> </ul>
And it filters for us on every keystroke! We only had to add a couple of lines of code to make this work, and didn’t have to load any additional libraries.
See the Pen Filter a list with Computed- end by Sarah Drasner (@sdras) on CodePen.
I can’t tell you how much time I save by using them. If you’re using Vue and haven’t explored them yet, please do, you’ll thank yourself.
WatchersWatchers
Vue has nice abstractions, and anyone who has been a programmer for a while will usually tell you that abstractions can be a pain because you’ll eventually get to a use case they can’t solve. However, this situation is accounted for, because Vue grants us some deeper access to into the reactivity system, which we can leverage as hooks to observe anything that’s changing. This can be incredibly useful because, as application developers, most of what we’re responsible for are things that change.
Watchers also allow us to write much more declarative code. You’re no longer tracking everything yourself. Vue is already doing it under the hood, so you can also have access to changes made to any properties it’s tracking, in
data,
computed, or
props, for example.
Watchers are incredibly good for executing logic that applies to something else when a change on a property occurs (I first heard this way of putting it from Chris Fritz, but he says he might have also heard it from someone else ☺️). This isn’t a hard rule- you can absolutely use watchers for logic that refers to the property itself, but it’s a nice way of looking at how watchers are immediately different from computed properties, where the change will be in reference to the property we intend to use.
Let’s run through the most simple example possible so you get a taste of what’s happening here.
new Vue({ el: '#app', data() { return { counter: 0 } }, watch: { counter() { console.log('The counter has changed!') } } })
As you can see in the code above, we’re storing
counter in
data, and by using the name of the property as the function name, we’re able to watch it. When we reference that
counter in
watch, we can observe any change to that property.
Transitioning State With WatchersTransitioning State With Watchers
If the state is similar enough, you can even simply transition the state with watchers. Here’s an example I built from scratch of a chart with Vue. As the data changes, the watchers will update it and simply transition between them.
SVG is also good for a task like this because it’s built with math.
See the Pen Chart made with Vue, Transitioning State by Sarah Drasner (@sdras) on CodePen.
watch: { selected: function(newValue, oldValue) { var tweenedData = {} var update = function () { let obj = Object.values(tweenedData); obj.pop(); this.targetVal = obj; } var tweenSourceData = { onUpdate: update, onUpdateScope: this } for (let i = 0; i < oldValue.length; i++) { let key = i.toString() tweenedData[key] = oldValue[i] tweenSourceData[key] = newValue[i] } TweenMax.to(tweenedData, 1, tweenSourceData) } }
What happened here?
- First we created a dummy object that will get updated by our animation library.
- Then we have an
updatefunction that is invoked on each tween step. We use this to push the data.
- Then we create an object to hold the source data to be tweened and the function pointer for update events.
- We create a for loop, and turn the current index into a string
- Then we can tween over the our target dummy object, but we’ll only do this for the specific key
We could also use animation in watchers to create something like this time difference dial. I travel a bit and all my coworkers are in different areas, so I wanted a way to track what local time we were all in, as well as some signification of the change from daytime/nighttime as well.
See the Pen Vue Time Comparison by Sarah Drasner (@sdras) on CodePen.
Here we’re watching the checked property, and we’ll fire different methods that contain timeline animations that change the hue and saturation and some other elements based on the relative association to the current time. As mentioned earlier- the change occurs on the dropdown, but what we’re executing is logic that’s applied elsewhere.
watch: { checked() { let period = this.timeVal.slice(-2), hr = this.timeVal.slice(0, this.timeVal.indexOf(':')); const dayhr = 12, rpos = 115, rneg = -118; if ((period === 'AM' && hr != 12) || (period === 'PM' && hr == 12)) { this.spin(`${rneg - (rneg / dayhr) * hr}`) this.animTime(1 - hr / dayhr, period) } else { this.spin(`${(rpos / dayhr) * hr}`) this.animTime(hr / dayhr, period) } } },
There are also a number of other interesting things about watchers, for instance: we’re given access to both the new and old versions of the property as parameters, we can specify
deep if we’d like to watch a nested object. For more detailed information, there’s a lot of good information in the guide.
You can see how watchers can be incredibly useful for anything that’s updating—be it form inputs, asynchronous updates, or animations. If you’re curious how reactivity in Vue works, this part of the guide is really helpful. If you’d like to know more about reactivity in general, I really enjoyed Andre Staltz’ post and the Reactivity section of Mike Bostock’s A Better Way to Code.
Wrapping UpWrapping Up
I hope this was a helpful breakdown on how to use each, and speeds up your application development process by using Vue efficiently. There’s a stat out there that we spend 70% of our time as programmers reading code and 30% writing it. Personally, I love that, as a maintainer, I can look at a codebase I’ve never seen before and know immediately what the author has intended by the distinction made from
methods,
computed, and
watchers.
Watchers! Holy crap.
Is there any concern with side effects? I can imagine instances where things are changing and nobody is quite sure why because the logic might not be in the same place as the property. But perhaps if the code is written well, it’s easy enough to just check for a watcher of the same name.
Great post! I am going to use this directly.
What was the safari bug that you targeted ‘padding:30px’ in your scss file on the location timer code pen?
Very clear presentation, easy to understand. thanks!
It’s a good ides to keep data, props and computed pros in different namespaces. We prepend props with
pr, computed props with
co, data has no prefix.
This way, you know exactly where to look in your component when you see one of those names used in a template or method. The bigger and more complex a component, the more this comes in handy.
|
https://css-tricks.com/methods-computed-and-watchers-in-vue-js/
|
CC-MAIN-2021-10
|
refinedweb
| 2,043
| 61.46
|
In this problem, Farmer John is mowing grass on a grid. He wants to figure out the largest period of time that exists such that Farmer John never mows the same square of grass twice within that amount of time.
Farmer John will mow at most one thousand squares of grass, so we can just keep track of the last point in time when Farmer John mowed the grass in a given square. We can store these times in a large two-dimensional array. As an implementation detail, because arrays do not support negative coordinates, we can pretend that Farmer John starts at the point (1000, 1000) and then simulate the mowing directly.
Here is my code demonstrating this.
import java.io.*; import java.util.*; public class mowing { public static void main(String[] args) throws IOException { // initialize file I/O BufferedReader br = new BufferedReader(new FileReader("mowing.in")); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("mowing.out"))); /* * Create a two-dimensional array where lastTime[i][j] stores the last time * that Farmer John visited point (i, j). If Farmer John has never visited that * point, then lastTime[i][j] == -1. */ int[][] lastTime = new int[2001][2001]; for(int i = 0; i < lastTime.length; i++) { for(int j = 0; j < lastTime[i].length; j++) { lastTime[i][j] = -1; } } // (currX, currY) is the point that Farmer John is currently at. int currX = 1000; int currY = 1000; lastTime[currX][currY] = 0; int currentTime = 0; // the longest period of time cannot exceed 1000, so if it is still 1001, he never visits the same square twice. int answer = 100 * 10 + 1; // read in N int n = Integer.parseInt(br.readLine()); for(int i = 0; i < n; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); // read in the direction that Farmer John goes in String direction = st.nextToken(); int dirX = 0; int dirY = 0; if(direction.equals("N")) { dirX = -1; } else if(direction.equals("S")) { dirX = 1; } else if(direction.equals("W")) { dirY = -1; } else { dirY = 1; } // read in the number of steps he travels int numSteps = Integer.parseInt(st.nextToken()); // travel that many steps for(int j = 1; j <= numSteps; j++) { currX += dirX; currY += dirY; currentTime++; // check if Farmer John has visited that square before, and the amount of time that has elapsed since then if valid if(lastTime[currX][currY] >= 0 && currentTime - lastTime[currX][currY] < answer) { answer = currentTime - lastTime[currX][currY]; } lastTime[currX][currY] = currentTime; } } // check if he has never visited the same square twice if(answer == 1001) { answer = -1; } // print the answer pw.println(answer); // close file I/O pw.close(); } }
|
http://usaco.org/current/data/sol_mowing_bronze_jan16.html
|
CC-MAIN-2018-17
|
refinedweb
| 429
| 63.7
|
The server runs a program (game of life) which has a
board with cells (bits). After a fixed number
of iterations, the simulation stops and the program jumps to the first bit of the memory containing the board. We want to create an input which contains shellcode in this area after
iterations. Obviously, we could choose any shellcode, and run game of life backwards. Cool, let us do that then! Uh-oh, inverting game of life is in fact a very hard problem… so it is not really feasible 😦
What to do, then?
Game of life
Game of life a cellular automata, found by Jon Conway, and is based on the following rules:
- A cell is born if it has exactly 3 neighbours. Neighbors are defined as adjacent cells in vertical, horistontal and diagonal.
- A cell dies if it has less than two or more than three neighbors.
Stable code (still life)
Still life consists of cell structures with repeating cycles having period 1. Here are the building blocks I used to craft the shellcode.
Of course, the still life is invariant of rotation and mirroring.
Shellcode
So, I tried to find the shortest shellcode that would fit one line (110 bits). This one is 8 bytes. Great.
08048334 <main>: 8048334: 99 cltd 8048335: 6a 0b push $0xb 8048337: 58 pop %eax 8048338: 60 pusha 8048339: 59 pop %ecx 804833a: cd 80 int $0x80
In binary, this translates to:
000001101001100101101010000010110101100001100000010110011100110110000000
Ok, so we note that
110101 ... 01110
cannot be constructed by our building blocks (there most certainly exist such blocks, but I didn’t consider them). So, I use a padding trick. By inserting an operation which does nothing specific
10110011 00000000 mov bl,0x0
we are able to use the blocks given in previous section. This Python code gives the binary (still-life-solvable) sequence:
from pwn import * pad = '\xb3\x00' shellcode = '\x06\x99' + pad + '\x6a\x0b\x58\x60\x59' + pad + '\xcd\x80' binary_data = ''.join([bin(ord(opcode))[2:].zfill(8) for opcode in shellcode]) context(arch = 'i386', os = 'linux') print disasm(shellcode) print binary_data[0:110]
which is
0000011010011001101100110000000001101010000010110101100001100000010110011100110110000000
The following cellular automata is stable, and the first line contains our exploit:
As can be seen in the animation below, we have found a still-life shellcode.
When feeding it to the program, we find that it remains in memory after any number of iterations:
Nice! Unfortunately, the code did not give me a shell, but at least the intended code was executed. I had a lot of fun progressing this far 🙂
|
https://grocid.net/2016/05/22/defcon-ctf-b3s23-partial/
|
CC-MAIN-2017-17
|
refinedweb
| 424
| 70.73
|
Download SATSAGEN 0.5 and latest versions from this page:
SATSAGEN Download Page
Highlights:
- Works with:
- ADALM-PLUTO
- HackRF One
- RTL-SDR Dongles
- Simple Spectrum Analyzer series like D6 JTGP-1033, Simple Spectrum Analyzer, and so on.
- Video trigger, real-time trigger, and fast-cycle feature
- ADALM-PLUTO custom gain table and Extended linearization table for all devices
- Transmit from raw format files
- I/Q balance panel
- Waterfall
- RX/TX converter offset
- Video Filter average option
- Keyboard or mouse wheel moving markers
- Status Display
- The X-Axis CT and SU indicators
Choose the device
In Settings->Devices select the device model from the Model list control.
If one or more type model selected devices are present, these will be proposed in the below Device list.
If you connect a device at this time, press the Scan button to refresh the Device list control.
In a multi-device scenario, different RX and TX device model is allowed, with the one exception that the RTL-SDR device obviously can’t act as a TX device.
Video trigger, real-time trigger, and fast-cycle feature
The Video trigger shows the spectrum graph when a signal of the minimum selected level occurs.
This is a random 4ms pulse caught by the Video trigger set at level 18. The Video level trigger is referred directly to the ADC depth value of the RX device.
The Line and Ext are real-time triggers, these start the acquisition when an external digital event occurs. With the knob select what type of digital event desire from Low, High, Chg, Neg, and Pos options.
- Low type starts the acquisition when the digital input is in a low state.
- High type starts the acquisition when the digital input in a high state.
- Chg type starts the acquisition when the digital input changes state.
- Neg type starts the acquisition at the falling edge of the input.
- Pos type starts the acquisition at the raising edge of the input.
Simple external hardware is required for the real-time triggers feature.
If a Generic serial is selected on the Trigger IN device control of Settings->EXT OUT tab, the Line trigger is mapped to DCD input of the serial specified by COM port control, and the Ext trigger is mapped to RI input of that serial COM port.
If a USB D/A albfer.com is selected on the Trigger IN device control of Settings->EXT OUT tab, the interface described on this page with FW version 2.0 can be used as a real-time input interface. The digital inputs are mapped like the above Generic serial on the USB D/A albfer.com interface, but an added feature of analog inputs can be used: the Line trigger is mapped to A0 input and the Ext trigger is mapped to A1 input. To enable this feature, click on the type title below the knob when a Line or Ext triggers are selected.
Now with the knob selects the analog level where the trigger starts the acquisition, with RE (rising edge) level or FE (falling edge) level.
To use the real-time trigger is required the Fast-Cycle set to on and the Optimize buffer size for real-time sampling checked (see on RX device controls on Settings->Devices tab).
The Line and Ext labels could be red blinking if the trigger fails to respond at the events in time.
Fast-Cycle
The Cycle-Time of the acquisitions (or Sweep-Time depending on the model of the RX device) is automatically tuned by the application to minimize CPU load according to sampling rate and FFT size selected by the user.
If the Fast-Cycle feature is turned on, the Cycle-time is fixed to the maximum speed of acquisition.
More speed performance (but with more CPU load) can be reached by selecting the SA uses CPU timestamp-based timer feature located in the Settings->Extra tab.
ADALM-PLUTO custom gain table
The ADALM-PLUTO standard gain table is optimized by ADI for the best RX noise factor in the whole range of frequencies. Unfortunately, the standard gain table doesn’t work as expected for spectrum analyzer operations because of the non-linear gain of LNA and for the table that is divided into three different ranges of frequencies.
This is what happens with the standard gain table after calibration and moving from 30dB of RX gain to 31dB.
A flat frequency custom gain table is provided with the SATSAGEN distribution, it is located on the program directory as ad9361_CGT.
Add these lines to the RX linearization INI file to load the custom gain table on Pluto at the power on:
[settings\device_0] PathNameCustomGainTable=ad9361_CGT
An extended RX linearization file is required to mitigate the non-linear gain of LNA in any case.
An extended RX linearization file model with the load of the custom gain table is provided on the program directory as curvecorrRX_PLUTOCGT.ini.
More information about compiling the extended RX linearization files will be published soon.
The standard gain table will be reloaded on the Pluto device at the power off of SATSAGEN to ensure the operation of other applications.
Transmit from raw format files
Open the EXT modulation panel from the menu or the EXTMOD Panel button of the Toolbar.
An only the RAW file is accepted. Specify in Format list the format to use to play the file and the sample rate according to the TX device selected capability.
If the Loop control is checked, the file will be transmitted endlessly until the stop command by the user.
The Offset DC value can be an aid to minimize the LO image residual component. Set initially to zero, check the control Apply changes to running thread and start TX streaming. During the reproduction, change the Offset DC value with the knob control until the LO image component reaches the lower position.
To start TX streaming of the file specified above, select the EXT modulation on the Generator panel and start the Generator.
The EXT label is red blinking when the thread is streaming.
I/Q balance panel
Open the I/Q balance panel with the context menu:
The Device I/Q balance panel is a tool useful to manually improve the quadrature of the RX/TX signal, especially when devices like RTL-SDR or HackRf are used.
This is the LO component of the RTL-SDR dongle before the I/Q balanced is applied.
After the right I/Q balanced is applied, the LO component is almost at -80dBm.
The values of I/Q balance will be saved on devices configuration and automatically restored when the devices are connected and used.
Waterfall
When the Spectrum Analyzer is running, open the Waterfall with the context menu or the Waterfall button on the new tool panel opened by the panels button.
The Min and Max controls adjust the contrast of the Waterfall according to the signal level.
Click to Info button to adding the frequency and the time information.
RX/TX converter offset
If your SDR device has a converter, it could be useful setting an offset in SATSAGEN to have a matching frequency scale and input field.
Two fields in the Settings->Devices tab can be used to specify converters offset, Converter RX and Converter TX:
When a down-converter like an LNB is connected to the RX port, it should set the Converter RX field with the LO converter’s exact frequency with a minus sign. E.g., for a converter like LNB should be -9750000 kHz.
The rule for both fields is a minus value for a down-converter and a plus value for an up-converter.
Video Filter average option
The video filter normally operates to displays each measurement’s max value for the number of times chosen by the user. To switch to the averaging video filter, click on the little Led/button VF avg over the Video filter knob control.
Keyboard or mouse wheel moving markers
After a marker is placed, it can be moved by the mouse’s wheel or by the two keys J and K. This features works either in SA and TSA operations, but to activate it should be clicking on the window scope, and the marker to move should be active firstly.
A marker was placed.
The above marker after pressing the J key three times.
The same marker after pressing the K key six times.
Status Display
The status display shows some peculiar information about the active RX and TX devices. To activate this feature, click on the Status display from the context menu. For each device are displayed the type model, the attenuator value, and the converter offset value.
The X-Axis CT and SU indicators
The CT indicator shows the Cycle Time of the SA. The Cycle Time includes the sampling time, the frequency switch time if the SA is in the swept-tuned mode, the Data computation and formatting time, and finally the display update time. For the SSA devices like the Simple Spectrum Analyzer, the CT is replaced by the Sweep-Time indicator.
The SU indicator shows the percentage of use of the stream from the SDR device. In the image example above, 7,43% of the sampling stream is used to display the spectrum.
55 thoughts on “SATSAGEN 0.5”
Hello !
What is the config for HackRF. (With ZADIG you can recognize the RF One. But no display
Hello Franz,
The config to using the HackRF should be simply select the HACKRF ONE model on the Settings->Devices tab:
Let me know
73, Alberto
Nice job! You should consider supporting Linux! Wine is not really an option…
Many thanks!
This is really good news! Though I’m now wondering whether you have any plans to support the LimeSDR in future as well?
Best regards
Hi,
Yes, I started developing LimeSDR support, but I need to buy the hardware to continue and carry out the tests.
Thank you!
Best Regards
Alberto
Hi Alberto
Did you get any further with support for the LimeSDR?
Cheers
John
Hi John,
Thank you for being so interested. I’m still working to obtain the hardware. Stay tuned.
Cheers
Alberto
Support Rtl_tcp or spyserver in future as well?
Yes, I hope in the next release.
Thank you!
Quella scheda! Indovino che e’ una scheda per Apple per un floppy di 8 polici??
Risate, avevo uno anche io!! Wirewrap!
Hi Peter!
Yes, what nostalgia!
I borrowed the card from a friend of mine in the ’80, and I had wirewrap cloned it!
I used it with this drive that I still own:
Cheers
Alberto
Hello, Alberto.
Thank you for great software!
Maybe you will think about adding LimeSdr support? It will be great alternative for HackRf.
Best Regards, Sergii.
Hi Sergii!
Thank you for your comment!
I started developing the LimeSDR support, but I need to buy that hardware to continue.
Best Regards
Alberto
Really nice work,
Will SDRPlay RSP1 be supported ?
Best regards
Lasse
Hi Lasse,
I would like to support it, but I would need the hardware to make the linearization data and tests.
Regards
Alberto
Hi Alberto,
The MSI.SDR 12bit are quite cheap.
Anyway, a really nice work you done.
Regards
Lasse // SM6WHY
Yeah! Good info, Lasse!
Thank you!
Cheers
Alberto
Ciao Alberto
Very fine job with SATSAGEN 0.5. Thank you.
A feature request: On the Spectrum Analyser I use the ‘hold’ feature to capture a short burst of transmission. Would it be possible to allow markers to be placed on the hold trace as well as the ‘active’ trace? This would be helpful in recording the results.
Thanks
Bob
MM0MMQ
Hi Bob!
You talk about the max-hold trace, I think. Yes, placing markers on the max-hold trace could be useful. I’ll try to insert this feature in the next release.
Thank you so much!
Regards
Alberto
Grazie Alberto,
ottimo lavoro.
Nicola
Grazie mille Nicola!
Ciao
Getting this error. How to solve it?
14/02/2021 07:38:17 *** Power ON, please wait… ***
14/02/2021 07:38:17 Connecting to RTL SDR id 0
14/02/2021 07:38:18 Successfull connection to RTL SDR id 0
14/02/2021 07:38:18 Default device TX correction curve set due to a empty INI file for selected device(C:\Program Files (x86)\albfer.com\SATSAGEN\CurveCorrTX.ini)
14/02/2021 07:39:25 Failed
Hi!
Try to change the USB port. I noticed incompatibility with USB 3.1 ports.
Thank you!
Regards
Alberto
Hi Alberto,
Congratulation for this nice work.
Unfortunately the Terratec sdr Stick ( Elonics E4000 / RTL2832U) doesnt work (not detected) but it work very well on the last release of Airspy (SDR#)
The other stick R820T2 is well reconized and work fine.
Is there something extra to do for the first one ?
73
Jeff, F5BCB
Hi Jeff!
Thank you so much for reporting!
I’ll try to fix the Terratec dongle you noticed SATSAGEN does not detect that.
See you soon
73, Alberto
Hi Alberto,
Here is the response to rtl_test tool for my Terratec E4000 stick.
Frequency coverage is very large (52 to 2193 MHz) but there is some gaps.
73, Jeff, F5BCB
pi@r2cloud:~ $ rtl_test -t
Found 1 device(s):
0: Realtek, RTL2838UHIDIR, SN: 00000001
Using device 0: Terratec Cinergy T Stick RC (Rev.3) 2194000000 Hz!
[E4K] PLL not locked for 1097000000 Hz!
[E4K] PLL not locked for 1241000000 Hz!
E4K range: 52 to 2193 MHz
E4K L-band gap: 1097 to 1241 MHz
pi@r2cloud:~ $
Hi Jeff,
Thank you again for the useful information!
73, Alberto
Bonjour Alberto, savez-vous si un utilisateur du pluto+ a fait un descriptif de cette solution ?
Ciao Alberto, sai se un utente pluto + ha descritto questa soluzione?
Cordialement Jean-Luc F1GPA
Bonjour Jean-Luc,
Purtroppo no, spero che si possa fare una recensione a breve, mi sembra un prodotto interessante.
Grazie
73, Alberto
Hi Alberto,
do You plan to support Funcube Dongle for Satsagen software?
Vy 73
Werner DK1KW
Hi Werner,
Unfortunately, I don’t own a Funcube dongle. Maybe more important thing, I don’t found an API to control this device.
Thank you anyway for your suggestion!
73, Alberto
Hi, amazing tool..
I have an ‘idea’.
I am using a spectrum analyzer by R&S (FS300) without tracking source.
Do You think, it’s possible, to sync the SATSAGEN with the FS300 . to use the SATSAGEN as tracking source?
ehm, using the pluto
the fs300 has possibility for extern Trigger Sgnals. so , it would be ok, if at start of a new sweep of satsagen as tracking source, to get impulse from -for example- the output (tx) from comport , to trigger the fs300..
Hi Jens,
You can try it. From the Settings->EXT OUT tab, select the COM Port you want to use. From the Sync Out mode list select Start only. Pulses will be generated on the RTS line every start sweep of TSA or Sweeper Satsagen operations.
WARNING: Connect the serial RTS line to the external trigger signals port of your device only through a voltage translator interface; otherwise, there is a risk of damaging your device!
Alternatively, Satsagen can generate an analog sweep output. Set Sweep Out device on USB D/A albfer.com and connect this device:
73, Alberto
Thank You ! Great, I will try & report.
I will share this thread in the satsagen mailing list.
Thank You fur the hint with voltage levels..
I am for work ‘Industrieelektroniker’ and working at a small company 5 minutes away from home (by feet) in the test-field or the department, which is building testequipment for our production lines . so, working with ‘levels’ is daily business 🙂
()
kind regards &73 stay healthy!
Jens DL1LEP
Its really so usefull program, well done !
I have try it with a cheap RTL stick and also a usb RTL (starts from 100Khz).
Is it possible to go under 24 Mhz ?
Kind Regards&73
John (SY1BJV)
Hi John!
Thank you so much for your comment!
I’m sorry, the direct sampling on the RTL dongle is not supported yet.
We can start from 100kHz with HackRf or RSP1A/RSP1 devices for now.
73, Alberto
Great 🙂 I will try the HackRF.
i just got the HackRF One with portapack .
Hello Alberto,
It’s an amazing job. Thank you.
Do you have a plan to support the direct sampling on the RTL dongle or not?
(I have a HackRF, and rtl-sdr dongle. They work both amazing for filter test above 24Mhz. I need to test HF ones :)))
Hello Orkun,
Not yet. I would like to do it. I hope in the next version.
In the meantime, you could use an MSi SDR as an RX device if you have one of them.
Regards
Alberto
Hello Alberto,
Can I use upconverter with rtl-sdr dongle to reach the lower frequencies? By adjusting the converter RX parameter?
Thank you
73
Hi!
The upconverters for RTL-SDR, like a 125MHz LO model, can be used from SATSAGEN version 0.6.0.4, adjusting the Converter RX field to 125000 kHz from Settings->Devices tab.
Thank you!
73’s Alberto
Hi Alberto,
tried to connect my Newgen.RTL2832 SDR but it is not found by the scan function.
It works well with e.g. SpectrumLab and HDSDR software. Do I have to install a different driver?
Vy 73
Werner DK1KW
Hi Werner,
Thank you for reporting.
I’m sorry. I don’t think that driver updating solves this issue.
I’ll try to check this with a similar dongle. I’ll keep you update.
73, Alberto
Hi Alberto,
renewed the driver and now, the grid shows up on satsagen. When I start Spectrum Analyzer, I get this:
15.04.2021 18:02:35 *** Power ON, please wait… ***
15.04.2021 18:02:35 Connecting to RTL SDR id 0
15.04.2021 18:02:35 Successfull connection to RTL SDR id 0
15.04.2021 18:02:35 Default device TX correction curve set due to a empty INI file for selected device(C:\Program Files (x86)\albfer.com\SATSAGEN\CurveCorrTX.ini)
15.04.2021 18:03:01 >>>> standardSATimer return (-1)
Alberto,
sri to bother you. It works, obviously my USB port was too weak for the stick. After using one of a active hub NEWGEN works with Satsagen.
Many thanks for Your help.
Vy 73
Werner DK1KW
Great! Thank you for reporting your experience!
73, Alberto
Dear Alberto,
I’m in the early phase of using Satsagen for a variety of HAM Radio messurements.
I would like to messure the decoupling of an high power coax relais for EME use (> 70 better > 80 dB).
If my recollection is right I saw a discussion “how to use 2 Plutos …” to extend the measuring depth – but can’t find it anymore.
Can Satsagen do this job and does a “how to … guide” exist ?
Thank you very much !
Kind Regards,
Wolf
Hi Wolf,
There are some basics about dual device operations in this post:
Thank you!
Best Regards,
Alberto
Hello Alberto,
I was very happy when I found this software. Thanks so much for your hard work. Thanks to you, I can make my own filters 🙂
Would you consider adding support for the Ettus B200 in the future?
Kindly Regards
Zeki
Hi Zeki!
Thank you so much for your comment!
The Ettus B200 seems to be a great object. I hope to able to buy and support it in the future! Thank you for the tip!
Cheers
Alberto
hello, I can start the spectrum analyzer, but I can not power up the spectrum analyzer w/tracking or the generator function, any help is appreciated, ZI am new to this and trying my hardest to learn its operation.
thanks Hal . .
Hi!
Maybe your device is not able to transmit. Devices like ADALM-PLUTO are required to run spectrum analyzer/tracking or generator operations.
Cheers
Alberto
|
http://www.albfer.com/en/2021/01/31/satsagen-0-5/
|
CC-MAIN-2022-21
|
refinedweb
| 3,324
| 65.52
|
django-trix 0.3.0
Trix rich text editor widget for Django
Trix rich text editor widget for Django, using Trix 0.10.1.
Using django-trix
django-trix includes a form widget, a model field, and a model admin mixin that enables the rich text editor. You can use any of these methods, but you do not need to use all.
Model
To enable the editor in the Django admin (or any form) via the model field, use the Trix model field TrixField which inherits from django.db.models.TextField:
from django.db import models from trix.fields import TrixField class Post(models.Model): content = TrixField('Content')
- Author: Jeremy Carbaugh
- License: BSD
- Platform: any
- Categories
- Package Index Owner: jcarbaugh, isl
- DOAP record: django-trix-0.3.0.xml
|
https://pypi.python.org/pypi/django-trix/0.3.0
|
CC-MAIN-2017-30
|
refinedweb
| 129
| 57.67
|
02 November 2009 21:48 [Source: ICIS news]
HOUSTON (ICIS news)--Ethanol sales in Iowa are on track to be lower in 2009 than they were in 2008, a troubling trend for a state that is considered the heart of the US ethanol industry, sources said on Monday.
The Iowa Renewable Fuels Association (IRFA) said for the first nine months of the year, ethanol accounted for 7.3% of all fuel sold at gasoline pumps in the midwestern, corn-producing state. That was down from 7.5% in all of 2008. September ethanol sales represented 7.1% of the fuel sold at gas stands.
IRFA spokesman Monte Shaw said there were no obvious reasons for the decline, calling it “puzzling".
"In 2006, Iowa was one of the nation’s leaders in ethanol sales," Shaw said. "Today, Iowa does not lead. Iowa is not average. Iowa is below average."
Shaw said no plan was in place to reverse the trend, but added that the IRFA would work with state lawmakers to discuss their options.
“These disappointing statistics should force a complete reexamination of how Iowa intends to move forward to be a leader in the use of ethanol, not just the production,” Shaw said.
Iowa has 40 ethanol refineries with an aggregate production potential of nearly 3.3bn gal/year, about a quarter of total US capacity, according to statistics from the IRFA and the national Renewable Fuels Association (RFA).
Ethanol refiners in the state also said they could not figure out what led to the statewide decline.
“Prices are favorable for blending. The margins are favorable for the plants to run. Just for me, looking at it, it doesn’t make much logical sense,”said Mark Heckman, commodity manager at the Big River Resources refinery in ?xml:namespace>
In contrast with Iowa’s general sales stumble, overall US ethanol demand has grown throughout 2009. Average monthly ethanol sales for the first seven months of 2009 were 862m gal, up from 747m gal in the preceding year, according to the RFA statistics.
The rise in national ethanol consumption in the US comes despite the recession causing year-on-year gasoline sales to fall 12% for the first seven months of 2009.
Instead, Iowa’s problem could lie with its insistence on tax credits to promote the biofuel instead of mandates requiring its use, RFA spokesman Matt Hartwig said.
“I don’t see this as a national trend,” Hartwig said. “You cannot extrapolate the Iowa experience to the rest of the country, as we continue to see ethanol use increase.”
Doris de Guzman examines alternative processing, new technology, R&D and other sustainability initiatives in Green Chemistry
For more information
|
http://www.icis.com/Articles/2009/11/02/9260280/ethanol-sales-slump-in-us-ethanol-heartland.html
|
CC-MAIN-2014-52
|
refinedweb
| 448
| 63.8
|
Both the Arduino IDE and Web Editor come with a servo library that we can use simply by including the header file. The following code will do this:
#include <Servo.h>
Next, we need to define the pin that the servo motor and the potentiometer are connected to. The following code will connect the signal wire to the digital 3 pin and the potentiometer to the analog 0 pin on the Arduino:
#define SERVO0_POT 0 #define SERVO0_OUT 3
Now we need to define an instance of the Servo type as shown in the following line:
Servo servo0;
Within the setup function, we need to call the attach() method from the servo instance to initialize the instance and to tell it what pin the servo is attached to. The following code shows this:
void setup() { servo0.attach(SERVO0_OUT); ...
|
https://www.oreilly.com/library/view/mastering-arduino/9781788830584/879c1a00-5a63-44da-8567-75970a460472.xhtml
|
CC-MAIN-2019-35
|
refinedweb
| 137
| 61.19
|
. Understanding the indexing operation
- 3. Creating an index
- 4. Basic index operations
- 5. Documents & fields
1. Introduction
The Index is the heart of any component that utilizes Lucene. Much like the index of a book, it organizes all the data so that it is quickly accessible. An index consists of Documents containing one or more Fields. Documents and Fields can represent whatever we choose but a common metaphor is that Documents represent entries in a database table and Fields are akin to the fields in the table.
2. Understanding the indexing operation
Let’s look at the diagrammatic representation of Lucene search indexing.
In a nutshell, when Lucene indexes a document it breaks it down into a number of terms. It then stores the terms in an index file where each term is associated with the documents that contain it. We could think of it a bit as a hashtable. Terms are generated using an analyzer which stems each word to its root form. When a query is issued, it is processed through the same analyzer that was used to build the index and then used to look up the matching term(s) in the index. That provides a list of documents that match the query.
Now lets take a look at the overall Lucene searching process.
The fundamental concepts are index, document, field and term.
- An index contains a collection of documents.
- A document is a collection of fields.
- A field is a collection of terms.
- A term is a paired string<field,term-string>.
2.1.
2.2.
2.3.
2.4.
2.5 Search Index
Search indexes are defined by a javascript function. This is run over all of your documents, in a similar manner to a view’s map function, and defines the fields that your search can query. Search index is a variant of database. It is similar with RDBMS as it needs to have a fast lookup for keys, but the bulk of the data resides on a secondary storage.
3. Creating an index
So far we have seen all the components of Lucene indexing. In this section we will create an index of documents using Lucene indexing.
Consider a project where students are submitting their yearly magazine articles. The input console consists of options for student name, title of the article, category of the article and the body of article. We are assuming that this project is running in the web & can be accessible through it. To index this article we will need the article itself, the name of the author, the date it was written, the topic of the article, the title of the article, and the URL where the file is located. With that information we can build a program that can properly index the article to make it easy to find.
Let’s look at the basic framework of our class including all the imports we will need.; public class ArticleIndexer { }
The first thing we will need to add is a way to convert our article into a Document object.
For that we will use a method
createDocument(),
private Document createDocument(String article, String author, String title, String topic, String url, Date dateWritten) { Document document = new Document(); document.add(Field.Text("author", author)); document.add(Field.Text("title", title)); document.add(Field.Text("topic", topic)); document.add(Field.UnIndexed("url", url)); document.add(Field.Keyword("date", dateWritten)); document.add(Field.UnStored("article", article)); return document; }
First we create a new
Document object. The next thing we need to do is add the different sections of the article to the
Document. The names that we give to each section are completely arbitrary and work much like keys in a
HashMap. The name used must be a
String. The add method of Document will take a Field object which we build using one of the static methods provided in the
Field class. There are four methods provided for adding
Field objects to a Document.
Field.Keyword – The data is stored and indexed but not tokenized. This is most useful for data that should be stored unchanged such as a date. In fact, the Field.Keyword can take a Date object as input.
Field.Text – The data is stored, indexed, and tokenized.
Field.Text fields should not be used for large amounts of data such as the article itself because the index will get very large since it will contain a full copy of the article plus the tokenized version.
Field.UnStored – The data is not stored but it is indexed and tokenized. Large amounts of data such as the text of the article should be placed in the index unstored.
Field.UnIndexed – The data is stored but not indexed or tokenized. This is used with data that you want returned with the results of a search but you won’t actually be searching on this data. In our example, since we won’t allow searching for the URL there is no reason to index it but we want it returned to us when a search result is found.
Now that we have a Document object, we need to get an
IndexWriter to write this
Document to the index.
String indexDirectory = "lucene-index"; private void indexDocument(Document document) throws Exception { Analyzer analyzer = new StandardAnalyzer(); IndexWriter writer = new IndexWriter(indexDirectory, analyzer, false); writer.addDocument(document); writer.optimize(); writer.close(); }
We first create a
StandardAnalyzer and then create an
IndexWriter using the analyzer. In the constructor we must specify the directory where the index will reside. The boolean at the end of the constructor tells the
IndexWriter whether it should create a new index or add to an existing index. When adding a new document to an existing index we would specify false. We then add the
Document to the index. Finally, we optimize and then close the index. If you are going to add multiple Document objects you should always optimize and then close the index after all the Document objects have been added to the index.
Now we just need to add a method to pull the pieces together.
To drive the indexing operation, we will write a method
indexArticle() which takes some parameters.
public void indexArticle(String article, String author, String title, String topic, String url, Date dateWritten) throws Exception { Document document = createDocument(article, author, title, topic, url, dateWritten); indexDocument(document); }
Running this for an article will add that article to the index. Changing the boolean in the
IndexWriter constructor to true will create an index so we should use that the first time we create an index and whenever we want to rebuild the index from scratch. Now that we have constructed an index, we need to search it for an article.
An index is stored as a set of files within a single directory.
An index consists of any number of independent segments which store information about a subset of indexed documents. Each segment has its own terms dictionary, terms dictionary index, and document storage (stored field values). All segment data is stored in _xxxxx.cfs files, where xxxxx is a segment name.
Once an index segment file is created, it can’t be updated. New documents are added to new segments. Deleted documents are only marked as deleted in an optional .del file.
4. Basic index operations
Indexing data
Lucene lets us index any data available in textual format. Lucene can be used with almost any data source as long as textual information can be extracted from it. We can use Lucene to index and search data stored in HTML documents, Microsoft Word documents, PDF files, and more. The first step in indexing data is to make it available in simple text format. It is possible to).
Analysis
Analysis is converting the text data into a fundamental unit of searching, which is called as term. During analysis, the text data goes through multiple operations: extracting the words, removing common words, ignoring punctuation, reducing words to root form, changing words to lowercase, etc. Analysis happens just before indexing and query parsing. Analysis converts text data into tokens, and these tokens are added as terms in the Lucene index.
Lucene comes with various built-in analyzers, such as
SimpleAnalyzer,
StandardAnalyzer,
StopAnalyzer,
SnowballAnalyzer, and more. These differ in the way they tokenize the text and apply filters. As analysis removes words before indexing, it decreases index size, but it can have a negative effect on the precision of query processing. You can have more control over the analysis process by creating custom analyzers using basic building blocks provided by Lucene. Table 1 shows some of the built-in analyzers and the way they process data.
4.1 Core indexing classes
Directory
An abstract class that represents the location where index files are stored. There are primarily two subclasses commonly used:
FSDirectory — An implementation of Directory that acceptsWriter exposes several fields that control how indices are buffered in the memory and written to disk. Changes made to the index are not visible to
IndexReader unless the commit or close method of
IndexWriter are called.
IndexWriter creates a lock file for the directory to prevent index corruption by simultaneous index updates.
IndexWriter lets users specify an optional index deletion policy.
4.2.
Details of Field metadata options
And a Document is a collection of fields. Lucene also supports boosting documents and fields, which is a useful feature if you want to give importance to some of the indexed data. Indexing a text file involves wrapping the text data in fields, creating a document, populating it with fields, and adding the document to the index using
IndexWriter.
5. Documents & fields
As you already saw previously, a Document is the unit of the indexing and searching process.
5.1 Documents.
You add a document to the index and, after you perform a search, you get a list of results and they are documents. A document is just an unstructured collection of Fields.
5.
Lucene offers four different types of fields from which a developer can choose:
Keyword,
UnIndexed,
UnStored, and
Text. Which field type you should use depends on how you want to use that field and its values.:
document.add(Field.Keyword("fieldname", text));
or
document.add(Field.UnIndexed("fieldname", text));
or
document.add(Field.UnStored("fieldname", text));
Although the
Field.Text,
Field.Keyword,
Field.UnIndexed, and
Field.UnStored calls may at first look like calls to constructors, they are really just calls to different Field class methods. Table 1 summarizes the different field types.
Table 1: An overview of different field types.
5.3 Boosting Documents in Lucene
In Information Retrieval, a document’s relevance to a search is measured by how similar it is to the query. There are several similarity models implemented in Lucene, and you can implement your own by extending the Similarity class, this has never worked correctly and depending on the type of query executed, might not affect the document’s rank at all.
With the addition of DocValues to Lucene, boosting documents is as easy as adding a
NumericDocValuesField and use it in a
CustomScoreQuery, which multiplies the computed score by the value of the ‘boost’Fields without re-indexing the documents, you can incorporate frequently changing fields (popularity, ratings, price, last-modified time…) in the boosting factor without re-indexing the document every time any one of them changes.
|
https://www.javacodegeeks.com/2015/09/building-a-search-index-with-lucene.html
|
CC-MAIN-2020-16
|
refinedweb
| 1,892
| 55.64
|
PKCS12_create —
create a PKCS#12 structure
#include
<openssl/pkcs12.h>
PKCS12 *
PKCS12_create(const char *pass,
const if
set to
KEY_EX it can be used for signing and
encryption. This option was useful for old export grade software which could
use signing only keys of arbitrary size but had restrictions on the
permissible sizes of keys which could be used for encryption.
If a certificate contains an alias or keyid then this will be used for the corresponding friendlyName or localKeyID in the PKCS12 structure.
PKCS12_create() returns a valid
PKCS12 structure or
NULL if an
error occurred.
crypto(3), d2i_PKCS12(3), PKCS12_new(3), PKCS12_newpass(3), PKCS12_parse(3), PKCS12_SAFEBAG_new.
|
https://man.openbsd.org/OpenBSD-6.7/PKCS12_create.3
|
CC-MAIN-2022-21
|
refinedweb
| 107
| 54.93
|
ThreadPooling
Multithreading is used to perform some tasks in the background typically so that
the main application thread or UI thread is not blocked. But there is an
overhead involved to create new threads and if the operations performed by these
threads are quite simple then the creation and destruction of new threads can
have impact on the performance of the system.
The ThreadPool class in the System.Threading namespace can be used if we are
required to create large number of threads. ThreadPool is a collection of
threads which can be used and returned to the pool once the processing is
complete.
Following diagram illustrates the how threads are used from the ThreadPool :
In the above diagram there are three requests in the Requests Queue and two
threads in the thread pool, in such a scenario the extra request waits its turn
in the requests queue till the thread becomes available to process it.
As soon as we create a new thread pool it creates a new thread to serve the
requests and keeps on creating the new threads unitl it reaches a defined limit.
And after the thread completes its job it is not destroyed immediately instead
it waits for some duration for the new request before it gets destroyed.
When a thread from the thread pool is reused the data in the thread local
storage remains. Also the fields that are marked with the ThreadStaticAttribute
retains there data.
But the threads in the ThreadPool are all background threads so when the
foreground thread exits the
Thread also terminates.
To execute the method in the thread from the threadpool we need to pass the
QueueUserWorkItem a
Waitcallback delegate instance to which we need to pass the method we have to
call.The method should be marked as static and void. class Program {
static void
Main(string[] args)
{
ThreadPool.QueueUserWorkItem (new WaitCallback(Process),null);
}
public static void Process(object
obj)
{
Console.WriteLine("Background
thread started ");
}
As you see in the above code we pass null as the second parameter, in place of
null we can pass the information to the method.
To check the number of threads currently available in the thread pool we can use
the GetAvailableThreads method which has the following signature: public static void
GetAvailableThreads(out int workerThreads, out int completionPortThreads);
Following gets the number of available worker and IO threads. int
availableWorkers = 0; int availableAsyncIO = 0;
ThreadPool.GetMaxThreads(out
availableWorkers, out availableAsyncIO);
Once a workitem has been queued in the pool it can not be cancelled.There can be
one thread pool per process.
View All
|
http://www.c-sharpcorner.com/uploadfile/ashish_2008/threadpool-class-in-net/
|
CC-MAIN-2017-26
|
refinedweb
| 431
| 67.18
|
bank details - JSP-Servlet
bank details hi i just need a coding for bank details...
since iam......
thank you.
Hi friend...://
Thanks
simple bank application - JSP-Servlet
simple bank application hi i got ur codings...But if we register a new user it is not updating in the database...so plz snd me the database also....
Thank you
Book Bank
Book Bank Dear Sir,
Could you send me the java codings for BOOK BANK.Its very urgent, please
Hi Friend,
Try the following code:
import java.io.*;
import java.util.*;
public class BookBank{
public
validate bank account number
validate bank account number how to validate bank account number in jsp
Hi!!!!!!!!!!!!!!!!!!!!! import java.awt.*;
import java.sql....=stmt.executeQuery("Select balance from bank where branch='kannur'");
Statement st...
project on bank - XML
project on bank how to add textfield and label to panel one below the other Hi Friend,
Try the following code:
import java.awt.*;
import javax.swing.*;
public class SwingFrame{
public static void main
Bank
Simple Bank Application in JSP
Simple Bank Application in JSP
In this section, we have developed a simple bank application
in jsp . In this application user can Update the User Profile, Cash
project on bank management system - Swing AWT
project on bank management system plz give me code to move from by clicking a button on one panel to other panel and the add textfield and label.... Hi Friend,
Try the following code:
import java.awt.*;
import
bank application
bank application hello sir I got the simple bank application project which is very useful but I want the database for this project kindly send me database for this simple online bank application
Bank project
Bank project
Create a class Customer
a. Having Instance variables Customer id(int), Customer Name(String), Customer Address(String), Customer Telephone(String) and Customer Email id(String)
b. Method which generates Customer Id
hi plzz reply
hi plzz reply in our program of Java where we r using the concept of abstraction Plz reply i m trying to learn java ...
means... a bank application in which there is a Customer Class.
Now what are the necessary
Bank Management System
Bank Management System I need a Bank Management System Project in Java Swing
|
http://www.roseindia.net/tutorialhelp/comment/95075
|
CC-MAIN-2014-52
|
refinedweb
| 373
| 58.92
|
I've been going nuts trying to write an automated test for my user sign up page. Users will be charged a recurring subscription via Stripe. They input their basic details (email, password, etc) and their credit card details on the same form, then the following flow happens:
Stripe::Customerobject, add the right subscription and charge them using Stripe's ruby gem etc.
All of this works perfectly fine... except I can't figure out how to test it. Testing step #4 is easy enough as it takes place on the server-side so I can mock out the Stripe calls with a gem like VCR.
Step #1 is what's giving me trouble. I've tried to test this using both
puffing-billy and the
stripe-ruby-mock gem, but nothing works. Here's my own javascript (simplified):
var stripeResponseHandler = function (status, response) { console.log("response handler called"); if (response.error) { // show the errors on the form } else { // insert the token into the form so it gets submitted to the server $("#credit_card_token").val(response.id); // Now submit the form. $form.get(0).submit(); } } $form.submit(function (event) { // Disable the submit button to prevent repeated clicks $submitBtn.prop("disabled", true); event.preventDefault(); console.log("creating token..."); Stripe.createToken( // Get the credit card details from the form // and input them here. }, stripeResponseHandler); // Prevent the form from submitting the normal way. return false; });
Just to reiterate, this all works fine when I test it manually. But my automated tests fail:
Failure/Error: expect{submit_form}.to change{User.count}.by(1) expected result to have changed by 1, but was changed by 0
When I try to use the gem
puffing-billy, it seems to be caching
stripe.js itself (which is loaded from Stripe's own servers at
js.stripe.com, not served from my own app, as Stripe don't support this.), but the call initiated by
Stripe.createToken isn't being cached. In fact, when I log into my Stripe server logs, it doesn't seem that the call is even been made (or at least Stripe isn't receiving it.)
Note those
console.log statements in my JS above. When I run my test suite, the line "creating token..." gets printed, but "response handler called." doesn't. Looks like the response handler is never being called.
I've left out some details because this question is already very long, but can add more on request. What am I doing wrong here? How can I test my sign up page?
UPDATE See [my comment on this Github issue] on stripe-ruby-mock for more info on what I've tried and failed.
If I understand correctly...
Capybara won't know about your ajax requests. You should be able to stub out AJAX requests with Sinatra. Have it return a fixtures much the same as VCR.
Here's an article on it.
You need to boot the Sinatra app in Capybara and then match the URLs in your ajax calls.
Something like:
class FakeContinousIntegration < Sinatra::Base def self.boot instance = new Capybara::Server.new(instance).tap { |server| server.boot } end get '/some/ajax' # send ajax back to capybara end end
When you boot the server, it will return the address and port which you can write to a config that your js can use.
@server = App.boot
Then I use the address and port to config the JS app
def write_js_config config['api'] = "{@server.host}:#{@server.port}" config.to_json end
In
spec_helper.rb send in the config to the js so your script points to your sinatra app. Mine compiles with gulp. So I just build the config into to is before the tests run:
system('gulp build --env capybara')
|
http://databasefaq.com/index.php/answer/146338/ruby-on-rails-testing-capybara-stripe-payments-poltergeist-how-can-i-test-stripejs-using-poltergeist-and-capybara
|
CC-MAIN-2019-09
|
refinedweb
| 619
| 76.72
|
Bag it up 💰 Greedy Algorithms in Javascript
Albert Wu
Originally published at
albertywu.com
on
・1 min read
Overview
One less understood idea among javascript engineers (unless you happen to be studying up for interviews) is the use of greedy algorithms. A greedy algorithm makes whatever choice seems best at the moment, and solves the subproblems that arise later. To use a visual metaphor, we put the result of each subproblem in a “bag” and then repeat with successively smaller subproblems. When the subproblem is empty (nothing left to do), we return the contents of the bag.
As it turns out, this strategy can lead to some very elegant solutions to practical problems. In the rest of this article, we’ll explore four seemingly different problems that have almost identical solutions (hint: they all use a greedy algorithm). In closing, we’ll take a closer look at the structure common to all four problems. Let’s dive in!
Example: coin change problem
You are given coins of different denominations and a total amount of money. Write a function that returns the smallest set of coins that sums to that amount.
Take a moment to consider how you’d do this before continuing… (answer is right below)
function makeChange(amount, coins, bag = []) { if (amount === 0) return bag let largestCoin = getLargestCoin(amount, coins) return makeChange(amount - largestCoin, coins, bag.concat([largestCoin])) } function getLargestCoin(amount, coins) { let sortedCoins = coins.sort((a, b) =\> a - b) for (let i = sortedCoins.length - 1; i \>= 0; i--) { if (sortedCoins[i] \<= amount) return sortedCoins[i] } throw new Error('no coin that divides amount') } console.log( makeChange(42, [1, 5, 10, 25]) ) // [25, 10, 5, 1, 1]
We keep a “bag” of coins and recursively add coins to the bag that matches our selection criteria
(pick largest coin denomination that is < amount). If the largest coin has value
C, we add
C to the bag and call
makeChange with
amount - C. This continues until the
amount is 0, and the bag of coins is returned.
A quick note on the expression
{ ...bag, ...{ [fn(array[0])]: matches } } since there’s a lot going on there. First of all, what does
{ ...a, ...b } mean? This is called object spreading. Think of it as smooshing together objects a and b to create a new object. So
{ ...bag, ...somethingElse } will combine the object
bag with object
somethingElse. In this case,
somethingElse is the object
{ [fn(array[0])]: matches } which is the new group we’re inserting into the bag.
I’ll also explain the difference between
{ [key]: value } and
{ key: value }. Those square braces signify computed properties. You can stick any expression between the square braces, and the value of that expression will become the value of the key. So for example
{ [1 + 1]: 2} would be the same as
{ 2: 2 }.
Example: groupBy
Implement the "groupBy" function which takes an array A and a function F, and returns an object composed of keys generated from the results of running each element of A through F. The corresponding value of each key is an array of elements responsible for generating the key.
Take a moment to consider how you’d do this before continuing… (answer is right below)
/* input: [6.1, 4.2, 6.3] function: Math.floor output: { '4': [4.2], '6': [6.1, 6.3] } */ function groupBy(array, fn, bag = {}) { if (array.length === 0) return bag let matches = array.filter(x =\> fn(x) === fn(array[0])) let rest = array.filter(x =\> fn(x) !== fn(array[0])) return ( groupBy( rest, fn, { ...bag, ...{ [fn(array[0])]: matches } } ) ) } console.log( groupBy([6.1, 4.2, 6.3], Math.floor) ) // { '4': [4.2], '6': [6.1, 6.3] }
Keep a “bag” of groups and recursively add groups to the bag that match our selection criteria
fn(x) === fn(array[0]). Then call
groupBy on the remaining elements, with the updated bag. This continues until the original array is empty, and the bag is returned.
Example: activity selection problem
Another classic problem is the activity selection problem.
Imagine you are trying to schedule a room for multiple competing events, each having its own time requirements (start and end time). How do you schedule the room such that you can host the maximum number of events with no scheduling conflicts?
Take a moment to consider how you’d do this before continuing… (answer is right below)
class Appointment { constructor(name, from, to) { this.name = name this.from = from this.to = to } } // push new appointments onto bag one-by-one until no more appointments are left function getMaxAppointments(appointments, bag = []) { if (appointments.length === 0) return bag let selectedAppointment = appointments.sort((a, b) =\> a.to - b.to)[0] // sort from earliest end to latest end let futureCandidates = appointments.filter(a =\> a.from \> selectedAppointment.to) return getMaxAppointments( futureCandidates, bag.concat([selectedAppointment]) ) } let a1 = new Appointment('brush teeth', 0, 2) let a2 = new Appointment('wash face', 1, 3) let a3 = new Appointment('make coffee', 3, 5) let a4 = new Appointment('blowdry hair', 3, 4) let a5 = new Appointment('take shower', 4.5, 6) let a6 = new Appointment('eat cereal', 7, 10) console.log( getMaxAppointments([a1, a2, a3, a4, a5, a6]).map(a =\> a.name) ) // ['brush teeth', 'blowdry hair', 'take shower', 'eat cereal']
Example: collect anagrams
For our final example, we’ll consider the problem of grouping anagrams.
Given an array of strings, group anagrams together. For example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
Take a moment to consider how you’d do this before continuing… (answer is right below)
function collectAnagrams(words, bag = []) { if (words.length === 0) return bag let matches = words.filter(w =\> isAnagram(w, words[0])) let rest = words.filter(w =\> !isAnagram(w, words[0])) return collectAnagrams( rest, bag.concat([matches]) ) } function stringSorter(a, b) { return a.localeCompare(b) } function isAnagram(a, b) { let aSorted = a.toLowerCase().split('').sort(stringSorter).join('') let bSorted = b.toLowerCase().split('').sort(stringSorter).join('') return aSorted === bSorted } let x = ['bag', 'gab', 'foo', 'abg', 'oof', 'bum'] console.log(collectAnagrams(x)) // [['bag', 'gab', 'abg'], ['foo', 'oof'], ['bum']]
The Common Structure
So what do all of these problems have in common? For every iteration through the loop, we select a subset of items from the input and add it to the bag. The remaining items feed through to the next iteration of the loop as the next input. When the input is empty, we return the bag.
The following diagram might help clarify things, using our groupBy example:
If you’re more comfortable with pseudocode, here is the pattern we used in all of the previous examples:
function bagItUp(things, bag = []) { if (things is empty) return bag let thingsToPutInBag = ... let restOfThings = ... return bagItUp( restOfThings, bag + thingsToPutInBag ) }
Connect
What do you think? Have you solved similar problems at work or personal projects using greedy algorithms? Let me know in the comments below, or on twitter!
(open source and free forever ❤️)
What do you wish you knew about Developer Relations?
A conversation... what do DevRel professionals wish devs knew about their job? And what do devs wish they knew about DevRel?
Traverse the entire global object in just 75 lines of JavaScript!
Brian Jenkins -
Your experiences debugging on serverless/micro-service architectures?
Rolf Streefkerk -
Javascript version of ColdFusion CFDump
James Moberg -
|
https://dev.to/albertywu/bag-it-up--greedy-algorithms-in-javascript-3gac
|
CC-MAIN-2020-10
|
refinedweb
| 1,210
| 58.28
|
NumPy Random | Python NumPy Tutorial in Hindi Part-9 | Machine Learning Tutorial #01.01.09
[ad_1]
Course name: “Machine Learning – Beginner to Professional Hands-on Python Course in Hindi”
In this python NumPy tutorial part-9, We explain NumPy random sampling functions in Hindi. List of some explained random sampling functions given below:
1. np.random.random()
2. np.random.randint()
3. np.random.seed()
4. np.random.rand()
5. np.random.randn()
6. np.random.choice()
7. np.random.permutation()
Practical Code link:
Course Playlists-
Machine Learning Beginner to Professional Hands-on Python Course in Hindi:
Python NumPy Tutorial in Hindi:
Python Pandas Tutorial in Hindi
For more information:
-Website:
-Instagram:…
-Twitter:
#NumPyRandom
#PythonNumPyTutorialInHindi #NumPyTutorial #NumpyPythonTutorial
#IndianAIProduction
Source
[ad_2]
Comment List
Thank you Sir .. Hello from Pakistan.. umeed hn mujhn 3 to 4 month may ya videos both uper jany wali InshahAllah
Awesome explainations
You teaching style is very good…
Very effective tutorial, easy to learn and fast. But please make some video for some complex task which are use in ML so that experience person can tall about some good project when interview happen. Means we can understand how numpy is use in ML projects.
All tutorial is very good. Very help to improve Indian IT engg. Its a good setp to teach our engg in Hindi in effective way. Good work keep it up.
what is the use of np.ranom.permutation()
can you give some other example?
Sir, I need one help, I am unable to understand this code.
import numpy as np
x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])
rows = np.array([[0,0],[3,3]])
cols = np.array([[0,2],[0,2]])
y = x[rows,cols]
print (y)
Output :
[[ 0 2]
[ 9 11]]
I just wanted to know from where this 0 2 and 9 11 is coming. Please explain.
Thanks in advance.
Your way of presentation is perfect. I just love it.
np.sin(180) , It returns value of angle in radian not in degree. and by using np.pi/180 this function return the value of angle in degree.
only this video contain practical video link
|
http://openbootcamps.com/numpy-random-python-numpy-tutorial-in-hindi-part-9-machine-learning-tutorial-01-01-09/
|
CC-MAIN-2021-21
|
refinedweb
| 362
| 67.35
|
Scenario: Download ScriptYou are working as C# developer, you need to write a program that can read file's information such as
- FolderPath
- FileName
- LastWriteTime
- CreateTime
- FileSizeinKB
from a table and write into SQL Server table. Also as part of file information , you would like to insert folder from which we are reading the file properties.
Step 1:
First of all you need to create a table in SQL Server database in which you would like to insert file information.
CREATE TABLE [dbo].[FileInformation]( id int identity(1,1), FolderPath VARCHAR(255), FileName VARCHAR(255), [LastWriteTime] DateTime, [CreateTime] Datetime, FileSizeinKB Int)
Step 2:
Create new Project and then choose Console Application and use below script.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Data.SqlClient; namespace _01_WriteFileProperitestoTable { class Program { static void Main(string[] args) { //Declare Variable and set value,Provide the folder which contains files string VarDirectoryPath = "C:\\Source\\"; //Create Connection to SQL Server SqlConnection SQLConnection = new SqlConnection(); SQLConnection.ConnectionString= "Data Source = (local); Initial Catalog =TechBrothersIT; "
+ "Integrated Security=true;"; //get all files from directory or folder to get file's information string[] files = Directory.GetFiles(VarDirectoryPath); SqlCommand SqlCmd = new SqlCommand(); SqlCmd.Connection = SQLConnection; SQLConnection.Open(); //loop through files foreach (string filename in files) { FileInfo file = new FileInfo(filename); SqlCmd.CommandText = "Insert into dbo.FileInformation("; SqlCmd.CommandText += "[FolderPath],[FileName],[LastWriteTime],[CreateTime],[FileSizeinKB])"; SqlCmd.CommandText +=" Values('" + VarDirectoryPath + "','" + file.Name + "','" + file.LastWriteTime + "','" + file.CreationTime + "','" + file.Length / 1024 + "')"; SqlCmd.ExecuteNonQuery(); } SQLConnection.Close(); } } }
Save the script and then execute. It should read the file properties from the folder you have given and insert into SQL Server Table.
How to read file's properties in C# and insert into SQL Server Table - C# Tutorial
Such a great post! It looks like a blog and in this content was useful for freshers. Keeping a good job.
Tableau Training in Chennai
Tableau Course in Chennai
Pega Training in Chennai
Excel Training in Chennai
Power BI Training in Chennai
Oracle Training in Chennai
Unix Training in Chennai
Tableau Training in Chennai
Tableau Course in Chennai
This is really a nice and informative, containing all information and also has a great impact on the new technology. Thanks for sharing it, Affinity at serangoon showroom
I really like your take on the issue. I now have a clear idea on what this matter is all about.. buy instagram likes uk instant
i really like this article please keep it up. gouna villas
Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. There tend to be not many people who can certainly write not so simple posts that artistically. Continue the nice writing gouna villas
I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information. offplan projects for sale in Dubai
With land being an unstable industry, you should invest in a great deal of energy to know the suitable planning and market rates prior to selling your property. Homes for sale in Huntington Hills
Next we tackle the property the board costs. Sell property Ireland
very interesting keep posting. developers in u!!!!!! Sobha windsor whitefield
I have read your blog it is very helpful for me. I want to say thanks to you. I have bookmark your site for future updates.Guess Bags for Women
I visit your blog regularly and recommend it to all of those who wanted to enhance their knowledge with ease. The style of writing is excellent and also the content is top-notch. Thanks for that shrewdness you provide the readers! Semi Detached duplex for sale in Ibadan Nigeria
I read that Post and got it fine and informative. Plots
|
http://www.techbrothersit.com/2016/04/c-how-to-get-file-properties-and-insert.html
|
CC-MAIN-2021-31
|
refinedweb
| 635
| 50.02
|
NAME
pmap_page_exists_quick - determine if a page exists in a physical map
SYNOPSIS
#include <sys/param.h> #include <vm/vm.h> #include <vm/pmap.h> boolean_t pmap_page_exists_quick(pmap_t pmap, vm_page_t m);
DESCRIPTION
The pmap_page_exists_quick() function is used to quickly determine if the page m exists in the physical map pmap. It is typically called from the VM paging code.
IMPLEMENTATION NOTES
The PV count used above may be changed upwards or downwards in future; it is only necessary that TRUE be returned for a small subset of pmaps for proper page aging.
RETURN VALUES
The pmap_page_exists_quick() returns TRUE only if the PV entry for the physical map pmap is one of the first 16 PVs linked from the page m.
SEE ALSO
pmap(9)
AUTHORS
This manual page was written by Bruce M Simpson 〈bms@spc.org〉.
|
http://manpages.ubuntu.com/manpages/intrepid/man9/pmap_page_exists_quick.9freebsd.html
|
CC-MAIN-2014-15
|
refinedweb
| 136
| 63.9
|
Riot vs React & Polymer
And how Riot differs from its closest cousins.
React
Riot is inspired by React and from the idea of “cohesion”. According to Facebook developers:
“Templates separate technologies, not concerns.”
We respect this insight. The goal is to build reusable components instead of templates. By separating logic from the templates we are actually keeping out things that should be together.
By combining these related technologies together under the same component the system becomes cleaner. We respect React because of this important insight.
React syntax
import React from 'react' import { render } from 'react-dom' class Todo extends React.Component { state = { items: [], value: '' } handleSubmit = e => e.preventDefault() || this.setState({ items: [...this.state.items, this.state.value], value: '' }) handleChange = e => this.setState({ value: e.target.value }) render() { return ( <div> <h3>TODO</h3> <ul> {this.state.items.map((item, i) => <li key={i}>{item}</li>)} </ul> <form onSubmit={this.handleSubmit}> <input value={this.state.value} onChange={this.handleChange} /> <button>Add #{this.state.items.length + 1}</button> </form> </div> ) } } render(<Todo />, mountNode)
JSX is mixture of HTML and JavaScript. You can include HTML anywhere on the component; inside methods and in property assignments.
Riot syntax
Here is the above thing with Riot:
<todo> <h3>TODO</h3> <ul> <li each={ item, i in items }>{ item }</li> </ul> <form onsubmit={ handleSubmit }> <input ref="input"> <button>Add #{ items.length + 1 }</button> </form> this.items = [] handleSubmit(e) { e.preventDefault() var input = this.refs.input this.items.push(input.value) input.value = '' } </todo>
And this is how the above tag is mounted on a page:
<todo></todo> <script>riot.mount('todo')</script>
Same, same — but different
In Riot HTML and JavaScript appear much more familiar. Both are under the same component, but neatly separated from each other. The HTML can be mixed with JavaScript expressions.
No proprietary stuff, except the notation of enclosing expressions inside curly braces.
You see less boilerplate. Less brackets, commas, system properties and method names. Strings can be interpolated:
"Hello {world}" instead of
"Hello " + this.state.world and methods can be defined with compact ES6 syntax. Just less everything.
We think Riot syntax is the cleanest way to separate layout and logic while enjoying the benefits of isolated reusable components.
Virtual DOM vs expressions binding
When a component is initialized React creates its Virtual DOM, Riot on the other hand traverses just a DOM tree.
Riot takes the expressions from the tree and stores them in an array. Each expression has a pointer to a DOM node. On each run these expressions are evaluated and compared to the values in the DOM. When a value has changed the corresponding DOM node is updated.
Since these expressions can be cached an update cycle is very fast. Going through 100 or 1000 expressions usually takes 1ms or less.
The React sync algorithm is much more complex since the HTML layout can change randomly after each update. Given the enormous challenge, Facebook developers did an impressive job with it.
We saw that the complex diffing can be avoided.
In Riot the HTML structure is fixed. Only loops and conditionals can add and remove elements. But a
div cannot be converted to a
label for example. Riot only updates the expressions without complex subtree replacements.
Flux and routing
React deals with the UI only, which is a good thing. All great software projects have a sharp focus.
Facebook recommends to use Flux to structure the client-side code. It’s more of a pattern than a framework and is packed with great ideas.
Riot comes bundled with custom tags, an event emitter (observable) and an optional router. We believe that these are the fundamental building blocks of client side applications. Events bring modularity, a router takes care of the URL and the back button and custom tags take care of the user interface.
Just like Flux, Riot is flexible and leaves the bigger architectural decisions for the developer. It’s just a library to help you achieve the goal.
You can build a Flux-like system by using Riot’s observable and router. In fact such thing already exists.
3x bigger
React (v16.4.0) is 3x bigger than Riot.
react.min.js – 33.27KB (gzip)
riot.min.js – 10.85KB (gzip)
The recommended React router (v4.1.1) is 6x larger than Riot router.
react-router.min.js – 10.95KB (gzip)
react-mini-router.min.js – 4.52KB (gzip)
riot.route.min.js – 1.77KB (gzip)
Admittedly this router comparison is a bit unfair because react-router has a lot more features. But the above chart clearly highlights the goal of Riot: to provide the most minimalistic API for the job.
The React ecosystem is more frameworky and favors larger API surfaces. The bigger alternative is more popular than react-mini-router in the React community.
Polymer
Polymer takes the Web Component standard and makes it available for the latest browsers. This allows you to write custom tags in a standard manner.
Conceptually Riot is the same thing but there are differences:
The Web Components syntax is experimental and complex.
Riot updates only the elements that have changed resulting to less DOM operations.
Individual components are imported with HTML
link rel="import". Polyfills must resort to queued up XHRs, which makes it painfully slow unless the dedicated vulcanize tool is used. Riot tags are imported with
script srcand multiple tags can be combined with regular tooling.
No ability to perform server side rendering.
6x bigger
Polymer(v1.8.0) + WebComponents(v0.7.24) is 6x bigger than Riot
polymer.min.js – 49.38KB (gzip)
riot.min.js – 10.85KB (gzip)
Web components are said to be the king of all polyfilling challenges and this is why Polymer requires such a large amount of code.
Web components
Because web components is a standard it is ultimately the way to go. It will take years, but eventually the web will be full of these standard components.
Because of the complexity involved there is a high chance that these components are not used directly. There will be layers on top of web components. Just like we have jQuery today. Most people are not using the DOM directly.
Riot is one such abstraction. It provides an easy to use API that our applications can stick to. Once the web component specs evolve Riot can start using them internally if there are any true benefits, such as performance gains.
The goal of Riot is to make UI development as easy as possible. The current API is designed to withstand the constant flux of web technologies. Think of it as the “jQuery for web components” - it takes syntaxical shortcuts to achieve the same goal. It simplifies the overall experience of writing reusable components.
|
https://riot.js.org/compare/
|
CC-MAIN-2018-47
|
refinedweb
| 1,121
| 60.41
|
Solution for Programmming Exercise 6.9
This page contains a sample solution to one of the exercises from Introduction to Programming Using Java.
Exercise 6.9:
Write a Blackjack program that lets the user play a game of Blackjack, with the computer as the dealer. The applet should draw the user's cards and the dealer's cards, just as was done for the graphical HighLow card game in Subsection 6.7.6. You can use the source code for that game, HighLowGUI.java, for some ideas about how to write your Blackjack game. The structures of the HighLow panel and the Blackjack panel are very similar. You will certainly want to use the drawCard() method from the HighLow program.
You can find a description of the game of Blackjack in Exercise 5.5. Add the following rule to that description: If a player takes five cards without going over 21, that player wins immediately. This rule is used in some casinos. For your program, it means that you only have to allow room for five cards. You should assume that the panel is just wide enough to show five cards, and that it is tall enough show the user's hand and the dealer's hand.
Note that the design of a GUI Blackjack game is very different from the design of the text-oriented program that you wrote for Exercise 5.5. The user should play the game by clicking on "Hit" and "Stand" buttons. There should be a "New Game" button that can be used to start another game after one game ends. You have to decide what happens when each of these buttons is pressed. You don't have much chance of getting this right unless you think in terms of the states that the game can be in and how the state can change.
Your program will need the classes defined in Card.java, Hand.java, Deck.java, and BlackjackHand.java.
Here is an applet version of the program for you to try:
The constructor for this exercise can be almost identical to that in the HighLow game. The text of the buttons just has to be changed from "Higher" and "Lower" to "Hit" and "Stand". However, the nested class, CardPanel has to be rewritten to implement a game of Blackjack instead of a game of HighLow. The basic structure of the revised class remains similar to the original. All the programming for the game is in this
BlackComponent()Component() method checks the state when it draws the applet. If the game is over, the card is face up. If the game is in progress, the card is face down. This is nice example of state-machine thinking.
Note that writing the paintComponent() method required some calculation. The cards are 80 pixels wide and 100 pixels tall. Horizontally, there is a gap of 10 pixels between cards, and there are gaps of 10 pixels between the cards and the left and right edges. (The total width needed for the card panel, 460, allows for five 80-pixel cards and six 10-pixel gaps: 5*80 + 6*10 = 460. The applet is another 6 pixels wide because of a 3-pixel wide border on each side).Component() method. Allowing 100 pixels for the second row of cards and 30 pixels for the message at the bottom of the board, we need a height of at least 290 pixels for the canvas. I set the preferred height of the panel to 310 to for some extra space between the cards and the message at the bottom of the panel. The applet has an even greater height to allow for the height of the button bar below the card panel.
In this GUI version of Blackjack, things happen when the user clicks the "Hit", "Stand", and "New Game" buttons. The program. This is similar to the way the three buttons in HighLowGUI are handled. as soon as it starts, so gameIsProgress has to be false, and the only action that the user can take at that point is to click the "New Game" button again. (Note that the doNewGame() routine is also called by the constructor of the BlackjackPanel class. This sets up the first game, when the panel still.
import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * In this program, the user plays a game of Blackjack. The * computer acts as the dealer. The user plays by clicking * "Hit!" and "Stand!" buttons. * * This class defines a panel, but it also contains a main() * routine that makes it possible to run the program as a * stand-alone application. In also contains a public nested * class, BlackJackGUI.Applet that can be used as an applet version * of the program. * When run as an applet the size should be about 466 pixels wide and * about 346 pixels high. That width is just big enough to show * 2 rows of 5 cards. The height is probably a little bigger * than necessary, to allow for variations in the size of buttons * from one platform to another. * * This program depends on the following classes: Card, Hand, * BlackjackHand, Deck. */ public class BlackjackGUI extends JPanel { /** * The main routine simply opens a window that shows a BlackjackGUI. */ public static void main(String[] args) { JFrame window = new JFrame("Blackjack"); BlackjackGUI content = new BlackjackGUI(); window.setContentPane(content); window.pack(); // Set size of window to preferred size of its contents. window.setResizable(false); // User can't change the window's size. Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize(); window.setLocation( (screensize.width - window.getWidth())/2, (screensize.height - window.getHeight())/2 ); window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); window.setVisible(true); } /** * The public static class BlackjackGUI.Applet represents this program * as an applet. The applet's init() method simply sets the content * pane of the applet to be a HighLowGUI. To use the applet on * a web page, use code="BlackjackGUI$Applet.class" as the name of * the class. */ public static class Applet extends JApplet { public void init() { setContentPane( new BlackjackGUI() ); } } /** * The constructor lays out the panel. A CardPanel occupies the CENTER * position of the panel (where CardPanel is a subclass of JPanel that is * defined below). On the bottom is a panel that holds three buttons. * The CardPanel listens for ActionEvents from the buttons and does all * the real work of the program. */ public BlackjackGUI() { setBackground( new Color(130,50,40) ); setLayout( new BorderLayout(3,3) ); CardPanel board = new CardPanel(); add(board, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); buttonPanel.setBackground( new Color(220,200,180) ); add(buttonPanel, BorderLayout.SOUTH); JButton hitButton = new JButton( "Hit!" ); hitButton.addActionListener(board); buttonPanel.add(hitButton); JButton standButton = new JButton( "Stand!" ); standButton.addActionListener(board); buttonPanel.add(standButton); JButton newGame = new JButton( "New Game" ); newGame.addActionListener(board); buttonPanel.add(newGame); setBorder(BorderFactory.createLineBorder( new Color(130,50,40), 3) ); } // end constructor /** * A nested class that displays the game and does all the work * of keeping track of the state and responding to user events. */ private class CardPanel extends JPanel implements ActionListener {. /** * The constructor creates the fonts and starts the first game. * It also sets a preferred size of 460-by-310 for the panel. * The paintComponent() method assumes that this is in fact the * size of the panel (although it can be a little taller with * no bad effect). */ CardPanel() { setPreferredSize( new Dimension(460,310) ); setBackground( new Color(0,120,0) ); smallFont = new Font("SansSerif", Font.PLAIN, 12); bigFont = new Font("Serif", Font.BOLD, 16); doNewGame(); } /** * Respond when the user clicks on a button by calling the appropriate * method. Note that the buttons are created and listening is set * up in the constructor of the BlackjackPanel class. */ public void actionPerformed(ActionEvent evt) { String command = evt.getActionCommand(); if (command.equals("Hit!")) doHit(); else if (command.equals("Stand!")) doStand(); else if (command.equals("New Game")) doNewGame(); } /** *. */ void doHit() {(); } /** * This method is called when the user clicks the "Stand!" button. * Check whether a game is actually in progress. If it is, the game * ends. The dealer takes cards until either the dealer has 5 cards * or more than 16 points. Then the winner of the game is determined. */ void doStand() {(); } /** * Called by the constructor, and called by actionPerformed() if the * user clicks the "New Game" button. Start a new game. Deal two cards * to each player. The game might end right then if one of the players * had blackjack. Otherwise, gameInProgress is set to true and the game * begins. */ void doNew(); /** * The paint method shows the message at the bottom of the * canvas, and it draws all of the dealt cards spread out * across the canvas. */ public void paintComponent(Graphics g) { super.paintComponent(g); // fill with background color. g.setFont(bigFont); g.setColor(Color.GREEN); g.drawString(message, 10, getHeight() -(); /** * Draws a card as a 80 by 100 rectangle with upper left corner at (x,y). * The card is drawn in the graphics context g. If card is null, then * a face-down card is drawn. (The cards are rather primitive!) */ void drawCard(Graphics g, Card card, int x, int y) { nested class CardPanel } // end class BlackjackGUI
|
http://math.hws.edu/javanotes/c6/ex9-ans.html
|
crawl-001
|
refinedweb
| 1,505
| 66.33
|
I have this:
public class myProgram{
public static void main(String[] args){
System.out.println("Hello everyone!");
}
}
class myInherit extends myProgram{
// Anything
}
class myInstance{
public static myProgram theInstance;
public static getInstance(){
myInstance.theInstance = new myProgram();
}
}
------------------------------------------------
I don't want people to inherit OR make an instance of the class myProgram(). Mainly because it would be pointless! There is nothing inside of the class to use! But it has to be Public so the program can run.
So I had a couple options, but none of them worked 100% (all 50%):
//Problem with this? They can still extend the class!
public abstract class myProgram{ // The abstract would prevent people making instances of this class
public static void main(String[] args){
System.out.println("Hello everyone!");
}
}
//Problem with this? They can still create instances of this class!
public final class myProgram{ // The final would prevent people inheriting this class
public static void main(String[] args){
System.out.println("Hello everyone!");
}
}
------------------------------------------------
Anyone have any suggestions? Thank you for your time!
a final class with a private constructor, can be neither instantiated, nor extended. it's a lot of effort for nothing though.. cjard!
"it's a lot of effort for nothing though.."
Yes, that is true lol
Forum Rules
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|
http://forums.devx.com/showthread.php?140000-Look-and-Feel&goto=nextoldest
|
CC-MAIN-2018-09
|
refinedweb
| 222
| 59.9
|
1 import java.io.*;2 import com.memoire.vainstall.*;3 import Acme.Crypto.*;4 /* 5 * I suggest to license this file under LGPL license so anyone 6 * could extend this class with own license key validators w/o need 7 * to release source code of validator. I suggest to no to license 8 * this file under GPL2 and stick with LGPL as otherwise it will put 9 * very much of burden on the users of vainstall w/o obvious value10 * to other user as different company polices could require different11 * fields to be supplied and this will be likely only difference in different12 * validators.13 *14 * copyrights are completly transfered to VAInstall team without any 15 * restriction.16 */17 /** 18 * this class is default implementation of license key support, that does nothing.19 */20 public class HelloLicenseKeySupport extends LicenseKeySupport21 {22 String key = "HW0123-4567-89AB-CDEF-8B58-85B7";23 String codekey; 24 /** @return true if license key query step need to be performed 25 */26 public boolean needsLicenseKey() {27 return true;28 }29 /** @return uri of page that contains registration page,30 * if such uri is not null, then it will be shown 31 * to user and launch browser button will be displayed32 * depending on ui and platform.33 */34 35 public String getRegistrationPage() {36 return "";37 }38 39 /** get field info for this installer 40 * @return array of field info.41 */42 public FieldInfo[] getFieldInfo() {43 return new FieldInfo[]{new FieldInfo("serial key", 20, key)};44 }45 /** set field values, this method coudl be called any number of times.46 * implementation of this class should keep last passed values.47 * @param values array of strings where each element correspond field 48 * info returned from get field info.49 */50 public void setFieldValues(String values[]) {51 key = values[0];52 }53 /** @return true, if license key is valid, this method should be called only54 * after set field values were called. 55 */56 public boolean isLicenseKeyValid()57 {58 StringBuffer tmp = new StringBuffer (key.toUpperCase());59 for(int n = tmp.length(),i=0;i<n;i++) {60 if(tmp.charAt(i) == '-'){61 tmp.deleteCharAt(i);62 i--;63 n--;64 }65 }66 String normalized = tmp.toString();67 if(normalized.length() < 26) {68 return false;69 }70 codekey = normalized.substring(0,normalized.length()-8);71 if(codekey.hashCode() != (int)Long.parseLong(normalized.substring(codekey.length(),normalized.length()),16) ){72 return false;73 }74 return true;75 }76 /** encode archive.zip stream with key supplied as string in 77 * configuration file, this fucntion is called during building install 78 * package 79 * @param is input steam to encode80 * @param key key supplied in configuration file81 * @return encrypted stream 82 */83 public OutputStream encodeStream(OutputStream os, String key) throws IOException84 {85 EncryptedOutputStream rc = new EncryptedOutputStream(new AesCipher(key), os);86 return rc;87 }88 /** decode archive.zip stream using infromation supplied in fieldValues 89 * @param is input steam to decode90 * @return decrypted stream 91 */92 public InputStream decodeStream(InputStream is) throws IOException93 {94 EncryptedInputStream rc = new EncryptedInputStream(new AesCipher(codekey), is);95 return rc;96 }97 98 }
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
|
http://kickjava.com/src/HelloLicenseKeySupport.java.htm
|
CC-MAIN-2018-05
|
refinedweb
| 526
| 51.99
|
Data Visualization is a revolutionary invention that is widely used today in almost every industry. Data Visualization becomes extremely useful in data storytelling. Charts, plots are visually appealing and one can catch the motive behind the story with a visual. A single chart or plot is enough to represent a thousand words.
One of the visualization techniques we are going to talk about is treemap. Treemaps are easy to visualize and can be understandable by a naive person. Due to its varying sizes of rectangles, one can relate that a larger rectangle means a large amount and a smaller rectangle means a small amount of the whole. In this article, we will learn how to build Treemaps in Python using the library Squarify.
Table of Contents:
- Introduction
- Building Treemap using Squarify
- Using Additional Parameters
- Applications of Treemap
- Conclusion
Introduction
Treemaps are used to visualize hierarchical data using rectangles nested together of varying sizes. The size of each rectangle is in proportion to the amount of data it represents out of the whole. These nested rectangles represent the branches of a tree and thus got their name. Apart from the sizes, each rectangle has unique color representing the unique category. Treemaps are widely used in industries ranging from Financial institutions to Sales organizations.
Treemaps were first invented in the early 1990s by an American Professor, Ben Shneiderman at the University of Maryland Human-Computer Interaction Lab. The idea behind this visualization was to compare the quantities by size in a fixed space. Now, we will look at how to build a word cloud practically.
Building Treemap using Squarify
Treemap in Python can be built straightforwardly using Squarify. The process of drawing a Treemap in Python is as follows:
1. Installing Necessary Libraries
!pip install squarify
2. Importing Necessary Libraries
import matplotlib.pyplot as plt import squarify
3. Creating Random Data
Randomly generating a list of values, which will be passed as data into our plot.
data = [500, 250, 60, 120]
4. Plotting the Treemap
Using the .plot() method of squarify, we will build the treemap. Here, we are giving our random data variable data as a parameter to this .plot() method. Also, the plt.axis(‘off’) will remove the axis to get the treemap without the axes.
squarify.plot(data) plt.axis('off') plt.show()
5. Putting it All Together
import matplotlib.pyplot as plt import squarify data = [500, 250, 60, 120] squarify.plot(data) plt.axis('off') plt.show()
On executing this code, we get:
Source – Personal Computer
Each time, on executing this code, it will generate a random set of colours for our nested rectangles.
Using Additional Parameters
More functionalities can be added to our Treemap with the help of parameters of the .plot() method. We can control the colours, labels, and padding of our treemap by explicitly specifying the attributes.
1. Specifying the Colours of Treemap
import matplotlib.pyplot as plt import squarify sizes = [500, 250, 120, 60] color = ['red', 'green', 'blue', 'orange'] squarify.plot(sizes,color=color) plt.axis('off') plt.show()
On executing this code, we get:
Source: Personal Computer
2. Adding Labels to Treemap
Labels can be added explicitly by passing a list of values into the label attribute of squarify.plot(). This will overwrite the existing labels or will add labels to our Treemap, if not present. Labels will be added in the same order they are passed as a list.
import matplotlib.pyplot as plt import squarify labels = ['A', 'AB', 'ABC', 'ABCD'] sizes = [500, 250, 120, 60] color = ['red', 'green', 'blue', 'orange'] squarify.plot(sizes,color=color, label = labels) plt.axis('off') plt.show()
On executing this code, we get:
Source – Personal Computer
3. Padding in Treemap
Padding can be added to our treemap which will help to distinguish the rectangles. This is helpful when we have a huge number of categories or rectangles. This can be invoked by setting the pad parameter to True
import matplotlib.pyplot as plt import squarify labels = ['AB', 'A', 'ABC', 'ABCD'] sizes = [500, 250, 120, 60] color = ['red', 'green', 'blue', 'orange'] squarify.plot(sizes,color=color, label = labels, pad = True) plt.axis('off') plt.show()
On executing the code, we get:
Source – Personal Computer
Applications of Treemaps
Today, Treemaps can be found in every industry from financial institutions to the health industry. Following are the few examples where Treemaps are widely used:
1. Treemap for comparing Literacy Rate in India
A treemap can be built to see the literacy rate in each state of India. The biggest-sized rectangle will represent the state having the highest literacy rate in the country. While the smallest sized rectangle will represent the state with the lowest literacy rate. But one might find this ambiguous when one or more states have almost equal literacy rates. Thus, such states will have almost the same sized rectangles and would be difficult to distinguish if state names are not printed.
2. Treemap for comparing Months in a Year
A treemap can be built to visualize months based on the number of hours spent by an individual studying. Thus, a larger rectangle will represent the most productive month while the smallest rectangle would represent the least productive month of the year.
3. Treemap for Comparing Players of a Team
A treemap can be built to visualize a team’s players based on the number of sixes hit by them. Here, the larger rectangle will represent the player who had scored the most sixes while the smallest rectangle would represent the player who had scored the least sixes throughout the tournament.
4. Treemap for Comparing Audio Tracks of an Artist
A treemap can be built to compare the audio tracks of an album by an artist based on the number of times the audio is streamed. Here, the largest rectangle would represent the track with the most number of streams while the smallest rectangle would represent the track with the least number of streams.
5. Treemap for the Comparing States in India based on Number of Vaccines Administered
A treemap can be built to compare states of India based on the Number of Vaccine Doses 1 administered. Thus, here the largest rectangle would represent the state which had administered the most number of vaccine doses while the smallest rectangle would represent the state which had administered the least number of vaccine doses.
Conclusion
Thus, building a Treemap was a piece of cake. Apart from squarify, Treemaps can be build using several libraries in Python. Numerous BI tools today are available to build Treemaps most simply.
Sometimes, ambiguity may arise in a Treemap. If we have more than one category having the same amount (or rectangle size) and the same shade of colour, this becomes difficult to distinguish between the two for the end-user. Thus, one must always consider the number of categories and the colour map involved. Treemap should always be clutter-free and difficult to understand._5<<
|
https://www.analyticsvidhya.com/blog/2021/06/build-treemaps-in-python-using-squarify/
|
CC-MAIN-2021-25
|
refinedweb
| 1,153
| 55.44
|
How to take Input in Java Using Scanner Class and BufferedReader Class
We know that a String in java is a collection of characters enclosed in double-quotes. We have learned the concepts of String in Java multiple times and also implemented them in many programs. But usually, we used to pass the String input in the code itself. To develop a console application using Java, it is very important to read input from the user through the console. In this article, we will learn to take the String input from the user after the successful compilation of the Java program. There are many ways to take String input in Java. So let’s start the tutorial on taking String input in Java.
Keeping you updated with latest technology trends, Join TechVidvan on Telegram
Taking String Input in Java
Taking string input in Java means taking the String input from the user through the keyboard and then the input values are processed and we get the desired output of the program. There are many utility classes and their methods that enable us to take the String input from the console. We can obtain as many as Strings inputs from the user as required. Let’s look forward to the various methods that take String input from the user.
Techniques to take String Input in Java
The following are some techniques that we can use to take the String input in Java:
1. Using Scanner class nextLine() method
2. Using Scanner class next() method
3. Using BufferedReader class
4. Using Command-line arguments of main() method
1. Using Java Scanner class nextLine() method
The Scanner class is a part of the java.util package in Java. It comes with various methods to take different types of input from users like int, float, double, long, String, etc. The nextLine() method of the Scanner class takes the String input from the user. To use this method we need to import the java.util.Scanner class in our code.
The Scanner class is defined with the InputStream and system.in. We create an object of the Scanner class and pass the predefined object System.in into it. The System.in represents the Standard input Stream that is ready and open to taking the input from the user.
Then using the object of the Scanner class, we call the nextLine() method to read the String input from the user.
The signature of the nextLine() method is:
public String nextLine()
When this method does not find any String input on the console window, it throws NoSuchElementException and also throws IllegalStateException if we close the object of the Scanner class.
So, the general syntax of taking String input using the Scanner class is:
Scanner scannerObject = new Scanner(System.in);
String str = scannerObject.nextLine();
Now, let’s see the example to understand this concept:
Code to take String input using the nextLine() method of Scanner class:
package com.techvidvan.takestringinput; import java.util.Scanner; public class ScannerClassMethodDemo { public static void main(String[] args) { String name,city,course; Scanner sc = new Scanner(System. in ); System.out.println("Welcome to Techvidvan Tutorials"); System.out.println("Enter your name"); name = sc.nextLine(); System.out.println("Enter your city"); city = sc.nextLine(); System.out.println("Enter the course that you want to learn from TechVidvan"); course = sc.nextLine(); System.out.println("You entered the following details:"); System.out.println("Name: " + name); System.out.println("City: " + city); System.out.println("Opted Course: " + course); } }
Output
Avina
Enter your city
Indore
Enter the course that you want to learn from TechVidvan
Java
You entered the following details:
Name: Avina
City: Ujjain
Opted Course: Java
In the above program, during the execution, the console waits after the line-Enter your name until the user enters something.
2. Using the next() method of Scanner class in Java
Java next() method can read the input before space encounters. It cannot read two words separated by space. It retains the cursor in the same line after reading the input.
The signature of next() method is:
public String next()
Next method returns the next complete token from this scanner. It does not accept any parameter and throws NoSuchElementException if no more tokens are available. It also throws IllegalStateException if the scanner is in a closed state.
Code to take String input using the next() method of Scanner class:
package com.techvidvan.takestringinput; import java.util.Scanner; public class ScannerClassMethodDemo1 { public static void main(String[] args) { Scanner sc = new Scanner(System. in ); System.out.println("Enter a string:"); String myStr = sc.next(); //reads string before the space System.out.println("You entered: " + myStr); } }
Output
Hello, I am learning from TechVidvan Java Tutorial
You entered:
Hello,
So, in the above output, you can see that the output of the next() method is just before the first space encounters.
3. Using Java BufferedReader class
The Bufferedreader class in Java is another predefined class that takes the String input from the user. It reads the text from the console from the character-based input stream. This class is present in the java.io package of Java. The readLine() method of Bufferedreader class reads the String input from the user.
The signature of the readLine() method is:
public String readLine() throws IOException
The readLine() method returns a String containing the contents of the line excluding the line- terminated characters.
To use the BufferedReader class, we need to wrap the predefined object System.in in the InputStreamReader class, then pass this wrapped object to the BufferedReader constructor. Then, finally, we call the readLine method using this object.
So, the general syntax of taking String input using the Bufferedreader class is:
InputStreamReader inputObject = new InputStreamReader(System.in);
Bufferedreader bufferReaderObject = new bufferedReader(inputObject);
String str = bufferReaderObject.readLine();
Code to take String input using the readLine() method of BufferedReader class:
package com.techvidvan.takestringinput; import java.io. * ; public class BufferedReaderExample { public static void main(String args[]) throws Exception { InputStreamReader ir = new InputStreamReader(System. in ); BufferedReader br = new BufferedReader(ir); System.out.println("Enter your name:"); String name = br.readLine(); System.out.println("You entered: " + name); String sentence; System.out.println("Enter a sentence:"); sentence = br.readLine(); System.out.println("You entered: " + sentence); } }
Output
Sneha
You entered: Sneha
Enter a sentence:
This is a Java Tutorial on String input from the user. It is a cool tutorial.
You entered: This is a Java Tutorial on String input from the user. It is a cool tutorial.
Another example of reading data from console until the user writes “Stop”
Let’s see another example when the user keeps entering the String input and can stop giving the input by typing “Stop”. So the data is read and processed until the user enters Stop. Let’s see this example:
Code to understand the concept:
package com.techvidvan.takestringinput; import java.io. * ; public class BufferedReaderExample1 { public static void main(String args[]) throws Exception { InputStreamReader ir = new InputStreamReader(System. in ); BufferedReader br = new BufferedReader(ir); System.out.println("Enter the courses and write Stop when over:"); String course = " "; while (!course.equals("Stop")) { System.out.println("Enter Course: "); course = br.readLine(); System.out.println("You entered: " + course); } br.close(); ir.close(); } }
Output
Enter Course:
Java
You entered: Java
Enter Course:
Python
You entered: Python
Enter Course:
Machine Learning
You entered: Machine Learning
Enter Course:
Artificial Intelligence
You entered: Artificial Intelligence
Enter Course:
Big Data and Hadoop
You entered: Big Data and Hadoop
Enter Course:
Stop
You entered: Stop
4. Using Java Command-Line Arguments of the main() method
Java also provides a way to take String input using the command-line arguments. We need to pass the values while executing the program, i.e., java MyClass arguments-list. So, we enter the command line arguments after the class name. These arguments are passed to the main method of the application through the array of Strings. We can pass any number of arguments through the command-line.
Syntax of passing command-line arguments:
java MyClass argument1 argument3 argumentN
Code to take String input using command-line arguments:
package com.techvidvan.takestringinput; public class CommandLineStringInput { public static void main(String args[]) { int iterator = 0; for (iterator = 0; iterator < args.length; iterator++) { String s = args[iterator]; System.out.println(s); } } }
Output
Conclusion
Here, we come to the end of the article on taking string input in Java. This concept of Java is one of the most important concepts because it is the most basic thing that you should know. There are many situations when your application becomes dependent on the user’s input, the same is the case when you need to know this concept so that you can easily apply it in your code. We learned the four different techniques to take String input from the user through the console. Two classes Scanner class and the Bufferedreader class are helpful to take user input and Command line arguments are useful in taking the String inputs.
|
https://techvidvan.com/tutorials/taking-string-input-in-java/
|
CC-MAIN-2021-17
|
refinedweb
| 1,487
| 57.57
|
UNVIS(3) NetBSD Library Functions Manual UNVIS(3)Powered by man-cgi (2020-09-24). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.
NAME
unvis, strunvis, strnunvis, strunvisx, strnunvisx -- decode a visual rep- resentation of characters
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <vis.h> int unvis(char *cp, int c, int *astate, int flag); int strunvis(char *dst, const char *src); int strnunvis(char *dst, size_t dlen, const char *src); int strunvisx(char *dst, const char *src, int flag); int strnunvisx(char *dst, size_t dlen, const char *src, int flag);
DESCRIPTION
The unvis(), strunvis() and strunvisx() functions are used to decode a visual representation of characters, as produced by the vis(3) function, back into the original form. The unvis() function is called with successive characters in c until a valid sequence is recognized, at which time the decoded character is available at the character pointed to by cp. The strunvis() function() and strnunvisx() functions do the same as the strunvis() and strnunvis() functions, but take a flag that specifies the style the string src is encoded with. The meaning of the flag is the same as explained below for unvis()._NOESCAPE unvis() will not decode backslash escapes. If set to VIS_HTTPSTYLE or VIS_HTTP1808, unvis() will decode URI strings as specified in RFC 1808. If set to VIS_HTTP1866, unvis() will decode entity references and numeric character references as speci- fied in RFC 1866. If set to VIS_MIMESTYLE, unvis() will decode MIME Quoted-Printable strings as specified in RFC 2045. If set to VIS_NOESCAPE, unvis() will not decode `\' quoted characters.: errx(EXIT_FAILURE, "Bad character sequence!"); } } if (unvis(&out, '\0', &state, UNVIS_END) == UNVIS_VALID) (void)putchar(out);.
BUGS
The names VIS_HTTP1808 and VIS_HTTP1866 are wrong. Percent-encoding was defined in RFC 1738, the original RFC for URL. RFC 1866 defines HTML 2.0, an application of SGML, from which it inherits concepts of numeric character references and entity references. NetBSD 9.99 May 8, 2019 NetBSD 9.99
|
http://man.netbsd.org/unvis.3
|
CC-MAIN-2021-10
|
refinedweb
| 332
| 55.84
|
21 March 2012 18:01 [Source: ICIS news]
LONDON (ICIS)--European polycarbonate (PC) buyers are bracing themselves for significant price increases in the second quarter of the year because of rising feedstock costs, sources said on Wednesday.
“I expect second-quarter prices will go up by at least €300/tonne but maybe even €400/tonne if the market becomes tight because of maintenances in ?xml:namespace>
Most PC producers are aiming to raise second-quarter contract prices by €0.40–0.50/kg ($0.52–0.65/kg) because of higher raw material costs.
US-based plastics, latex and rubber producer Styron is targeting a €0.25/kg price increase for all European Calibre and Emerge PC compounds and blends, effective as of 1 April or as existing contract terms allow, the producer said in a statement in early March.
“This price increase comes as a result of the further escalation of key raw material costs associated with the manufacturing of [PC],” the statement said.
This was the second announcement Styron has made after a similar €0.25/kg price-hike notice in January.
Two other PC makers are targeting similar price increases. One of them, Saudi-based chemicals, fertilizers and plastics producer SABIC, has announced a €0.15/kg rise on top of a previous €0.19/kg increase because of higher-than-expected feedstock costs.
Producers said they viewed the market as bullish with sales improving every month.
They said the market was surprisingly good, which was unexpected after the sluggishness experienced in the last quarter of 2011.
It was unclear whether demand has increased because buyers are filling up inventories ahead of the announced price increases or whether it is because of underlying good demand from the construction and automotive industries.
Some PC makers said demand from these two sectors was good, although recently released statistics data showed contraction in European new car registrations and construction output.
Eurozone construction output fell by 0.8% in January 2012 compared with the previous month, and dropped by 4.1% in the 27-member EU, statistics office Eurostat said on Monday.
New registrations for passenger cars in the 27-member EU fell by 9.7% year on year in February, with
In light of this, PC buyers do not expect a major upturn in demand and describe the market as less bullish than producers do.
One consumer said it expected PC demand would drop by up to 7% compared with the same period last year.
“With all the additional capacity coming online in Asia and the
Consumers described the European market as balanced. Two said it was on the long side and there were no supply problems.
In addition, buyers said upstream tightness in phenol and bisphenol A (BPA) supply did not seem to be affecting PC supply and it was easy to obtain material at short notice.
But this may change in April and May when one major PC producer in
Styron will shut its 145,000 tonne/year PC plant in
A source at the company said everything is going according to plan and it is stocking up for the shutdown.
Another producer is expected to shut down in April but the dates and the length of the shutdown had not been confirmed by the company at the time of writing.
Second-quarter contract negotiations are ongoing and are expected to be finalised by the end of next week.
First quarter moulding grade PC is €2.60–2.70/kg and extrusion grade PC is €2.50–2.65/kg
(
|
http://www.icis.com/Articles/2012/03/21/9543799/rising-feedstock-costs-to-drive-up-price-of-european-pc.html
|
CC-MAIN-2015-11
|
refinedweb
| 592
| 61.97
|
This action might not be possible to undo. Are you sure you want to continue?
EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE) UNIT I LINEAR STRUCTURES Abstract Data Types
(ADT) – List ADT – array-based implementation – linked list implementation – cursor-based linked lists – doubly-linked lists – applications of lists – Stack ADT – Queue ADT – circular queue implementation – Applications of stacks and queues UNIT II TREE STRUCTURES Need for non-linear structures – Tree ADT – tree traversals – left child right sibling data structures for general trees – Binary Tree ADT – expression trees – applications of trees – binary search tree ADT UNIT III BALANCED SEARCH TREES AND INDEXING AVL trees – Binary Heaps – B-Tree – Hashing – Separate chaining – open addressing – Linear probing UNIT IV GRAPHS Definitions – Topological sort – breadth-first traversal - shortest-path algorithms – minimum spanning tree – Prim's and Kruskal's algorithms – Depth-first traversal – biconnectivity – Euler circuits – applications of graphs UNIT V ALGORITHM DESIGN AND ANALYSIS Greedy algorithms – Divide and conquer – Dynamic programming – backtracking – branch and bound – Randomized algorithms – algorithm analysis – asymptotic notations – recurrences – NP-complete problems
TEXT BOOKS 1. M. A. Weiss, “Data Structures and Algorithm Analysis in C”, Pearson Education Asia, 2002. 2. ISRD Group, “Data Structures using C”, Tata McGraw-Hill Publishing Company Ltd., 2006. REFERENCES 1. A. V. Aho, J. E. Hopcroft, and J. D. Ullman, “Data Structures and Algorithms”, Pearson Education, 1983. 2. R. F. Gilberg, B. A. Forouzan, “Data Structures: A Pseudocode approach with C”, Second Edition, Thomson India Edition, 2005. 3. Sara Baase and A. Van Gelder, “Computer Algorithms”, Third Edition, Pearson Education, 2000. 4. T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, "Introduction to algorithms", Second Edition, Prentice Hall of India Ltd, 2001.
UNIT I LINEAR STRUCTURES Abstract Data Types (ADT) – List ADT – array-based implementation – linked list Implementation – cursor-based linked lists – doubly-linked lists – applications of lists – Stack ADT – Queue ADT – circular queue implementation – Applications of stacks and queues
ABSTRACT DATA TYPE In programming each program is breakdown into modules, so that no routine should ever exceed a page. Each module is a logical unit and does a specific job modules which in turn will call another module. Modularity has several advantages 1. Modules can be compiled separately which makes debugging process easier. 2. Several modules can be implemented and executed simultaneously. 3. Modules can be easily enhanced. Abstract Data type is an extension of modular design. An abstract data type is a set of operations such as Union, Intersection, Complement, Find etc., The basic idea of implementing ADT is that the operations are written once in program and can be called by any part of the program. THE LIST ADT List is an ordered set of elements. The general form of the list is A1, A2, A3, ..... ,AN A1 - First element of the list AN - Last element of the list N - Size of the list If the element at position i is Ai then its successor is Ai+1 and its predecessor is Ai-1. Various operations performed on List
1. Insert (X, 5) - Insert the element X after the position 5. 2. Delete (X) - The element X is deleted 3. Find (X) - Returns the position of X. 4. Next (i) - Returns the position of its successor element i+1. 5. Previous (i) - Returns the position of its predecessor i-1. 6. Print list - Contents of the list is displayed. 7. Makeempty - Makes the list empty. 2.1 .1 Implementation of List ADT 1. Array Implementation 2. Linked List Implementation 3. Cursor Implementation. Array Implementation of List Array is a collection of specific number of data stored in a consecutive memory locations. * Insertion and Deletion operation are expensive as it requires more data movement * Find and Printlist operations takes constant time. * Even if the array is dynamically allocated, an estimate of the maximum size of the list is required which considerably wastes the memory space. Linked List Implementation Linked list consists of series of nodes. Each node contains the element and a pointer to its successor node. The pointer of the last node points to NULL. Insertion and deletion operations are easily performed using linked list. Types of Linked List 1. Singly Linked List 2. Doubly Linked List
int IsLast (List L) .2 Singly Linked List A singly linked list is a linked list in which each node contains only one link field pointing to the next node in the list. Position P) /* Insert after the position P*/ . position FindPrevious(int X. int IsEmpty (List L) . void Insert(int X. ROUTINE TO INSERT AN ELEMENT IN THE LIST void Insert (int X. position Next . List L) . 2. void Delete(int X. Position P) . DECLARATION FOR LINKED LIST Struct node . List L. List L) .1. List L) . position Find(int X. typedef struct Node *Position . Struct Node { int element . }. typedef struct Node *List . List L) . List L.3. position FindNext(int X. void DeleteList(List L) . Circular Linked List.
P.{ position Newnode. Newnode = malloc (size of (Struct Node)). If (Newnode! = NULL) { Newnode ->Element = X. L) ROUTINE TO CHECK WHETHER THE LIST IS EMPTY int IsEmpty (List L) /*Returns 1 if L is empty */ { if (L -> Next = = NULL) return (1). Newnode ->Next = P-> Next. } ROUTINE TO CHECK WHETHER THE CURRENT POSITION IS LAST int IsLast (position P. } } INSERT (25. List L) /* Returns 1 is P is the last position in L */ { if (P->Next = = NULL) return } . P-> Next = Newnode.
FIND ROUTINE position Find (int X. } FINDNEXT ROUTINE position FindNext (int X. while (P! = NULL && P Element ! = X) P = P->Next. NULL if X is not found */ position P. while (P -> Next ! = Null && P ->Next P = P ->Next. List L) Element ! = X) . return P. return P. List L) { /* Returns the position of the predecessor */ position P. } } FIND PREVIOUS ROUTINE position FindPrevious (int X. List L) { /*Returns the position of X in L. P = L-> Next. P = L.
} } ROUTINE TO DELETE THE LIST void DeleteList (List L) { .L)) { Temp = P→Next.L). If (!IsLast(P. Free (Temp). return P→Next. P = Findprevious (X. Temp. } ROUTINE TO DELETE AN ELEMENT FROM THE LIST void Delete(int X. while (P Next! = NULL && P Element ! = X) P = P→Next. List L) { /* Delete the first occurence of X from the List */ position P. P →Next = Temp→Next.{ /*Returns the position of its successor */ P = L ->Next.
position P) { . L→Next = NULL. forward link (FLINK) and Backward Link (BLINK). Struct Node *FLINK. } } 2.1.position P. ROUTINE TO INSERT AN ELEMENT IN A DOUBLY LINKED LIST void Insert (int X. STRUCTURE DECLARATION : Struct Node { int Element. Temp. P = L →Next. while (P! = NULL) { Temp = P→Next free (P). Struct Node *BLINK }.3 Doubly Linked List A Doubly linked list is a linked list in which each node has three fields namely data field. FLINK points to the successor node in the list whereas BLINK points to the predecessor node. list L. P = Temp.
L). P →Blink →Flink = NULL. P →Flink →Blink = Newnode. Newnode →Flink = P Flink. P = Find (X. Newnode = malloc (size of (Struct Node)). List L) { position P. If (Newnode ! = NULL) { Newnode →Element = X.Struct Node * Newnode. } else . P →Flink = Newnode . L)) { Temp = P. } } ROUTINE TO DELETE AN ELEMENT void Delete (int X. free (Temp). If ( IsLast (P. Newnode →Blink = P.
. * Finding the predecessor & Successor of a node is easier.{ Temp = P. Advantages of Circular Linked List • It allows to traverse the list starting at any point. • It allows quick access to the first and last records. 2. free (Temp). P →Blink→ Flink = P→Flink. Doubly Linked Circular List A doubly linked circular list is a Doubly linked list in which the forward link of the last node points to the first node and backward link of the first node points to the last node of the list. Circular linked list can be implemented as Singly linked list and Doubly linked list with or without headers.4 Circular Linked List In circular linked list the pointer of the last node points to the first node. P →Flink →Blink = P→Blink. Disadvantage * More Memory Space is required since it has two pointers. Singly Linked Circular List A singly linked circular list is a linked list in which the last node of the list points to the first node. } } Advantage * Deletion operation is easier.1.
Multilist Polynomial ADT We can perform the polynomial manipulations such as addition. Struct poly *Next.5 Applications of Linked List 1. subtraction and differentiation etc. int power. if (head1= =NULL) { head1 = newnode1. poly *newnode1) { poly *ptr. Radix Sort 3. DECLARATION FOR LINKED LIST IMPLEMENTATION OF POLYNOMIAL ADT Struct poly { int coeff .1. *list 3. Polynomial ADT 2. *list 2. CREATION OF THE POLYNOMIAL poly create (poly *head1. }*list 1. return (head1).2. } .
*ptr2. while (ptr1! = NULL && ptr2! = NULL) { newnode = malloc (sizeof (Struct poly)). ptr→next = newnode1. ptr1 = list1. . } ADDITION OF TWO POLYNOMIALS void add ( ) { poly *ptr1. *newnode. while (ptr next ! = NULL) ptr = ptr→next. if (ptr1→power = = ptr2 power) { newnode→coeff = ptr1→coeff + ptr2→coeff. ptr2 = list2. newnode→next = NULL. } return (head1). newnode→power = ptr1→power.else { ptr = head1.
list 3 = create (list3. ptr1 = ptr1→next. newnode). } else { if (ptr1→power > ptr2→ power) { newnode→coeff = ptr1→coeff. } else { newnode→coeff = ptr2→coeff. } } . newnode→power = ptr1→power. newnode). newnode). ptr1 = ptr1→next. ptr2 = ptr2→ next. newnode→next = NULL. ptr2 = ptr2→next. newnode→power = ptr2→power. list3 = create (list3. list3 = create (list3. newnode→next = NULL.
} SUBTRACTION OF TWO POLYNOMIAL void sub ( ) { poly *ptr1. if (ptr1 power = = ptr2 power) { newnode→coeff = (ptr1 coeff) . newnode→next = NULL. } else { if (ptr1→power > ptr2→power) { . list3 = create (list 3. ptr2 = list 2. while (ptr1! = NULL && ptr2! = NULL) { newnode = malloc (sizeof (Struct poly)). *newnode. ptr1 = list1 . *ptr2. ptr2 = ptr2→next. newnode). ptr1 = ptr1→next.(ptr2 coeff). newnode→power = ptr1 power.
newnode→power = ptr1→power. } } } } POLYNOMIAL DIFFERENTIATION void diff ( ) { poly *ptr1. ptr1 = ptr1→next. } else { newnode→coeff = .newnode→coeff = ptr1→coeff. newnode).(ptr2 coeff). newnode→power = ptr2→ power. newnode→next = NULL. list 3 = create (list 3. while (ptr1 ! = NULL) . ptr1 = list 1. ptr2 = ptr2 next. *newnode. newnode→next = NULL. newnode). list 3 = create (list 3.
newnode next = NULL. newnode power = ptr1 power . 187. 80. 174. } } Radix Sort : .(Or) Card Sort Radix Sort is the generalised form of Bucket sort. 15. In First Pass. 174. 10. PASS 1 : INPUT : 25. 187. 256. 256.1. 25. 8. It can be performed using buckets from 0 to 9. 256. all the elements are sorted according to the least significant bit. 174. 15. 15. 15. list 3 = create (list 3. 80. newnode). 10. In second pass. 25. 174. the numbers are arranged according to the next least significant bit and so on this process is repeated until it reaches the most significant bits of all numbers. 8 After Pass 2 : 8. ptr1 = ptr1→next. 10. newnode coeff = ptr1 coeff *ptr1 power. 8 PASS 2 : INPUT : 80.{ newnode = malloc (sizeof (Struct poly)). 256. 187 Buckets After Pass 1 : 80. The numbers of passes in a Radix Sort depends upon the number of digits in the numbers given. 187 PASS 3 : . 10. 25.
256.1 Stack Model : A stack is a linear data structure which follows Last In First Out (LIFO) principle. 10. 187. Pop PUSH : The process of inserting a new element to the top of the stack. For every push operation the top is incremented by 1.2. 256 Maximum number of digits in the given list is 3. 25. Example : Pile of coins.. 15. Push 2. 10. 25. Therefore the number of passes required to sort the list of elements is 3.INPUT : 8. a stack of trays in cafeteria. 2. 15. After every pop operation the top pointer is decremented by 1. 80.2 Operations On Stack The fundamental operations performed on a stack are 1. POP : The process of deleting an element from the top of stack is called pop operation.2 THE STACK ADT 2. EXCEPTIONAL CONDITIONS OverFlow Attempt to insert an element when the stack is full is said to be overflow. 174. UnderFlow . in which both insertion and deletion occur at only one end of the list called the Top. 187 After pass 3 : 8. 175. 80.2. 2.
ROUTINE TO PUSH AN ELEMENT ONTO A STACK void push (int x. else { Top = Top + 1. S[Top] = X. • To pop an element.2. • To push an element X onto the stack. Stack S) { if (IsFull (S)) Error ("Full Stack"). • pop on an empty stack or push on a full stack will exceed the array bounds. which is -1 for an empty stack. Top Pointer is incremented and then set Stack [Top] = X.Attempt to delete an element. when the stack is empty is said to be underflow.3 Implementation of Stack Stack can be implemented using arrays and pointers. the stack [Top] value is returned and the top pointer is decremented. 2. } } int IsFull (Stack S) { if (Top = = Arraysize) . Array Implementation In this implementation each stack is associated with a pop pointer.
} } int IsEmpty (Stack S) { if (S Top = = -1) return (1). .return (1). } ROUTINE TO RETURN TOP ELEMENT OF THE STACK int TopElement (Stack S) { if (! IsEmpty (s)) return S[Top]. } ROUTINE TO POP AN ELEMENT FROM THE STACK void pop (Stack S) { if (IsEmpty (S)) Error ("Empty Stack"). else { X = S [Top].1. Top = Top .
void pop (Stack S). }. typedef Struct Node *Stack.else Error ("Empty Stack"). ROUTINE TO CHECK WHETHER THE STACK IS EMPTY . Stack S). int Top (Stack S). Struct Node *Next. Struct Node { int Element . • Pop operation is performed by deleting at the front of the list. void MakeEmpty (Stack S). int IsEmpty (Stack S). DECLARATION FOR LINKED LIST IMPLEMENTATION Struct Node. • Top operation returns the element at the front of the list. return 0. Stack CreateStack (void). void push (int X. } LINKED LIST IMPLEMENTATION OF STACK • Push operation is performed by inserting an element at the front of the list.
int IsEmpty (Stack S) { if (S→Next = = NULL) return (1). } void MakeEmpty (Stack S) { if (S = = NULL) Error (" Create Stack First"). } ROUTINE TO CREATE AN EMPTY STACK Stack CreateStack ( ) { Stack S. MakeEmpty (s). else while (! IsEmpty (s)) pop (s). return S. S = malloc (Sizeof (Struct Node)). } . if (S = = NULL) Error (" Outof Space").
ROUTINE TO PUSH AN ELEMENT ONTO A STACK void push (int X. If (Tempcell = = NULL) Error ("Out of Space"). Tempcell = malloc (sizeof (Struct Node)). else { Tempcell Element = X. return 0. Stack S) { Struct Node * Tempcell. } ROUTINE TO POP FROM A STACK . Tempcell Next = S Next. } } ROUTINE TO RETURN TOP ELEMENT IN A STACK int Top (Stack S) { If (! IsEmpty (s)) return S→Next→Element. Error ("Empty Stack"). S→Next = Tempcell.
else { Tempcell = S→Next.void pop (Stack S) { Struct Node *Tempcell. Different Types of Notations To Represent Arithmetic Expression There are 3 different ways of representing the algebraic expression. (v) 8 Queen Problem. S→Next = S→Next→Next. Free (Tempcell).4 APPLICATIONS OF STACK Some of the applications of stack are : (i) Evaluating arithmetic expression (ii) Balancing the symbols (iii) Towers of Hannoi (iv) Function Calls.2. They are * INFIX NOTATION . If (IsEmpty (S)) Error ("Empty Stack"). } } 2.
CD XYAB . Also called as polish notation./ 2.* POSTFIX NOTATION * PREFIX NOTATION INFIX In Infix notation. . For example : . Evaluating Arithmetic Expression To evaluate an arithmetic expressions. The arithmetic operator appears between the two operands to which it is being applied.* + 3. (A + B) / (C .B) / +X/*Y .D) /+AB . A * B/C + D + / * ABCD AB * C / D + 1. ((A/B) + C) For example : .D) +A*B .+/ABC INFIX PREFIX (or) POLISH POSTFIX (or) REVERSE POLISH 1. ((A/B) + C) For example : ./ * XABD X A*B/D4.AB / C + PREFIX The arithmetic operator is placed before the two operands to which it applies. Also called reverse polish notation.A / B + C POSTFIX The arithmetic operator appears directly after the two operands to which it applies.CD ABCD .D) 5.CD AB + CD .*CD .AB .D . first convert the given infix expression to postfix expression and then evaluate the postfix expression using stack. A + B*(C . X + Y * (A ./ + (C . X * A / B .
If the character is an operand. POP two values from the stack. If N = 1. Step 3 : If the character is a left paraenthesis. discard both the parenthesis in the output. push its associated value onto the stack. Step 2. Step 2 : . Step 4 : If the character is a right paraenthesis. Step 3. push it onto the stack. Step 1. move the disk from A to C. Then move the 2nd disk from A to C. Recursive Solution N .represents the number of disks. The move the 1st disk from B to C. Repeat the step (2) to more the first 2 disks from A to B using C as intermediate. "#" Step 1 : If the character is an operand.Infix to Postfix Conversion Read the infix expression one character at a time until it encounters the delimiter. Step 1 : . pop all the operators from the stack till it encounters left parenthesis. If the stack operator has a higher or equal priority than input operator then pop that operator from the stack and place it onto the output. Evaluating Postfix Expression Read the postfix expression one character at a time until it encounters the delimiter `#'. If N = 3. Step 2 : If the character is an operator.If the character is an operator. . move the 1st disk from A to B. apply the operator to them and push the result onto the stack. If N = 2. place it on to the output. push it onto the stack.
Apply the recursive technique to move N . return. d. char d. } else { hanoi (n .1 disks from A to B using C as an intermediate. Then repeat the step (2) to move 2 disks from B to C using A as intermediate.1 disks from B to C using A as an intermediate. char i) { /* n no. Then move the Nth disk from A to C. i. s). d destination i intermediate */ if (n = = 1) { print (s. s. print (s. of disks. s source. RECURSIVE ROUTINE FOR TOWERS OF HANOI void hanoi (int n. } } . char s. In general.1. d) hanoi (n-1. i. d). to move N disks. d). return. Then again apply the recursive technique to move N .Then the 3rd disk is moved from A to C.
} 2. in which insertion is performed at rear end and deletion is performed at front end.3.2 Operations on Queue The fundamental operations performed on queue are 1. RECURSIVE FUNCTION TO FIND FACTORIAL : int fact (int n) { int s.1 Queue Model A Queue is a linear data structure which follows First In First Out (FIFO) principle. Enqueue 2.3 The Queue ADT 2. Similarly the current location address in the routine must be saved so that the new function knows where to go after it is completed. 2. if (n = = 1) return (1). otherwise the new function will overwrite the calling routine variables. else s = n * fact (n .3. Example : Waiting Line in Reservation Counter.Function Calls When a call is made to a new function all the variables local to the calling routine need to be saved. return (s). Dequeue Enqueue : .1).
ROUTINE TO ENQUEUE void Enqueue (int X) { if (rear > = max _ Arraysize) print (" Queue overflow").The process of inserting an element in the queue. 2. else { . the Queue [Front] is returned and the Front Pointer is incremented by 1. Exception Conditions Overflow : Attempt to insert an element. when the queue is empty is said to be underflow. Dequeue : The process of deleting an element from the queue.3. Underflow : Attempt to delete an element from the queue.3 Implementation of Queue Queue can be implemented using arrays and pointers. when the queue is full is said to be overflow condition. To insert an element X onto the Queue Q. the rear pointer is incremented by 1 and then set Queue [Rear] = X To delete an element. Array Implementation In this implementation queue Q is associated with two pointers namely rear pointer and front pointer.
else { X = Queue [Front]. F = 0. R = -1) . } } In Dequeue operation.Rear = Rear + 1.e. } } ROUTINE FOR DEQUEUE void delete ( ) { if (Front < 0) print (" Queue Underflow"). } else Front = Front + 1 . if Front = Rear. Queue [Rear] = X. then reset both the pointers to their initial values. Rear = -1. (i. if (Front = = Rear) { Front = 0.
Struct Node { int Element. Queue Q). void Enqueue (int X. int IsEmpty (Queue Q).Linked List Implementation of Queue Enqueue operation is performed at the end of the list. Struct Node *Next. Dequeue operation is performed at the front of the list. } . typedef Struct Node * Queue. void Dequeue (Queue Q). ROUTINE TO CHECK WHETHER THE QUEUE IS EMPTY int IsEmpty (Queue Q) // returns boolean value / { // if Q is empty if (Q→Next = = NULL) // else returns 0 return (1). }* Front = NULL. void MakeEmpty (Queue Q). Queue ADT DECLARATION FOR LINKED LIST IMPLEMENTATION OF QUEUE ADT Struct Node. Queue CreateQueue (void). *Rear = NULL.
newnode = Malloc (sizeof (Struct node)). return Q. Q = Malloc (Sizeof (Struct Node)). if (Q = = NULL) Error ("Out of Space").ROUTINE TO CHECK AN EMPTY QUEUE Struct CreateQueue ( ) { Queue Q. } ROUTINE TO ENQUEUE AN ELEMENT IN QUEUE void Enqueue (int X) { Struct node *newnode. else while (! IsEmpty (Q) Dequeue (Q). } void MakeEmpty (Queue Q) { if (Q = = NULL) Error ("Create Queue First"). MakeEmpty (Q). .
Rear = newnode. Rear = newnode. Front = newnode. if (Front = = NULL) Error("Queue is underflow"). Rear →next = newnode. newnode → Next = NULL. } } ROUTINE TO DEQUEUE AN ELEMENT FROM THE QUEUE void Dequeue ( ) { Struct node *temp. newnode →Next = NULL. } else { newnode → data = X.if (Rear = = NULL) { newnode →data = X. else { .
3. in which the first element comes just after the last element. } } 2. 2. Advantages It overcomes the problem of unutilized space in linear queues. the position of the element is calculated by the relation as Rear = (Rear + 1) % Maxsize. insertion and deletion operations are performed at both the ends.5 Circular Queue In Circular Queue. if (Front = = Rear) { Front = NULL. Print (temp→data). } else Front = Front →Next. Rear = NULL. free (temp).3. when it is implemented as arrays.temp = Front. and then set .4 Double Ended Queue (DEQUE) In Double Ended Queue. To perform the insertion of an element to the queue. the insertion of a new element is performed at the very first location of the queue if the last location of the queue is full.
Queue [Rear] = value. . } } To perform the deletion. the position of the Front printer is calculated by the relation Value = CQueue [Front] Front = (Front + 1) % maxsize. else { if (front = = -1) front = rear = 0. else rear = (rear + 1)% Maxsize. ROUTINE TO INSERT AN ELEMENT IN CIRCULAR QUEUE void CEnqueue (int X) { if (Front = = (rear + 1) % Maxsize) print ("Queue is overflow"). CQueue [rear] = X. ROUTINE TO DELETE AN ELEMENT FROM CIRCULAR QUEUE int CDequeue ( ) { if (front = = -1) print ("Queue is underflow").
else { X = CQueue [Front].3.3. 2. . } return (X). * Mathematics user Queueing theory. * Priority Queues can be used to sort the elements using Heap Sort. } 2. * Computer networks where the server takes the jobs of the client as per the queue strategy. else Front = (Front + 1)% maxsize. * Simulation.7 Applications of Queue * Batch processing in an operating system * To implement Priority Queues.6 Priority Queues Priority Queue is a Queue in which inserting an item or removing an item can be performed from any position based on some priority. if (Front = = Rear) Front = Rear = -1.
What are the advantages of doubly linked list over singly linked list? 4. What are the operations performed on stack and write its exceptional condition? 7. Write a procedure for polynomial differentiation. 18.Important Questions Part . 2. Convert the infix expression a + b * c + (d * e + f) * g to its equivalent postfix expression and prefix expression. 12. What are the advantages of linked list over arrays? 3. Write a routine to return the top element of stack. What do you mean by cursor implementation of list? 8. What is Circular Queue? 15. 11. What is Deque? 14. 6. What is Priority Queue? 16. 17. List the applications of List ADT. Write the recursive routine to perform factorial of a given number. Convert the infix expression (a * b) + ((c * g) . 13. Define Queue data structure and give some applications for it. Write a routine to check IsEmpty and Islast for queue. Define ADT. 10. 5.A 1.(e / f)) to its equivalent polish and reverse polish expression. Write a procedure to insert an element in a singly linked list . List the application of stack 9.
Write routines to implement addition. Write the recursive routine for Towers of Hanoi. Explain the array and linked list implementation of Queue. Write the operations performed on singly linked list? 9. Write the insertion and deletion routine for doubly linked list? 10. 3. What is Multilist? Part . Explain how stack is applied for evaluating an arithemetic expression. What is the principle of radix sort? 20. 7. Write the procedure for polynomial addition and differentiation? . 6. Explain the array and linked list implementation of stack.19. 2.B 1. subtraction & differentiation of two polynomials. 5. What are the various linked list operations? Explain 4. Explain Cursor implementation of List? 8.
The ADT tree A tree is a finite set of elements or nodes.. that node is called a leaf node.4. while the root is referred to as the parent of each subtree. F. The root of the subtree D is a leaf node. It is a notational convenience to allow an empty tree. F. while each of E. G and H have the same parent B.4: A simple tree.UNIT II TREE STRUCTURES Need for non-linear structures – Tree ADT – tree traversals – left child right sibling data structures for general trees – Binary Tree ADT – expression trees – applications of trees – binary search tree ADT TREES 3. Example 3. . each of which is itself a tree. each of whose roots are connected by a directed edge from Root R. T2. If a tree consists of a single node. 3. It is usual to represent a tree using a picture such as Fig. so the tree in Fig.4 is different from the one in which nodes E and F are interchanged. one of the nodes is distinguished as the root node. If the set is non-empty. Figure 3. while the remaining (possibly empty) set of nodes are grouped into subsets. as are the remaining nodes. in which the root node is A.4 Show how to implement the Abstract Data Type tree using lists. The node C has a single child I.1 PRELIMINARIES : TREE : A tree is a finite set of one or more nodes such that there is a specially designated node called the Root. and zero or more non empty sub trees T1. This hierarchical relationship is described by referring to each such subtree as a child of the root... 3. The subtrees rooted at a given node are taken to be ordered. G. E. Thus it makes sense to say that the first subtree at A has 4 leaf nodes. C and D.Tk. H and I. and there are three subtrees rooted at B.
4 is [A [[B [[E] [F] [G] [H]]] [C [I]] [D]]].n3. 3. .. PATH : A path from node n.. 3. LEAF : A node which doesn't have children is called leaf or Terminal node. Thus the list-based representation of the tree in Fig 3. are full. or one in which every node: • • • • has no children.5.. or has just a left child. while on the last level. We can represent a tree as a list consisting of the root and a list of the subtrees in order. There is exactly only one path from each node to root. Maximum number of nodes at level i of a binary tree is 2i-1.. DEGREE : The number of subtrees of a node is called its degree. to nk is defined as a sequence of nodes n1. except perhaps the last. A complete binary tree is a special case of a binary tree. G are siblings. ROOT : A node which doesn't have a parent. An example is shown in Fig. and distinguish A from [A]. any missing nodes are to the right of all the nodes that are present. LENGTH : The length is defined as the number of edges on the path. for .2 BINARY TREE Definition :Binary Tree is a tree in which no node can have more than two children. A binary tree is a tree which is either empty. NODE : Item of Information. n2. F. or has just a right child.nk such that ni is the parent of ni+1. in which all the levels. In the above tree.Solution We write [A B C] for the list containing three elements. or has both a left and a right child. SIBLINGS : Children of the same parents are said to be siblings.
5 Give a space . Example 3. Thus traversing the tree can be done very efficiently. while the parent of node A[k] is at A[k div 2]. more than two children. Describe how to pass from a parent to its two children. Struct TreeNode *Left . . and vice-versa Solution An obvious one. providing they both exists.Figure 3.efficient implementation of a complete binary tree in terms of an array A.5: A complete binary tree: the only ``missing'' entries can be on the last row. }. COMPARISON BETWEEN GENERAL TREE & BINARY TREE General Tree Binary Tree * General Tree has any * A Binary Tree has not number of children. BINARY TREE NODE DECLARATIONS Struct TreeNode { int Element. the two children in A[2] and A[3]. An element A[k] has children at A[2k] and A[2k+1]. Struct TreeNode *Right. the next generation at A[4] up to A[7] and so on. in which no space is wasted. stores the root of the tree in A[1].
For any element in position i. Linked Representation The elements are represented using pointers. of nodes in full binary tree is = 23+1 -1 = 15 nodes. 3. 3. both the pointer fields are assigned as NULL. preorder and postorder traversal. In the bottom level the elements should be filled from left to right. . Each node in linked representation has three fields.2.1REPRESENTATION OF A BINARY TREE There are two ways for representing binary tree.2 EXPRESSION TREE Expression Tree is a binary tree in which the leaf nodes are operands and the interior nodes are operators. namely. COMPLETE BINARY TREE : A complete binary tree of height h has between 2h and 2h+1 .1 nodes. and the parent is in position (i/2). the left child is in position 2i. they are * Linear Representation * Linked Representation Linear Representation The elements are represented using arrays. Like binary tree.FULL BINARY TREE :A full binary tree of height h has 2h+1 . Here height is 3 No. * Pointer to the left subtree * Data field * Pointer to the right subtree In leaf nodes.2.1 nodes. the right child is in position (2i + 1). expression tree can also be travesed by inorder.
Read one symbol at a time from the postfix expression. * It doesn't have any order. Comparision Between Binary Tree & Binary Search Tree Binary Tree Binary Search Tree * A tree is said to be a binary * A binary search tree is a binary tree in which tree if it has atmost two childrens. .node tree and push a pointer on to the stack. typedef struct TreeNode * SearchTree. the key values in the left node is less than the root and the keyvalues in the right node is greater than the root. the values of all the keys in its left subtree are smaller than the key value in X. Check whether the symbol is an operand or operator.Constructing an Expression Tree Let us consider postfix expression given as an input for constructing an expression tree by performing the following steps : 1. create a one .Binary Search Tree Definition : Binary search tree is a binary tree in which for every node X in the tree. Note : * Every binary search tree is a binary tree. A pointer to this new tree is then pushed onto the stack. (a) If the symbol is an operand. and the values of all the keys in its right subtree are larger than the key value in X. (b) If the symbol is an operator pop two pointers from the stack namely T1 and T2 and form a new tree with root as the operator and T2 as a left child and T1 as a right child. * All binary trees need not be a binary search tree. 2. 3. DECLARATION ROUTINE FOR BINARY SEARCH TREE Struct TreeNode.3 The Search Tree ADT : .
int FindMax (SearchTree T).SearchTree Insert (int X. }. SearchTree MakeEmpty (SearchTree T). int FindMin (Search Tree T). Make Empty :This operation is mainly for initialization when the programmer prefer to initialize the first element as a one .node tree. SearchTree T). Struct TreeNode { int Element . SearchTree Left. Right). } left). SearchTree T). SearchTree Delete (int X. . SearchTree Right. ROUTINE TO MAKE AN EMPTY TREE :SearchTree MakeEmpty (SearchTree T) { if (T! = NULL) { MakeEmpty (T MakeEmpty (T free (T). int Find (int X. SearchTree T).
. Then x is placed in T Right.return NULL . * Check with the root node T * If it is less than the root. * If X is greater than the root. { T →Element = X. Traverse the left subtree recursively until it reaches the T T left equals to NULL. if (T! = NULL) // First element is placed in the root. Then X is placed in left. T→ left = NULL. ROUTINE TO INSERT INTO A BINARY SEARCH TREE SearchTree Insert (int X. Traverse the right subtree recursively until it reaches the T right equals to NULL. searchTree T) { if (T = = NULL) { T = malloc (size of (Struct TreeNode)). } Insert : To insert the element X into the tree.
* Otherwise. 5. return T. left = Insert (X.e. Traverse the left of T recursively. Traverse towards left 10 > 8. Find : * Check whether the root is NULL if so then return NULL. T (1) If X is equal to T (2) If X is less than T data. return T. } Example : To insert 8. As 5 < 8. // Else X is in the tree already.T →Right = NULL. Check the value X with the root node value (i. 3 * First element 8 is considered as Root. 18. 10. 15. data. T →left). } } else if (X < T →Element) T else if (X > T →Element) T Right = Insert (X. data) . Similarly the rest of the elements are traversed. 20. Traverse towards Right. T →Right).
SearchTree T) { If T = = NULL) Return NULL . The stopping point is the smallest element.(3) If X is greater than T data. // returns the position of the search element. RECURISVE ROUTINE FOR FINDMIN int FindMin (SearchTree T) . Go to the right child of 8 10 is checked with Root 15 10 < 15. else If (X > T→ Element) return Find (X. 10 is checked with root 10 (Found) Find Min : This operation returns the position of the smallest element in the tree. Go to the left child of 15. ROUTINE FOR FIND OPERATION Int Find (int X. traverse the right of T recursively. } Example : . start at the root and go left as long as there is a left child. If (X < T Element) return Find (X. else return T. To perform FindMin. X = 10) 10 is checked with the Root 10 > 8.To Find an element 10 (consider. T →left). T →Right).
{ if (T = = NULL). (b) T! = NULL and T→left!=NULL. return NULL . Example : Root T T (a) T! = NULL and T→left!=NULL. else if (T →left = = NULL) return T. Traverse left Traverse left Min T (c) Since T left is Null.RECURSIVE ROUTINE FOR FINDMIN int FindMin (SearchTree T) { if (T! = NULL) while (T →Left ! = NULL) T = T →Left . NON . } FindMax . return T as a minimum element. return T. else return FindMin (T → left).
NON . RECURSIVE ROUTINE FOR FINDMAX int FindMax (SearchTree T) { if (T = = NULL) return NULL . (b) T! = NULL and T→Right!=NULL. else if (T →Right = = NULL) return T. return T as a Maximum element. } Example :Root T (a) T! = NULL and T→Right!=NULL. .RECURSIVE ROUTINE FOR FINDMAX int FindMax (SearchTree T) { if (T! = NULL) while (T Right ! = NULL) T = T →Right . start at the root and go right as long as there is a right child. Traverse Right Traverse Right Max (c) Since T Right is NULL. To perform a FindMax. else FindMax (T →Right).FindMax routine return the position of largest elements in the tree. The stopping point is the largest element.
To delete an element. Node with one child. it can be deleted by adjusting its parent pointer that points to its child node. searchTree T) { . it can be deleted immediately.return T . Node with no children (Leaf node) If the node is a leaf node. } Delete : Deletion operation is the complex operation in the Binary search tree.Node with one child If the node has one child. CASE 1 CASE 2 CASE 3 CASE 1 Node to be deleted is a leaf node (ie) No children. Case 3 : Node with two children It is difficult to delete a node which has two children. Node with two children. the pointer currently pointing the node 5 is now made to to its child node 6. To Delete 5 before deletion After deletion To delete 5. Delete : 8 After the deletion CASE 2 : . The general strategy is to replace the data of the node to be deleted with its smallest data of the right subtree and recursively delete that node. DELETION ROUTINE FOR BINARY SEARCH TREES SearchTree Delete (int X. consider the following three possibilities.
T →Right = Delete (T → Element. T →Right). // Found Element tobe deleted else // Two children if (T→ Left && T→ Right) { // Replace with smallest data in right subtree Tmpcell = FindMin (T→ T →Element = Tmpcell Right). } else // one or zero children { Tmpcell = T.int Tmpcell . T Left). if (T →Left = = NULL) T = T→ Right. T →Right). . if (T = = NULL) Error ("Element not found"). else if (X > T Element) // Traverse towards right T →Right = Delete (X. Element . else if (X < T →Element) // Traverse towards left T →Left = Delete (X.
Right = = NULL) free (TmpCell).else if (T→ T = T →Left . } return T. } .
the difference in the heights of its two subtrees is at most 1. An equivalent definition. AVL trees overcome this problem. and an empty binary tree has height -1. the binary search tree is very unbalanced. When sorted data is inserted. As another example. for an AVL tree is that it is a binary search tree in which each node has a balance factor of -1. The balance factor of a node is the height of its right subtree minus the height of its left subtree. However. note that the root node with balance factor +1 has a right subtree of height 1 more than the height of the left subtree. that is. essentially more of a linear list. Note that a balance factor of -1 means that the subtree is left-heavy. A balanced binary search tree has Theta(lg n) height and hence Theta(lg n) worst case lookup and insertion times.) . (The balance factors are shown at the top of each node. then. height-balanced binary search trees and are named after the inventors: Adelson-Velskii and Landis. 7 / 3 / 2 / 9 10 \ 11 / \ 12 \ 20 An AVL tree is a binary search tree in which every node is height balanced. the following binary tree has height 3. For example. or +1. 0. and a balance factor of +1 means that the subtree is right-heavy.UNIT III BALANCED SEARCH TREES AND INDEXING 9 AVL trees – Binary Heaps – B-Tree – Hashing – Separate chaining – open addressing – Linear probing AVL Trees The Concept These are self-adjusting. A singlenode binary tree has height 0. in the following AVL tree. Definitions The height of a binary tree is the maximum path length from the root to a leaf. ordinary binary search trees have a bad worst case. with Theta(n) height and thus Theta(n) worst case insertion and lookup times.
. Hence it should have Theta(lg n) height (it does . like a binary search tree which can become very unbalanced and give Theta(n) worst case lookup and insertion times. An AVL tree does not have a bad worst case. The following binary search tree is not an AVL tree. There are three main cases to consider when inserting a new node. -1 100 / -2 70 / +1 30 / 0 10 0 36 / \ -1 40 \ 0 80 +1 130 \ 0 140 / \ -1 150 \ 0 180 Inserting a New Item Initially. Note that the item always goes into a new leaf. The tree is then readjusted as needed in order to maintain it as an AVL tree. Notice the balance factor of -2 at node 70. a new item is inserted just as in a binary search tree.always) and so have Theta(lg n) worst case insertion and lookup times.+1 30 / -1 22 / 0 5 +1 44 \ 0 51 / 0 77 / \ 0 62 \ -1 95 The idea is that an AVL tree is close to being completely balanced.
Consider the following example. 0 40 / +1 20 \ 0 30 0 45 / \ 0 50 \ 0 70 After inserting 60 we get: +1 40 / +1 20 \ 0 30 0 45 / \ +1 50 \ -1 70 / 0 60 Case 2: A node with balance factor -1 changes to 0 when a new node is inserted in its right subtree. Note that after an insertion one only needs to check the balances along the path from the new leaf to the root. -1 40 / +1 20 \ 0 50 . Consider the following example.Case 1: A node with balance factor 0 changes to +1 or -1 when a new node is inserted below it.) No change is needed at this node. No change is needed at this node. (Similarly for +1 changing to 0 when inserting in the left subtree.
The tree is restored to an AVL tree by using a rotation. This is accomplished by doing a right rotation at P. (Similarly for +1 changing to +2 when inserting in the right subtree.the -1 changed to a 0 (case 2) / +1 20 / case 1 0 10 0 22 / \ 0 30 \ 0 32 0 45 / 0 60 / 40 \ +1 <-.) Change is needed at this node. This is very important since it means that we still have a legitimate binary search tree. Note that rotations do not mess up the order of the nodes given in an inorder traversal. Subcase A: This consists of the following situation. that the mirror image situation is also included under subcase A.an example of 70 Case 3: A node with balance factor -1 changes to -2 when a new node is inserted in its left subtree. and X is the new node added./ 0 10 0 22 \ 0 30 / \ 0 32 0 45 / \ 0 70 After inserting 60 we get: 0 <-. Note that inserting X makes P have a balance factor of -2 and LC have a balance factor of -1.) (rest of tree) | -2 P / -1 \ sub . (Note. LC is P's left child. where P denotes the parent of the subtree being examined. The -2 must be fixed.an example of case 1 50 \ -1 <-. too.
LC / sub tree of height n / X \ sub tree of height n tree of height n The fix is to use a single right rotation at node P. (In the mirror image case a single left rotation is used at P. (Always check from the bottom up.) . -1 80 / -1 30 / 0 15 0 10 / \ 0 20 \ 0 40 0 90 / \ -1 100 We then insert 5 and then check the balance factors from the new leaf up toward the root. (rest of tree) | 0 LC / sub tree of height n / X \ P / sub tree of height n \ sub tree of height n Consider the following more detailed example that illustrates subcase A.) This gives the following picture.
) The fix is accomplished with a right rotation at node 30.-2 80 / -2 30 / -1 15 -1 10 / \ 0 20 \ 0 40 0 90 / \ -1 100 / 0 5 This reveals a balance factor of -2 at node 30 that must be fixed. leading to the following picture. we reach the -2 at 30 first. The following is a general illustration of this situation. -1 80 / 0 15 / -1 10 0 5 / 0 20 / \ 0 30 \ 0 40 0 90 / \ -1 100 Recall that the mirror image situation is also included under subcase A. Then draw a picture of a particular example that fits our general picture below and fix it with a left rotation. (rest of tree) | +2 P / sub tree \ +1 RC . See if you can draw a picture of the following after the left rotation at P. The other -2 problem will go away once we fix the problem at 30. (Since we work bottom up. The fix is to use a single left rotation at P.
Note that inserting X makes P have a balance factor of -2 and LC have a balance factor of +1. and X is the new node added. This consists of a single right rotation at the right child RC followed by a single left rotation at P. LC is P's left child. (rest of tree) | -2 P . (In the mirror image case a double left rotation is used at P. A double right rotation at P consists of a single left rotation at LC followed by a single right rotation at P.) In the above picture.) (rest of tree) | -2 P / +1 LC / sub tree of height n \ -1 NP / \ sub sub tree tree n-1 n-1 / X \ sub tree of height n The fix is to use a double right rotation at node P. (Note that the mirror image situation is also included under subcase B. NP is the node that will be the new parent. X might be added to either of the subtrees of height n-1. This is accomplished by doing a double rotation at P (explained below). the double rotation gives the following (where we first show the result of the left rotation at LC. where P denotes the parent of the subtree being examined. then a new picture for the result of the right rotation at P). The -2 must be fixed.of height n / sub tree of height n \ sub tree of height n \ X Subcase B: This consists of the following situation.
(rest of tree) | 0 NP / 0 LC / sub tree of height n \ sub tree n-1 / X / sub tree n-1 \ +1 P \ sub tree of height n Consider the following concrete example of subcase B./ -2 NP / 0 LC \ sub tree n-1 \ sub tree of height n / sub tree of height n \ sub tree n-1 / X Finally we have the following picture after doing the right rotation at P. -1 80 / 0 30 / -1 20 0 10 / 0 40 / \ 0 50 \ 0 60 0 90 / \ 0 100 \ 0 120 .
as seen below.After inserting 55. First we do a single left rotation at 30. -2 80 / -1 50 / -1 30 / -1 20 \ 0 40 / 0 55 \ -1 60 0 90 / \ 0 100 \ 0 120 / 0 10 Finally. a balance factor of -2 at the root node. this calls for a double rotation. The resulting picture is shown below. This gives the following picture. the right rotation at 80 restores the binary search tree to be an AVL tree. . -2 80 / +1 30 / -1 20 0 10 / 0 40 / \ +1 50 \ / 0 55 -1 60 0 90 / \ 0 100 \ 0 120 As discussed above. we get a problem.
As it is represented as array it doesn't require . which is a completely filled binary tree with the possible exception of the bottom level. Like AVL trees. A complete binary tree of height H has between 2H and 2H+1 -1 nodes. Binary heap is merely referred as Heaps. so a heap operation must not terminate until all heap properties are in order. (ie) (23 and 24-1). the left child is in position 2i. Both the operations require the average running time as O(log N). Heap have two properties namely * Structure property * Heap order property. Structure Property A heap should be complete binary tree. which is filled from left to right. and the parent is in i/2.0 50 / -1 30 / -1 20 0 10 / \ 0 40 / 0 55 -1 60 / 0 90 / \ 0 80 \ 0 100 \ 0 120 BINARY HEAP The efficient way of implementing priority queue is Binary Heap. For example if the height is 3. Then the numer of nodes will be between 8 and 15. the right child is in position 2i + 1. For any element in array position i. an operation on a heap can destroy one of the properties.
for every node X. Initialization PriorityQueue Initialize (int MaxElements) { PriorityQueue H. Heap Order Property In a heap. int DeleteMin (PriorityQueue H). . H = malloc (sizeof (Struct Heapstruct)). }. the key in the parent of X is smaller than (or equal to) the key in X. we get the FindMin operation in constant time. typedef struct Heapstruct * priority queue. void insert (int X. Declaration for priority queue Struct Heapstruct. PriorityQueue Initialize (int MaxElements). But the only disadvantage is to specify the maximum heap size in advance. Struct Heapstruct { int capacity. with the exception of the root (which has no parent). int *Elements. PriorityQueue H).pointers and also the operations required to traverse the tree are extremely simple and fast. int size. Thus. This property allows the deletemin operations to be performed quickly has the minimum element can always be found at the root.
return. i/=2) /* If the parent value is greater than X. H→ Elements [i/2] > X. This process continues until X can be placed in the hole. . Routine To Insert Into A Binary Heap void insert (int X. PriorityQueue H) { int i. then place the element X there itself. thus bubbling the hole up toward the root. This general strategy is known as Percolate up. then place the element of parent node into the hole */. } for (i = ++H→ size. Otherewise. in which the new element is percolated up the heap until the correct location is found. BASIC HEAP OPERATIONS To perform the insert and DeleteMin operations ensure that the heap order property is maintained. H size = 0. we create a hole in the next available location.H Capacity = MaxElements. return H. If (Isfull (H)) { Error (" priority queue is full"). otherwise the tree will not be complete. H elements [0] = MinData. we slide the element that is in the hole's parent node into the hole. If X can be placed in the hole without violating heap order. Insert Operation To insert an element X into the heap.
child. thus pushing the hole down one level. int MinElement.H→ H→ } Elements [i] = H→Elements [i/2]. When this minimum is removed. we slide the smaller of the hole's children into the hole. elements [i] = X. return H → Elements [0]. ROUTINE TO PERFORM DELETEMIN IN A BINARY HEAP int Deletemin (PriorityQueue H) { int i. If X can be placed in hole without violating heaporder property place it. i * 2 < = H size . } MinElement = H → Elements [1]. a hole is created at the root. if (IsEmpty (H)) { Error ("Priority queue is Empty"). We repeat until X can be placed in the hole. LastElement. This general strategy is known as perculate down. Otherwise. size. // otherwise. LastElement = H→Elements [H→ for (i = 1. i = child) . DeleteMin DeleteMin Operation is deleting the minimum element from the Heap. Since the heap becomes one smaller. makes the last element X in the heap to move somewhere in the heap. In Binary heap the minimum element is found in the root.-]. place it in the hole.
} OTHER HEAP OPERATIONS The other heap operations are (i) Decrease .{ /* Find Smaller Child */ child = i * 2. .key (ii) Increase . // Percolate one level down if (LastElement > H →Elements [child]) H→ else break . if (child ! = H → size && H →Elements [child + 1] < H →Elements [child]) child + +.key (iii) Delete (iv) Build Heap DECREASE KEY Elements [i] = H → Elements [child]. } H → Elements [i] = LastElement. return MinElement.
Note that a large node size (with lots of keys in the node) also fits with the fact that with a disk drive one can usually read a fair amount of data at once. Definitions A multiway tree of order m is an ordered tree where each node has at most m children.Key The increase . then. H) operation increases the value of the key at position p by a positive amount . . . the following is a multiway search tree of order 4. which can be fixed by percolate down. may also be large. Note that the first row in each node shows the keys. which can be fixed by percolate up. in any useful application there would be a record of data associated with each key. then this is called a multiway search tree of order m. If the keys and subtrees are arranged in the fashion of a search tree.The Decreasekey (P. . The example software will use the first method. B-Trees Introduction A B-tree is a specialized multiway tree designed especially for use on disk. This means that only a small number of nodes must be read from disk to retrieve an item. A B-tree is designed to branch out in this large number of directions and to contain a lot of keys in each node so that the height of the tree is relatively small. if k is the actual number of children in the node. Of course. and with disk drives this means reading a very small number of records. Another approach would be to have the first row of each node contain an array of records where each record contains a key and a record number for the associated data record. Increase .1 is the number of keys in the node. H) operation decreases the value of the key at position P by a positive amount . The goal is to get fast access to the data. while the second row shows the pointers to the child nodes. This last method is often used when the data records are large. This may violate the heap order property. For example.key (p. In a B-tree each node may contain a large number of keys. For each node. then k . which is found in another file. This may violate heap order property. so that the first row in each node might be an array of records where each record contains a key and its associated data. The number of subtrees of each node.
Branch[3] has only keys that are greater than Node. All internal nodes (except the root node) have at least ceil(m / 2) (nonempty) children. } NodeType. long Branch[4]. .Branch[0] has only keys that are less than Node.Key[0].Key[1]. o The subtree starting at record Node.Key[0] and at the same time less than Node.Key[2]. ItemType Key[3]. At every given node (call it Node) the following is true: o The subtree starting at record Node.Key[1] and at the same time less than Node.Branch[2] has only keys that are greater than Node. these 4 conditions are truncated so that they speak of the appropriate number of keys and branches.What does it mean to say that the keys and subtrees are "arranged in the fashion of a search tree"? Suppose that we define our nodes as follows: typedef struct { int Count. This generalizes in the obvious way to multiway search trees with other orders. A B-tree of order m is a multiway search tree of order m such that: • • All leaves are on the bottom level. Note that if less than the full number of keys are in the Node. o The subtree starting at record Node. // number of keys stored in the current node // array to hold the 3 keys // array of fake pointers (record numbers) Then a multiway search tree of order 4 has to fulfill the following conditions related to the ordering of the keys: • • • The keys in each node are in ascending order. o The subtree starting at record Node.Key[2].Branch[1] has only keys that are greater than Node.
ceil(5.98) = 2. ceil(7) = 7.• • The root node can have as few as 2 children if it is an internal node. Of course. the whole tree consists only of the root node). A B-tree is a fairly well-balanced tree by virtue of the fact that all leaf nodes must be at the bottom. Operations on a B-Tree Question: How would you search in the above tree to look up S? How about J? How would you do a sort-of "in-order" traversal. ceil(3. Note that ceil(x) is the so-called ceiling function. According to condition 4. Example B-Tree The following is an example of a B-tree of order 5. each leaf node must contain at least 2 keys. In practice B-trees usually have orders a lot bigger than 5. ceil(1. the maximum number of children that a node can have is 5 (so that 4 is the maximum number of keys).5) = 3 children (and hence at least 2 keys). that is. a traversal that would produce the letters in ascending order? (One would only do such a traversal on rare occasion as it would require a large amount of disk activity and thus be very slow!) Inserting a New Item According to Kruse (see reference at the end of this file) the insertion algorithm proceeds as follows: When inserting an item. Thus ceil(3) = 3. This causes the tree to "fan out" so that the path from root to leaf is very short even in a tree that contains a lot of data.1 keys. etc.35) = 4. and can obviously have no children if the root node is a leaf (that is. Each leaf node must contain at least ceil(m / 2) . first do a search for it in the B-tree.01) = 6. If the item is not . It's value is the smallest integer that is greater than or equal to x. Condition (2) tries to keep the tree fairly bushy by insisting that each node have at least half the maximum number of children. This means that (other that the root node) all internal nodes have at least ceil(5 / 2) = ceil(2.
resulting in this picture: When we try to insert the H. if that node has no room. moving the median item G up into a new root node. so we split it into 2 nodes. not only might we have to move some keys one position to the right. If there is room in this leaf. If the root node is ever split. The median (middle) key is moved up into the parent node. The first 4 letters get inserted into the same node. the median key moves up into a new root node. but the associated pointers have to be moved right as well.) Note that when adding to an internal node.. this unsuccessful search will end at a leaf. Note that this may require that some existing keys be moved one to the right to make room for the new item. then the node must be "split" with about half of the keys going into a new node to the right of this one. K. just insert the new item here. Inserting E. Let's work our way through an example similar to that given by Kruse. If instead this leaf node is full so that there is no room to add the new item. (Of course. Note that in practice we just leave the A and C in the current node and place the H and N into a new node to the right of the old one. then it may have to be split as well. we find no room in this node. thus causing the tree to increase in height by one. and Q proceeds without requiring any splits: . All nodes other than the root must have a minimum of 2 keys.already in the B-tree..
Deleting an Item.)
Although E is in a leaf. In our example. let's combine the leaf containing F with the leaf containing A C. the N P node would be attached via the pointer field to the right of M's new location.Finally. Suppose for the moment that the right sibling (the node with Q X) had one more key in it somewhere to the right of Q. Since in our example we have no way to borrow a key from a sibling. We also move down the D. Of course. If this problem node had a sibling to its immediate left or right that had a spare key. then we would again "borrow" a key. . In such a case the leaf has to be combined with one of these two siblings. let's delete E. the leaf has no extra keys. G. nor do the siblings to the immediate right or left. In other words. This one causes lots of problems. you immediately see that the parent node now contains only one key. This includes moving down the parent's key that was between those of these two leaves. the old left subtree of Q would then have to become the right subtree of M. This is not acceptable. We would then move M down to the node with too few keys and move the Q up where the M had been. However.
Let's consolidate with the A B node. which would be D. We begin by finding the immediate successor. this leaves us with a node with too few keys. and move the D up to replace the C. Let's try to delete C from it. Since neither the sibling to the left or right of the node containing E has an extra key. we must combine the node with one of these two siblings.we must again combine with the sibling. However. the tree shrinks in height by one. Another Example Here is a different B-tree of order 5. In this case. and move down the M from the parent. .
move it up to the parent. Note that the K L node gets reattached to the right of the J.Hash (92) . Thus we borrow the M from the sibling. A simple Hash function HASH (KEYVALUE) = KEYVALUE MOD TABLESIZE Example : . and bring the J down to join the F. containing the keys. A key is a value associated with each record. However.address transformation. its sibling has an extra key.But now the node containing F does not have enough keys.to . Hashing Function A hashing function is a key . Hashing Hash Table The hash table data structure is an array of some fixed size. which acts upon a given key to compute the relative position of the key in an array.
Mid . Module Division 2. Radix Transformation.Square Method 3. int Table Size) { int Hashvalue = 0. return Hashval % Tablesize. (ie) When two key values hash to the same position. Collisions Collision occurs when a hash value of a record being inserted hashes to an address (i. while (* key ! = `\0') Hashval + = * key ++. Collision Resolution The process of finding another position for the collide record. Digit or Character Extraction Method 6. Some of the Collision Resolution Techniques . PSEUDO Random Method 5. } Some of the Methods of Hashing Function 1. Relative position) that already contain a different record.Hash (92) = 92 mod 10 = 2 The keyvalue `92' is placed in the relative location `2'.e. Folding Method 4. ROUTINE FOR SIMPLE HASH FUNCTION Hash (Char *key.
Insertion To perform the insertion of an element. Open Addressing 3.1. the table can never overflow. If it is a duplicate element. traverse down the appropriate list to check whether the element is already in place. since the linked list are only extended upon the arrival of new keys. it is insertd either at the front of the list or at the end of the list. . an extra field is kept and placed. Seperate Chaining 2. If the element turns to be a new one. INSERT 10 : Hash (k) = k% Tablesize Hash (10) = 10 % 10 NSERT 11 : Hash (11) = 11 % 10 Hash (11) = 1 INSERT 81 : Hash (81) = 81% 10 Hash (81) = 1 The element 81 collides to the same hash value 1. Multiple Hashing Seperate Chaining Seperate chaining is an open hashing technique. In this method. When an overflow occurs this pointer is set to point to overflow blocks making a linked list. To place the value 81 at this position perform the following. A pointer field is added to each record location.
If (Newcell ! = NULL) ( L=H Thelists [Hash (key. ROUTINE TO PERFORM INSERTION void Insert (int key. Since it is not already present. insert at end of the list. H Tablesize)]. /* Insert the key at the front of the list */ L →Next = Newcell. Next = L → Next. Similarly the rest of the elements are inserted.Traverse the list to check whether it is already present. Hashtable H) { Position Pos. H). Newcell→ Newcell → Element = key. /* Traverse the list to check whether the key is already present */ Pos = FIND (Key. If (Pos = = NULL) /* Key is not found */ { Newcell = malloc (size of (struct ListNode)). List L. Newcell. } } } .
. L = H→ P = L→ Thelists [Hash (key.are tried in succession. while (P! = NULL && P Element ! = key) P = p→Next... if a collision occurs. * It takes more effort to perform a search. } Advantage More number of elements can be inserted as it uses array of linked lists. alternative cells are tried until an empty cell is found. h2(x). h1(x). They are (i) Linear Probing . OPEN ADDRESSING Open addressing is also called closed Hashing. There are three common collision resolution strategies. H→Tablesize)]. Disadvantage of Seperate Chaining * It requires pointers. which is an alternative to resolve the collisions with linked lists. which occupies more memory space. since it takes time to evaluate the hash function and also to traverse the list.FIND ROUTINE Position Find (int key. Hashtable H) { Position P. List L. return p. In this hashing system. Next. (ie) cells h0(x)..
which degrades the performance of the hash table for storing and retrieving . for the ith probe the position to be tried is (h(k) + i) mod tablesize. is the linear function. In linear probing. where F(i) = i. then the search is continued from the beginning of the table. LINEAR PROBING In linear probing.(ii) Quadratic probing (iii) Double Hashing. the position in which a key can be stored is found by sequentially searching all position starting from the position calculated by the hash function until an empty cell is found. If the end of the table is reached and no empty cells has been found. It has a tendency to create clusters in the table. Advantage : * It doesn't requires pointers Disadvantage * It forms clusters.
w) = (w. . V and set of edges E. it is said to be weakly connected graph. (V2. which consists of undirected edges.e) (V1.. A complete graph with n vertices will have n (n . Length The length of the path is the number of edges on the path.) v = V1. where N represents the number of vertices. w V. Otherwise. Strongly Connected Graph If there is a path from every vertex to every other vertex in a directed graph then it is said to be strongly connected graph. Each edge is a pair (v. V2). (i. (i. It is also referred as Digraph. The length of the above path V1 to V3 is 2.shortest-path algorithms – minimum spanning tree – Prim's and Kruskal's algorithms – Depth-first traversal – biconnectivity – Euler circuits – applications of graphs GRAPH A graph G = (V. where each edge in E is unidirectional.e. w) where u. Vertics are referred to as nodes and the arc between the nodes are referred to as Edges. which is equal to N-1. V3). v) Weighted Graph A graph is said to be weighted graph if every edge in the graph is assigned a weight or value. If (v. v) Undirected Graph An undirected graph is a graph.1)/2 edges. If (v. Complete Graph A complete graph is a graph in which there is an edge between every pair of vertics. w) # (w. BASIC TERMINOLOGIES Directed Graph (or) Digraph Directed graph is a graph which consists of directed edges. It can be directed or undirected graph. w) is an undirected edge then (v.UNIT IV GRAPHS Definitions – Topological sort – breadth-first traversal . E) consists of a set of vertices. w) is a directed edge then (v. w = V2.
ACyclic Graph A directed graph which has no cycles is referred to as acyclic graph. with no edges. if there is an edge Vi to Vj . The degree of the vertex V is written as degree (V). such that Aij = 1.If there is a path from a vertex to itself. It is abbreviated as DAG.Directed Acyclic Graph. Similarly the out degree of the vertex V is the number of edges exiting from that vertex V. One simple way to represents a graph is Adjacency Matrix. A simple cycle is the simple path of length atleast one that begins and ends at the same vertex. then the path length is 0. The indegree of the vertex V. Representation of Graph Graph can be represented by Adjacency Matrix and Adjacency list. then the path is referred to as a loop. Simple Path A simple path is a path such that all vertices on the path. Loop If the graph contains an edge (v. DAG . v) from a vertex to itself. except possibly the first and the last are distinct. Cycle A cycle in a graph is a path in which first and last vertex are the same. E) with n vertices is an n x n matrix. is the number of edges entering into the vertex V. The adjacency Matrix A for a graph G = (V. Degree The number of edges incident on a vertex determines its degree.
Step 5 : . Step 6 : .3 Topological Sort A topological sort is a linear ordering of vertices in a directed acyclic graph such that if there is a path from Vi to Vj. Step 3 : . 5. Step 1 : .Aij = 0.Find the indegree for every vertex. perform the following steps. Disadvantage * Takes O(n2) space to represents the graph * It takes O(n2) time to solve the most of the problems.Repeat from step 3 until the queue becomes empty.The topological ordering is the order in which the vertices dequeued. If the graph has a cycle. Topological ordering is not possible.Dequeue the vertex V and decrement the indegree's of all its adjacent vertices. . Since there can be 0(n) vertices on the adjacency list for vertex i. then Vj appears after Vi in the linear ordering.Place the vertices whose indegree is `0' on the empty queue. if there is no edge. Step 2 : .Enqueue the vertex on the queue. We store all vertices in a list and then for each vertex. Adjacency List Representation In this representation. we store a graph as a linked structure. Advantage * Simple to implement. since for two vertices v and w on the cycle. we have a linked list of its adjacency vertices Disadvantage * It takes 0(n) time to determine whether there is an arc from vertex i to vertex j. Step 4 : . if its indegree falls to zero. v precedes w and w precedes v. To implement the topological sort.
while (! IsEmpty (Q)) { V = Dequeue (Q).Routine to perform Topological Sort /* Assume that the graph is read into an adjacency matrix and that the indegrees are computed for every vertices and placed in an array (i. TopNum [V] = + + counter. for each W adjacent to V if (--Indegree [W] = = 0) Enqueue (W.e. for each vertex V if (indegree [V] = = 0) Enqueue (V. Vertex V. Q). Makeempty (Q). W . . } if (counter ! = NumVertex) Error (" Graph has a cycle"). Indegree [ ] ) */ void Topsort (Graph G) { Queue Q . Q). int counter = 0. Q = CreateQueue (NumVertex).
This is applied to the weighted graph G. which generally solve a problem in stages by doing what appears to be the best thing at each stage.DisposeQueue (Q). Dijkstra's algorithm is the prime example of Greedy technique. vertex V. W. Table T) { int i . TopNum [V] indicates an array to place the topological numbering. At each stage. T [i]. it selects a vertex v. Dequeue (Q) implies to delete a vertex from the queue Q. known = False. T) /* Read graph from adjacency list */ /* Table Initialization */ for (i = 0. We should set dw = dv + Cvw. and declares that as the shortest path from S to V and mark it to be known. if the new value for dw would be an improvement. Dist = Infinity. Read Graph (G. ROUTINE FOR ALGORITHM Void Dijkstra (Graph G. i < Numvertex. i++) { T [i]. just like the unweighted shortest path algorithm. . Dijkstra's Algorithm The general method to solve the single source shortest path problem is known as Dijkstra's algorithm. Q) implies to insert a vertex V into the queue Q. which has the smallest dv among all the unknown vertices. This algorithm proceeds in stages. /* Free the Memory */ } Note : Enqueue (V.
path = V.5.T [i].1 Prim's Algorithm Prim's algorithm is one of the way to compute a minimum spanning tree which uses a greedy technique. T[V]. Dist = Min [T[W]. It this grows a spanning tree.v) such that the . it finds a shortest edge (u. T[V]. At each step. for ( . for each W adjacent to V if ( ! T[W]. known) { T [W]. Dist + CVW] T[W]. This algorithm begins with a set U initialised to {1}. dist = 0. . path = NotA vertex.) { V = Smallest unknown distance vertex. if (V = = Not A vertex) break . one edge at a time. Dist. known = True. } } } Minimum Spanning Tree Cost = 5 Spanning Tree with minimum cost is considered as Minimum Spanning Tree 5. } T [start].
v) be a lowest cost such that u is in U and v is in V . v)}. /* Table initialization */ for (i = 0. i++) . /* Initialization of Tree begins with the vertex `1' */ U = {1} while (U # V) { Let (u.cost of (u. v. U = U U {V}. W. v) is the smallest among all edges. SKETCH OF PRIM'S ALGORITHM void Prim (Graph G) { MSTTREE T. T = NULL. where u is in Minimum Spanning Tree and V is not in Minimum Spanning Tree. Vertex u. i < Numvertex . Set of tree vertices U. T = T U {(u. Set of vertices V. } }ROUTINE FOR PRIMS ALGORITHM void Prims (Table T) { vertex V.U.
Known) { T[W]. the algorithm backsup one edge to the vertex it came from and tries to continue visiting unvisited vertices from there. This process continues until a dead end (i.Dist = Min (T[W]. T[V]. known = True. dist = 0. At a deadend. for each W adjacent to V If (! T[W] . . known = False. T[i]. . path = 0.path = V.) { Let V be the start vertex with the smallest distance T[V]. Then each unvisited vertex adjacent to V is searched in turn using depth first search recursively. Dist = Infinity. T[W].e) a vertex with no adjacent unvisited vertices is encountered.{ T[i]. V is marked visited. } } } Depth First Search Depth first works by selecting one vertex V of G as a start vertex . } for (. CVW). Dist. T[i].
for each W adjacent to V if (! visited [W]) Dfs (W). return to the previous search node and continue from there. ROUTINE FOR DEPTH FIRST SEARCH Void DFS (Vertex V) { visited [V] = True. Designate it as the search node and mark it as visited. If no nodes satisfying (2) can be found. choose any node that has not been visited and repeat step (1) through (4). Designate this as the new search node and mark it as visited. Step : 2 Using the adjacency matrix of the graph. Step : 4 When a return to the previous search node in (3) is impossible. If unvisited vertices still remain. By then. the search from the originally choosen search node is complete. find a node adjacent to the search node that has not been visited yet. Step : 5 If the graph still contains unvisited nodes. with the latter being a dead end. To implement the Depthfirst Search perform the following Steps : Step : 1 Choose any node in the graph. Step : 3 Repeat step 2 using the new search node. the depth first search must be restarted at any one of them.The algorithm eventually halts after backing up to the starting vertex. } . all the vertices in the same connected component as the starting vertex have been visited.
Find the immediate adjacent unvisited vertex `B' of `A' Mark it to be visited. From `D' the next unvisited vertex is `C' Mark it to be visited. Biconnected Graph [Basic Concepts] • • • Articulation point: An Articulation point in a connected graph is a vertex that. a graph is biconnected if and only if any vertex is deleted. Let `A' be the source vertex. Biconnected graph: A graph with no articulation point called biconnected. 5. Biconnected component: A biconnected component of a graph is a maximal biconnected subgraph.Example : Fig. 4. Mark it to be visited. if delete.a biconnected subgraph that is not properly contained in a larger biconnected . In other words. From `B' the next adjacent vertex is `d' Mark it has visited. 2. would The graphs we discuss below are all about loop-free break the graph into two or more pieces undirected ones.6 Adjacency Matrix ABCD A0111 B1001 C1001 D1110 Implementation 1. (connected component). the graph remains connected.
H. L. G.] [Step 2. E. J. B}、B、H、I、K How to find articulation points? [Step 1. sets of nodes mutually accessible via two distinct paths.] Find the depth-first spanning tree T for G Add back edges in T Determine DNF(i) and L(i) DNF(i): the visiting sequence of vertices i by depth first search L(i): the least DFN reachable frome i through a path consisting of zero or more tree edges followed by zero or one back edge . F}、{G. C. Figure 1.] [Step 3. D. • A graph that is not biconnected can divide into biconnected components. The graph G that is not biconnected [Example] Graph G in Figure 1: • • Articulation points: A. J Biconnected components: {A.subgraph. G.
Depth-first panning tree of the graph G Vertex i is an articulation point of G if and only if eather: i is the root of T and has at least two children i is not the root and has a child j for which L(j)>=DFN(i) [Example] The DFN(i) and L(i) of Graph G in Figure 1 are: Vertex G is an articulation point because G is not the root and in depth-first spanning tree in Figure 2. B and F Vertex E is not an articulation point because E is not the root and in depth-first spanning tree in Figure 2. L(G)<DFN(E) and L(D)<DFN(E). it has more than one child. L(L)>=DFN(G).[Step 4. that L is one of its children Vertex A is an articulation point because A is the root and in depth-first spanning tree in Figure 2. that G and D are its children .] Figure 2.
[Program] .
array. I. and . Generally. x. Divide-and-conquer algorithms are often implemented using recursion. it is subdivided into one or more subproblems each of which is similar to the given problem.e. To solve a given problem.. find i (if it exists) such that The usual solution to this problem is binary search . . Finally. The sequence S is split into two subsequences. Therefore. given the sorted sequence and an item x.UNIT V ALGORITHM DESIGN AND ANALYSIS Greedy algorithms – Divide and conquer – Dynamic programming – backtracking – branch and bound – Randomized algorithms – algorithm analysis – asymptotic notations – recurrences – NP-complete problems Top-Down Algorithms: Divide-and-Conquer In this section we discuss a top-down algorithmic paradigm called divide and conquer . the solutions to the subproblems are combined in order to obtain the solution to the original problem. However. we can quickly determine the list in which x must appear. Of course. not all recursive functions are divide-and-conquer algorithms. The original problem is split into two subproblems: Find x in or . Program defines the function BinarySearch which takes four arguments. it considers the following elements of the array: . we only need to solve one subproblem. Specifically. This routine looks for the position in array at which item x is found. Binary search is a divide-and-conquer strategy. since the original list is sorted. the subproblems solved by a divide-and-conquer algorithm are non-overlapping. Each of the subproblems is solved independently. Example-Binary Search Consider the problem of finding the position of an item in a sorted list. i and n.
In this case. the running time is given by the recurrence Equation is easily solved using repeated substitution: Setting gives . .Program: Divide-and-Conquer Example--Binary Search The running time of the algorithm is clearly a function of n. Although Program works correctly for arbitrary values of n. the number of elements to be searched. it is much easier to determine the running time if we assume that n is a power of two.
Example-Computing Fibonacci Numbers
The Fibonacci numbers are given by following recurrence
Section presents a recursive function to compute the Fibonacci numbers by implementing directly Equation . (See Program ). The running time of that program is shown to be .
In this section we present a divide-and-conquer style of algorithm for computing Fibonacci numbers. We make use of the following identities
for
. (See Exercise
). Thus, we can rewrite Equation
as
Program
defines the function Fibonacci which implements directly Equation and
. and
Given n>1 it computes by calling itself recursively to compute then combines the two results as required.
Program: Divide-and-Conquer Example--Computing Fibonacci Numbers To determine a bound on the running time of the Fibonacci routine in Program assume that T(n) is a non-decreasing function. I.e., for all . we
Therefore . Although the program works correctly for all values of n, it is convenient to assume that n is a power of 2. In this case, the running time of the routine is upper-bounded by T(n) where
Equation
is easily solved using repeated substitution:
Thus, T(n)=2n-1=O(n).
Example-Merge Sorting
Sorting algorithms and sorters are covered in detail in Chapter . In this section we consider a divide-and-conquer sorting algorithm--merge sort . Given an array of n items in arbitrary order, the objective is to rearrange the elements of the array so that they are ordered from the smallest element to the largest one. The merge sort algorithm sorts a sequence of length n>1 by splitting it into to subsequences--one of length , the other of length and then the two sorted sequences are merged into one. . Each subsequence is sorted
Program defines the function MergeSort which takes three arguments, array, i and n. The routine sorts the following n elements:
The MergeSort routine calls itself as well as the Merge routine. The purpose of the Merge routine is to merge two sorted sequences, one of length , the other of length into a single sorted sequence of length n. This can easily be done in O(n) time. (See Program ). ,
Program: Divide-and-Conquer Example--Merge Sorting The running time of the MergeSort routine depends on the number of items to be sorted, n. Although Program works correctly for arbitrary values of n, it is much easier to determine the running time if we assume that n is a power of two. In this case, the running time is given by the recurrence
Backtracking Algorithms A backtracking algorithm systematically considers all possible outcomes for each decision. Sometimes a backtracking algorithm can detect that an exhaustive search is unnecessary and. and we are required to place all of the weights onto the scales so that they are balanced. In this sense. Example-Balancing Scales Consider the set of scales shown in Figure . . therefore. Suppose we are given a collection of n weights. it can perform much better. backtracking algorithms are distinguished by the way in which the space of possible solutions is explored.Equation is easily solved using repeated substitution: Setting gives . However. Figure: A Set of Scales The problem can be expressed mathematically as follows: Let which weight is placed such that represent the pan in . backtracking algorithms are like the brute-force algorithms.
the goal is to minimize the difference between between the total weights in the left and right pans. In effect. our objective is to minimize where subject to the constraint that all the weights are placed on the scales. we search for a solution to the problem by first trying one solution and then backing-up to try another. Let be the difference between the the sum of the weights currently placed in the left and right pans. . Figure shows the solution space for the scales balancing problem. Therefore.The scales are balanced when the sum of the weights in the left pan equals the sum of the weights in the right pan. If the scales balance. A solution always exists if. Thus. given . instead of balancing the scales. Given an arbitrary set of n weights. At the root (node A) no weights have been placed yet and the scales are balanced. a solution has been found. remove some number of the weights and place them back on the scales in some other combination. we might solve the problem by trial-anderror: Place all the weights onto the pans one-by-one. Given a set of scales and collection of weights. In this case the solution space takes the form of a tree: Each node of the tree represents a partial solution to the problem. there is no guarantee that a solution to the problem exists. If not. at node A.
The . I. where n is a measure of the problem size. Conversely. The complete solution tree has depth n and leaves.e.. node C represents the situation in which the weight has been placed in the right pan. Then it should be a fairly simple matter to compare the two functions and to determine which algorithm is the best! . for solving a given problem. Furthermore. the solution is the leaf node having the smallest value. respectively. In this case . In this case (as in many others) the solution space is a tree. let us say that we have done a careful analysis of the running times of each of the algorithms and determined them to be and .Figure: Solution Space for the Scales Balancing Problem Node B represents the situation in which weight difference between the pans is has been placed in the left pan. In order to find the best solution a backtracking algorithm visits all the nodes in the solution space. A and B. Both kinds can be used to implement a backtracking algorithm. Clearly. Asymptotic Notation Suppose we are considering two algorithms. it does a tree traversal . Section presents the two most important tree traversals--depth-first and breadth-first .
In this case.'' which we write f(n)=O(g(n)). P. a priori. According to Definition . we have no a priori knowledge of the problem size..g.But is it really that simple? What exactly does it mean for one function. we conclude that . suppose the problem size is and algorithm A is better than algorithm B for problem size . Bachmann invented a notation for characterizing the asymptotic behavior of functions. . .e. We say that ``f(n) is big oh g(n).. f(n) is non-negative for . Clearly. E. suppose we choose c=1. we consider the asymptotic behavior of the two functions for very large problem sizes. Then clearly . in and a constant c>0 such that for all It does not matter what the particular constants are--as long as they exist! E. if there exists an and a constant c>0 such that for all integers A Simple Example Consider the function f(n)=8n+128 shown in Figure all integers . We wish to show that order to show this we need to find an integer integers . if it can be shown. Then Since (n+8)>0 for all values of . we usually don't know the problem size beforehand. An Asymptotic Upper Bound-Big Oh In 1892. . However. say better than another function.g. . . . nor is it true that one of the functions is less than or equal the other over the entire range of problem sizes. . I. then algorithm A is better than Unfortunately. say.. . His invention has come to be known as big oh notation: Definition (Big Oh) integer Consider a function f(n) which is non-negative for all integers . to be ? One possibility arises if we know the problem size In the general case. that algorithm B regardless of the problem size.
For example.'' which we write and a constant c>0 such that for all integers The definition of omega is almost identical to that of big oh. Definition (Omega) an integer Consider a function f(n) which is non-negative for all integers . for all integers . In this section. Figure: Showing that . it is conventions and caveats apply to omega as they do to big oh. Of course. (See Figure ). for omega. is greater than the . . there are many other values of c and will do. but in this case it is a lower bound. if there exists . we have that for c=1 and .So. All of the same . Figure clearly shows that the function function f(n)=8n+128 to the right of n=16. we introduce a similar notation for characterizing the asymptotic behavior of a function. . An Asymptotic Lower Bound-Omega The big oh notation introduced in the preceding section is an asymptotic upper bound. Hence. We say that ``f(n) is omega g(n). . c=2 and . as will c=4 and that will do. The only difference is in the comparison--for big oh it is .
f(n) is non-negative for all integers . Clearly. Hence. . . Figure of c and clearly shows that the function . suppose we choose c=1. in order to show this we need to find an integer that for all integers . is less than the So. Then Since for all values of . . we conclude that for all integers . it does not matter what the particular constants are--as long as they exist! E. . For example.g. We wish to show that Definition . c=2 and . we have that for c=1 and . there are many other values Figure: Showing that . ..A Simple Example Consider the function which is shown in Figure . Of course. function f(n)=5n-64n+256 for all values of that will do. According to and a constant c>0 such As with big oh.
(Definition ). . since not matter what c we choose. . for the .'' which we write f(n) is O(g(n)) and f(n) is Recall that we showed in Section Section will write Definition (Little Oh) is O(g(n)) but f(n) is not that a such a polynomial is . for the Definition (Theta) Consider a function f(n) which is non-negative for all integers . . Clearly too. Consider a function f(n) which is non-negative for all integers . . 2. to describe a function which is O(g(n)) but not same g(n). . to describe a function which is both O(g(n)) and same g(n). if and only if f(n) Little oh notation represents a kind of loose asymptotic bound in the sense that if we are given that f(n)=o(g(n)). We say that ``f(n) is theta g(n). . NP . . We say that ``f(n) is little oh g(n). For example. is . Therefore. say . but g(n) is not an asymptotic lower bound since f(n)=O(g(n)) and implies that . They are: • • A notation.More Notation-Theta and Little Oh This section presents two less commonly used forms of asymptotic notation. Every problem in NP is polynomially reducible to D. according to Definition . It belongs to class NP. for large enough n. (Definition ).Complete Problems A decision problem D is said to be NP complete if 1. that a polynomial in n. A notation. . We also showed in . Clearly. consider the function f(n)=n+1. then we know that g(n) is an asymptotic upper bound since f(n)=O(g(n)).'' which we write f(n)=o(g(n)). . if and only if . we .
P2 is NP . Hamilton cycle problem can be polynomially reduced to travelling salesman problem. By applying the closure property to polynomials.complete problems are the hardest NP problems is that a problem that is NP . Suppose we have an NP . so that we can solve P1 by using P2 with only a polynomial time penalty. Bin packing and partition problem. numbers are entered into a pocket calculator in decimal. Suppose further that P1 polynomially reduces to P2. Hamilton Cycle Problem transformed to travelling salesman problem. and all calculations are performed in binary. we see that every problem in NP is polynomially reducible to P2. As an example.complete. The reason that NP . graph coloring.Complete. all the work associated with the transformations must be performed in polynomial time. Then the final answer is converted back to decimal for display. Some of the examples of NP . Thus.complete problems are Hamilton circuit. Since P1 is NP complete. we reduce the problem to P1 and then reduce P1 to P2. The decimal numbers are converted to binary. Travelling salesman problem is NP .A problem P1 can be reduced to P2 as follows Provide a mapping so that any instance of P1 can be transformed to an instance of P2. It is easy to see that a solution can be checked in polynomial time. Suppose P2 is known to be in NP. with only a polynomial amount of overhead. so it is certainly in NP. every problem in NP polynomially reduces to P1. knapsack. For P1 to be polynomially reducible to P2. Travelling salesman.complete problem P1. Solve P2 and then map the answer back to the original. .complete can essentially be used as a subroutine for any problem in NP.
a3. ai+1 the successor of ai and ai-1 is the predecessor of ai. Define double circularly linked list? .EE2204 Data Structure Answer Unit 1 part a 1. 2. Pointer is basically a number. 8. there will be one pointer named as ‘NEXT POINTER’ to point the next element. What is a pointer? Pointer is a variable. where as in a doubly linked list. size. Intersection. there will be two pointers one to point the next element and the other to point the previous element location. Abstract data types are mathematical abstractions. complement and find are the various operations of ADT. What are the various operations done under list ADT? Print list Insert Make empty Remove Next Previous Find kth 5. 3. What is a doubly linked list? In a simple linked list. an and the size of the list is ‘n’. a2. What are the different ways to implement list? Simple array implementation of list Linked list implementation of list 6..Objects such as list.What is meant by an abstract data type? An ADT is a set of operation. which stores the address of the next element in the list.Eg. Any element in the list at the position I is defined to be ai. which are not necessarily adjacent in memory. What are the advantages in the array implementation of list? a) Print list operation can be carried out at the linear time b) Fint Kth operation takes a constant time 7. 9. General list of the form a1. What are the operations of ADT? Union. What is meant by list ADT? List ADT is a sequential storage structure. 10. Each structure contain the element and a pointer to a record containing its successor. 4. set and graph along their operations can be viewed as ADT’s. What is a linked list? Linked list is a kind of series of data structures.….
Write down the operations that can be done with queue data structure? Queue is a first – in -first out list. In the case of array implementation of queue. 19. The other name of stack is Last-in -First-out list. Give some examples for linear data structures? Stack Queue 14. The operations that can be done with queue are addition and deletion. 11. What is a stack? Stack is a data structure in which both insertion and deletion occur at one end only. What is a circular queue? The queue. which wraps around upon reaching the end of the array is called as circular queue. 17. stack data structures is used to store the return address when a recursive call is Encountered and also to store the values of all the parameters essential to the current state of the procedure. if the last node or pointer of the list. Explain the usage of stack in recursive algorithm implementation? In recursive algorithms. we have to check whether READ=HEAD where REAR is a pointer pointing to the last node in a queue and HEAD is a pointer that pointer to the dummy header. the condition to be checked for an empty queue is READ<FRONT. How do you test for an empty queue? To test for an empty queue. It points to the first data element of the list. 12. 15.What are the postfix and prefix forms of the expression? A+B*(C-D)/(P-R) Postfix form: ABCD-*PR-/+ Prefix form: +A/*B-CD-PR 18.In a doubly linked list. then it is a circularly linked list. Unit 1 part B 1. Write postfix from of the expression –A+B-C+D? A-B+C-D+ 16. Stack is maintained with a single pointer to the top of the list of elements. What is the need for the header? Header of the linked list is the first element in the list and it stores the number of elements in the list. point to the first element of the list.Explain the linked list implementation of list ADT in Detail? _ Definition for linked list _ Figure for linked list _ Next pointer . List three examples that uses linked list? Polynomial ADT Radix sort Multi lists 13. 20.
_ Header or dummy node _ Various operations Explanation Example figure Coding 2. REAR _ Operations Coding Example figure Unit 2& 3 part A . Explain the array implementation of queue ADT in detail? _ Definition for stack _ Stack model _ Figure _ Pointer-FRONT. Explain the linked list implementation of stack ADT in detail? _ Definition for stack _ Stack model _ Figure _ Pointer-Top _ Operations Coding Example figure 5. Explain the various applications of linked list? _ Polynomical ADT Operations Coding Figure _ Radix Sort Explanation Example _ Multilist Explanation Example figure 4. Explain the cursor implementation of linked list? _ Definition for linked list _ Figure for linked list _ Next pointer _ Header or dummy node _ Various operations Explanation Example figure Coding 3.
Define pre-order traversal? Pre-order traversal entails the following steps. 4. Process the left subtree b. File index schemes b. What is meant by traversing? Traversing a tree means processing it in such a way. c. Linked representation 10. a. Pre-order traversal-yields prefix from of expression. In-order traversal-yields infix form of expression. Process the root node 12. 9. What is a ordered tree? In a directed tree if the ordering of the nodes at each level is prescribed then such a tree is called ordered tree. What are the applications of binary tree? Binary tree is used in data processing. a. 2. Define leaf? In a directed tree any node which has out degree o is called a terminal node or a leaf. 8. Process the right subtree . What are the two methods of binary tree implementation? Two methods to implement a binary tree are.1. What are the different types of traversing? The different types of traversing are a. Define non-linear data structure Data structure which is capable of expressing more complex relationship than that of physical adjacency is called non-linear data structure. Hierarchical database management system 7. Post-order traversal-yields postfix from of expression. 5. a. What is meant by directed tree? Directed tree is an acyclic diagraph which has one node called its root with indegree o whille all other nodes have indegree I. which represents hierarchical relationship between individual data items. Process the root node c. Process the left subtree b. a. Define in -order traversal? In-order traversal entails the following steps. 6. Define tree? A tree is a data structure. Process the root node b. Linear representation. Process the left subtree c. 3. b. that each node is visited only once.Define post-order traversal? Post order traversal entails the following steps. a. Process the right subtree c. b. Process the right subtree 11.
Overflow 21. What is a balance factor in AVL trees? Balance factor of a node is defined to be the difference between the height of the node's left subtree and the height of the node's right subtree. Explain the different tree traversals with an application? _ In order Explanation with an example Figure _ Preorder Explanation with an example Figure _ Postorder Explanation with an example Figure 2.13. 19. List out the different types of hashing functions? The different types of hashing functions are. deletions and find in constant average time. a. Define expression trees? The leaves of an expression tree are operands such as constants or variable names and the other nodes contain operators. What is meant by pivot node? The node to be inserted travel down the appropriate branch track along the way of the deepest level node on the branch that has a balance factor of +1 or -1 is called pivot node. The division method b. What are the problems in hashing? When two keys compute in to the same location or address in the hash table through any of the hashing function then it is termed collision. The folding method d. Define binary search tree? Explain the various operations with an example? . Digit analysic 20. 17. 15. What is the need for hashing? Hashing is used to perform insertions. In a tree there is exactly one path form the root to each node. Define hash function? Hash function takes an identifier and computes the address of that identifier in the hash table using some function. 14. Multiplicative hashing e. 16. Unit 2 and 3 part B 1. 18. Collision b. What is the length of the path in a tree? The length of the path is the number of edges on the path. The mind square method c. What are the problems in hashing? a.
and a mapping from the set for edge E to a set of pairs of elements of V. if and edge x V. What is a directed graph? A graph in which every edge is directed is called a directed graph. 2. What is a loop? . RR.v) where u. 4. For example. v 3. Define priority queue? Explain the basic heap operation with an example? _ Definition _ Basic operation Insert Delmin Delmax _ Coding _ Explanation _ Example 5. Define AVL trees? Explain the LL. It can also be represented as G=(V. 5. RL.Define Graph? A graph G consist of a nonempty set V which is a set of nodes of the graph._ Definition _ Figure for binary search tree _ Operations Codings Explanation Example 3. LR case Figure Example Explanation 4. RR. LR case with an example? _ Definition _ LL. then we say that the edge x connects the nodes u and v. Explain any two techniques to overcome hash collision? _ Separate chaining Example Explanation Coding _ Open addressing Linear probing Quadratic probing Unit 4 part A 1. RL. E). ∈(u. a set E which is the set of edges of the graph. What is a undirected graph? A graph in which every edge is undirected is called a directed graph. Define adjacent nodes? Any two nodes which are connected by an edge in a graph are called E is associated with a pair of nodes∈adjacent nodes.
Where is dynamic programming used? Dynamic programming is used when the problem is to be solved in a sequence of intermediate steps. to verify that the results obtained by the execution of the program with arbitrary inputs are in accord with formally defined output Specifications. it is necessary to set-up and proves verification conditions individually. What is binary doubling strategy? The reverse of binary doubling strategy. i. when all the variables have the same value.Network analysis 13.What is proof of termination? To prove that a program accomplishes its stated objective in a finite number of steps is called program termini nation.e. How will you verify branches with segments? To handle the branches that appear in the program segments. This strategy is used to avoid the generation of intermediate results. What is program verification? Program verification refers to the application of mathematical proof techniques. i. What is program testing? Program testing is process to ensure that a program solves the smallest possible problem. 15. Unit V part B 1. What are the steps taken to improve the efficiency of an algorithm? Definition .Explain top-down design in detail? Definition Breaking a problem in to subproblems Choice of a suitable data structure Constructions of loops Establishing initial conditions for loops Finding the iterative construct Terminations of loops 2. Define top-down design? Top-down design is a strategy that can be applied to find a solution to a problem from a vague outline to precisely define the algorithm and program implementation by stepwise refinement. The prooft of termination is obtained directly from the properties of the interactive constructs. 18. 19. 16. the biggest possible problem. 20. 14. combining small problems in to one is known as binary doubling strategy. It is particularly relevant for many optimization problems. frequently encountered in Operations research.e. unusual cases etc. Mention the types of bugs that may arise in a program? The different types of bugs that can arise in a program are Syntactic error Semantic error Logical error 17.
Design an algorithm for reversing the digit of an integer. Design an algorithm fro sine function computation. Design an algorithm for base conversion. Explain it with an example? Algorithm development Algorithm description Pascal implementation Application 4. Explain it with an example? Algorithm development Algorithm description Pascal implementation Application 5.Redundant computations Referencing array elements Inefficiency due to late termination Early detection of desired output conditions Trading storage for efficiency gains 3. Explain it with an example? Algorithm development Algorithm description Pascal implementation Application .
Unit 2 and 3 part a . 6. What are the basic operations of Queue ADT? 4. 2. (a) What is a stack? Write down the procedure for implementing various stack operations(8) (b) Explain the various application of stack? (8) 7. 2. 11. What is a queue? Write an algorithm to implement queue with example. Define a queue model. 3. Infix and postfix expressions with example. Define ADT (Abstract Data Type). What is linear pattern search? 18. 9. Explain the operations and the implementation of list ADT. Explain Prefix. Give the applications of Queue. Swap two adjacent elements by adjusting only the pointers (and not the data) using singly linked list. What is Enqueue and Dequeue? 5. What are the advantages of doubly linked list over singly linked list? 12. What is linear list? 16. What is the use of stack pointer? 7. 6. Give a procedure to convert an infix expression a+b*c+(d*e+f)*g to postfix notation 5. How will you delete a node from a linked list? 17. What is an array? 8. (a) Given two sorted lists L1 and L2 write a procedure to compute L1_L2 using only the basic operations (8) (b) Write a routine to insert an element in a linked list (8) 8. What is doubly linked list? Unit 1 part B 1. What is recursive data structure? 19. Design and implement an algorithm to search a linear ordered linked list for a given alphabetic key or name. 10. Define a graph 13. Explain the implementation of stack using Linked List. Give the structure of Queue model. 3.EE 2204 Data Structure and Algorithms analysis Unit 1 2 marks 1. 4. Define ADT. What is a Queue? 14. What is a circularly linked list? 15.
What is Pre order traversal? 6. Unit 2and 3 part B 1. 2. What is Post order traversal? 7.1. 3. 6. 3. Explain the operation and implementation of Binary Heap. Define Double Hashing. 9. Define complete binary tree. 13. 4. Explain the implementation of different Hashing techniques. return. Define (i) inorder (ii) preorder (iii) postorder traversal of a binary tree.9679. Compare the various hashing Techniques. with find min. Show that maximum number of nodes in a binary tree of height H is 2H+1 – 1.1989} and a hash function h(X)=X(mod10). What is In order traversal? 5. 16. How a binary tree is represented using an array? Give an example 17. Explain the representation of priority queue 2.4199. 18. Define hash function. 10. 11. and removes the minimum element in the priority queue. the sum of the heights of the nodes 2h+1 -1-1(h+1). 4. (a) How do you insert an element in a binary search tree? (8) (b) Show that for the perfect binary tree of height h containing2h+1-1 nodes. show the resulting: . Define Binary tree.6173. What is meant by BST? 9. Give the prefix. What is meant by Binary Heap? 14. Prove that the number of full nodes plus one is equal to the number of leaves in a non empty binary tree. which finds. Define AVL trees. What is meant by traversal? 3. Mention some applications of Priority Queues. Define Binary search tree. A full node is a node with two children. (8) 5. List out the steps involved in deleting a node from a binary search tree. What is an expression tree? 1. 10. Define Hashing. 15. Given input {4371. What is meant by depth first order? 4. What is binary heap? 5. 19. 12. Give example for single rotation and double rotation. Define AVL tree. List out the various techniques of hashing 7. can both insert and find min be implemented in constant time? 20.1323. Suppose that we replace the deletion function.4344. 8. Define hashing. 8. infix and postfix expressions corresponding to the tree given in figure.Explain Tree concept? 2.
complete problems 12. Explain in detail (i) Single rotation (ii) double rotation of an AVL tree. What is topological sort? 14. What is depth-first spanning tree 18. Explain how to find a maximum element and minimum element in BST? Explain detail about Deletion in Binary Search Tree? 1. What is Euler Circuit? 20. Explain the topological sort. What is Bio connectivity? 19. Write an algorithm for initializing the hash table and insertion in a separate chaining (16) Unit 4 part A Define Graph. Define NP. What is meant by Single-Source Shortest path problem? 8.(a) Separate chaining table (4) (b) Open addressing hash table using linear probing (4) (c) Open addressing hash table using quadratic probing (4) (d) Open addressing hash table with second hash function h2(X) =7-(X mod 7). What is meant by Shortest Path Algorithm? 7. (16) 6. Define (i)indegree (ii)outdegree 1. . What is meant by directed graph? 3. Write a program in C to create an empty binary search tree & search for an element X in it. Explain in detail about Open Addressing (16) 4. 2. What is meant by topological sort? 5. What is space requirement of an adjacency list representation of a graph 13. Write a recursive algorithm for binary tree traversal with an example. What is meant by Dijkstra’s Algorithm? 9. (a) Construct an expression tree for the expression A+(B-C)*D+(E*F) (8) (b) Write a function to delete the minimum element from a binary heap (8) 2. Give a diagrammatic representation of an adjacency list representation of a graph. What is meant by acyclic graph? 6. What is meant by ‘Hamiltonian Cycle’? 22. What is minimum spanning tree? 10. Mention the types of algorithm. (16) 3. Explain in detail insertion into AVL Trees (16) 5. What is breadth-first search? 15. 7. 11. (4) 6. Explain the efficient implementation of the priority queue ADT 8. What is a directed graph? 21. 4. Define undirected graph 17. Define minimum spanning tree 16.
What is an activity node of a graph? 6. 2. 2. What is minimum spanning tree? 10. Explain the application of DFS. What is a directed graph? 21.Find a minimum spanning tree for the graph using both Prim’s and Kruskal’s algorithms. Explain in detail the simple topological sort pseudo code 7. Define (i)indegree (ii)outdegree Unit 4 part B 1. Define Biconnectivity. Prove that the number of odd degree vertices in a connected graph should be even. 7. Define Breadth First Search. What is breadth-first search? 15. What is meant by Shortest Path Algorithm? 7. What is depth-first spanning tree 18. What is meant by Dijkstra’s Algorithm? 9. Define Depth First Search. (16) . Give a diagrammatic representation of an adjacency list representation of a graph. What is meant by acyclic graph? 6. Define NP. Explain how to find shortest path using Dijkstra’s algorithm with an example. What is meant by Single-Source Shortest path problem? 8. 1. 3. Define Graph. 8. 6. Write notes on NP-complete problems 1. What is meant by ‘Hamiltonian Cycle’? 22. What is meant by directed graph? 3.2. 9. What is meant by topological sort? 5. Formulate an algorithm to find the shortest path using Dijkstra’s algorithm and explain with example. 4. 4. What is Bi connectivity? 19. (16) 2. What is Euler Circuit? 20. Describe Dijkstra’s algorithm with an example. 5. Define Shortest Path of a graph. 4. 3. Define NP hard & NP complete problem. 10. Define Minimum Spanning Tree. 11. What is space requirement of an adjacency list representation of a graph 13. Explain Prim’s & Kruskal‘s Algorithm with am example. What is topological sort? 14. Define minimum spanning tree 16. Define undirected graph 17. What is an adjacency list? When it is used? 5.complete problems 12. Explain the minimum spanning tree algorithms with an example. Mention the types of algorithm.
(i) Time Complexity (ii) Space Complexity 8. 6. Define Verification Condition 11. Find a minimum spanning tree for the graph using both Prim’s and Kruskal’s algorithms. 3. Define Symbolic Execution 10. What is Recursion? Explain with an example. Explain the application of DFS. Write and explain weighted and unweighted shortest path algorithm (16) 5. 4. Explain the various applications of Depth First Search. Define algorithmic Strategy (or) Algorithmic Technique. Explain how to find shortest path using Dijkstra’s algorithm with an example. Define Algorithm 3. What are the ways to specify an algorithm? . 13. What is the basic idea behind Divide & Conquer Strategy? 7. List out the performance measures of an algorithm. What are the various algorithm strategies (or) algorithm Techniques? 12. Define Problem Definition Phase 4. How is an algorithm’s time efficiency measured? 5.3. 6. 5. Mention any four classes of algorithm efficiency. Define Algorithm & Notion of algorithm. (a) Write short notes on Biconnectivity. (8) 4. What is analysis framework? 3. Explain in detail the simple topological sort pseudo code 7. Describe Dijkstra’s algorithm with an example. 11. Write notes on NP-complete problems Uint V part A 1. What is O – notation? 14. Define Program 2. Explain Prim’s & Kruskal‘s Algorithm with am example. 2. Define Program Verification. What are the problem solving strategies? 5. (16) 1. Define Computational Complexity. 9. 7. (8) (b) Write an algorithm for Topological Sort of a graph. Define Top Down Design. State the following Terms. Define the qualities of good algorithm. Define Input & Output Assertion. 8. 6. What are the important problem types? 10. 2. What are the various asymptotic Notations? 9. 12. 15. Define Order of Growth. 1. What are the algorithm design techniques? 4.
3. 18. Write an algorithm to exchange the values of two variables 9 Write an algorithm to find N factorial (written as n!) where n>=0. 8. 13. What is divide & conquer strategy? 6. Give any four algorithmic techniques. What are the Basic Efficiency Classes. Design an algorithm to evaluate the function sin(x) as defined by the infinite series expansion sin(x) = x/1!-x3/3! +x5/5!-x7/7! +…… 3. What is dynamic programming? 7. 7. Design an algorithm that accepts a positive integer and reverse the order of its digits.13. Describe the backtracking problem using knapsack problem . 1. 16. Write an algorithm to generate and print the first n terms of the Fibonacci series where n>=1 the first few terms are 0. 14.(16). What is meant by algorithm? What are its measures? 2. Explain in detail about Greedy algorithm with an example(16). 1. 5. 6. Define the worst case & average case complexities of an algorithm 5. 8. Define Worst case Time Complexity. 3. Define Average case time complexity. Define Asymptotic Notation. 2. . Write an algorithm to find the factorial of a given number? 4. 4. Explain the Base conversion algorithm to convert a decimal integer to its corresponding octal representation. Explain in detail about Divide and conquer algorithm with an example also mark the difference between Greedy and divide and conquer algorithm. (a) Explain in detail the types on analysis that can be performed on an algorithm (8) (b) Write an algorithm to perform matrix multiplication algorithm and analyze the same (8) 2. 5.(16). Unit V part B 1. Write at least five qualities & capabilities of a good algorithm 8. Define Best case Time Complexity . How to calculate the GCD value? 1. 15. 17.
|
https://www.scribd.com/document/61247835/1071
|
CC-MAIN-2017-30
|
refinedweb
| 19,889
| 69.58
|
A.
I have a application, embedded in IE (html assambly).
That aplication need to connect back to the server in order to get some
data.
What are conditions to succeed without requesting any special permissions
from client? As an applet do it….
Should I connect back to the server only using port 80?
Right now the client app is serverd by Apache and connection back is tryed
to another aplication on port 9500
Changing security permission by the client is not an option.. same for stron names.
This depends on which version of the framework your embedded assembly is targeting. With v1.0 of the framework, this is not possible without having the client trust your code. However, with v1.1 and higher, all code run off the internet has same site web access back to where they are hosted from. You can use the System.Web.HttpWebRequest class to gain access back to this site.
This is the first explanation of the security in the .Net Framework that I’ve found that makes sense. I’ve been trying to create WinForm controls that use the PropertyGrid as a component and have been failing miserably in terms of getting all the functions to work properly.
I figured out the strongname/code group relationship that is required and am able to get the control to work partially. However, I can’t get all the functionality of the PropertyGrid to work in IE. What I’ve been stuck on is how one would get expandable object types and custom UItypeeditors to work in the control while in IE. I’ve coded the control and when it runs in an executable, the expandable properties work and I can use the ellipsis buttton to call my custom UItypeeditor. The problem is that hosted in IE, the expandable property doesn’t expand and the ellipsis button is not available.
From what you’re saying is that IE hosts the control in an AppDomain that doesn’t have enough permissions to use expandable types or custom UItypeeditors. So, I have to assert the permissions for my public classes and methods? Would this apply to all classes and methods (including those for the expandable types and UItypeeditors)?
How do you assert the permissions? Is that when you prefix the class with :
<SecurityPermissionAttribute( _
SecurityAction.LinkDemand, Unrestricted:=True)>
Do you have to prefix every property and method as well?
Thanks.
<p>I’m not very familiar with the PropertyGrid control myself, so I don’t know what extra security demands are made of it. I suspect that you are not actually running into a security problem however, as long as you are asserting for permissions before you create your control. My first step would be to debug your control’s binding to the assembly containing your custom type editors. For assistance on doing that, check out Suzanne’s blog entry: <a href=""></a></p>
Asserting permissions is different from creating a LinkDemand. To assert permissions, at every entry point to your control (the control’s constructor as well as every method called from your HTML page or by IE), you need to create the permissions that the control needs to execute (i.e. new FileIOPermission(PermissionState.Unrestricted); ), and then call their assert method.
How can I give a SocketPermission to managed code in IE( winform UserControl) so that the UserControl can open an IP socket to the server that it came from??
I will appreciate ur answer!
This is an interesting question, which I’ll write a blog post about this week. The quick answer is that using the default security objects you can’t. The best you can do is grant same-site web access, and communicate using HTTP or HTTPS. However, if you write a custom security object to create same-site socket permissions, this is achievable. I’ll post a link back here when I write the blog.
Greetings!
I need help. I am trying to load a usercontrol in IE. I know that the AppDomain has not enough security permissions. I don’t think that asserting permissons works for me. Everything works fine for me when I use the site condition with my machine name. When I try with the strong name condition it doesnt load at all. Can you provide a full source of a window control than can be load in IE using ONLY his strong name as a security condition? There is no documentation on this. Thank you for your time.
Just saw this on the newsgroups too, so I’ll copy and paste my answer from there:
Unfortunately, you can’t just use the strong name, for reasons I mention in my blog (which I see you’ve already found 😉 ):
I see that you understand that the problem is with the permission set associated with the AppDomain, and not with the assembly itself. Now what you need to think about are what evidence is available to IE at the time the AppDomain is created (and its PermissionSet assigned). Since the AppDomain must be created before the assembly is loaded into it, nothing specific about the assembly is available (including the strong name, or authenticode signature). Instead, you have only the site, URL, and zone evidence to work with. In order to get your control to work, you’ll need to use a membership condition that matches one of these types of evidence to grant trust to your control. Since you say that you’ve gotten this to work already on your dev machine with the site membership condition, I see that you didn’t have a problem getting that far.
Is there a specific reason you need to move away from using the site membership condition?
Hi, I’m not very familiar with .NET security (or .NET for that matter), but I did develop a user control that is embedded in IE and am getting the problems that you described in the blog.
I’m not sure how to word this, but calling Assert() on a Permission will only work if my user control is allowed to be able to get access to whatever I’m asking permission for right? For example, I tried new WebPermission(PermissionState.Unrestricted).Assert() and got a SecurityException. I found that only when I add my dll to a code group in the client machine with some sort of trust would the Assert() method call work.
Am I completely off track here?
So is it even possible for the client machines (anywhere on the internet) to load my application (a dll embedded in a webpage) without making changes to their security policy on their machine?
Thanks
Hi Wendy,
You’re correct, Asserting a permission requires that you be granted the permission in the first place. This post is mostly about getting the control to not throw once it has already been granted permissions.
If you need to have the user’s machines trust your code, you have two options. The easiest would be to simply code with only those permissions that appear in the Internet code group. If that’s not a possibility, then another option is for you to modify the policy of your local machine so that your control is trusted (see my post here for information on that: … I recommend trusting based on strong name), and then creating an .MSI deployment file out of the policy, and placing that on your website. Have users install the custom policy before running your control, and then your Asserts should work fine.
-Shawn
Hi Shawn,
Thanks for such a quick reply.
I don’t think that the .MSI deployment file is a viable solution since we don’t want our users to have to deliberately download and install something.
The actual problem I’m having is that my windows control needs to access an .aspx page that is located on the same web server that the control .dll is from. If the user (who could be connecting from anywhere on the internet) who downloaded the .dll is not connected to the internet through a proxy server, everything works perfectly. But if the user is connected through a proxy server, I get a HTTP 407 Authorization Required error when my code does a httpwebrequest.GetResponse(). I realized that HttpWebRequest has a Proxy property, however whenever I try to access that property, I get a SecurityException stating that the request for type WebPermission has failed. I tried to Assert a WebPermission with PermissionState.Unrestricted as parameter, but that caused a SecurityException as well. I’m assuming this is because my application isn’t granted unrestricted WebPermission. Given this information, do you know if I need any kind of extra permissions that are not available just by adding the site that the control .dll is from to the Trusted Sites list in IE?
Thanks,
Wendy
Right, your application is not granted unrestricted web permission, but you should have same site web access. Try just asserting for access back to your site.
The reason you can’t go unrestriced is if we allowed all web controls to have unrestricted web access by default, it would open up huge cross-site scripting holes.
-Shan
Excellent! Thanks a Million. This really helped me sort out my problem!
Hi,
Thanks for this wonderful insight. I actually tried creating a limited permission appdomain with codegroup having only named permission "Execution". To provide full access to my own assemblies I added them as fulltrust assemblies. Also I created another fulltrust codegroup for these assemblies using UnionCodeGroup and added it as a child of root codegroup. However I still get the security exception. It would be nice If you could provide a code snippet based on strongnamemembershipcondition to clarify doubts of mortals like us. Thanks.
– Shailendra
Hi, thanks for the info. Was tearing my hair out trying to understand how this works. But I still have issues…
Issue #1. I’ve granted UIPermission.AllWindows to my assembly using URL method. I call
new UIPermission(UIPermissionWindow.AllWindows).Assert()
in my constructor and it passes (doesn’t throw an exception).
However, as soon as I override PreTranslateMessage in my class my control fails to load – I just get the red X. From the docs this just requires UIPermissionWindow.AllWindows. I really need these lower-level overrides for my control.
Issue #2. If I use the strong name method my control fails to load – red X again. Doesn’t matter what code I put in the class (ie. I don’t call any code that requires special permissions).
Any help much appreciated.
Alfie.
Ok, I think I understand(?) what’s going on from a bit of digging.
The second issue is the AllowPartiallyTrustedCallers problem. Once I added that it went away.
The first issue seems to be a documentation error. If I use Reflector, ProcessCmdKey seems to require UnmanagedCode access. It has:
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode=true), SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
By the way, the Message struct which is one of the parameters also has UnmanagedCode=true.
Is this correct? Do I really need full trust to use a control that overrides ProcessCmdKey (and others)?
What’s annoying is that I rewrote a lot of code to use GDI+ rather than PInvoke to avoid requiring full trust and now I find I need it anyway!
Thanks, Alfie.
FYI, in answer to the "How can I give a SocketPermission to managed code in IE?" question, you can assert multiple stack walk modifiers / permission sets simultaneously to create a socket by doing something like this:
PermissionSet ps = new PermissionSet(PermissionState.None);
ps.AddPermission(new SocketPermission(PermissionState.Unrestricted));
ps.AddPermission(new SecurityPermission(PermissionState.Unrestricted));
ps.Assert();
Hi shawn,
I change the clinet CAS to full trush Internet zone, why I still get this.
Thanks
Richard
************** Exception Text **************
System.Security.SecurityException: Request for the permission of type ‘System.Net.SocketPermission, System,.Net.Sockets.Socket.CheckCacheRemote(EndPoint& remoteEP, Boolean isOverwrite)
at System.Net.Sockets.Socket.SendTo(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, EndPoint remoteEP)
at System.Net.Sockets.Socket.SendTo(Byte[] buffer, EndPoint remoteEP)
at ActiveXDotNet.UDPClient.btnJoin.Net.SocketPermission
The Zone of the assembly that failed was:
Internet
I have below code, without any attribute assertion, I got RegistryPermission failed at Internet Zone.
when I added [RegistryPermission(SecurityAction.Assert, Unrestricted = true)]
, I got SecurityPermission failed at My computer zone.
After I added [SecurityPermission(SecurityAction.Assert, Unrestricted = true)]
, I still got same exception.
Both internet zone and my computer zone has full trust to its own zone.
Can you help me out with this?
Thanks.
private void btnJoin_Click(object sender, System.EventArgs e)
{
Microsoft.Win32.RegistryKey rk;
rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
"Software\Microsoft\.NetFramework",false);
string[] skNames = rk.GetSubKeyNames();
for (int i=0;i<skNames.Length;++i)
{
Console.WriteLine("Registry Key: {0}", skNames[i]);
}
rk.Close();
}
I reccomend strong naming your assembly and creating a new code group that specifies the strong name and not worry about the other zones.
If you set the keyfile into your project for Wrapper Assembly Key File when you add your reference it will strong name the wrapper using your key.
Also if you need to use tlbimp or aximp you can also set your keyfile.
I was having problems using the attribute assertions, so I just use
PermissionSet ps = new PermissionSet(PermissionState.None);
ps.AddPermission(new SocketPermission(PermissionState.Unrestricted));
ps.AddPermission(new SecurityPermission(PermissionState.Unrestricted));
ps.Assert();
and life is good.
Is there any way to bypass permission check without setting the client code groups?
FYI, I recently ran into an issue where I create a CAG that fully trusted the strong name key through a Deployment Package, but when I loaded the page with the assembly it would throw SecurityExceptions or tell me in the IE Debug log that "that assembly does not allow partially trusted callers", when it certainly did trust them.
I was developing on Win 2000 with 1.1 (and this worked fine) and then tested on XP Pro SP2 with 1.1 and 2.0
The problem is that I was creating the CAG in the .Net 1.1 framework only and IE was using the .Net 2.0 Framework when it loads inside of its own app domain.
The fix was to create an identical CAG for the .Net 2.0 framework using mscorcfg or caspol.exe. I have to check for the newer framework version even though my app and installer only need 1.1.
This will be a maintenence issue, since IE uses the latest installed version of .Net for some reason, any ".Net Framework 2.1" upgrades will break this in the same way.
This discovery cost me one ms support incident, enjoy!
Hello,
I have written a windows forms control that we are attempting to host in an
IE browser. The application hosting the control is ASP.NET. The control uses
the following CAS permissions: IsolatedStorageFilePermission,
SqlClientPermission. Using a strong name I have signed both the web
application and the windows forms control. In addition I created a code group
below intranet applications that specifies this strong name and allows full
trust. This has alleviated the IsolatedStorageFilePermission exception.
However, the application still throws the SqlClientPermission exception any
time it attempts to access a SQL Server resource.
Any ideas and/or thoughts would be apperciated.
Thanks,
Phil
I have a Windows Forms app running in IE which needs to make use of a web service (.ASMX page) hosted at the same site as the DLL is downloaded from. It’s all built in .NET and I’m using the proxy class that Visual Studio builds to talk to the ASMX page.
However, even though it only tries to contact the same site, I get web permission exceptions when running in the Local Intranet zone, which according to the documentation ought to allow this by default. If I bump up the zone to full trust, everything works – but clients don’t like me asking them to do this!
Signing the assembly is not (yet) an option as it simply doesn’t run in that case.
Is there anything I can put in my code to fix this? Any other ideas?
Hi Julia,
You should be able to get details from the SecurityException about what you were actually granted and what demand failed — from there you can see the difference between the WebPermission you have and the one that you’re trying to use.
-Shawn
Hi. I am developing an ie based project which needs to have full-trust in internet zone for it to function well. I was just wondering what can i do if i want my specific sight (and only my sight) to have full trust in internet zone of clients viewing it? can i place my web address in their registry or sumthing then it will detect that this site has full trust in internet zone?
help needed badly…
Sure — you can use the Url membership condition for that. You’d want to have a command line like:
caspol -m -ag 1.2 -url* FullTrust
-Shawn
Ei thanx! But can I imbed it in C# or ASP.NET? I want to automatically set the settings of the viewer when he tries to view my page.
No you cannot. If code running on the Internet was able to modify policy on anyone’s machine to trust themselves, then there’s not really much point to the security system 🙂
What’s going to prevent some malicious code from doing the same thing?
-Shawn
I created an asp application that creates a word object,fills in the necessary content and sends this mail as an attachment..teh application is working fine from the server which is my machine..but when acessed from a client machine it throws an object required error..Can someone plz help me on this as i am stuck up on this for 1 week..plz help
thx kiran
I want to display a UserControl on a web page using an
In the old days of ActiveX, It was possible to download and install whatever was needed and simply activate it on the web page after that. This provided huge value in terms of good performance, ability to do things on the client not allowed/supported by the browser, and simplicity. I’m hoping there is a way to gain those benefits but with the much better security offered by code access control and UserControls.?
Thanks.
-Shawn.
-Shawn.
-Shawn.
-Shawn
System.Security.SecurityException: Request for the permission of type ‘System?
|
https://blogs.msdn.microsoft.com/shawnfa/2003/06/26/how-to-provide-extra-trust-for-an-internet-explorer-hosted-assembly/
|
CC-MAIN-2019-39
|
refinedweb
| 3,090
| 56.86
|
I have been experimenting with acceptance tests for a few weeks now - you can read more about my journey in my article about implementing cross-browser acceptance tests with TestCafe. A common problem when working with acceptance tests is that the implementation and the tests get out of sync. For example: somebody changes the markup of a module which leads to a failing test although the functionality stays the same.
Today we’re going to look at the approach of using separate, namespaced CSS selectors to help us with detecting changes, which have to be considered in the tests, before even running them. Using separate selectors for testing also leads to a more stable way of structuring our code without tightly coupling our tests with the markup and CSS styles of the implementation.
I first read about this concept in an article by Harry Roberts about more transparent UI code with namespaces. If you’re not familiar with the approach of using namespaces in CSS, I highly recommend you to read the whole article.
Tightly coupled acceptance tests
Methodologies like OOCSS and BEM have tackled the problem of tightly coupling markup and styling. But when we’re writing acceptance tests, many of us fall into the old pattern of tightly coupling the selectors used in the acceptance tests to the markup of the tested module, even worse, we often use selectors intended to represent a certain styling of a module, which has nothing to do with the functionality we’re testing.
// Tightly coupled selectors, don't to this! test(`Some test case.`, async (t) => { const heroLink = Selector(`.hero > .hero-body > .button`); // ... });
<div class="hero"> <h2 class="hero-headline">Headline</h2> <div class="hero-body"> <a class="button">Click me!</a> </div> </div>
Take a look at the code above – imagine the
.hero-body element is moved somewhere else or the
.hero section is renamed or the
.button class is removed from the element because somebody decides it should look like a regular link… All of those changes break the test but won’t affect the functionality in any way.
// Separate `qa-` namespaced selector. test(`Some test case.`, async (t) => { const heroLink = Selector(`.qa-hero-link`); });
<div class="hero"> <h2 class="hero-headline">Headline</h2> <div class="hero-body"> <a class="button qa-hero-link">Click me!</a> </div> </div>
In this example you can see that we’ve added a separate class
qa-hero-link. The
qa- prefix signals that this selector is used for quality assurance purposes only. This selector is not allowed to be used for styling or as a JavaScript hook.
There are two main benefits of this approach: no more tight coupling between a specific implementation of the markup or styling and it’s clearly visible to the programmer, that there are changes to be made to the tests if an element with a
qa- prefixed class is removed or its behavior is changed.
Removing quality assurance classes in production
If you’re obsessed about performance and you want to eliminate every unnecessary byte which is delivered to the user, you might think about removing those
qa- classes before deploying to production. If you’re planning to go this way, keep in mind the following caveat: what you’re delivering to production, is not what you’ve tested – there might be side effects you don’t catch because, well, you ran your tests on a different output.
const declassify = require('declassify'); const fs = require('fs'); const html = fs.readFileSync('index.html', { encoding: 'utf8' }); const declassifiedHtml = declassify.process(html, { ignore: [/js-.+/, /is-.+/], (process.env.NODE_ENV === `test` ? /qa-.+/ : undefined), }); fs.writeFileSync('index.html', declassifiedHtml);
In the very basic example above you can see how you can use declassify to remove CSS classes, which are not declared anywhere in your CSS code, from HTML tags.
By specifying the
ignore option we can configure
declassify to keep certain selectors which are not used for styling but which we still want to keep. If the script is started with the
NODE_ENV variable set to
test, selectors prefixed with
qa- are ignored and not removed although they are not declared in the CSS code.
|
https://markus.oberlehner.net/blog/css-selector-namespaces-for-stable-acceptance-tests/
|
CC-MAIN-2019-47
|
refinedweb
| 692
| 60.45
|
Why we need Data Manipulation ?
Real world data is so messy , we by doing certain operations make data meaningful based on one’s requirement this process of transforming messy data into insightful information can be done by data manipulation.There are various language that do support data manipulation (eg:-sql,R,Excel..etc). In this blog we will broadly discuss Pandas for data manipulation.In this section I will take titanic dataset for broader understanding.
Seaborn will load example dataset that is present in online repository.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset("titanic")
…
Prediction of Disaster Tweets using tensorflow 2.0
Here we will Be applying Deep learning Based NLP approach to predict the disaster based on tweets.I have taken dataset from Here.The dataset is present in csv format.There are various features present in dataset i.e:- id,location,keyword,text and target.Target column is given in binary format where 1 represent the condition of abnormality(Disaster) and 0 represent the normal condition(No Disaster).Let’s get started………
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from tensorflow import keras from keras.layers import Embedding,Dense,Dropout,Bidirectional,LSTM from keras.models import Sequential from sklearn import metrics from…
this section will cover almost all Data cleaning approach
In the real world, we won’t get modified data all we need to do to modify it by itself, Here we introduce data cleaning. A good Data Scientist has a great ability for data cleaning/data modification. I will be using pandas for data cleaning operations. In this blog, I will create a toy dataset for the data cleaning process. Let’s get started…..
Step I:- Creating toy dataset and importing necessary libraries
import pandas as pd
import numpy as np
How to handle large dataset
Suppose You are dealing with image dataset having 100 classes and each class consists 1000 images if we will train the model on low configuration device it will give run out of memory.Then the question is what should we do? Here Keras wrapper comes with an idea of ImageDataGenerator . Instead of taking whole dataset with the help of ImageDataGenerator We will divide the data into batches and then will feed the batches of image data into network for image classification or various CNN applications.Please read documentation of tensorflow believe me it will give more…
It is so much chaos in loading large-sized data set. Here PyTorch comes into the picture to make our task easy with its DataSet and DataLoader libraries. By importing these two libraries we can load our data in batches and will give less load to our system. let’s get started……..
I have taken the Wine dataset from here
Before going ahead let’s understand some of the confusing terms
epochs:- One complete cycle of the forward pass and backward pass.
batch:- number of training samples has been taken for one epoch
iterations (datasize/batch):-number of iteraions for one epoch
import torch from…
This dataset consists information about used car listed on cardekho.com. It has 9 columns each columns consists information about specific features like Car_Name gives information about car company .which Year the brand new car has been purchased.selling_price the price at which car is being sold this will be target label for further prediction of price.km_driven number of kilometre car has been driven.fuel this feature the fuel type of car (CNG , petrol,diesel etc).seller_type tells whether the seller is individual or a dealer. transmission gives information about the whether the car is automatic and manual.owner number of previous owner of the…
What is Feature importance ?
It assigns the score of input features based on their importance to predict the output. More the features will be responsible to predict the output more will be their score. We can use it in both classification and regression problem.Suppose you have a bucket of 10 fruits out of which you would like to pick mango, lychee,orange so these fruits will be important for you, same way feature importance works in machine learning.In this blog we will understand various feature importance methods.let’s get started…….
It is Best for those algorithm which natively does not support…
When we predict one class out of multi class known as multi class classification .Suppose your mother has given you a task to bring mango from a basket having variety of fruits , so indirectly you mother had told you to solve multi class classification problem.
But our main is to apply the binary classification approach to predict the result from multi class.
There are some classification algorithm which has not been made to solve multi class classification problem directly these algorithms are LogisticRegression and SupportVectorClassifier. By applying heuristic approach to these algorithms we can solve multi class classification problem…
The dataset I chose is the affairs dataset that comes with Stats models. It was derived from a survey of women in 1974 by Red book magazine, in which married women were asked about their participation in extramarital affairs.I decided to treat this as a classification problem by creating a new binary variable affair (did the woman have at least one affair?) and trying to predict the classification for each woman.Variables that is present in the dataset for prediction are :-rate_marriage(women’s rating for her marriage) ,age(women’s age),yrs_married(number of years married), children(no. …
What is correlation?
Correlation defines the mutual relationship between two or more features. Suppose you want to purchase a house , property dealer has shown some houses to you and you observed that the house price is increased with increase in size of house.Here Size of the house is strongly correlated with price.
Suppose you are a player and there is humongous recession came into white collar jobs . This recession won’t affect your earning because the recession of white collar job has nothing to do with your profession.In this case there is no any correlation between both the features.
…
In a process of becoming Doer.
|
https://akhilanandkspa.medium.com/?source=post_internal_links---------1----------------------------
|
CC-MAIN-2021-17
|
refinedweb
| 1,040
| 55.95
|
Gates Steps Down As CEO, Ballmer In 575
migooch was the first of many people to write with news that Bill Gates has stepped down as CEO of Microsoft. Steve Balmer, who replaced him as President, will be CEO. Gates will become "Chief Software Architect", and will remain as Chairman. Update: 01/13 10:27 by E : The official Microsoft press release is here.Alright - Salon's Top 10 reasons Bill Gates stepped down is pretty funny as well. What do you think are the Top 10?
Link to the zdnet story (Score:5)
http://
Getting ready for inevitable break up? (Score:4)
Truly, we live in interesting times.
Correction (Score:5)
Nice photo (Score:2)
Hey, does anyone else think Steve looks anything like Drew's brother from The Drew Carey Show? I think it would be funny to see him in a dress, wig, and heels...
---
Bald! (Score:3)
BALDIES UNITE! WE'LL HAVE THE WORLD!!!
Is this good or bad? (Score:2)
I can't decide - is this a good or bad thing? I mean, Bill G. was never THAT great of a software designer in the first place. Why not just consider retirement instead? What's worse - Bill running the entire company, and other's doing the job of design, or, Balmer running the company, and Bill getting his grubbies on to designing the overall systems concepts?
Plus, didn't he used to say that he could never see anyone above the age of 50 at the helm of MS? I thought Balmer was older than that 'limit'.
Gates is still in charge . . . (Score:3)
Re:So....... (Score:2)
More likely, this lets Gates be not quite as uberscrewed by the impending breakup (is anyone else moaning?), just partly screwed.
Chief Software Archetect... (Score:3)
-=- SiKnight
Not a suprise (Score:2)
I think the real thing to watch for is if Steve B. tries to pull a "Steve Jobs"(tm) on Gates.
In the end not a whole lot will change. The ego and aditude is about the same. Steve is better spoken and doesn't have that child molester look that Gates has.
Re:Bald! (Score:2)
Steven of nine? (Score:3)
Re:Is this good or bad? (Score:2)
Only on Slashdot... (Score:2)
I think that's great
Ballmer's credentials? (Score:2)
And the ineveitable question - Does it run Lin-- whoops, answered my own question =)
It's the Steve Factor (Score:2)
a Steve, as in a Woz or a Jobs, is just a more portentous name in computing than a Bill.
Re:Getting ready for inevitable break up? (Score:2)
Or maybe not. My understanding of all that may no be so great.
A brief Steve Balmer biography... (Score:4)
Speaking of which... (Score:3)
Baby-Bills (Score:2)
Now Bill Gates resigned
so he can CEO for
Babe-Bills tomorrow
Re:Getting ready for inevitable break up? (Score:4)
That really has to be the underlying theme. This press conference had almost no lead time, and the annoucement was so suspicious that the AP Wire put it up on the top of the important annoucements. The implication from the resignation is that the negotiations with DOJ over the breakup are not going well.
Of course Gates and Ballmer will trumpet that they have done nothing wrong, and that the breakup would be horribly bad. But this is kinda like bankruptcy planning - if you see doom on the horizon, there is nothing illegal about getting your money put away (in certain ways - other ways are called 'fraud' {g}). I think Bill is just aiming to be sitting in the right chair when the music stops.
Of course, he has been Microsoft CEO for nearly 25 years, and he has a huge image problem. Maybe the conspiracy theory *is* garbage, and he just wants to do something else. That wouldn't be the first time that happened in the software industry.
==
"This is the nineties. You don't just go around punching people. You have to say something cool first."
Resistance is futile (Score:2)
the other shoe (Score:2)
here [msnbc.com] is the link. Interesting that this was posted almost simultaneously as the Gates/Ballmer one....
Come in Bill, your time is up ... (Score:2)
Bill gets the last laugh (Score:5)
The government might split Microsoft into 3 (or so) entities, but it can't strip Bill Gates of what will be his large ownership in all 3 companies. And will breaking Microsoft up instantly produce a viable competitor for Windows? Office? Internet Explorer? (Note: I'm not talking technical merit, I'm talking end-users BUYING what they know).
Very likely all three companies will do really well, just inflating Bill Gates' personal fortune into even more stratospheric heights. It happened to Rockerfeller when the government split up Standard Oil, don't be surprised to see it happen again.
Why Gates would do this... (Score:2)
If he takes baby-steps away from the helm... and out of the lime-light... then he can safely cash out his stock, and retire...
It's a rough game in life when you use money to keep score... 'cause you don't want to give up any points...
sim city (Score:5)
It's easy to understand why bill stepped down if you've played sim city. Once the city gets to a certain size, the effort required to run it begins to outweigh the fun of making it bigger.
Running MS has probably been similar. I bet it was fun launching windows 1.0. Likewise it was no doubt a blast watching OS2 nose dive while windows picked up speed. And the success of MS's internet strategy after nearly missing the boat completely had to have been thrilling.
What next? 10 years of slow, expensive court appeals? That's not fun - that's like trying to build enough police stations to handle the population of your 700 arcologies.
There comes a point in sim city where you either quit or click on the disasters menu and select all of them. I'm glad bill decided to step back instead of building a flying robotic monster and having it lay waste to the campus -- that's what I would have done.
--Shoeboy
I'm not a microsoft employee, and I'm certainly not speaking for them.
What about code reviews? (Score:2)
In some ways, this is an insurance policy. If they split up the company, Bill is no longer CEO and can just get shares in each company and control it through himself and his buds shares.
Two Questions (Score:3)
C|Net News.Com article (Score:2)
Chief Software Architect? (Score:2)
Re:Getting ready for inevitable break up? (Score:3)
What do they do? (Score:2)
-r
That's what the problem was. (Score:3)
If only Bill had realized the problem years ago, we might have great software today.
Slate foreshadowed this nicely... (Score:5)
The article is actually rather interesting for those who don't know the answer. Anyway, here's a link:
http:
Re:Hysterical Parallell (Score:2)
Not true. Lenin is in Seattle, in the center of the Fremont neighbourhood just two blocks from my house. It's a large iron statue, kind of hard to miss, albeit not as well-known as the Fremont Troll.
And Bill is more of a Rasputin character in his own way
Re:Getting ready for inevitable break up? (Score:5)
While that is a possibility, I don't think it matters whether Bill is Chairman and CEO, or just Chairman. He'd still get first choice. There is no way that any serious individual thinks he will come out of the DOJ trial crippled in any truly signifigant way. Bill is a very clever fellow and he would end up in the best remaining position no matter what. He could always BUY a smaller compay and start over, if he wanted.
The tongue in cheek answer is that someone gave him a perfectly functioning version of Windows 2000 that will run any software it is supposed to. He has only weeks to break it and make sure that 1) no competing products work and 2) it looks like it is their fault.
Finally we have something more realistic: Gates is a celebrity. He knows that he is one and has a lot of stuff that he has to do as a CEO. He either wants to give the impression, or actually does want to get back into the trenches to some degree and work with the developers. If you acutally talk to some Microsoft developers, many of them will tell you about how he goes through their offices every so often and talks to them, sometimes motivating more than anything else they can think of and sometimes just chewing them out. (I interviewed with MS folks at Redmond before, just for fun.) Bill has to be under an incredible amount of stress from the trial, too. He may want to give up the reins a bit, but doesn't trust anyone else absolutely, so he remains chairman. As Chief Developer, he can pick any project as his pet and work with it, or step back and look at all of them. He has pretty much said: this CEO thing is too defined for me, so I am making up a title, retaining the real power of veto, and doing what I want.
B. Elgin
It's all in a name (Score:2)
If I was Ballmer, I sure wouldn't want to be in the CEO spot when everything hits anyway. It's always a slim possibility that something might happen, and he becomes...ahem...dispensable as many CEOs seem to be in the tech world. Gates did a smart thing getting himself out of the hot seat, and probably he sold it real well to Ballmer
"Hey look, Steve, you can have the celebrity and spotlight. It's all good, and I promise you'll have a good spot after the breakup...what? No, I wasn't laughing under my breath. You must be hearing things."
Aww gee. (Score:2)
1) Gates has been MS President since Linus was 4 years old, and perhaps its time to move on.
2) He's becoming chief software architect - i was not aware he knew how to code.
3) Is he, perhaps, up to something as this is right on the heels of the latest noises from the monopoly trial...
And it also reminds me; who is slated to take over for (knock on wood) Linus, if something happens to him? The worst thing that could happen to the linux community would be to run around like a headless chicken.
Just my $0.02 (add GST if in Canada)
#include <signal.h> \ #include <stdlib.h> \ int main(void){signal(ABRT,SIGIGN);while(1){abort(-1)
CEO? What's that? (Score:2)
To understand my point, consider id Software. Todd Hollensomething is CEO, but John Carmack is in charge, AFAIK.
Bill Gates will always be in charge, but he may have less paperwork to do. This just changes the names around a bit....
Re:Question (Score:3)
----------------
"Great spirits have always encountered violent opposition from mediocre minds." - Albert Einstein
Juxtaposition (Score:3)
I guess the sort of means they failed badly . . . .
If They Break Up, He'll Have to Choose (Score:2)
Re:What do they do? (Score:3)
CEO is Chief Executive Officer. Tends to run the company. The big cheese.
Chairman of the board runs the meetings of the Board of Directors, which can hire and fire the President and the CEO. The chairman can either run the board (usually holding many shares then) or can be just someone who makes sure meetings occur (usually few shares or a compromise position for a company with large shareholders who disagree on certain issues).
Any of these can be given powers the others might have. This is decided by the shareholders and the Board of Directors. And their jobs can be changed at whim. The Chief Technology Architect could take control if he happened to own nearly 20% of the company (e.g. Bill Gates), for example.
It's just a name. Bill is still Bill. He just doesn't want to do the boring legal stuff anymore and at $100 billion that's his call.
Love him or hate him (Score:3)
Love him or hate him, Bill Gates is the reason why Linux exist. If it was not for dos and windows 3.11 inferior code, Linus would not of been inspired to write linux. Can anyone argue where Linus got his inspiration? No, cuz he admited himself , look at Novemebrs issue of MIT Magazine of Innovation Technology Technology Review.
People can argue this back and foward all they want, but growing up in an era with Bill Gates pushing the internet into everyones home is the reason why some of us are what we are today. No can argue the fact that Internet is readly available toady to millions is partly because of Microsoft Mission Statement which is " A computer on every desk and in every home using great software as an empowering tool". Now some might argue that their software is somewhat not so great, but the fact of the matter most of would still be using "MAC's" today if it was not for this man we love to hate.
Bill Gates, is proably the most influential man in the high tech industry next to Tim Berns and Marc Anderson. Yea , the company was on a mission to destroy every one in its path, but thats what having a good strategy is "to over come your competition using best cost / low cost leader to differentiate yourself and gain market share at any cost."
If Netscape, Apple, and all those wining company recognized the oppurtunity before Microsoft had, then the table would of been turned. I have to wonder what kind of management these companies had, to forgo oppurtunties that existed. Proably not astute managers, thats for sure. Why else would of Netscape surrendered to competetion?Netscape had their web site to leverage to be able to capture market share in the internet arena. They didn't.. Obviously AOL know's how based on the appearance and marketing of it today. The same with Apple, if they would have liscnesed the "OS" things might be different today. They didn't. Who's fault is that? Microsoft! Wrong, it's managements fault.
When it all comes down to it, a company with astute managers and good business sense is more likely to succeed and fend of competetion than one that is just made up of a bunch of "TECHIES".
With that in mind, I say Bill Gates is the greatest man to have come along since Henry Ford. He was able to mass produce a product and make it available to every one of us at an affordable price. Thus, making some of us who we are today. Network Engineers, Programers, Linux Geeks, Hackers, Web Site Desingers, entrapanuers, and so forth. Well you get the picture.
The man we love to hate! Bill Gates
Remeber him, cuz when we get older we'll all have something to talk about.
TTYL
Re:sim city (Score:2)
I couldn't think of *any* job more enjoyable than giving away billions of dollars to causes *I* considered worthy (provided I still spent an hour or two each day coding free software
:) ).
Re:Getting ready for inevitable break up? (Score:2)
Immediately after the break-up, chances are he's going to own a big chunk of all 3 divisions anyway, so his money is more or less safe. I also imagine, he will have some degree of influence over the individual companies, due to his holdings in the company (ofcourse, I imagine the DOJ could force him to put his eggs in one basket or put other similar constraints on his involvement).
(Also, I read somewhere that after the break up of Standard Oil and AT&T the respective market caps of the offshoot companies was greater than that of the whole, or somesuch. Basically, they were saying it's good to invest in a company just before a forced break up. Anyone got references to this? Or am I talking crap?).
I imagine that the market would react favourably to whichever (if any!) of the companies Gates aligned himself with. Gates being Gates and all.
But from the announcement, it sounds like he's going in to the applications division anyway.
It'll be interesting to see how the market reacts over the next few days. MSFT has been on a bit of a roller coaster for the past week. It's worth pointing out that they're up 2% or so as of writing this, which is good considering they've been falling for a week or so. Have a look at bigcharts.com [bigcharts.com] or your favourite financial news site.
...j
This has nothing to do with a split - sort of (Score:3)
Ballmer has been the heir apparent for some time as the designated hardass that can (they hope) keep Microsoft moving ahead of its problems. Gates is now at that age (like many of us) where the day to day business stuff that was once so exciting is a bore. He has a family, a house on Lake Washington about the size of Rhode Island, and enough money (no matter what happens) that will allow him to do what he wants as long as he wants. All he needs to do now is find something that interests him. What is there left for him to do in business? Build the richest company in the world? Become the richest man in the world? Talk about been there, done that . . .
Gates is now looking to create a different kind of legacy for himself. As far as the lawsuit or splitup is concerned, a move like this is an upraised middle finger. If they really thought a splitup was going to happen, they (Gates, Ballmer, etc.) would either both move into division management to prepare, while leaving someone with more legal/financial backgroud to manage the details of the split with the DOJ and Wall Street. Microsoft knows it has to settle to survive, and Gates has put his chief junkyard dog in charge to handle the negotiations and aftermath -- he's the bad guy who will have to take all the actions to comply along with all the blame.
Re:Aww gee. (Score:2)
--
Re:Question (Score:2)
engineers never lie; we just approximate the truth.
Re:Steven of nine? (Score:3)
Make Seven
Re:Bill gets the last laugh (Score:2)
You're very likely to be right about that. But that isn't the point! Bill Gates' net worth isn't too interesting to me, other than as a point of trivia. The point is to put an end to the days when MS could illegally take advantage of their monopoly status. Breaking up the company, combined with whatever other restrictions they place on MS, will hopefully achieve this goal. That's great! That's the point.
If investors (not just Mr. Gates) make a profit from this a la Standard Oil, well, so be it...
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Noooo!!! (Score:3)
___
Re:Aww gee. (Score:2)
In any case, we know he didn't write DOS, and it's obvious that all the later versions of DOS were pretty much just hacked up from the earlier versions. (FAT12 -> FAT16, and now VFAT / FAT32? Puh-leese.)
Windows 1.0 and 2.0 sucked, and they had teams of people working like that. Of the two, I still like GEOS better. Windows 3.0 and 3.1 was better, and more stable, but still couldn't multi-task well. In Windows '95/'98, they managed to fix the multi-tasking but drop the stability.
In Windows NT, they originally fixed the stability, but raised the resource requirements massively. In later versions, they managed to speed it up some, but now it's less stable.
It will be interesting to see what Windows 2000 brings, but none of this implies that people at Microsoft are good at big projects. Maybe they can all code great small assembler programs, and maybe they should have started with that and stuck to it for a while. After all, that's what got UNIX started. Maybe Microsoft will eventually manage to reinvent it. Or offer a good product at a fair price. Or give good tech support. Or take responsibility for their product's shortcomings, and advertise and benchmark truthfully.
...or they can just sue Al Gore for claiming to invent the Internet when we all *know* it was Bill Gates! That sounds more like it!
---
pb Reply or e-mail; don't vaguely moderate [152.7.41.11].
The Wizard of OS (Score:3)
Seriously, tho, my first response to this was to see it as the obvious reply to the rumors of the split-up--leverage the top execs so that they are all at least somewhat experienced with the CEO seat before they get plopped into it. That, combined with Gates getting tired of being at the helm. All reliable reports I've heard is that it is true that he'd rather be in the trenches.
Whether that's a good thing or not, well...
Sim City analogy continued... (Score:3)
> decided to step back instead of building a flying robotic
> monster and having it lay waste to the campus -- that's what I
> would have done.
What do you think Windows 2000 is?!
Re:sim city (Score:2)
It would be awesome to have billg hacking Linux kernel! He's a smart guy, and I am sure he would add a lot
Hey, Bill, give it a try - why not?!
Why is it? (Score:2)
The DOJ is *NOT* going to break up Microsoft. They can huff and puff all they want but if they try to they will be into 10 years of court battles. (They know that and so does anyone with half a brain.) And with every AOL/Warner deal that goes down MS can point the finger and say "look at that." It won't be hard for them to find a judge that will agree. So get over it. It's not going to happen. Microsoft is here to stay, it's power may fall or climb but it's not going to go anywhere as much as some would like it to go *poof*.
If Bill wants to have more time to spend with the product groups hell I say go for it. If he wants to spend time writing code more power to him. (Although I don't know what he has the skills to write nowadays). He should do what he enjoys and wants to do. He has that right just like the rest of us.
Alternate text on image! :) (Score:2)
... but Steve is a much bigger man!
Re:sim city (Score:3)
I can see bill's first post to linux-kernel now:
You^H^H^HWE are all thieves...
Why not?
--Shoeboy
Re:Does this make him harder to touch? (Score:2)
I think he's trying to make himself impossible to touch, but I think he'll do it in stages. First he drops his CEOship. A year from now he decides MS doesn't need him anymore and retires to Guatemala or something.
And then, BAM! DoJ slams down on MS. But Billy Boy left the business.
I don't think Bill even cares about the future of MS. I'll bet he's selling off shares as we speak, quietly.
Re:Love him or hate him (Score:2)
--
The second time he's done this. (Score:2)
Re:So? (Score:2)
apprentice.
Re:Question -- what is President, CEO, etc. (Score:3)
The CEO is responsible for the LONG TERM management of a company -- issues like: does the company as a whole have enough funding? What is the appropriate positioning in the marketplace? Can we forge alliances with other companies, or buy them outright? What markets should we be entering or leaving?
In a way, the CEO is the actual head of the company.
The board is another story. The board functions as an overseer. Typically, the board does NOT set policy, make rules or even high-level decisions. This, however, varies widely from company to company, but in general, they can't -- the typical company has board meetings once or twice a quarter at most. Their job is to act as advisor to the CEO (who almost almost ALWAYS has a seat on the board, and is usually chairman), and as a brake on them. They are not employees of the company -- frequently they ARE of other companies, or are executives of other companies, and they are also the elected representatives of the shareholders. Usually a fraction, or all of the board members are re-elected each year. As a last resort, they usually have the ability to remove the CEO, as they did at Compaq last year. oh, they one area they usually do rule over are issues like executive compensation.
Pulling a Steve Jobs? (Score:2)
Joseph Elwell.
I like this photo better (Score:4)
Not even the kernel . . . (Score:2)
Therefore, I'd like to challenge Bill to get a (non-documentation) patch accepted into *any* well-known free software project. In fact, I'd personally like to ask Bill to use his newly acquired free time to help out with GnuCash [gnucash.org] project.
On the theory that people contribute to free software to scratch a personal itch, I reckon Bill might like to add support for arbitrary-precision arithmetic to prevent floating-point overflows . . .
It's time for him to step down anyway (Score:5)
Stop sounding like a bunch of conspiracy theorists who've been listening to too much Art Bell. (shrug)
Consider this: how long has Bill Gates been running Microsoft as CEO? 25 years? Given the fact he's raising a family and also does have some other serious hobbies in life (e.g., his considerable interest in biotechnology), I think Mr. Gates wants a change of scenery and do something that won't be so taxing.
His place in history is already completed; he wants to do other things like life, just like when Steve Wozniak stepped down from Apple Computer.
Re:Getting ready for inevitable break up? (Score:2)
From what I understand, Bill Gates's purported image problem does not extend to the general public. I recall seeing a recent (post-Findings of Fact) poll that said that something like 66% of Americans see him as the embodiment of the American Dream. Of course polls are fallible, but just beacause he isn't terribly popular among the slashdot crowd doesn't mean that nobody likes him.
Re:Getting ready for inevitable break up? (Score:2)
Funny how people mesh together things like Microsoft, AOL and the internet - kind of viewing them as a contiguous whole, and Bill is the most recognizable figure in all that. "Steve Case, didn't he play for the Red's in the '70's?"
On another note, like how MS mouthpiece jumps on the TW/AOL merger as further proof that Microsoft is not a monopoly? What?!
Bah
Re:The DOJ can't force him to do anything (Score:2)
Take a minute and critically (that means no demagogic knee-jerking kids) about what life would be like if Microsoft didn't exist tomorrow. Are you Open Source guys ready to give free tech support to every 90 yr old granny who wants to print a birthday card? I sure hope so in such a circumstance...
This is why specialized support companies exist. I personally won't do even phone support for my own fhttpd for every non-technical user, but this is the reason why open source software is profitable for businesses -- someone else can have its own support infrastructure make money on it.
As for every grandma trying to print a greeting card, no one would be hurt if she wouldn't be able to -- Hallmark makes better ones anyway. One who is interested in selling software to users, whose support doesn't justify the distribution cost should deal with this problem, not developers.
Re:Getting ready for inevitable break up? (Score:2)
Well, the theory is that Microsoft is going to be the 600-pound gorrilla that takes over the software industry. That has always been a stretch, but it's now even more ridiculous with AOL suddenly doubling in size and getting revenue streams outside the computer industry. There's no way they are going to back down if MS tries to strong-arm them.
Re:Getting ready for inevitable break up? (Score:2)
Re:Slate foreshadowed this nicely... (Score:3)
The story was posted "Posted Wednesday, Jan. 12, 2000, at 9:07 a.m." and in the article it says "On Thursday, Microsoft founder Bill Gates announced that he was handing over the job of CEO"
I what to know how they know, you know?
Re:Is this good or bad? (Score:2)
(I cant' believe I'm doing this...) Just a minute there. He was no god, but he actually pulled off some decent stuff in the 70s. I remember getting quite intimate with the inner workings of a Microsoft BASIC interpreter for the 6502 and being rather amazed that someone had written such a large project in assembly language. It may not sound very hard or complex to people nowdays, but try to imagine writing your own floating point routines on a processor that doesn't even know how to multiply integers, and only has one "general purpose" register.
It's not a godlike project (and I'm sure that many people reading this have done similar things), but it's quite nontrivial too, and simply impossible if you are clueless. I don't know how much of that code Gates wrote (none? all? some?) but MS was a pretty small company back then, so I wouldn't be surprised if he did much of the work.
(Not to mention the story about the Altair BASIC interpreter that ran correctly the very first time that it was loaded onto the hardware...)
Gates may have once been a decent programmer. It wasn't really until the 80s that he stopped relying on his production skills and started to concentrate on market manipulation instead. I don't even want to think about what must have happened to him, to make him turn to such limitless evil, and to so willfully betray and sacrifice even the pretense of ethical conduct.
Perhaps that's what makes him so infamous. When PHBs in suits attack our culture and try to stop the advance of technology, it is 'only' war. When a programmer does it, it is defection and treason.
---
Is everyone here a cynic? (Score:5)
I agree with the previous post. Nearly everyone on this site is biased against Microsoft to some degree. Maybe this is flamebait but it's completely true.
I curse Windows and Microsoft on a daily basis as much as everyone else, and don't get me wrong, I fully support Linux as a superior operating system... it is. However I haven't killed my hope that Microsoft can improve. Can anyone truly say they believe that Microsoft has no talented people working for them? It's a question of how that talent is being used.. (namely, for marketing, not QA oriented goals)
Bill Gates isn't a god, or a monster. He's flesh and blood just like the rest of us, trying to do good in the hyper-competitive, vicious world we have created for ourselves.
How many of you have even considered the possibility that Gates has regrets? I doubt very much he's blind to what an unstable operating system Windows is. I think he stepped down as head of Microsoft simply because he's currently unpopular, and he wants to protect Microsoft, his life's work. (Before you start yelling at me that he made himself unpopular, I suggest you take a good look at Slashdot's Gates/Borg icon and ask yourself who really makes demons of men)
I'm not saying Microsoft is going to turn around and start laying golden eggs, but Gates stepping down from CEO and focusing more on improving their software is at least an ATTEMPT to move in that direction. Oh no, wait, I forgot. It's a big monstrous conspiracy to cleverly position himself as the uber antichrist of the next millenium. Silly me.
I'm sorry to be caustic, but the amount of suspicion and hatred flowing from what I usually find an extremely open minded, intelligent, and positive community just sickens me sometimes.
Re:Bill gets the last laugh (Score:4)
I don't understand the preoccupation that people seem to have with the idea that a split up microsoft could be worth more than a whole microsoft. Who cares?
The point in splitting up Microsoft is not to make the resulting companies less successful than the parent. It's to keep the interaction of those individual businesses fair, so that MS Windows corp has to compete with {Linux,BeOS,MacOS,etc} on its own merits. Not on the fact that it can tie MS Applications corp's products into its products, and force MS Applications corp not to port to any other environment.
I just keep thinking of how cool it would be if suddenly MS Applications corp decided that it was in their financial interest to port to {Linux,BeOS,etc}. In such a situation, I *WANT* that company to succeed, and to be a pioneer in encouraging other applications companies in porting to {insert non-Windows OS here}.
Re:Not a big shock (Score:2)
I don't mean this as a flame, but over the years, Bill has mellowed from someone who can get things done into "Tweedledee".
Now he's being replaced by Tweedle-You-WILL-get-that-goddamned-module-up-and
It's obvious that for the past several years, Ballmer has been the asshole behind the stink that is Microsoft, anyway.
(And by that, I mean he's been the guy to make sure company goals are being pursued as vigorously as possible. Now if we could only convince them that *stability* and *security* are valid company goals along with a unified, friendly, consistent user interface.)
And BTW, I think that almost every successful BIG company has one of these...
Re:Getting ready for inevitable break up? (Score:2)
Now, with the possibility that M$ will be broken up into 3 parts - OS, Software and Internet, Gates has positioned himself at the head of the section he believes is the way forward anyway.
The other two sections - OS (which is facing increasing competition from Linux, MacOS, BeOS, etc) and software (now facing renewed competition from Sun with StarOffice, amongst others) are both, it would seem, on downward spirals, meanwhile IE usage (which I know isn't the entirety of M$'s Internet business, but is a good indication) is skyrocketting - the website I run has approximately 60% of users using IE5, another 20% using IE4. IIS has crushed Netscape's web server platform, and, if you believe what M$ say, is a serious contender for the www server crown. ASP is widespread, backending into SQL6.5 and SQL7 databases.
Gates has simply positioned himself at the top of the fastest growing section of M$ for the breakup - he's kept M$ alive for 25 years by making "smart" decisions - M$ never rose to the heady heights they've reached because they had the best software - but because Gates made the right decisions for the company's longetivity, and it appears he's doing it again.
You have to remember - if M$ survives, Gates survives. People say he's the richest man in the world, but a LOT of his wealth is tied up in M$ - and if M$ fails, he'll lose a LOT of money.
Re:Question (Score:2)
The board typically meets quarterly or so and does things like hire/fire CEOs, elect new board members, bitch and moan about stock performance, set dividends, set major corporate strategy directives (buy/sell divisions, mergers, what businesses to get into/out of) and pretty much vote themselves big stock bonuses. These are the folks at the top of the capital pyramid and the Chairman is the Alpha Capitalist. The Chairman is the one most accountable to the stockholders.
Chief Executive Officer in my company is the one that runs the operations. He is the one that all of the business unit presidents and vice-presidents report to. He tells them what to do. He sets financial and operating targets for them and they cower in fear if they don't meet their targets. CEO typically is brought in by the board on a contract basis, with all kinds of bonuses and penalties based on performance written in, and usually a nice early termination insurance clause.
Our CEO is also our president so I may have the distinction a little confused, but the President has the CEO, CFO, CIO and resource units (R&D, HR, etc) all reporting to him. He sets the overall direction for the business. He is the one who carries the business results to the board and comes back with his head in his hands and his marching orders from the board. His bottom line responsibility is to maximize shareholder value (read: run the company profitably so the stock goes up and the board doesn't get fired at the next stockholder meeting).
At least this is the way it seems to work in my company. I know there is quite a bit of difference depending on the industry (I'm in a Phone Company spin-off IS/Service Bureau) and such.
Re:Getting ready for inevitable break up? (Score:3)
An earlier
In addition, IIRC the W2K project has already driven two managers into early retirement, and Brad Silverberg (of W95 fame) didn't want to touch it with a 10' cattle prod. One has to wonder if W2K hasn't acquired the stench of being a career killer for those put in charge of it within the halls of Microsoft. Once again, putting The Man in charge could be a (internal) PR boost for W2K.
He can't possibly give a damn about money (Score:4)
Generally speaking, wealth is meausured in terms of orders of magnitude, not total dollar amounts. That's why somebody who has $9 million is in the same bracket as someone who has $1.2 million. Obviously, the difference of 7.8 million is a HUGE difference, but they're both "millionaires" and we leave it as that.
Billy isn't that close to jumping up another order of magnitude, because the higher you go, the harder it is to progress in terms of order of magnitude. In terms of day to day, and even life long decisions including providing for your next 3 generations, *there is no functional difference between having $5 billion and having $9 billion* Again, sure one is a hell of a lot more than the other (to the tune of $4 billion) but that is such an absurd amount of cash that I would think most people never touch the capital to begin with. You just stick it in reasonably conservative investments, and live like a king off of the interest.
Bill isn't dumb, he knows all this since he's probably got a small army of CPAs that just administer his finances. So let's be optimistic and say that with "Baby Bills" he could stand to end up $4 billion richer than he was before. WHO CARES??? He can't spend that amount in his lifetime, and it's doubtful his kids could either. (short of wholesale gambling and simply throwing it away). What's the motivation for earning the extra $4 billion? There isn't one...
Bill gets off on control and ego. He gets off on having one of the largest corporations on earth under his control, and being a celebrity probably. Money just can't be a motivating factor. If it is, then he is WAY more shallow than anyone could possibly have ever imagined. And comfortable living can't be it either, because he achieved that a long time ago.
Re:Getting ready for inevitable break up? (Score:3)
Gates looks at him and says, "You know, if I had a million dollars for every time someone called me a nerd... Oh... nevermind. I do."
If I were Bill Gates, instead of stepping down as CEO of MS, I'd leave completely, buy Apple or Be, and try and crush MicroSoft. You know, just for the hell of it. Of course, BillG selling all his stock at once would seriously hurt MS as it is.
Re:Is this good or bad? (Score:2)
By software designer, of course, I don't mean programmer, but rather the person who decides which projects to focus on and directs new development. And Gates has been incredible at that in the past.
The seamless integration of the Office Suite, Linking and embedding, the concept of COM everywhere, getting the entire product line Internet-ready in an amazingly short time, VBA across the product line, etc. Forget the silly flames: Gates has a very good knack of identifying the needs of the public and providing software for those needs.
This move has been rumored quite a bit over the last year as service packs kept getting recalled and NT2K kept getting pushed back. MS needs someone to get the development groups focused, and Gates is the perfect person for this. I'm not surprised he's tired of dealing with lawsuits all day long.
My take on the matter: (Score:5)
He can't buy off the government- he's tried. But he can buy a fall guy. That is Ballmer. He can extricate himself, claim Ballmer set the whole tone for the abuses of MS, and spend the rest of his life giving away huge sums of money while still living better than most kings. Who wouldn't want that? Gates wants that.
It is also true that the kind of person who can build an empire of this nature simply will not let go- but this isn't Gates letting go, really. Microsoft's _reputation_ is being wrested from him, and I'd say this also indicates no plans of Microsoft's indicate any change in overall strategy or approach. MS will play dirty to the end- Gates doesn't see this as wrong, but he's not a dope and he does see that _others_ see it as wrong. Given enough incentive, people do change- I picture Gates thinking about his image, how he wishes to be seen. He can afford to be the benevolent philanthropist for the rest of his life, a Carnegie in the best possible way- if he chooses. But at some point he must accept that Microsoft has taken him as far as it can- and has started to get in the way of his new dreams for a well-loved future as a philanthropist. And, just like any of a thousand unfortunate tech startups that were in the way and had to go, now Microsoft, its culture, its legacy are in the way of the life Gates wants for himself- and it has to go.
Gates is not a sentimental man, and he is easily as perceptive as the Judge and intelligent enough to see the full implications of his position. At some point he began taking all this seriously- and started laying escape plans.
Ballmer is left in a position to preside over the decay of an empire. There's really no way for MS to expand further- _especially_ with AOL Time Warner suddenly appearing- and MS is hopelessly dependent not on profitability alone but an outlandish growth rate. That cannot continue and won't. Ballmer is also combative, a perfect match to the job of making Microsoft fight to the death. They won't in fact die, but their being relegated to only one choice in an industry of choices will be a very, very painful and bitterly fought loss.
Gates has the opportunity, having made MS what it is, to now cut it loose, cash in, and go home to be a lovable billionaire. Doing this is perfectly in character with the approach that made MS what it is- ironically, I'd been saying for awhile that there was no reason to believe MS would have loyalty to the USA, and now it turns out that Gates does not have loyalty to a losing MS either. Perhaps surprising, but plausible.
Get used to the idea of Gates as a benevolent philanthropist. He _will_ be able to separate himself from the unpleasantness, but his ways of doing so may be startling...
Re:sim city (Score:2)
What you are looking for is a flock of penguins!
Re:Aww gee. (Score:2)
You're right, Windows '95-2000 (there's a Y2K bug), Office, and Visual Studio all are very "featured". They also have many "mis-features", and many bugs. Unix has features that people actually *need* (that's why they put them there). Also, Unix is an Operating System, not a Word Processor, let's maintain that distinction. If you want a Word Processor for Unix, I'm sure you can find a good one, but you don't buy it from UNIXSoft, okay?
I'll have to disagree with this next one: Linux looks like Unix, it behaves like Unix, and it's implemented *well* compared to many commercial unixes. Of course, this all depends on what you want, but... ever used HP/UX? Linux makes *much* more sense compared to that. If you've used one particular commercial Unix for a while, you might be biased towards a particular flavor, as I surely am towards Linux, but they all share a lot of similarities.
What I like about Linux is that it caches *very* well, does very efficient process creation, is pretty stable, and supports a lot of devices (a note on these two: of course, some drivers are more stable than others, and there are always patches. That's what happens when you get something in development. However, I've never seen Linux get Unstable in the sense that Windows does--everything happens for a reason in Linux, and you can find out what it is if you know what you're doing.)
VMS is supposed to be good for scalability. I can't personally vouch for that, because I've seen it in situations where it must have been badly misconfigured. But that says something for its stability, because it didn't go down, it just went *really* slow. However, NT didn't get either of those features right. And I've seen Unix be just as stable as VMS, and far more friendly.
Win32 *does* have APIs for just about everything. It's a headache. Especially since it manages them with DLLs, which have to be the worst excuse for libraries that I've ever seen. First off, who in their right mind would let a program randomly modify/overwrite crucial system libraries? (or, even worse, let a *user* do this...) And even if you did, what if you have different, incompatible library versions with the same name? Microsoft did this many times in different versions of Office--they would replace a DLL that another Windows program used, such that installing Office breaks the other Windows program! That's apparently Microsoft Binary Compatibility for you. Maybe you could give them different names in a filesystem that did symlinks properly. Hmm...
In the meantime, if you want APIs to program with, you can find tons of them for Linux. DGA instead of DirectX, many of the Windows APIs are implemented in Wine, there are many sound / graphics interfaces, some of them crossplatform like SDL, and many widget sets (I wish Windows knew what a widget set was!) and window managers (ditto for that, Windows needs more cool shells) and many free ready-made applications and stuff.
---
pb Reply or e-mail; don't vaguely moderate [152.7.41.11].
SOFWARE SHOULD GET BIGGER EVERY YEAR!! (Score:2)
Re:Getting ready for inevitable break up? (Score:2)
Assume you meant 'takes over the internet media industry.'
Sure enough, that's the spin they're trying to put on it. That's not the focus of the anti-trust case though, is it? They'd like you to think that but it is more about their past illegal business practice of leveraging their monopoly position in desktop OS to the detriment of conusmers, competitors and others that is at issue.
This has been said over and over, a monopoly in itself is not illegal, it's the things you do *as* a monopoly that break laws. (INAL)
You are thinking of Paul Allen (Score:2)
Paul Allen (a very GOOD hacker at the time) did most of the Altair work.
At most Bill acted as Allen's "agent". He was the one angling to make sure he (and Allen) made money off of Allen's skills. Witness his now infamous "big foot" letter [curtisfong.org] to Altair hobbiests, regarded now as the start of retail software sales. That is Bill Gates' primary legacy to computing, not any real programming.
My thoughts exactly. (Score:2)
I love the "Breaking up this company is such a terrible idea!!" comments from Ballmer.
______________________________________
um, sigs should be heard and not seen?
linux was not written to crush windows (Score:2)
I doubt too many of the early kernel hackers cited "hatred of windows" as their prime motivation. They most likely considered dos/windows irrelevant and were motivate by dislike of the high price and unfree nature of commercial *nixen.
--Shoeboy
Mood Music - Microsoft Rhapsody (Score:4)
Re:My take on the matter: (Score:5)
The idea of Gates as a well-loved philanthropist is something we should hold more strongly in our minds than the "BillGatus of Borg" image we beat to death. Whether truth or opinion, the image of Gates as an evil dictator is not very appealing and does no one good. The image of Gates as the next Carnegie, on the other hand, is very pleasing and beneficial to our minds and our society. My belief is that the entire presence of computers in our world is entirely mythical - although I don't want to get into that. Based on that idea, if you can swallow it, there are no heroes or villians on the Internet or in the tech industry different from those in real life. Such is why the entire antitrust case against MS is a complete fallacy, such is why AOL could merge with AT&T and all the Baby Bells if they wanted to and our existence will be no different, such is why Linus Torvalds is just some guy from Finland when he walks into a local bar.
I hate to see this as the beginning of the end (or some substantial part of it) for MS. First of all, I think Gates is taking his natural role right now rather than cashing out (as this move has little to do with money). Even if it is motivated by the imminent collapse of MS or the current turmoil, it's not as if the power structure is radically shifting - it's more like the movement of the tectonic plates. Second, the idea of this leading into the bitter end for MS is just nauseating. After all, this is a company with tens of thousands of employees, the highest market capitalization of any company existing today, hundreds of (arguably) quality products on store shelves, and a solid financial foundation. Sure, any company can give up the ghost tomorrow for any reason, but it doesn't HAVE to be that way for MS. Especially in light of the AOL-TimeWarner merger, it seems STUPID that a company like Microsoft can lose everything. AOL-TimeWarner could collapse under it's own weight, and yet Microsoft has stayed agile and responsive to the industry over the years throughout failure and success. This alone should be a good reason to not count MS out yet. Finally, like I said computers are mythical and only real people make the difference. Microsoft is still a real corporation with real people in charge... pretty much the same real people as before. No one is going to skip buying Office 2000 tomorrow because Gates isn't CEO. Office 2000 will be the same product as it was yesterday, and Microsoft's ability to continue releasing good or half-baked products and making money regardless is what will tell their future.
That said, is this the end of an era for MS and the computing industry? Maybe. I can't see how that AOL-TimeWarner merger really changes the success of other companies... for example, Yahoo isn't going to be upstaged just because they DIDN'T merge with another company. Same goes for Microsoft... it's a pure battle of control and hype, and in the end the real world fact is that I can hardly think of any major products that the new AOL-TimeWarner possesses that directly compete with anything from Microsoft and vice versa. Microsoft can still succeed in the face of AOL, the DOJ, Linux, temp workers, whatever. If they heavily rely on what they've done in the past to dictate their future, THEN THEY'RE DONE. But they really never have. Not in the real world anyway. Sure, on the computer, it's slow reused 16-bit legacy code in Windows98, it's a web browser given away for free just to crush Netscape, it's Service Pack 7 for NT, it's that annoying paper clip animation. But you have to think for a second... these are all little nitpicks. No one is going to totally upheave their computer(s) because of these things. Microsoft's OS dominance might outlast Microsoft itself. But MS can't live on that alone. And if you naively think that MS has no chance of continuing to be a dominant company, well then you are probably forgetting that all MS has to do is to keep making progress like they have been for 20 years to keep alive and healthy, never mind being the market leader.
Which is why I'm sure that Gates isn't thinking MS is doomed right now. Knowing Gates, he's doing something radical that he probably knows is in the best interests of the company... kinda like John Carmack stepping in and hiring an outsider to improve the bot code in Quake 3 Arena. I think that it's probably a nice side effect that he drops the negative attention directed toward him, and I think it's good for everyone in the real world that someone like him have as little negative attention possible focused on him. The idea of Gates as a benevolent philanthropist sounds heartwarming, even. It would be a shame if all of this posturing, hype, and hypocrisy in the tech industry ruined that for the rest of us. But that's not an issue until Bill quits everything and starts handing out all the cash. Even if Microsoft florishes or whithers, he's going to win in this situation for himself. But I think he still has MS on his mind, and I think that this might be the start of something real good for Microsoft. And possibly the rest of us.
Could this possibly be Linus envy? (Score:3)
Thats my $.02
Re:Question (Score:5)
When a corporation is organized, by law (and in some cases regulations close to being laws) it must have
For a small company, the board of directors is likely to be the investors themselves (VCs, for example). For a large company, then you see execs from other companies. (somebody here (Cliff Stoll?) said "go to the library" -- uh, there's this new thing, I like to call it the "web"? take a look here [sec.gov]
The board meets quarterly, sometimes more, and hears a pitch from the President, who then leaves while the board discusses and votes. Some decisions require board approval, but the President mostly better do what they say because they can fire her. They decide things like "we need to sell a new chunk of shares to raise money to buy AOL" or "we are not going to pay a dividend this quarter because we wish to use the money to pay down our debt"
I think there are other jobs like "counsel" (a lawyer) and "secretary" (keeps track of the decisions) which I will ignore. Remember, these positions must exist by law.
Now, in large organizations and those where insiders are the shareholders and they maintain a lot of control, it can be convenient for them to switch some of the roles around, consolidating and delegating on the basis of the needs of the business or the particular strengths of the personalities. This is where we get unofficial but descriptive titles like
Re:Bill gets the last laugh - no he won't (Score:3)
No, he won't, see below
The government might split Microsoft into 3 (or so) entities, but it can't strip Bill Gates of what will be his large ownership in all 3 companies.
The conventional wisdom is that the value of the separated entities will rise higher than the value of the original entity, as happened with the Standard Oil breakup. This is just false. What will happen is the bottom will fall out of the stock price - faced with competition from free software, and no longer having the means of forcibly maintaining the existing monopoly, the Baby Bills revenue can go nowhere but down.
Microsoft's current annualized revenue is about $25 billion (being generous); its market capitalization is about $500 billion. That's a 20 times multiple on earnings whereas a mature, stable business with stable revenue would normally have something more like 2x. Microsoft's valuation is based on one thing: expectation of continued exponential earnings growth. That just ain't gonna happen. In fact, the baby Bills are going to have to dance like crazy just to avoid having their earnings decimated by the need to compete with free software and unshackled industry competitors. In short: end of exponentional earnings growth == goodbye 20x multiple on revenue. Hello 2x multiple, and maybe worse. Shareholders aren't so clueless that they can't see that as well as anybody else can; neither are the professional short sellers.
Hooboy, that means Microsoft's stock will fall like a lead balloon.
My, but the MS stockholders (Score:3)
Damage control! Battlestations!! Ensign, prepare a press release...
Boojum
Re:Question (Score:3)
Good one!
:)
actually, to clarify, CTO is abused. Let me explain it this way: note that there is never a CMO, a chief marketing officer. This is because marketing the company's products is so central to the company that it doesn't need explicit representation in the executive suite beyond what the CEO brings. In a like manner, if you are a technology company, the CEO looks after the technology in the products, and the engineers are perfectly capable of selecting their own technology tools.
But think about supermarkets 20 years ago: who was going to champion the expensive installation of scanners? That's a CTO role, created when a CEO is visionary enough to understand that the company needs one.
It's important not to have strict rules about this stuff, none of it is hard and fast. Does Real Networks or AOL need a CTO? I.e., are they media companies or technology companies? There is no answer to that question, just like there is no one way to coach a football team. You make your best predictions, look at the people-assets you have, deploy them and see if you win. Winning says that what you did worked in your situation.
|
https://slashdot.org/story/00/01/13/1550250/gates-steps-down-as-ceo-ballmer-in?sdsrc=rel
|
CC-MAIN-2018-17
|
refinedweb
| 10,135
| 71.65
|
Over the weekend I was able to release the first of many Windows 8 applications (Download and Rate here) into the store that I have been working on. This first one is just a RSS type application for DZone.com, but it just the first
version and the next installment will add more content. If you have ever planned a good, cross platform application before you may or may not understand that picking
the right tools for job are important, and yes even what you're using for the front end language matters sometimes as it did in my case here.
Here is a run down of the application architecture components:
TypeScript was also used in the Node.js project as well
to build out some of the model objects.
I wanted my app to present more. More than just the headline and a link off to another web browser as well as offer the ability to re-use
what I had done for Windows Phone or other mobile devices.
The RSS feeds don't change that much, so I want to create a way to have an API I could reuse for other platforms, but also leverage some caching for high availability,
scale out if necessary and also make the development as fast as possible. I chose to go with Node.js
on Azure to solve this challenge.
Node.js () - Node.js is a packaged compilation of Google's
V8 JavaScript engine, the libUV platform abstraction layer, and a core library, which is itself primarily written in JavaScript.
Node.js was created by Ryan Dahl starting in 2009, and its growth is sponsored by Joyent, his employer.
Node also has Node Package Manager (npm) which I would or most would say is the equivelant to .NET's nuget package library repository for getting community
contributed libraries for accomplishing common tasks such as caching, async and so forth.
I hadn't used node before but I have plenty of JavaScript experience and it was on my list of "want to learn" this year.
I was recently asked why node instead of Web API, other just to say "I used node.js"? Good question, and a legit one too. So here is the answer:
Web API is great, I love it and give a talk on "Why you should be using it" at code camps quite often.
However, I found that using C# to parse HTML to not be as flexible and lacked performance in comparison to using Cheerio (JQuery on node.js)
when outside of the standard RSS or ATOM formatted feeds. JavaScript is really great at parsing strings. Secondly, the ability for me to make routes
in Express was really easy in comparison to ASP.NET. For example, in ASP.NET if I wanted to setup a route to handle a controller / action / id route;
there are changes needed in the routing configuration as well as potential changes in the controller too.
routes.MapHttpRoute(
name: "myNewRouteAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
public class ProductsController : ApiController
{
[HttpGet]
public string Details(int id) { ... }
}
Or:
public class ProductsController : ApiController
{
public string GetDetails(int id) { ... }
}
This sets up the API for the action name to be in the url like.
By contrast in node the same is accomplished with Express.js by doing the following:
app.get('/api/products/details/:id', function(request, response) { ... });
Next, in node I can take advantage of running multiple processes at once for checking for updates while also hosting a REST API for the application. In another
application there are two worker roles in Azure, basically Windows Services, doing this type of work and a single Web role for my Web API. This allows for me to consolidate
the processes into one right now and if the need arises I can break the back end architecture into multiple processes. Flexibility and some simplicity I like here.
Here is an example where 3 processes are running at once doing tasks at different intervals all non-blocking.
var job = function() {
console.log("working at 1 second.");
};
var job2 = function() {
console.log("working at 3 seconds.");
};
setInterval(job, 1000);
setInterval(job2, 3000);
Finally, I chose JavaScript/HTML for the UI portions which I'll cover more reasons why later and it's nice to code JavaScript everywhere.
Now I will mention that C# is my first language of choice when diving into any new project and in fact that is what I initially started with, but I found that
when getting the contents of the RSS feeds, which were non-standard formatted and in order to consume RSS nicely in C# or VB.NET you have a dependency
on the SyndicationFeed assembly which is good and bad. Good if the feed is formatted in the standard RSS or ATOM formats, but bad if the provider has extended it.
Once more the article content was also available in nice print formatted HTML, however when using C# in Windows 8 you must embed a browser control
and the flow is not fluid in landscape mode. At least, not the way it should intuitively should appear. However in JavaScript you can take the HTML from the print
view and set the innerHTML equal to the result and sprinkle some CSS in there and you are set. No fuss. So HTML5 is the choice here.
In making the decision there are some features that I really enjoy about the language and the ability to create Windows applications versus XAML.
There is a clear separation of concerns between what is Presentation, Styling, and Logic that I think I had taken for granted in my web development projects.
When using C# and XAML I really structure my project with MVVM pattern using MVVM Light, use some naming convention on my files and folder structures to ensure that just
by looking at the project I know what does what where.
In a JavaScript Windows 8 project it's clear, just in the tooling and file types. Now make no mistake you can embed all of the CSS and JavaScript right in the HTML
and spaghetti it all up just like anything. However, the templates and the maturity of the tool set and language almost keeps you from doing so.
The HTML5 support in Blend is also great, especially when seeing what CSS styles are applied to what HTML elements, and using the tooling to create a new style
from an existing style. I encourage you to view the video on blendinsider.com.
Some other items I'll quickly mention that I like about JavaScript projects in Windows 8:
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
|
https://www.codeproject.com/Articles/536495/PickingplustheplusRightplusToolsplusforplusYourplu
|
CC-MAIN-2018-26
|
refinedweb
| 1,124
| 69.52
|
Overview
Atlassian SourceTree is a free Git and Mercurial client for Windows.
Atlassian SourceTree is a free Git and Mercurial client for Mac.
LaTeX Plugin for Sublime Text 2
by Marciano Siniscalchi []
Introduction
This plugin provides several features that simplify working with LaTeX files:
- The ST2 build command takes care of compiling your LaTeX source to PDF using
texify(Windows/MikTeX) or
latexmk(OSX/MacTeX or Windows/TeXlive). Then, it parses the log file and lists errors and warning. Finally, it launches (or refreshes) the PDF viewer (SumatraPDF on Windows and Skim on OSX) and jumps to the current cursor position.
- Forward and inverse search with the named PDF previewers is fully supported
- Easy insertion of references and citations (from BibTeX files) via tab completion
- Plugs into the "Goto anything" facility to make jumping to any section or label in your LaTeX file(s)
- Smart command completion for a variety of text and math commands is provided
- Additional snippets and commands are also provided
Requirements and Setup
First, you need to be running a recent dev version of Sublime Text 2 (ST2 henceforth); as of 11/27/2011, I am on Build 2144.
Second, get the LaTeXTools plugin. These days, the easiest way to do so is via Package Control: see here for details on how to set it up (it's very easy). Once you have Package Control up and running, invoke it (via the Command Palette or from Preferences), select the Install Package command, and look for LaTeXTools.
If you prefer a more hands-on approach, you can always clone the git repository, or else just grab this plugin's .zip file from GitHub and extract it to your Packages directory (you can open it easily from ST2, by clicking on Preferences|Browse Packages). Then, (re)launch ST2.
I encourage you to install Package Control anyway, because it's awesome, and it makes it easy to keep your installed packages up-to-date (see the aforelinked page for details).
Third, follow the OS-specific instructions below.
<br>
On OSX, you need to be running the MacTeX distribution (which is pretty much the only one available on the Mac anyway) and the Skim PDF previewer. Just download and install these in the usual way. I have tested MacTeX versions 2010 and 2011, both 32 and 64 bits; these work fine. On the other hand, MacTeX 2008 does not seem to work out of the box (compilation fails), so please upgrade.
To configure inverse search, open the Preferences dialog of the Skim app, select the Sync tab, then:
- uncheck the "Check for file changes" option
- Preset: Custom
- Command:
/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl.
- Arguments: "%file":%line
Note: in case you have created a symlink to Sublime Text somewhere in your path, you can of course use that, too in the Command field. The above will work in any case though, and does not require you to create a symlink or mess with the Terminal in any way!
<br>
On Windows, both MikTeX and TeXlive are supported (although TeXlive support is relatively recent, as of 9/23/2011). Also, you must be running a current (>=1.4) version of the Sumatra PDF previewer. Install these as usual; then, add the SumatraPDF directory to your PATH (this requirement will be removed at some point).
You now need to set up inverse search in Sumatra PDF. However, the GUI for doing this is hidden in Sumatra until you open a PDF file that has actual synchronization information (that is, an associated
.synctex.gz file): see here. If you have one such file, then open it, go to Settings|Options, and enter
"C:\Program Files\Sublime Text 2\sublime_text.exe" "%f:%l" as the inverse-search command line (in the text-entry field at the bottom of the options dialog). If you don't already have a file with sync information, you can easily create one: compile any LaTex file you already have (or create a new one) with
pdflatex -synctex=1 <file.tex>, and then open the resulting PDF file in SumatraPDF.
As an alternative, you can open a command-line console (run
cmd.exe), and issue the following command:
sumatrapdf.exe -inverse-search "\"C:\Program Files\Sublime Text 2\sublime_text.exe\" \"%f:%l\""
(this assumes that sumatraPDF is in your path). I'm sorry this is not straightforward---it's not my fault :-)
Recent versions of MikTeX add themselves to your path automatically, but in case the build system does not work, that's the first thing to check. TeXlive can also add itself to your path.
Finally, you must check the file
LaTeX.sublime-build in the directory in which you unzipped the LaTeXTools plugin to make sure that the configuration reflects your preferred TeX distribution. Open the file and scroll down to the section beginning with the keyword "windows". You will see that there are two blocks of settings for the "cmd" and "path" keywords; by default, the MikTeX one is active, and the TeXlive one is commented out. If you use MikTeX, you don't need to change anything: congratulations, you are done!
If instead you use TeXlive, comment out the lines between the comments
*** BEGIN MikTeX 2009 *** and
*** END MikTeX 2009 ***, and uncomment the lines between the comments
*** BEGIN TeXlive 2011 *** and
*** END TeXlive 2011 ***. Do not uncomment the
BEGIN/
END lines themselves---just the lines between them. Now you are really done!
TeXlive has one main advantage over MikTeX: it supports file names and paths with spaces. Furthermore, it is easier to change the compilation engine from the default,
pdflatex, to e.g.
xelatex: see below for details.
Compiling LaTeX files
The ST2 Build command (
CMD+B on OSX;
Ctrl+B on Windows) takes care of the following:
- It saves the current file
- It invokes the tex build command (
texifyfor MikTeX;
latexmkfor TeXlive and MacTeX).
- It parses the tex log file and lists all errors and warnings in an output panel at the bottom of the ST2 window: click on any error/warning to jump to the corresponding line in the text, or use the ST2-standard Next Error/Previous Error commands.
- It invokes the PDF viewer for your platform and performs a forward search: that is, it displays the PDF page where the text corresponding to the current cursor position is located..
Toggling window focus following a build
By default, after compilation, the focus stays on the ST2 (
Ctrl+Cmd+F on OSX;
Shift+Win+B on Windows).
Forward and Inverse Search
When working in an ST2 view on a TeX document,
CMD+Shift+j (OSX),
Alt+Shift+j (Windows) will display the PDF page where the text corresponding to the current cursor position is located; this is called a "forward search". The focus remains on ST2; this is useful especially if you set up the ST2 window and the PDF viewer window side by side.
If you are viewing a PDF file, then hitting
CMD+Shift+Click in Skim (OSX), or double-clicking in Sumatra (Windows) will bring you to the location in the source tex file corresponding to the PDF text you clicked on. This is called "inverse search".
References and Citations
Type
ref_, then
Ctrl+Space to get a drop-down list of all labels in the current file. You can filter the list: e.g., if you type
ref_a, then
Ctrl+Space, you get only labels beginning with the letter "a". Find the label you want and click on it, or hit Return. The correct reference command will be generated: e.g.,
\ref{my-label}.
Using
refp_ instead of
ref_ will surround the reference with parentheses. You can also use
eqref to generate
\eqref{my-equation}.
Citations from bibtex files are also supported in a similar way. Use
cite_, as well as
citet_,
citeyear_ etc.; again, you can filter the keys, as in e.g.
cite_a. If you want e.g.
\cite*{...}, use
citeX_; that is, use X instead of an asterisk.
Jumping to sections and labels
The LaTeXtools plugin integrates with the awesome ST2 "Goto Anything" facility. Hit
CMD+R (OSX) /
Ctrl+R (Windows) to get a list of all section headings, and all labels. You can filter by typing a few initial letters. Note that section headings are preceded by the letter "S", and labels by "L"; so, if you only want section headings, type "S" when the drop-down list appears.
Selecting any entry in the list will take you to the corresponding place in the text.
LaTeX commands and environments
To insert a LaTeX command such as
\color{} or similar, type the command without backslash (i.e.
color), then hit
CMD+Shift+] (OSX) /
Ctrl+Shift+] (Windows). This will replace e.g.
color with
\color{} and place the cursor between the braces. Type the argument of the command, then hit Tab to exit the braces.
Similarly, typing
CMD+Shift+[ (OSX) /
Ctrl+Shift+[ (Windows) gives you an environment: e.g.
test becomes
\begin{test} \end{test}
and the cursor is placed inside the environment thus created. Again, Tab exits the environment.
Note that all these commands are undoable: thus, if e.g. you accidentally hit
CMD+Shift+[ but you really meant
CMD+Shift+], a quick
CMD+Z, followed by
CMD+Shift+], will fix things.
Wrapping existing text in commands and environments
The tab-triggered functionality just described is mostly useful if you are creating a command or environment from scratch. However, you sometimes have existing text, and just want to apply some formatting to it via a LaTeX command or environment, such as
\emph or
\begin{theorem}...\end{theorem}.
LaTeXTools' wrapping facility helps you in just these circumstances. All commands below are activated via a key binding, and require some text to be selected first.
Shift+Alt+w,cwraps the selected text in a LaTeX command structure. If the currently selected text is
blah, you get
\cmd{blah}, and the letters
cmdare highlighted. Replace them with whatever you want, then hit Tab: the cursor will move to the end of the command.
Shift+Alt+w,egives you
\emph{blah}, and the cursor moves to the end of the command.
Shift+Alt+w,bgives you
\textbf{blah}
Shift+Alt+w,ugives you
\underline{blah}
Shift+Alt+w,nwraps the selected text in a LaTeX environment structure. You get
\begin{env},
blah,
\end{env}on three separate lines, with
envselected. Change
envto whatever environment you want, then hit Tab to move to the end of the environment.
On OSX, replace
Alt with
Option: e.g. to emphasize, use
Shift+Option+w,e.
Command completion, snippets, etc.
By default, ST2 provides a number of snippets for LaTeX editing; the LaTeXTools plugin adds a few more. You can see what they are, and experiment, by selecting Tools|Snippets|LaTeX and Tools|Snippets|LaTeXTools from the menu.
In addition, the LaTeXTools plugin provides useful completions for both regular and math text; check out files
LaTeX.sublime-completions and
LaTeX math.sublime-completions in the LaTeXTools directory for details. Some of these are semi-intelligent: i.e.
bf expands to
\textbf{} if you are typing text, and to
\mathbf{} if you are in math mode. Others allow you to cycle among different completions: e.g.
f in math mode expands to
\phi first, but if you hit Tab again you get
\varphi; if you hit Tab a third time, you get back
\phi.
Using different TeX engines
In short: on OS X, or on Windows if you use TeXLive, changing the TeX engine used to build your files is very easy. Open the file
LaTeX.sublime-build and look for the following text (correct as of 11/8/11):
"cmd": ["latexmk", "-e", "\\$pdflatex = 'pdflatex %O -synctex=1 %S'", "-silent", "-f", "-pdf"],
(note the final comma). On Mac OS X, the relevant entry is in the
osx section; on Windows, it is in the
windows section, between
*** BEGIN TeXlive 2011 *** and
*** END TeXlive 2011 ***, and (per the above instructions) it should be uncommented if you are using TeXlive.
The trick is to change the second line: e.g.
"-e", "\\$pdflatex = 'pdflatex %O -synctex=1 %S'",
becomes
"-e", "\\$pdflatex = 'xelatex %O -synctex=1 %S'",
I have very little experience with "exotic" TeX engines. You probably know more than I do. Anyway, the key is to customize the
latexmk parameters so they do what you want it to. Please, do not ask for assistance doing so: most likely I won't be able to help you. I just want to point out where to change the build variables.
If you use MikTeX, you are out of luck. The
texify command can read an environment variable to decide which engine to use, but setting this variable requires Windows- and MikTeX-specific additions to the build command. Alternatively, you can try to use
latexmk with MikTeX, and configure the build command as above. Again, I have not tried this, and you probably know more than I do on the subject. Sorry, and thanks for your understanding!
Troubleshooting
Many LaTeXTools problems are path-related. The
LaTeX.sublime-build file attempts to set up default path locations for MikTeX, TeXlive and MacTeX, but these are not guaranteed to cover all possibilities. Please let me know if you have any difficulties.
On Mac OS X, just having your
$PATH set up correctly in a shell (i.e., in Terminal) does not guarantee that things will work when you invoke commands from ST2. If something seems to work when you invoke
pdflatex or
latexmk from the Terminal, but building from within ST2 fails, you most likely have a path configuration issue. One way to test this is to launch ST2 from the Terminal, typing
/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl
(and then Return) at the prompt. If things do work when you run ST2 this way, but they fail if you launch ST2 from the Dock or the Finder, then there is a path problem. From the Terminal, type
echo $PATH
and take note of what you get. Then, run ST2 from the Dock or Finder, open the console (with
Ctrl+ `) and type
import os; os.environ['PATH']
and again take note of what you see in the output panel (right above the line where you typed the above command). Finally, look at the
path keyword in the
osx section of the
LaTeX.sublime-build file in the LaTeXTools package directory. For things to work, every directory that you see listed from the Terminal must be either in the list displayed when you type the
import os... command in the ST2 console, or else it must be explicitly specified in
LaTeX.sublime-build. If this is not the case, add the relevant paths in
LaTeX.sublime-build and please let me know, so I can decide whether to add the path specification to the default build file. Thanks!
On Windows, sometimes a build seems to succeed, but the PDF file is not updated. This is most often the case if there is a stale pdflatex process running; a symptom is the appearence of a file with extension
.synctex.gz(busy). If so, launch the Task Manager and end the
pdflatex.exe process; if you see a
perl.exe process, end that, too. This kind of behavior is probably a bug: LaTeXTools should be able to see that something went wrong in the earlier compilation. So, please let me know, and provide me with as much detail as you can (ideally, with a test case). Thanks!
|
https://bitbucket.org/ses_schulz/latextools/overview
|
CC-MAIN-2016-44
|
refinedweb
| 2,587
| 63.29
|
Exception handling with try & catch method
java program only with output.
Try and catch in Exception Handling.
Try and catch in Exception Handling. How can we use try and catch block in exception handling?
Here is an example of Exception handling.... Then to perform exception handling, we have used try and catch block where we have - JSP-Servlet
" and then try the JSP.
I hope that this will help you in solving your problem...Exception handling I have added DSN 'online_exam' in Administrative... the following exception
type Exception report
description The server
Exception handling mechanism
keywords you can handle exception in java they are as follows:
try
catch... an exception, but try block must
followed by catch or finally.
Syntax : ....
Example : Code without using exception handling
mechanism
public class
exception handling
of exception handling mechanism.
Java Exception
Exception... an exception whenever a calling method encounters an error providing... a separate block of codes. This is done with the help of try-catch blocks.
4
Handling exception in jsp - JSP-Servlet
Handling exception in jsp Hai..... Could you please tell me "How to handle Servlet Exception object in jsp pages?" Hi friend,
For solving the problem visit to :
Exception Handling with and without using try catch block
Description:
Without using try catch block. If you do not want to
explicitly make try catch block then to you program write throws Exception to
your method where Exception handling is required
Code:
class
Exception Handling - Java Beginners
method instead of try and catch exception handler. For instance,
public static...Exception Handling hi,can u pls make me understand d clear cut difference between throw n throws keyword...
n how can we make our own exception..i
Struts Exception Handling
Struts Exception Handling Hi
I want to display an user defined error message in my JSP by setting it in Struts 1.x custom handler class when some exception occurs.
For example, I have 2 classes, Category and Product
|
http://www.roseindia.net/tutorialhelp/allcomments/1920
|
CC-MAIN-2014-49
|
refinedweb
| 325
| 58.58
|
A function is a block of code that performs a specific task.
C allows you to define functions according to your need. These functions are known as user-defined functions. For example:
Suppose, you need to create a circle and color it depending upon the radius and color. You can create two functions to solve this problem:
createCircle()function
color()function
Example: User-defined function
Here is an example to add two integers. To perform this task, we have created an user-defined
addNumbers().
#include <stdio.h> int addNumbers(int a, int b); // function prototype int main() { int n1,n2,sum; printf("Enters two numbers: "); scanf("%d %d",&n1,&n2); sum = addNumbers(n1, n2); // function call printf("sum = %d",sum); return 0; } int addNumbers(int a, int b) // function definition { int result; result = a+b; return result; // return statement }
Function prototype
A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used in the program.
Syntax of function prototype
returnType functionName(type1 argument1, type2 argument2, ...);
In the above example,
int addNumbers(int a, int b); is the function prototype which provides the following information to the compiler:
- name of the function is
addNumbers()
- return type of the function is
int
- two arguments of type
intare passed to the function
The function prototype is not needed if the user-defined function is defined before the
main() function.
Calling a function
Control of the program is transferred to the user-defined function by calling it.
Syntax of function call
functionName(argument1, argument2, ...);
In the above example, the function call is made using
addNumbers(n1, n2); statement inside the
main() function.
Function definition
Function definition contains the block of code to perform a specific task. In our example, adding two numbers and returning it.
Syntax of function definition
returnType functionName(type1 argument1, type2 argument2, ...) { //body of the function }
When a function is called, the control of the program is transferred to the function definition. And, the compiler starts executing the codes inside the body of a function.
Passing arguments to a function
In programming, argument refers to the variable passed to the function. In the above example, two variables n1 and n2 are passed during the function call.
The parameters a and b accepts the passed arguments in the function definition. These arguments are called formal parameters of the function.
The type of arguments passed to a function and the formal parameters must match, otherwise, the compiler will throw an error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be of float type.
A function can also be called without passing an argument.
Return Statement
The return statement terminates the execution of a function and returns a value to the calling function. The program control is transferred to the calling function after the return statement.
In the above example, the value of the result variable is returned to the main function. The sum variable in the
main() function is assigned this value.
Syntax of return statement
return (expression);
For example,
return a; return (a+b);
The type of value returned from the function and the return type specified in the function prototype and function definition must match.
Visit this page to learn more on passing arguments and returning value from a function.
|
https://cdn.programiz.com/c-programming/c-user-defined-functions
|
CC-MAIN-2020-40
|
refinedweb
| 583
| 54.42
|
] 2 Writing to a file
The following program writes the first 100 squares to a file:
This will override the old contents of the file, or create a new file if the file doesn't exist yet. If you want to append to a file, you can use
-- generate a list of squares with length 'num' in string-format. numbers num = unlines $ take num $ map (show . \x -> x*x) [1..] main = do writeFile "test.txt" (numbers 100) putStrLn "successfully written"
.
appendFile
[edit] 3 Creating a temporary file
TODO: abstract via 'withTempFile', handle exception
import System.IO import System.Directory main = do tmpDir <- getTemporaryDirectory (tmpFile, h) <- openTempFile tmpDir "foo" hPutStr h "Hello world" hClose h removeFile tmpFile
|
https://wiki.haskell.org/index.php?title=Cookbook/Files&diff=55964&oldid=28011
|
CC-MAIN-2015-32
|
refinedweb
| 116
| 59.09
|
Programming With XML Using Visual Basic 9
Bill Burrows
myVBProf.com
August 2007
Applies to:
XML
Microsoft Visual Basic 9.0
Microsoft Visual Studio 2008
Summary: In this paper, using a realistic application, we will look at the new features and capabilities that are available in Microsoft Visual Basic 9.0 that relate to programming with XML. (18 printed pages)
Contents
Introduction
Application Overview
LINQ to XML in Visual Basic 9.0: Key Features
Getting Home Sales Data from Windows Live Expo
Office_Open_XML_File_Format
Using XML Literals and Embedded Expressions to Create the New Worksheet
Modifying the Office Excel Workbook Container
Putting It All Together
Productivity Enhancements Within Visual Basic 9.0 and Visual Studio 2008
Conclusion
Introduction
Programming with XML has traditionally been done using the document object model (DOM) API, XSLT, and XPath. Using this approach, the developer not only must understand XML, but also must become proficient in these additional technologies in order to be productive.
Microsoft Microsoft Visual Studio 2008 and provides a distinctive approach to programming with XML. In addition, enhanced user experience and debugging support within Visual Studio helps improve a developer's productivity while working with XML.
In this paper, using a realistic application, we will look at the new features and capabilities available in Visual Basic 9.0 that relate to programming with XML.
Application Overview
We will be looking at an application where information on homes for sale is extracted from an RSS feed and placed into a Microsoft Office Excel workbook. This application runs on a server, builds the Office Excel workbook, and then makes it available for downloading to the client. Online listings are fine, but sometimes you want to just download all that into Office Excel, so that you can do some more processing of your own offlinesuch as which homes you've visited, tracking attributes that interest you, or performing such analyses as computing the average cost per square foot.
In this application, we will be using a LINQ to XML query to extract XML from Microsoft Windows Live Expo (expo.live.com) using the Windows Live Expo API and the Expo Web service that exposes an HTTP/GET request interface with XML response. (Click here for information on getting started with Windows Live API.) The user will provide a ZIP code as the basis of what home information to extract. They will also provide a distance (in miles) to define the area to be searched for houses for sale. After this information is extracted from the Expo Web service, it will be used to create a new Office Excel workbook on the server by creating an Office Open XML file. This process will demonstrate the use of embedded expressions to insert the data into the workbook. Finally, the user will be given the option to download the workbook for use on the client computer.
LINQ to XML in Visual Basic 9.0: Key Features
XML literals. In Visual Basic 9.0, one can treat XML as a literal value. The developer experience is enhanced when working with XML literals with autocompletion and outlining. You can create a variable and associate it to an XML literal by either typing the literal or, more likely, pasting some XML directly into the code editor. This feature is unique to Visual Basic 9.0. In the sample application, we will create an XML literal by pasting Office Open XML that represents an Office Excel worksheet.
XML literals can also contain embedded expressions. An embedded expression is evaluated at run time and provides the means to modify the XML dynamically, based on values obtained while the program is executing. In our sample application, we will be using embedded expressions to insert values taken from an RSS feed, and inserting them into the XML that represents an Office Excel worksheet.
Figure 1 shows an XML literal and embedded expressions.
Figure 1. XML literal with an LINQ to XML query and embedded expressions
XML axis properties. XML axis properties, also known simply as XML properties, are used to reference and identify child elements, attributes, and descendent elements. These provide a shorter, more readable syntax than using equivalent LINQ to XML methods. Table 1 provides a summary of XML properties. Intellisense is provided for axis properties when an appropriate XML schema is added to the project. Details on this feature will be explored in the last section of this article.
Table 1. XML axis properties
XML namespaces. To define a namespace that can be used in XML literals or a LINQ to XML query or embedded expression, one uses the Imports statement. In our application, we will have to define a specific namespace that relates to the RSS feed that is supplied by the Windows Live Expo API. To define this namespace within our code, we will use the following Imports statement:
Imports <xmlns:
This statement creates an identifier named expo that can be used to qualify an element within queries and literals. The following line of code returns all the category child elements in the expo namespace:
Item.<expo:category>
To define a default namespace, one also uses the Imports statement, but no identifier is provided. An example definition of a default namespace is the follow:
Imports <
By default, the empty namespace is the "default" namespace. If you define another namespace to be the default and you need the use of the empty namespace, you can create a prefix for the empty namespace as in the following example.
Imports <xmlns:
Type inference. In previous versions of Visual Basic, dropping the As clause from a variable declaration resulted in the variable being typed as the Object type, where late binding was used to deal with the contents of the variable. In Visual Basic 9.0, the type of local variables is "inferred" by the type of the initialize expression on the right-hand side. For instance, in the following statement:
Dim x = 1
the x variable would be inferred as Integernot Object, as in earlier versions of Visual Basic. If you look at the code in Figure 1, you will see that type inference is being used for the sheetTemplate variable. Because the variable is being assigned an XML literal, its type is implied as XElement, because that is the type of the XML literal on the right-hand side. Visual Basic 9.0 supports a new option named Option Infer. This option is used to turn type inference on or off, and is on by default. It is important to note that type inference applies only to local variables. Type inference does not apply to class-level and module-level variables. This means that in the class definition that follows, the status variable will be an Object type, not a String type.
Public Class DemoClass
Dim status = "Default"
End Class
Getting Home Sales Data from Windows Live Expo
We are using the XML over HTTP interface named to get the data in the form of an RSS feed. The syntax of this request is the following:
When making the call to the service, the user may provide a number of parameters. For this application, the parameters that will be passed to the service are the following:
Using this Web service, we obtain the RSS feed and store it as an XElement type. The code to do this is straightforward and is shown in Figure 2. Notice that in defining the feed variable, we are using "type inference," as described earlier.
Private Function GetSheetXML() As XDocument
' get the "xml over http" rss feed url
Dim url As String = BuildURL()
' get the xml feed - note that type inference is used here
Dim feed = XElement.Load(url)
Figure 2. Getting the RSS feed
The application uses a helper function named BuildURL to define the service call and its parameters. This function is shown in Figure 3. Note that there is little error checking in this application. This is not because error checking is not needed, but instead because the error checking could make it harder to focus on the technologies that are the subject of this article. Also, be aware that MyAppID is a numerical identifier that is available to developers from the Windows Live Expo API site.
Figure 3. Building the Web service call URL (Click on the picture for a larger image)
The XML that is returned from the Web service is in the form of an RSS feed. A sample of this XML is shown in Figure 4.
Figure 4. The RSS feed from expo.live.com
An important attribute in the <rss> element is the namespace definition:
xmlns:classifieds=""
We will have to define this namespace in our code in order to identify correctly elements in the document that are qualified by the namespace (such as the <classifieds:totalListings> element in Figure 4).
The key elements for our application in the RSS feed are the <item> elements. Figure 4 shows one <item> element; but, in reality, there are many returned from the service. A closer look at an <item> element reveals the elements and attributes with which we will be working. Figure 5 shows the XML.
Figure 5. Details of the <item> element (Click on the picture for a larger image)
We are interested in data about the homes for sale including the price ; the ZIP code (postcode) ; and details on the home, including number of bedrooms and bathrooms, the year the home was built, and the size of the home . Note that the element named <classifieds:LOT_SIZE> is actually storing the square footage of the home.
You can see how we will be using these elements in the worksheet that is shown in Figure 6.
Figure 6. Spreadsheet created from the RSS feed (Click on the picture for a larger image)
The other thing that is noted in the <item> element in Figure 5 is the classifieds:transactionType attribute .
We will now look at the code that will process the XML RSS feed data. The RSS feed includes homes both for sale and for rent, so the first thing that we must do is to get only elements that are for sale. To do this, we must query the RSS XElement holding the feed; therefore, we use a LINQ to XML query, as seen in Figure 7 (which is the continuation of the GetSheetXML() function that is shown in Figure 2). Again, note the use of type inference in the definition of itemList.
Figure 7. LINQ to XML query to get selected <item> elements (Click on the picture for a larger image)
In addition to this code, namespaces must be defined. This is done at the beginning of the code using Imports statements, as shown in Figure 8. We will discuss these namespaces as they are used in the code.
' define an expo.live namespace
Imports <xmlns:
' define an empty namespace
Imports <xmlns:
' define the default namespace
Imports <
Figure 8. Defining the namespace
Let's look at the LINQ to XML query in Figure 7 in some detail. The From clause identifies an iterator named itemElement that refers to the element that is in scope for each iteration. The expression feed...<empty_ns:item> identifies the IEnumerable(Of XElement) "feed" reference and uses the "descendants axis" (...) to get all the <item> elements within the feed reference, no matter how deeply they occur. The XML axis property must be qualified with the empty namespace. Otherwise, the default namespace—in this case,—would be applied to the axis property. The Where clause filters these <item> elements to only those that have "For Sale" in the <category> item's transactionType attribute. Note the use of the namespace identifier (expo) and attribute axis (@) in the query syntax.
Because our ultimate objective is to place data from each "For Sale" item into a separate row of our worksheet, we need a way to identify easily the row in the worksheet in which each selected item will be stored. In this application, we do this by converting the itemList—which is an IEnumerable—into a List(Of T), so that we can later use the list's IndexOf() method to get each <item> index and use it to determine a row number in the worksheet.
Office Open XML File Format
Now that we have our XML extracted from the Live Expo site, we must get it into an Office Excel 2007 worksheet. To do this, we will need to understand the Office Open XML File Format. The specification for this format is quite extensive; we will touch only the surface, as far as our understanding is concerned. In addition, an excellent reference that is specific to the Office Open Excel File format is available on the Web. (Please see Standard ECMA-376 Office Open XML File Formats.) Note that when we talk about Office Excel in this article, we are referring to Office Excel 2007.
An Office Excel file (.xlsx) is a container file or package that is actually in an industry-standard ZIP file format. Each file comprises a collection of parts, and this collection defines the document. For an Office Excel file, these various parts and their relationships are shown in Figure 9.
Figure 9. The various parts and their relationships in an Office Excel document (Click on the picture for a larger image)
You can see these parts if you open an Office Excel document using a ZIP application. Figure 10 shows such a view. Notice the paths that are shown in the figure; they give you a sense of the file and directory structure within the document. To work with an Office Excel document as a ZIP archive, just change the file extension from ".xlsx" to ".zip".
Figure 10. Files (parts) stored within the ZIP container of an XML document (Click on the picture for a larger image)
In our application, we will store an existing Office Excel document file (named baseWorkbook.xlsx) on the server. We will then build a new worksheet (such as sheet1.xml, shown in Figure 10) using the XML <item> elements we extracted from the RSS feed. We will then delete the existing worksheet from the Office Excel document and then add our new one. Finally, we will offer the user the opportunity to download the newly modified workbook with the newly added worksheet.
We are ready to write the code to create the new worksheet using the <item> elements from the RSS feed. It must be restated that we have just touched the surface of Office Open XML Format. In fact, there are things that we might want to add to our workbook that might cause "issues" when we open the workbook. These issues deal with the many parts of the document and their relationships. If you add XML that does not include all the relationships, an informational dialog box might be displayed indicating that there are issues that must be resolved. You are given the option to have Office Excel try to fix these issueswhich really means that it attempts to resolve the references, update shared-value tables, and so on.
Using XML Literals and Embedded Expressions to Create the New Worksheet
The code that we will see next is a continuation of the GetSheetXML() function that was shown earlier. We will be working with a large XML literal that was created initially by copying and pasting the complete XML definition of the worksheet from an existing Office Excel workbook. This XML literal is then modified by placing embedded expressions at the appropriate locations.
We begin by looking at a few lines of code that define some parameters for modifying the XML literal that represents the new worksheet. This code (again, a continuation of the GetSheetXML() function) is shown in Figure 11.
Figure 11. Continuation of the GetSheetXML() function that creates the new worksheet (Click on the picture for a larger image)
The code in Figure 11 determines what the last row will be by first determining the number of <item> elements in the RSS feed. Because there will be one new row in the worksheet for each <item> element, we can determine the last row (because the first rowthe headingsare in row 2, we calculate the last row by adding 2 to the number of <item> elements). The last line of code in Figure 11 sets the value of a String variable that defines the cell range for our worksheet.
Now, we start working with the XML literal. Figure 12 shows the first few lines of the literal. We started by writing the code:
Dim sheetTemplate = _
and then just pasting in the XML definition from the existing Office Excel worksheet. This is one of the great features in Visual Basic 9.0: Instead of having to create a document using the DOM API, we just take the XML that we want to manipulate and paste it into our code as an XML literal. Then, we replace the original "ref" attribute value from:
ref="B2:H3"
to
ref=<%= cellRange %>
This embedded expression uses the previously defined cellRange variable to take into account the new rows of data to be added.
' finally we go into the actual XML literal and insert the new range
' and the appropriate data from the RSS feed
Dim sheetTemplate = _
<?xml version="1.0"?>
<worksheet>
<dimension ref=<%= cellRange %>/>
Figure 12. First part of the XML literal
Also note that the object reference named "sheetTemplate"—used to store the XML literalis defined using type inference. In this case, the type will become an XDocument, as opposed to an XElement. The difference between the two is that XDocuments may contain processing instructions (PI) and comments before the root element definition, while XElement types cannot. The following special XML declaration:
<?xml version="1.0"?>
in our document will be seen by the type-inference engine and, therefore, will type "sheetTemplate" as an XDocument.
The final step that we must perform is to define the rows using values from each <item> element in the RSS feed. Figure 13 shows this code. (There is additional XML in the literal between the <dimension> element in Figure 12 and the start of the embedded expression in Figure 13. See the code download for this article to view this XML.) There is a lot going on in these lines of code. First, note that we have a LINQ to XML query that queries across the List(Of XElement) RSS feed named rssItems:
<%= From item In rssItems Let rowNum = rssItems.IndexOf(item) + startRow _
As mentioned earlier, we must identify the row number for the row that we are inserting; we use the IndexOf method of the List to compute this. This computed value is stored in a local variable named rowNum that will be computed for each iteration of the query.
For each item in the collection, we select a number of values and use them in embedded expressions. These embedded expressions are fairly straightforward.
Figure 13. Creating new rows in the worksheet using the RRS feed data (Click on the picture for a larger image)
We are accessing specific data items from the feed. For example, in column D of each row, we are adding the value of the YEAR_BUILT element (item.<expo:details>.<expo:YEAR_BUILT>.Value). Note that we have used the namespace that we defined in Figure 8. As you will see in a later section, XML Intellisense is a big help in entering element references. We can easily create the formula found in column H by using an embedded expression that includes string constants, row values, and string concatenation. Something that Visual Basic programmers must remember is that XML is case sensitive; this means that XML properties, like attribute names, are case sensitive.
The issue of namespaces and how they are applied within the XML literals and XML axis properties can be confusing, and it is helpful to review what we have done here. Figure 14 summarizes what is happening by showing the namespace definitions and Tool Tip–enhanced segments of code. In this figure, we see <expo:category>, which resolves to fully qualified name:
{}category
This resolution is the result of applying the <expo> prefix. Similarly, we see <row>, which resolves to fully qualified name:
{}row
This resolution is a result of the fact that the default namespace is being applied. Finally, <empty_ns:item> resolves to item, because the empty namespace is applied (the empty_ns prefix).
Figure 14. Namespaces applied to code (Click on the picture for a larger image)
Finally note the entire new XDocument contents are returned by the function. In the next step, we will take this XDocument and place it into our workbook document container.
Modifying the Office Excel Workbook Container
As mentioned previously, the Office Excel workbook is a container stored in the standard ZIP archive format. Microsoft introduced a new API, known as the Packaging API, with the introduction of Microsoft .NET 3.0. This API, which is found in WindowsBase.dll, must be added as a reference to the application in order to get access to the packaging API.
For this application, a small class named SpreadSheet has been created to manage the workbook. It includes a constructor that opens the package and establishes a reference to the workbook part (sheet1.xml) that will be replaced with the new worksheet that is stored in the XDocument object. The original worksheet must be removed, so there is a RemoveOldSheet method. The new worksheet must then be added, so an AddNewSheet method is included for the class.
The complete code for this SpreadSheet class is available in the code download for this article.
Putting It All Together
With the background of the code presented previously, it is time to look at the main Web application and code that orchestrates the fetching of the RSS feed, converts it to a new Office Open XML file, and then replaces an existing worksheet with the newly created one.
Figure 15 shows the user interface for the application prototype. The user supplies a ZIP code as the center of the home search and a distance in miles around that ZIP code. A simple click event is defined for the Get Spreadsheet button.
Figure 15. The Web interface for the prototype application
When the click event finishes executing, a hyperlink pointing to the newly modified Office Excel workbook is made visible as shown in Figure 16. This allows the user to download the workbook to the client machine.
Figure 16. The Web interface with the worksheet download link active
The code for the Web application and the first part of the click event is shown in Figure 17. Note the Imports of the necessary namespaces. Regarding the system-derived namespaces, this application was built using Beta 2 of Visual Studio 2008; as later betas and release candidates are released, there might be a need to use a different set of Imports. Also note the Import statements that define the XML namespaces used within the Expo Live RSS feed, an empty namespace, and the default namespace used within the Office Open Excel worksheet XML document.
Figure 17. The Imports and first few lines of the Web application (Click on the picture for a larger image)
Note As of Beta 2, the Web application template does not include the reference to System.Xml.Linq.dll. In Beta 2, this reference is located at C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5.
We looked at the GetSheetXML() function in Figures 2, 7, and 11 through 13. This function got the RSS feed from Expo Live by using the user-supplied parameters; then, it took the RSS feed, and used an XML literal and embedded expressions to build the new worksheet.
The final steps involve using the SpreadSheet class and the Packaging API to replace an existing worksheet with our new one. Figure 18 shows this code as the continuation of the click event.
Figure 18. Continuation of the click-event code (Click on the picture for a larger image)
Note that the first part of the code works with getting some configuration settings from the web.config file. These settings define the location of the template workbook as well as the relative location of the workbook part that will be replaced (sheet1.xml). The relevant section of web.config is shown in Figure 19.
Figure 19. Application settings from the web.config file (Click on the picture for a larger image)
The new worksheet first must be saved, because the Packaging API can add only a part from a file. Following this, a new SpreadSheet object is created and used to remove the old worksheet part and replace it with the new worksheet part. Finally, the hyperlink that points to the updated workbook is made visible.
This concludes the in-depth description of our sample application. It shows how Visual Basic 9.0, with its LINQ to XML and embedded XML features, provides an extremely powerful way to work with XML. Note in particular how important the use of XML literals and XML axis properties—which are unique to Visual Basic 9.0—were to the application solution. Next, we look at some of the productivity features in Visual Basic 9.0 that make it much easier for the developer, working within Visual Studio, to use the new language features.
Productivity Enhancements Within Visual Basic 9.0 and Visual Studio 2008
When dealing with XML literals, there are two important features that are available within Visual Basic 9.0. The first is autocompletion. With autocompletion, when an opening element is entered into the code, the closing element is entered automatically. In addition, if you change the spelling of the opening tag, the system will automatically change the spelling of the matching closing tag. The second is outlining where the literal can easily be collapsed or expanded based on parent/child relationships.
In addition to outlining and autocompletion, XML literals are checked for syntax. Figure 20 shows an XML literal that contains two errors. In the top image, an attribute value is shown without being enclosed in quotes. When that error is corrected, the lack of the closing ">" character in the </phone> element is highlighted.
Figure 20. Syntax error in an XML literal (Click on the picture for a larger image)
Arguably, however, the most significant productivity enhancement in Visual Basic 9.0 deals with Intellisense and XML axis properties. If a schema is available within the project for the XML, the information from the schema is used within the context of Intellisense to provide the developer with a set of choices while entering LINQ queries and embedded expressions.
For our application, we do not have a schema available, so we must create one. Fortunately, Visual Studio provides a tool to do this, if we have the XML available. To get the XML, open the URL that was created in the application (see Figure 3) in Visual Studio by using the File menu and selecting Open. Visual Studio will open the XML editor with the query result (you might want to use the Save As command to shorten the file name). You can now create the schema using the XML menu item and selecting Create Schema. For the RSS feed in our application, three schema files will be created. Be sure to save these schemas and add them to the project. You can see these schema files in the Solution Explorer that is shown in Figure 21.
Figure 21. Solution Explorer highlighting the new schema files
You can then see the namespaces defined in the RSS feed schema in the Imports statement. Figure 22 shows the Intellisense (which is called schema discovery).
Figure 22. Schema-enhanced Intellisense on Imports
Now that we have imported the namespace that is backed up with the schema information, we can see the enhanced Intellisense when we enter code. The first code that we will enter is the LINQ query shown in Figure 7. Figure 23 shows the Intellisense list that is displayed as possible values for the descendant's axis of the feed list variable.
Figure 23. Intellisense applied within a LINQ query
Note that there are many choices for descendant attributes and the Intellisense engine cannot identify which ones are known with certainty. Items in which the XSD type is not known with certainty are placed in what is called the "candidate" list. To indicate that an item is in this candidate list, a question-mark glyph is added to the item. Figure 24 shows this glyph.
Figure 24. Glyph to indicate item is in the "candidate" list
Figure 25 shows the Intellisense list within an embedded expression. Intellisense matches not only on the prefix, but also on the local names of the element or attribute. Looking at Figure 25, you can start typing "cou...", and the match on "expo:country" will be found.
Figure 25. Intellisense applied within an embedded expression
The choices available as descendants of the <location> element are well defined in the schema and thus are added to what is called the "matched" list by Intellisense. The fact that a choice is a member of the matched list is indicated by the use of the green check-mark glyph as shown in Figure 26.
Figure 26. Glyph to indicate item is in the "matched" list
In addition to the great Intellisense and compile-time support for XML, Visual Basic 9.0 also supports enhanced information while debugging. Figure 27 shows the Locals window while the application is in Break mode. The breakpoint has been set right after the following statement:
Dim rssItems As List(Of XElement) = itemList.ToList
has been executed. This statement causes the LINQ query to be executed. In Figure 27, we are looking at the in-memory results of the query for the itemList variable. You can see how the contents of this variable can be expanded to see the XML elements that are returned from the query. The value column shows the XML content of the variable which makes it extremely easy to examine the results.
Figure 27. Run-time information available for debugging (Click on the picture for a larger image)
Conclusion
In this article, we have seen a number of new features that are available in Visual Basic 9.0 and Visual Studio 2008. The processing of XML has been improved significantly with the addition of LINQ to XML, XML literals, XML axis properties, and improved Intellisense and debugging support. With these new features, Visual Basic 9.0 has raised the bar, as far as processing XML is concerned. The realistic prototype application demonstrates the value of these new features, in addition to a brief look at the new Office Open XML format.
|
https://msdn.microsoft.com/en-us/library/bb687701.aspx
|
CC-MAIN-2018-30
|
refinedweb
| 5,121
| 60.95
|
SPIM and DS1302 | Cypress Semiconductor
SPIM and DS1302
Hi Everyone,
I am new to the world of PSoC and working on my second project.
I am trying to 'talk' with a DS1302 (a pointless exercise I know as the PSoC has a RTC) as a way to learn SPI and the three wire interface, and this was the only device I had to hand.
I have tried numerous ways to do this and had no sucess with any. Can somebody with more experience than I have please tell me if it is a fault in my code or some quirk of this particular chip. One thing I did notice on the data sheet was that during a read cycle the address is clocked on the rising edge but the data packet is clocked on the falling edge - is that normal?
The code is as follows:
#include <project.h>
int main()
{
//Declare a few variables
int8 myData = 0u;
//Enable Interupts
CyGlobalIntEnable;
//Start the SPI Module
SPIM_1_Start();
//Clear all buffers just for good luck!
SPIM_1_ClearFIFO();
/* --------------------------------------------- */
// Let's try to send some data to the slave device.
/* --------------------------------------------- */
//Enable the manual slave select line
//This needs to go HIGH to enable the chip
Control_Reg_1_Write(1);
//Enable Transmit from Master
SPIM_1_TxEnable();
//Clear the write protect bit by setting register 0x8E to be zero
SPIM_1_WriteTxData(0x8E);
SPIM_1_WriteTxData(0x00);
//Set the first RAM address to contain 0xAA
SPIM_1_WriteTxData(0xC0);
SPIM_1_WriteTxData(0xAA);
//Wait for transmission to complete and then go back to receive mode
while(!(SPIM_1_ReadTxStatus() & SPIM_1_STS_SPI_DONE));
SPIM_1_TxDisable();
//Disable the manual slave select line
Control_Reg_1_Write(0);
//Have a short delay and than start again
CyDelay(100);
/* --------------------------------------------- */
// Now read the data back from the slave device.
/* --------------------------------------------- */
//Clear all the buffers
SPIM_1_ClearFIFO();
//Enable the manual slave select line
//This needs to go HIGH to enable the chip
Control_Reg_1_Write(1);
//Enable Transmit from the Master
SPIM_1_TxEnable();
//Send the address that we wish to read from
SPIM_1_WriteTxData(0xC1);
//Wait for transmission to complete and then go back to receive mode
while(!(SPIM_1_ReadTxStatus() & SPIM_1_STS_SPI_DONE));
SPIM_1_TxDisable();
//Disable the manual slave select line
Control_Reg_1_Write(0);
//Read the received data
myData = SPIM_1_ReadByte(); //Returns 00
myData = SPIM_1_ReadByte(); //Returns C1
myData = SPIM_1_ReadByte(); //Returns 00
myData = SPIM_1_ReadByte(); //Returns C0
//Enter never ending loop
for(;;)
{
/* Place your application code here. */
}
}
/* [] END OF FILE */
You should always consider posting the complete project with all of your settings, that is much easier for us to find any bug. To do so, use
Creator->File->Create Workspace Bundle (minimal)
and attach the resulting file (you may use chrome, that should work from now on).
Bob
Thanks for the heads up om that Bob.
Please find the project attached.
Regards,
Roop
The DS1302 follows the normal SPI procedure. Data is changed in the falling edge of the clock, and read at the rising edge of the clock. During a read operation, after the address has been written, the rolses of who is writing data swaps between PSoC and DS1302. Thats why the diagram is a little bit confusing.
I see two mistakes: when writing to the DS1302, you should clear CE after each operation. Otherwise I'm not sure whether the DS1302 will accept the next operation (or finish the first one properly). Also, when trying to read you should not disable the CE line after sending the address - it still needs to be 1 during the read.
And since you didn't specify burst mode, you should read only one byte (and not 4).
Have changed the code as shown below, but unfortunately still no joy :-(
Are you QUITE sure that the ss - signal is active high? Usually this is an active low signal as it is in the SPI-component.
Bob
That is my understanding based on the timing diagram from the datasheet.
DS1302 Datasheet attached.
You are using SPI clock of 1MHz. Since you are working at 3.3V I would suggest to lower the speed.
As you can see all inputs of the ds1302 are having pull-down resistors. your PSoC's output pin should not have strong drive or you will never read anything other than the output value. better use open drain dives high. So when PSoC outputs a zero you are able to read the signal at the input.
Bob
I have changed the clock to run at 1Mhz (500 KHz SPI) and changed the pind drive as suggested.
The device now returns 0xC3 rather than 0xC1!
Think I will have to wait till I get a scope unless you have any other ideas?
Thanks to everyone for your continued support and suggstions. What I thought was going to be simple is proving more difficlt than I thought!
Asin the SPI sample application where they create a master and a slave on the one device, is there any way that I can easily make an SPI 3-wite slave to test the code or is that just going to make things even more complicated?
Roop
Read carefully in SPI's datasheet about SPIM_GetRxData(). You should wati until the byte is ready.
Bob
If I have understood the Datasheet for the SPI module and your instructions correctly, I now have the following:-
<code>
//Wait for transmission to complete and then go back to receive mode
while(!(SPIM_1_ReadTxStatus() & SPIM_1_STS_SPI_DONE));
SPIM_1_TxDisable();
//Wait for data to be received from the slave device
while(SPIM_1_GetRxBufferSize() == 0);
//Collect all data from the buffer
int i;
for (i = 1; i <= SPIM_1_GetRxBufferSize(); i++){
myData = SPIM_1_ReadRxData();
}
//Disable the manual slave select line
Control_Reg_1_Write(0u);
</code>
Unfortunately this still produces the same result.
|
http://www.cypress.com/forum/psoc-5-device-programming/spim-and-ds1302
|
CC-MAIN-2016-44
|
refinedweb
| 916
| 68.3
|
The first step in implementing a directory is determining what information to store in the directory. The naming context of your server has already been defined as:
dc=plainjoe,dc=org
Store contact information for employees in the people organzational unit:
ou=people,dc=plainjoe,dc=org
There are several ways to identify the data that should be placed in an employee's entry. Information stored in an existing Human Resources database can provide a good starting point. Of course, you may not want to place all of this information in your directory. As a general rule, I prefer not to put information in a directory if that data probably won't be used. If it turns out that the data is actually necessary, you can always add it later. Eliminating unnecessary data at the start means that there's less to worry about when you start thinking about protecting the directory against unauthorized access.
An alternative to starting with an existing database is to determine which employee attributes you wish to make available and define a schema to match that list. The reverse also works: you can select a standard schema and use the attributes already defined. I prefer this approach because it makes it easy to change from one server vendor to another. Widely used, standard schemas are more likely to be supported by a wide range of vendors. Custom, in-house schemas may need to be redesigned to adapt to a new vendor (or even a new version from the same vendor).
For your directory, the inetOrgPerson schema defined in RFC 2798 is more than adequate. From Section 3.5.1 in Chapter 3, we know that this object class and associated attributes are defined in OpenLDAP's inetorgperson.schema file. As shown in Figure 4-1, an inetOrgPerson is a descendant of the organizationalPerson, which was itself derived from the person object class.
The union of these object classes defines the set of required and optional attributes that are available. This means that the only required attributes in an inetOrgPerson object are the cn and sn attributes derived from the person object class.
Your directory will use the cn attribute as the RDN for each entry. Remember that the RDN of an entry must be unique among siblings of a common parent. In larger organizations, two people may have the same first and last name. In these cases, using a more specific value for the cn, such as including a middle name (or initial), can alleviate name collisions.
Another way to reduce the number of name collisions is to redesign the directory layout to reduce the total number of user entries sharing a common parent. In other words, group employees in some type of logical container, such as a departmental organizational unit. Figure 4-2 illustrates how this design avoids namespace conflicts. In this directory the "John Arbuckle" in sales is different from the "John Arbuckle" in engineering because the entries possess different parent nodes.
For our example, going with a single container of ou=people is fine; furthermore, our employee base is small enough to use an employee's common name (cn) without fear of conflict. Figure 4-3 shows the directory namespace developed so far.
Here is an employee entry that contains the attributes needed for our directory. Notice that the two required attributes outlined in Figure 4-1, cn and sn, are present in addition to several optional attributes.
## LDIF entry for employee "Gerald W. Carter" dn: cn=Gerald W. Carter,ou=people,dc=plainjoe,dc=org objectClass: inetOrgPerson
|
http://etutorials.org/Server+Administration/ldap+system+administration/Part+I+LDAP+Basics/Chapter+4.+OpenLDAP+Building+a+Company+White+Pages/4.2+Defining+the+Schema/
|
CC-MAIN-2017-04
|
refinedweb
| 596
| 54.02
|
Is this restaurant family-friendly?
Does this restaurant offer delivery?
Does this restaurant serve dinner?
Is this a fast food place?
Does this restaurant serve Bar / Pub food?
Does this restaurant have parking?
Does this restaurant have tables with seating?
Does this restaurant offer takeout or food to go?
Does this restaurant serve American food?
Does this restaurant serve Italian food?
Thanks for helping!
People rave about this place like its some sort of hidden gem of Cape Cod, trust me its not. Just decent bar style pizza and beer. I guess the surprise is you would normally never consider stopping there and eating, but its surprisingly "average."
We order pizza at 8:45pm the person on the phone told us 25-30 minutes. An hour later we had cold pizza. I called twice,twice put on hold. We asked for plates and napkins they did arrive at all. Pizza wasn't that great.
Jacks pizza is absolutely delicious. We have ordered several times and never have we been disappointed. The calzones are iutstanding as well. Last time I had a bacon and pineapple pizza. The waitress asked if I wanted honey on it as well. I hesitated, but she said it was great. Well she was spot on! Amazing!!! You can also order...
More
Great pizza. Don't ask for extra cheese. They put plenty on it anyways. Ribs are good too. They offer you a "cook it at home " pizza. It comes with directions and in one of their pans that you need to return ( you get your deposit back).
So, why do I go? Because they make the best darn pizza around! So, I order a pizza and an iced tea. OK I'm different. But I know a good pizza when I eat one.
cooks are allowed to mingle with customers and serve burnt food so just remember to ask for 'cooked light'
Excellent calzones and quesidia
We went to Jack's and had one of the most amazing calzones not to mention the ribs were so tender.... this is a local neighborhood bar just makes you think of cheers where everybody knows your name, seemed as though everyone that walked in was a regular..I found the prices were very reasonable.. On our second visit we ordered a...
More
The pizzas and burgers are fantastic. Friends swear they have the best ribs in Hyannis, Daily specials are often unusual and are always home made. Pub-style local watering hole atmosphere, but the food is very fresh. Take out and delivery is available.
We went to Jacks with a discount from Restaurant .com expecting to get a really good pizza. Boy where we disappointed. The Pizza was oily and heavy and had no flavor . Sauce was lacking and what was on it was too sweet. Being of Italian background we found that this Pizza just didn't make it. The service was good...
More
We visited Jack's twice on our recent trip to Hyannis. Most of the customers appeared to be locals and families, which added to the appeal. The menu was varied and the waitress was helpful. The portion sizes were large and the food was fresh and hot. We can certainly recommend the ribs and the pizzas.
Own or manage this property? Claim your listing for free to respond to reviews, update your profile and much more.
|
http://www.tripadvisor.com/Restaurant_Review-g41623-d384768-Reviews-Jack_s_Lounge-Hyannis_Cape_Cod_Massachusetts.html
|
CC-MAIN-2016-07
|
refinedweb
| 564
| 87.52
|
csPartialOrder< T > Class Template ReferenceA generic finite partial order class. More...
#include <csutil/partialorder.h>
Detailed Description
template<class T>
A generic finite partial order class.
class csPartialOrder< T >
A finite partial order is a graph with the following properties:
- A finite number of nodes (of type T).
- A finite number of reflexive tuple relations T1 <= T2.
- An absense of any non-trivial cycles, e.g., T1 < T2 < T1 where T1!=T2.
An insert of an edge which violates the third constraint will fail (return false and have no effect).
There must be a csHashComputer for type T.
Definition at line 52 of file partialorder.h.
Constructor & Destructor Documentation
Create a partial order graph.
Definition at line 78 of file partialorder.h.
Copy constructor.
Definition at line 85 of file partialorder.h.
Copy constructor.
Definition at line 124 of file partialorder.h.
Member Function Documentation
Add a node. If the node is already present, has no effect.
Definition at line 131 of file partialorder.h.
Add an ordering constraint (node1 precedes node2).
Edge addition is not idempotent, i.e., if you add an edge three times, it must be removed three times before it will disappear from the graph.
Definition at line 224 of file partialorder.h.
Clear all "marked" flags.
Definition at line 357 of file partialorder.h.
Clear the "marked" flag for a given node.
Definition at line 346 of file partialorder.h.
Query an edge's presence. Does not check for transitive connectivity.
Definition at line 148 of file partialorder.h.
Query a node's presence.
Definition at line 142 of file partialorder.h.
Delete a node and all edges connected to it.
Definition at line 165 of file partialorder.h.
Remove an ordering constraint (node1 precedes node2).
Definition at line 251 of file partialorder.h.
Return a node with a given index (0 through Size()-1).
Definition at line 270 of file partialorder.h.
Return an enabled node.
Definition at line 392 of file partialorder.h.
Return true if any node is enabled.
Definition at line 379 of file partialorder.h.
Return true if all of the node's (zero or more) predecessors have been marked and the node itself has not.
Definition at line 369 of file partialorder.h.
Query whether a given node is "marked".
Definition at line 335 of file partialorder.h.
Set the "marked" flag for a given node.
This is useful for implementing your own graph iterators.
Definition at line 324 of file partialorder.h.
Number of nodes in the graph.
Definition at line 264 of file partialorder.h.
Produce a valid "solution" to the partial order graph, i.e., a sequence of nodes that violates no constraints.
Definition at line 279 of file partialorder.h.
The documentation for this class was generated from the following file:
- csutil/partialorder.h
Generated for Crystal Space 1.2.1 by doxygen 1.5.3
|
http://www.crystalspace3d.org/docs/online/api-1.2/classcsPartialOrder.html
|
CC-MAIN-2015-11
|
refinedweb
| 481
| 71.61
|
stdarg.h - handle variable argument list
#include <stdarg.h> void va_start(va_list ap, argN); type va_arg(va_list ap, type); void va_end(va_list ap);
The <stdarg.h> header contains a set of macros which allows portable functions that accept variable argument lists to be written. Functions that have variable argument lists (such as printf()) but do not use these macros are inherently non-portable, as different systems use different argument-passing conventions.
The type va_list is defined for variables used to traverse the list.
The va_start() macro is invoked to initialise ap to the beginning of the list before any calls to va_arg().
The object ap may be passed as an argument to another function; if that function invokes the va_arg() macro with parameter ap, the value of ap in the calling function is indeterminate and must behaviour is undefined.
The va_arg() macro will return the next argument in the list pointed to by ap. Each invocation of va_arg() modifies ap so that the values of successive arguments are returned in turn. The type parameter is the type the argument is expected to be. This is the type name specified such that the type of a pointer to an object that has the specified type can be obtained simply by suffixing a * to type. Different types can be mixed, but it is up to the routine to know what type of argument is expected.
The va_end() macro is used to clean up; it invalidates ap for use (unless va_start() is invoked again).
Multiple traversals, each bracketed by va_start() va_end(), are possible.
This]; int argno = 0; va_start(ap, args); while (args != 0) { array[argno++] = args; args = va_arg(ap, const char *); } va_end(ap); return execv(file, array); }
It is up to the calling routine to communicate to the called routine how many arguments there are, since it is not always possible for the called routine to determine this in any other way. For example, execl() is passed a null pointer to signal the end of the list. The printf() function can tell how many arguments are there by the format argument.
None.
exec, printf().
|
http://www.opengroup.org/onlinepubs/007908799/xsh/stdarg.h.html
|
crawl-001
|
refinedweb
| 351
| 60.85
|
I haven’t posted in a while so I figured I’d post a quick update on what’s been going on (work and far from work-related):
- We’re definitely getting into ship mode. Tough decisions are being made about what changes can still be made to the beta and every day they get tougher. The good news is that it’s been going pretty smoothly so far and I haven’t had to answer the “Why didn’t you guys find this issue earlier?“ question yet, though I may have just jinxed myself. Nah, I’m confident (though still crossing my fingers).
- Advice: Don’t name any of your namespaces “System.“ You just don’t want to do that. Ran into a couple of situations where people had and shipped that way, meaning they’re stuck with it for now. Whidbey makes the situation much better, but you still should avoid doing so.
- I recently discovered how useful LiveMeeting is for conducting “phone” interviews. Definitely recommend it if you find yourself looking for an easier, more effective way to conduct technical phone interviews.
- Bought a Strat a couple of weeks ago. Still prefer my Les Paul, but I dig the Strat for some sounds but the Gibson is just so much angrier and louder it just can’t be replaced.
- Speaking of angrier (tongue sorta in cheek), I’m somehow on an Avril streak where I’m suddenly firmly believing she can write pretty good, catchy songs. Is it just me? Did I really just write this? Should I be embarassed?
- Trying to balance work and regular life a bit more lately as well. See Jay’s recent post for a description of what I’m talking about (except for the yoga and sailing). Let’s see how long it lasts.
- Been playing a lot more guitar again. After ~15 years (wow, I really am almost 30 eh?) of playing tons of covers and some weak attempts at writing I finally decided to dig into the whole theory side and it’s been far easier than I ever thought it would be. My hands are in pretty good shape from playing other people’s songs and solos, so physically doing it isn’t that hard (though definitely have plenty of room to improve), but the theory, scales, chords, modes, and all that good stuff are so much clearer to me now. It’s interesting to see how many of the patterns (boxes, or whatever you call them) I’ve gotten used to playing over are clearly defined concepts. It’s definitely been fun to learn all that I’ve so far taken the long route on. Over the three weeks I’ve read about 5-6 of the 20 or so books I’ve collected over time. They all make more sense than they ever did before. Not sure why. Better late than never I guess.
Bullet five, question three: YES
Thanks Stuart. I hear ya. Don’t know what I was thinking.
Embarrassed?
Yes.
Bah, Good is good. Doesn’t matter if it also happens to be popular at the same time.
Try standing out now-a-days and not hating something just because it’s kewl to hate. It’s a hell of a lot harder to like things and stand up for it.
Avril does a pretty damn good job and I hope she makes shed loads of money, even though I expect that the record company is taking most of it for no good reason.
I made the mistake of listening to one of her tunes the other day and I couldn’t stop listening to the entire CD all day. I finally had to peel the headphones away from my ears. They are too darn catchy. I can’t help but feel she’s really just a corporate poser who acts all "mean" and "tough" to get the kiddies to buy more albums, t-shirts and lunchboxes, but oh well. I say this as I drink my Starbucks latte in my branded T-shirt and blue jeans working on my name-brand PC, so I can’t really say much about that.
PingBack from
PingBack from
PingBack from
PingBack from
|
https://blogs.msdn.microsoft.com/gusperez/2004/05/27/update/
|
CC-MAIN-2016-30
|
refinedweb
| 707
| 81.53
|
Prerequisites
Please read this post to get an explanation on how to modify the service tier to use NTLM authentication and for a brief explanation of the scenario I will implement in PHP.
BTW. Basic knowledge about PHP is required to understand the following post:-)
Version and download
In my sample I am using PHP version 5.2.11, which I downloaded from, but it should work with any version after that.
In order to make this work you need to make sure that SOAP and CURL extensions are installed and enabled in php.ini.
PHP does not natively have support for NTLM nor SPNEGO authentication protocols, so we need to implement that manually. Now that sounds like something, which isn’t straightforward and something that takes an expert. Fortunately there are a lot of these experts on the internet and I found this post (written by Thomas Rabaix), which explains about how what’s going on, how and why. Note that this implements NTLM authentication and you will have to change the Web Services listener to use that.
License of the code
The code can be used freely as long as you include Thomas’ copyright notice in the code.
/*
*
* Author : Thomas Rabaix
*
*.
*/
“My” Version
I have modified Thomas’ version slightly (primarily removing debug echo’s etc.).
I have also changed the way the username and password is specified to be a script constant:
define('USERPWD', 'domain\user:password');
The Stream wrapper now looks like:
class NTLMStream
{
private $path;
private $mode;
private $options;
private $opened_path;
private $buffer;
private $pos;
/**
* Open the stream
*
* @param unknown_type $path
* @param unknown_type $mode
* @param unknown_type $options
* @param unknown_type $opened_path
* @return unknown
*/
public function stream_open($path, $mode, $options, $opened_path) {
$this->path = $path;
$this->mode = $mode;
$this->options = $options;
$this->opened_path = $opened_path;
$this->createBuffer($path);
return true;
}
/**
* Close the stream
*
*/
public function stream_close() {
curl_close($this->ch);
}
/**
* Read the stream
*
* @param int $count number of bytes to read
* @return content from pos to count
*/
public function stream_read($count) {
if(strlen($this->buffer) == 0) {
return false;
}
$read = substr($this->buffer,$this->pos, $count);
$this->pos += $count;
return $read;
}
/**
* write the stream
*
* @param int $count number of bytes to read
* @return content from pos to count
*/
public function stream_write($data) {
if(strlen($this->buffer) == 0) {
return false;
}
return true;
}
/**
*
* @return true if eof else false
*/
public function stream_eof() {
return ($this->pos > strlen($this->buffer));
}
/**
* @return int the position of the current read pointer
*/
public function stream_tell() {
return $this->pos;
}
/**
* Flush stream data
*/
public function stream_flush() {
$this->buffer = null;
$this->pos = null;
}
/**
* Stat the file, return only the size of the buffer
*
* @return array stat information
*/
public function stream_stat() {
$this->createBuffer($this->path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
/**
* Stat the url, return only the size of the buffer
*
* @return array stat information
*/
public function url_stat($path, $flags) {
$this->createBuffer($path);
$stat = array(
'size' => strlen($this->buffer),
);
return $stat;
}
/**
* Create the buffer by requesting the url through cURL
*
* @param unknown_type $path
*/
private function createBuffer($path) {
if($this->buffer) {
return;
}
, USERPWD);
$this->buffer = curl_exec($this->ch);
$this->pos = 0;
}
}
The NTLM SOAP Client also uses the USERPWD constant defined above and looks like:, USERPWD);
$response = curl_exec($ch);
return $response;
}
function __getLastRequestHeaders() {
return implode("\n", $this->__last_request_headers)."\n";
}
}
Putting this into the PHP script now allows you to connect to NAV Web Services system service in PHP and output the companies available on the service tier:
// we unregister the current HTTP wrapper
stream_wrapper_unregister('http');
// we register the new HTTP wrapper
stream_wrapper_register('http', 'NTLMStream') or die("Failed to register protocol");
// Initialize Soap Client
$baseURL = '';
$client = new NTLMSoapClient($baseURL.'SystemService');
// Find the first Company in the Companies
$result = $client->Companies();
$companies = $result->return_value;
echo "Companies:<br>";
if (is_array($companies)) {
foreach($companies as $company) {
echo "$company<br>";
}
$cur = $companies[0];
}
else {
echo "$companies<br>";
$cur = $companies;
}
Note that is return value is an array if there are multiple companies, but a company name if there is only one. I have NO idea why this is or whether I can write the code differently to avoid this.
Now I have the company I want to use in $cur and the way I create a URL to the Customer page is by doing:
$pageURL = $baseURL.rawurlencode($cur).'/Page/Customer';
echo "<br>URL of Customer page: $pageURL<br><br>";
and then I can create a Soap Client to the Customer Page:
// Initialize Page Soap Client
$page = new NTLMSoapClient($pageURL);
and using this, I read customer 10000 and output the name:
$params = array('No' => '10000');
$result = $page->Read($params);
$customer = $result->Customer;
echo "Name of Customer 10000:".$customer->Name."<br><br>";
Last, but not least – lets create a filter and read all customers in GB that has Location Code set to RED or BLUE:
$params = array('filter' => array(
array('Field' => 'Location_Code',
'Criteria' => 'RED|BLUE'),
array('Field' => 'Country_Region_Code',
'Criteria' => 'GB')
),
'setSize' => 0);
$result = $page->ReadMultiple($params);
$customers = $result->ReadMultiple_Result->Customer;
Note that Bookmark is an optional parameter and doesn’t need to be specified.
Now echo the customers and restore the http protocol – again, the return value might be an array and might not.
echo "Customers in GB served by RED or BLUE warehouse:<br>";
if (is_array($customers)) {
foreach($customers as $cust) {
echo $cust->Name."<br>";
}
}
else {
echo $customers->Name."<br>";
}
// restore the original http protocole
stream_wrapper_restore('http');
All of the above will output this when the script is opened in a browser (on my machine running NAV 2009SP1 W1)
I hope this is helpful.
Good luck
Freddy Kristiansen
PM Architect
Microsoft Dynamics NAV
Hey Freddy,
I’m trying to use your php script to connect with my dynamics NAV web service but it fails to authenticate… I’ve tried to surf to the web services URL with internet explorer and that works perfect…
I’ve adjusted the config file…
Is there something else I need to do?
thanks!
gert
I know a number of people followed this example to successfully connect to NAV Web Services from PHP – so no.
Setting WebServicesUseNTLMAuthentication to true in the CustomSettings.config is the only thing.
Is it necessary to run NAV with a three tier server configuration?
and which version of NAV did they use?
3T or 2T – doesn’t matter, but it needs to be NAV 2009 SP1.
and do I have to use some kind of proxy or delegations?
Nothing special – everything you need is explained in this post and the first.
Hey Freddie, thanks to your post I have most of my NAV 2009SP1 3 tier setup. SPNs continue to give me grief and I’m assuming that in my NAV WS setup to use with php I’m running into that very issue.
I’m running php5.2.12 on a none domain system running linux. I’ve copied your code and even re added all the debug just to see what’s going on. I can see and connect to the NAV Service tier on port 7047. But it fails to pass on the credentials to the DB and I get the infamous ANONYMOUS login attempt in the SQL logs.
My PHP is returning
a:Microsoft.Dynamics.Nav.Types.NavDatabasePasswordExceptionThe login failed when connecting to SQL Server <SQL Server><SQL Instance>.The login failed when connecting to SQL Server <SQL Server><SQL Instance>.
I have setup the http SPN records, and I’m using the service user/pass which I know are correct, if I do it with IE on the <Service Tier Server> it works perfect, so I know it’s SPN related and your example here doesn’t say anything about SPNs for the WS (http/<service tier>).
Thanks for any help in this matter.
Hej Freddy,
Jeg får en PHP fejl når jeg forsøger ovenstående eksempel:
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn’t load from ‘”>‘ : Start tag expected, ‘<‘ not found in D:wampwwwnavindex.php:10 Stack trace: #0 D:wampwwwnavindex.php(10): SoapClient->SoapClient(‘…’) #1 {main} thrown in D:wampwwwnavindex.php on line 10
Har du nogen idé til hvad problemet kan være? Jeg tror selv at det skyldes, at I mangler følgende i starten af den XML som sendes tilbage fra webservicen:
<?xml version=’1.0′ encoding=’UTF-8′?>
Hvis jeg gemmer XMLen som en fil og indsætter dette så går det meget bedre. Jeg undrer mig blot over at I ikke skulle være opmærksomme på dette hvis det er problemet?
Jeg har oplevet det samme hvis jeg forsøge at bruge SOAPui til at explore NAV webservices. Dette program melder også fejl på samtlige XML filer fra NAV fordi denne tag mangler.
It looks like you forgot to set the Service Tier to use NTLM authentication and restart both services (Web Service and Service tier)
Hi, Service Tier is set to use NTLM, so that is not the problem:
<add key="WebServicesUseNTLMAuthentication" value="true"></add>
I got mine running, for me it was the SPNs, took awhile to figure out, if you have all the proper SPNs on your domainuser running the services (if using a domain user) you have to select using any protocol, unlike the 3 tier setup that says to use kerb only. But make sure your SPNs are right to start with, I had them wrong so that setting didn’t help on my first attempt.
Freddy,
You were right. I had a problem with the authentication. Thanks for pointing me in the right direction 🙂
How can i do create a customer using the CREATE method with PHP and Dynamics NAV
Hi Freddy,
Your code works very well, it helped me a lot. But now I need to Create a Customer instead of Read it.
Can you help me?
Thanks.
I have set the NTML as true.However I get the following error..its very urgent..pls help freddy…
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from '' : Start tag expected, '<' not found in E:wampwwwnavconnect.php:185 Stack trace: #0 E:wampwwwnavconnect.php(185): SoapClient->SoapClient('…') #1 {main} thrown in E:wampwwwnavconnect.php on line 185
Hi Navshae,
It seems your curl request pads with some white space and the parser is expecting '<'.
Please change the code here as follows in two places one at soapclient and another one at readbuffer:
$response = trim(curl_exec($ch));
This will remove uncessary white space before the '<'.
I faced the same problem and it takes a while to find that.
Hi,
The php script looks great.Good Job., but haven't tried yet. Let's say the customer wants to have real time data of a php timesheet application with Navision. Will it be secure to expose the Navision web service tier with a public ip address?the scenario is that the php application is hosted on a hosted service company and the navision database is in the company's internal network.
Or is it better to host the php application on the company's network in a DMZ and hire someone to secure the websever?
the idea is to make customer's data secure and not to be published by the webservice.
I have used NAV 2009 services with vb.net and c sharp and works great.
Thanks,
vasilis
Navision and PHP developer.
Hi.
Im doing a specialization-project on Magento and NAV integration.
Im hoping to find a sample/tutorial on how to add database items to NAV by using php. Do you already have a blog about this or can anyone give me a hint from where to start?
Hi Freddy,
Thanks for your tutorial. I can get the above examples to work, but have encountered a problem creating a new ItemCard record. I would much appreciate it if you could look at the problem I have addressed here: community.dynamics.com/…/45411.aspx, but i think that this will get more attention if this has been written into here.
I happen to have a similar problem. copied from the page he is giving us. Hopefully this will get more attention when in here. I got similar problem.
Hi Freddy,
First of all, thanks for this post. It has helped me a lot and, now, I'm able to use Navision WebServices from PHP, wich, in turn, has also helped me to use PHP as a bridge to use Adobe Flex as a remote client.
One thing I cannot get to work is: Wen you connect to a Codeunit WEBService that returns a XMLPort in one of its parameters, hou can you manage it from PHP?
Here is an example:
On Codeunit 50000, whe create a function:
WSExportCustomer(codPrmCustomerNoFrom : Code[20],(codPrmCustomerNoTo : Code[20];VAR xmlCustomer : XMLport "WS Customer")
recCustomer.SETFILTER("No.", '%1..%2', codPrmCustomerNoFrom, codPrmCustomerNoTo);
xmlCustomer.SETTABLEVIEW(recCustomer);
I cannot find a way to manage this.
Hi, all,
As I found the solution to the previous post, I respond myself so perhaps this can help to the rest of you.
Regarding the Sample CodeUnit of the previous post, here you have a sample PHP script to use it:
take into account that the name of the "published" CodeUnit is OperariosAlmacen
require_once("ntlm/NTLMStream.php");
require_once("ntlm/NTLMSoapClient.php");
stream_wrapper_unregister('http');
stream_wrapper_register('http', 'NTLMStream') or die("Failed to register protocol");
$NoOP = "3039678";
$Params = array();
$Params["codPrmProdOrderNoFrom"] = $NoOP;
$Params["codPrmProdOrderNoTo"] = $NoOP;
$Params["xmlNoStockEntrada"] = null;
$client = new NTLMSoapClient($baseURL . 'DE-FASE2/Codeunit/OperariosAlmacen');
stream_wrapper_restore('http');
$Result = $client->WSExportNoStockEntrada(&$Params);
$Result is an object containing an array (or another object containing an array) of Objects
In my case, to get wat's inside $Result, you have to do:
$xmlNoStockEntrada = $Result->xmlNoStockEntrada;
$ProdOrderLine = $xmlNoStockEntrada->ProdOrderLine;
echo $ProdOrderLine[0]->ItemDescription;
Hope this can help somebody.
Hi All,
At first thanks Freddy for your tutorial. I really helped me. I, as some of you, had some problems with creating new card. I found solution so here is a code and I hope it could help others:
First you must create a new class with name which is the same as your Web Service:
class CustomerCard
{
public $CustomerCard;
}
Then you can add code to your script:
$pageURL = $baseURL.rawurlencode($cur).'/Page/CustomerCard';
$page = new NTLMSoapClient($pageURL);
$customer = new CustomerCard;
$customer->CustomerCard->Name = "Any Value";
$customer->CustomerCard->Post_Code = '02-515';
$page->Create($customer);
That's all 🙂
Hello this create code is not working, while cretion step throws error “Fatal error: Uncaught SoapFault exception: [a:Microsoft.Dynamics.Nav.Service.WebMetadata.ServiceBrokerException] Evalution failed for field Type due to the following error: “OptionString not found.”.” can u please resolve this error
The code was written for NAV 2009. A lot of things have changed since then (both with PHP and with NAV). The primary reason why things would be hard back then was, that NAV was only Windows Authentication (NTLM). Since then, NAV has become much simpler to use from other products – I will try to redo some articles especially focused on NAV on Azure (the gallery image).
Hi, I connected the webservices correctly , but when i put the data i got the error message :
———————————————
[faultstring] => The Element is expected by Min Occurs value: Once. Element received: .
[faultcode] => a:Microsoft.Dynamics.Nav.Types.Exceptions.NavNCLXmlPortMetadataException
[detail] => stdClass Object
(
[string] => The Element is expected by Min Occurs value: Once. Element received: .
)
———————————————-
I am sending data like :
—————————————————
$arr['salesOrder'] = array("SalesLine"=>array("ItemNo"=> '1','Quantity'=> 1.00,'UnitPrice'=> 450.00));
try {
$results = $client->CreateSalesOrder($arr);
echo $results->retrun_value;
}
catch (SoapFault $soapFault) {
print_r($soapFault);
echo "Request :<br>", htmlentities($client->__getLastRequest()), "<br>";
echo "Response :<br>", htmlentities($client->__getLastResponse()), "<br>";
}
Dear Jega,
I have same problem like Navshae. I found one at soapclient but another one i can't find.
Can you give me a hint, thanks.. 🙂
Thanks for this tutorial. Very helpful. It took me a little while to get everything hooked up, but eventually I got the standard CRUD methods working. So I can read, insert, update and delete records in NAV from my PHP Zend application. Which is awesome. However, there are still some things I have to figure out before I can actually implemend solutions based on NAV webservices. I hope someone can put me into the right direction for the remaining issues.
1. How does the primary key mechanism work? Some tables do have 'No' field. Others have a 'Code' field. How do I know in advance what fieldname to use to retrieve a record? I think that somehow I have to extract this from the WSDL document. But I can't find this info anywhere.
2. When I try to delete a Customer record which has dependend rows somewhere I get an error: "You cannot delete Customer 01445544 because it has ledger entries in a fiscal year that has not been closed yet.". That's not an error. My question is: How do you deal with return messages? I feel it has something to do which the _Result nodes, but I can't figure it out because the error is raised when calling the service the very first time. Maybe I can catch this error and deal with it, but I think that's going down the wroing road.
I am happy to publish my finished class as soon as everything is working properly.
Junior NAV / PHP developer, The Netherlands
I'm having the same problem as navshae, I want to use your demo php code to test my Nav Webservice installations.
Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from '' : Start tag expected, '<' not found in
How can i read the fields and type from the card as listed in the XML?
Any help will be appreciated.
Thanks
<xsd:sequence><xsd:element<xsd:element<xsd:element<xsd:element<xsd:element<xsd:element<xsd:element<xsd:element<xsd:element<xsd:element<xsd:element<xsd:element<xsd:element</xsd:sequence>
Now a days such lot of hot stuffs blogs are coming for the notification. Its really interesting highly reputated concerns were doing such a blogs. Recently i read such a high stuff blog from the Custom web development company website.
This post really helped to get my service working to NAV Web Services from PHP..thank you so much……
The reason why you get a company name if there's one result and an array otherwise is down to PHP doing this by default. You can disable it with the options you pass into the SoapClient constructor
@dsas Could you elaborate that with an example? How would you pass the options into the SoapClient constructor? I could really use this. I'm tired of doing it over and over again in the code.
Thanks!
Hi all,
I have a problem while updating the record via Internet Explorer. I have error like this:
Other user has modified "Table_Name" "Nr=CONST(Record_ID)"
I do not have this error in Chrom and FireFox. Is anyone had that problem?
Kind regard,
Kris
PHP Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from '' : Start tag expected, '<' not found
Error still exist even I changed to $response = trim(curl_exec($ch));
Allow NTLM connection in Navision configuration file. By default it is set to false.
There is a definitive problems with placing anything INTO NAV web services:
Adding a bunch of data and sending via SOAP -> result is below:
SoapFault exception: [a:Microsoft.Dynamics.Nav.Types.Exceptions.NavNCLXmlPortMetadataException] The Element is expected by Min Occurs value: Once. Element received: .
For everyone still struggling importing data into MS'NAV using PHP – I have a solution here:
blog.artea.info/ms-nav-web-services-tofrom-php-receiving-and-sending-data/
Hi,
We have implemented exact PHP code but still getting below error..
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from '">
We have set the authentication key but as we arent IIS experts, please advise on how to create SPNs.
Regards,
Abhijeet
Marjin,
Please share a document or steps how you connected to Navision using Zend framework. We are using the same but keep getting below error.
PHP Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from '' : Start tag expected, '<' not found
NTLM connection in Navision configuration file is properly configured.
Regards,
Abhijeet
Hi Freedy,
I connect my nav web service in my php but it's given error
SOAP-ERROR: Parsing WSDL: Couldn't load from '' : Start tag expected, '<' not found .
Could you tell me where I went wrong?
thanks in advance………
Hi
I'm trying to get this to work with NAV 2013 but getting the following error:-
PHP Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from 'nav.haygrove.co.uk/…/SystemService
Does 2013 work differently?
Thanks
sam
Hi Freedy,
First of all thanks for your code and help.
Now. I try your code and result is the common:
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from '192.168.4.18/…/SystemService& : Start tag expected, '<' not found in C:wampwwwsoapnavcreaped.php:163 Stack trace: #0 C:wampwwwsoapnavcreaped.php(163): SoapClient->SoapClient('….') #1 {main} thrown in C:wampwwwsoapnavcreaped.php on line 163
I try with all the comments of the users of this post but nothing cahnges.
Could you help me?…
Thanks and regards from Spain.
I find the mistakes, now I can connect to my NAV web service.
First:
Great error!!! I add the NTLM autentication code <add key="WebServicesUseNTLMAuthentication" value="true"></add> but few lines down, in the same configuration file I found another call to NTLM set to False!!!!!.
Second:
I must have some problem with autentication, becouse I install wamp server in my dynamics nav server and locally I can access. But remotely, from another PC i cant access.
I hope this could help someothers.
To access remotely you must add delegation control in active directory
Anyone know how to Release_Sales_Document in PHP??
Thanks a lot Freddy ! This works for Dynamics AX 2009 too !
This is a great page Freddy. Thank you
I spend some time with Start tag expected, '<' not found .
figured out at last I need to stop both webservices on server after changed the WebServicesUseNTLMAuthentication setting and the start again. Just restart the services is not working
Thank you, you saved me a lot of time!
Hi!
I have a web service to create sales order in NAV from Magento. All works fine but in some cases one of the items have no cross reference in NAV, then I get this error:
———————————————————————————————————————–
Code: Select all
Fatal error: Uncaught SoapFault exception: [a:Microsoft.Dynamics.Nav.Types.Exceptions.NavNCLDialogException] There are no items with cross reference: SMARTSC in C:wampwwwsoapgridpedanav.php:120 Stack trace: #0 C:wampwwwsoapgridpedanav.php(120): SoapClient->__call('Update', Array) #1 C:wampwwwsoapgridpedanav.php(120): NTLMSoapClient->Update(Object(stdClass)) #2 C:wampwwwsoapgridcrearpednav.php(112): crearpedidonav(Array, Array, 3, '…') #3 {main} thrown in C:wampwwwsoapgridpedanav.php on line 120
———————————————————————————————————————–
I loose this new sales order in NAV, but this is not the problem, the real problem is that the nav web service become inaccesible. If I try to create another sales order (in this case with all cross references ok) I get the next error, like the service is blocked:
———————————————————————————————————————–
Code: Select all
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't find <definitions> in '' in C:wampwwwsoapgridpedanav.php:34 Stack trace: #0 C:wampwwwsoapgridpedanav.php(34): SoapClient->SoapClient('…') #1 C:wampwwwsoapgridcrearpednav.php(112): crearpedidonav(Array, Array, 2, '…') #2 {main} thrown in C:wampwwwsoapgridpedanav.php on line 34
———————————————————————————————————————–
If I use Internet Explorer to navigate to the web service URL '' I can see the web service definition and all become working again. I can use the web service to ceate new sales order without problem.
The quetions is… Why the service become unavalilable afther an error?… How can I solve or restart the service with code in php?
Note: In windows service configuration and services tab I have configured the service to restart in case of errors.
Resume:
All right creating sales order –> Error with not found cross reference in one new sales order –> web service become inavailable –> Cant create new sales order –> Navigate with browser to web service url –> All work right again.
Thanks!!
I'm getting this error below
Fatal error: Uncaught SoapFault exception: [Client] SoapClient::SoapClient(): Invalid parameters in
Please help 🙁
Your code works. I jus have to get my log in credentials right. I thought i did not need 'domainuser' coz i am on a work group but after i serched my log in account , i found out that all accounts have that format.
Am also using WAMP server and the code works
Hi,
In case someone also has this issue
SOAP-ERROR: Parsing WSDL: Couldn't load from '' : Start tag expected, '<' not found .
Here is how I solved it,
First I followed the steps mentioned above,
-> Allow NTLM connection in Navision configuration file. By default it is set to false.
->add the NTLM autentication code <add key="WebServicesUseNTLMAuthentication" value="true"></add>
Double check that a few lines down, in the same configuration file there isn’t another call to NTLM set to False.
->After changing the WebServicesUseNTLMAuthentication setting, stop webservices on server and start again. Just restarting the services does not working
After that didn't work (giving me the same error), I double checked the authentication, and that worked for me
// Authentification parameter
class MyServiceNTLMSoapClient extends NTLMSoapClient {
protected $user = 'xxxxxxxxxx';
protected $password = 'xxxxxxxxxx';
}
class MyServiceProviderNTLMStream extends NTLMStream {
protected $user = 'xxxxxxxxxx';
protected $password = 'xxxxxxxxxx';
}
stream_wrapper_unregister('http');
// we register the new HTTP wrapper
stream_wrapper_register('http', 'MyServiceProviderNTLMStream') or die("Failed to register protocol");
// so now all request to a http page will be done by MyServiceProviderNTLMStream.
// ok now, let's request the wsdl file
// if everything works fine, you should see the content of the wsdl file
// Initialize Soap Client
$baseURL = 'xxxxxxxxxxxx:1234/LS_201554321/WS/Services';
$client = new MyServiceNTLMSoapClient($baseURL);
hope this helps someone else
after all the integration i am getting soapfault like :
“Type: SoapFault
Message: SoapClient::SoapClient(): Invalid parameters” please help me to solve this problem.
Some one have this error?
PHP Fatal error: SOAP-ERROR: Parsing WSDL: Couldn’t load from ‘’ : Document is empty
Can you give me an hint?
Thanks,
Jacopo
Hi,
I’ve same error.
Did you solve the problem “Document is empty”?
Can you give me a hint?
Thanks
Did you notice, that there is a newer blog post on how to do stuff like this with newer versions of NAV and without Windows Authentication?
Hey Freddy,
“Note that is return value is an array if there are multiple companies, but a company name if there is only one. I have NO idea why this is or whether I can write the code differently to avoid this.”
Just pass array(‘features’ => SOAP_SINGLE_ELEMENT_ARRAYS) to avoid this:)
Dirk
Thanks a lot Dirk
The code helps in solving authentication problems
All I’m getting is a “Document is empty” response.
Loging through the browser works, but through PHP fails:
PHP Fatal error: SOAP-ERROR: Parsing WSDL: Couldn’t load from ‘’ : Document is empty
in /home/skerit/projects/navision.php on line 199
PHP Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn’t load from ‘’ : Document is empty
in /home/skerit/projects/navision.php:199
Stack trace:
#0 /home/skerit/projects/navision.php(199): SoapClient->SoapClient(‘….’)
#1 {main}
thrown in /home/skerit/projects/navision.php on line 199
Hi, this is an awesome blog and nice method, however despite being able to install it on many servers (locally and remotely) I can’t use it on Nav running from Azure. I can access webservices through the browser without any hassle, but NTLM just doesn’t work. Would that be SSL problem (web service is on HTTPS) or Azure? I tried to modify the code to add ssl certificate but no luck 🙁
Hello!
I’ve made a package you can use via composer to make this painless.
This article helped a lot!
Also there is some weird caching going on in php, if your request fails on the first time, then the second run won’t even perform a request (skip the http stream replacement or SoapClient->__doRequest method) – and will fail automatically. To avoid it append a random query string to your web service url like ‘’ and save yourself a lot of headaches 🙂
Hi
Thanks for this post do anyone have any code example . I am facing a error
Hi Freddy.
Thank’s for the this post I need some help please Is most appreciated.
I can connect and everything is fine apart from when I call my $result = $client->MyFunction();
I need to post an xml and I get error like:
Fatal error: Uncaught SoapFault exception: [a:Microsoft.Dynamics.Nav.Service.WebMetadata.ServiceBrokerException] Parameter pxmlRequest in method WebRequest in service RetailWebServices is null!
when I pass the xml in $request the error then turns to be :
Catchable fatal error: Object of class stdClass could not be converted to string in.
Can you or anyone help with this issue have anyone came across this? thank’s in advance.
Sorry Juliano, but it has been many years since I last looked at PHP and NAV. The primary reason for this post was, that back then, the connection piece was hard (due to limited authentication methods). Today connection is easier (using basic auth) and both Soap and OData uses standards. You could try to ask on mibuso.com for assistance.
I am getting this error, please help
Fatal error: Uncaught SoapFault exception: [a:Microsoft.Dynamics.Nav.Types.Exceptions.NavObsoleteMethodException] The CONTEXTURL() method is obsolete. in importorders.php:73 Stack trace: #0 importorders.php(73): SoapClient->__call(‘Read’, Array) #1 {main} thrown in importorders.php on line 73
Somewhere in the NAV Application code, the function CONTEXTURL is used.
I guess that this is not allowed in Web Services and the function might not even be allowed in later versions of NAV
Hi Freddy,
Thank you very much for your response. Do you know where CONTEXTURL() function has been used in the code? Or how can I debug the application code to find out the problem? I get this error message every time when I try to call Read or Create method in SOAP.
ERROR: SoapException: [SoapFault exception: [a:Microsoft.Dynamics.Nav.Types.Exceptions.NavObsoleteMethodException] The CONTEXTURL() method is obsolete. in G:\xampp\htdocs\magentodev2\nav\importorders.php:37 Stack trace: #0 G:\xampp\htdocs\magentodev2\nav\importorders.php(37): SoapClient->__call(‘create’, Array) #1 {main}]
|
https://blogs.msdn.microsoft.com/freddyk/2010/01/19/connecting-to-nav-web-services-from-php/
|
CC-MAIN-2017-51
|
refinedweb
| 5,040
| 53.51
|
I’ve seen several people ask lately how to compute the distribution (CDF) function for a standard normal random variable, often denoted Φ(x). They want to know how to compute it in Java, or Python, or C++, etc. Every language has its own standard libraries, and in general I recommend using standard libraries. However, sometimes you want to minimize dependencies. Or maybe you want more transparency than your library allows. The code given here is in Python, but it is so compact that it could easily be ported to any other language.
I just posted Python code for computing the error function, erf(x). The normal density Φ(x) is a simple transformation of erf(x). Given code for erf(x), here’s code for Φ(x).
def phi(x): return 0.5*( 1.0 + erf(x/math.sqrt(2)) )
After deriving the transformations between erf(x) and Φ(x) several times, including their complements and inverses, I wrote them down to save. See the PDF file Relating Φ and erf.
See also stand alone code for computing the inverse of the standard normal CDF.
One thought on “Stand-alone normal (Gaussian) distribution function”
If high accuracy isn’t essential, there’s also Polya’s approximation to the standard Gaussian c.d.f. which Aludaat and Alotdat have recently improved, at least in a maximum error sense (Applied Mathematical Sciences, Vol. 2, 2008, no. 9, 425 – 429). Polya’s is still of interest, at least to me, because its peak deviations are farther out in number of standard errors than Aludaat & Alodat’s. Both have error which approaches zero as the number of standard errors increases in magnitude beyond two. Polya’s maximum deviation from Gaussian c.d.f. is a tad over 0.003 at just over 1.5 standard errors.
The Polya approximation is: 0.5 +- 0.5 sqrt(1-exp(-2z^2/pi))
The inverse is available by algebra.
|
https://www.johndcook.com/blog/2009/01/19/stand-alone-normal-gaussian-distribution-function/
|
CC-MAIN-2017-43
|
refinedweb
| 323
| 59.9
|
getpwuid()
Get information about the user with a given ID
Synopsis:
#include <sys/types.h> #include <pwd.h> struct passwd* getpwuid( uid_t uid );
Since:
BlackBerry 10.0.0
Arguments:
- uid
- The userid whose entry you want to find.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The getpwuid() function gets information about user uid. This function uses a static buffer that's overwritten by each call.
The getpwent(), getpwnam(), and getpwuid() functions share the same static buffer.
Returns:
A pointer to an object of type struct passwd containing an entry from the group database with a matching uid, or NULL if an error occurred or the function couldn't find a matching entry.
Examples:
/* * Print password info on the current user. */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <pwd.h> int main( void ) { struct passwd* pw; if( ( pw = getpwuid( getuid() ) ) == NULL ) { fprintf( stderr, "getpwuid: no password entry
|
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/g/getpwuid.html
|
CC-MAIN-2017-09
|
refinedweb
| 167
| 61.73
|
Group node that renders its children to one or more "targets".
More...
#include <Inventor/nodes/SoRenderToTarget.h>
This group node renders its children to one or more render targets.
Multiple targets can be "attached" to the different outputs of the node.
This node also provides antialiasing. When FrameBufferObjects (FBO) are used (this is the default mode if they are available) multisampling can be configured in order to perform antialiasing on the FBO. This MSAA feature is not related to the viewer's FSAA. The quality factor is set between 0.f(default value) and 1.f. The underlying system will setup the FBO with the correct number of samples according to the quality value and according to the attachments configuration.
By default the node clears the targets when the rendering is started. The values used to clear the buffers can be specified by the fields clearColorValue, clearDepthValue and clearStencilValue. It is also possible to disable this feature by setting the field clearTargets to FALSE.
During rendering, the viewport from the Open Inventor state is used, which means that the current size of the render area is used. It is possible to change this default behavior by setting the size field. Setting it to (-1, -1) will switch back to the default mode, other values will be used as the custom rendering size in pixels. The targets are automatically resized to the correct size.
The SoRenderToTextureProperty node can also be used to create a texture image and is useful for simpler cases.
NOTES:
This enum defines modifiers for the auto detection mechanism.
Default constructor.
Returns the type identifier for this class.
Reimplemented from SoSeparator.
Returns the number of samples generated by the rasterizer during the last GLRender action.
To enable this feature the enableFragmentsQuery field must be set to TRUE. Otherwise the result is undefined.
Returns the type identifier for this specific instance.
Reimplemented from SoSeparator.
Indicates if this node can be used on the actual hardware.
When using a debug build of Open Inventor, some "no context available" warning messages may be generated. You can ignore them or see SoGLExtension for an example of using SoGLContext to avoid them.
This field defines the antialiasing quality between 0.0 and 1.0 for the rendering.
The value 1.0 represents the maximun quality possible on this hardware. Default is 0.
NOTE: Hardware limitations: The result depends on the support for multisampling in FBO or the FSAA support for PBuffers.
Value used to clear the color buffer before the rendering.
Default is (0.0, 0.0, 0.0, 0.0).
Value used to clear the depth buffer before the rendering.
Default is 1.0.
Value used to clear the stencil buffer before the rendering.
Default is 0.
If this field is set the targets are cleared before the rendering.
Default is TRUE.
This field enables or disables the query counter used to count the number of fragments rasterized during the render to texture operation.
Default is FALSE.
The method getRasterizedSamplesCount() can be used to get the result of the query.
This field is used when targets are SoTexture3.
It describes the layer, along the Z dimension of SoTexture3, where the color attachment must be written. This field is indexed by color attachments (i.e. from COLOR0 to COLOR15) and has no effect when targets are of type SoTexture2 or when target attachments are DEPTH or STENCIL, which require a SoTexture2 Target.
This field allows a custom rendering size for the render to texture.
When this field is set to the default value (-1, -1) the global viewport size from the viewer is used. The size is in pixels.
This field allows to attach a texture to a specific attachment.
Supported target types are SoTexture2 and SoTexture3, default is empty (no targets).
NOTE: This field is indexed using the Attachment enum. For example (in pseudo-code):
|
https://developer.openinventor.com/refmans/latest/RefManCpp/class_so_render_to_target.html
|
CC-MAIN-2021-25
|
refinedweb
| 643
| 60.31
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.